<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>« Simple and Pragmatic Thoughts »</title>
	<atom:link href="http://isagoksu.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://isagoksu.com</link>
	<description>Nobody can be perfect, but you can think better, design better, and always use baby steps!</description>
	<lastBuildDate>Tue, 16 Mar 2010 03:39:58 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Occam&#8217;s Razor</title>
		<link>http://isagoksu.com/2009/development/quotes/occams-razor/</link>
		<comments>http://isagoksu.com/2009/development/quotes/occams-razor/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 08:52:42 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[Quotes]]></category>
		<category><![CDATA[occam]]></category>
		<category><![CDATA[quote]]></category>
		<category><![CDATA[razor]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=644</guid>
		<description><![CDATA[The simplicity is laying under this principle:

The explanation requiring the fewest assumptions is most likely to be correct.&#160;



William of Occam

]]></description>
			<content:encoded><![CDATA[<p>The simplicity is laying under this principle:</p>

<blockquote>The explanation requiring the fewest assumptions is most likely to be correct.<br />&nbsp;
</blockquote>

<p>
<strong class="author">William of Occam</strong>
</p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/quotes/occams-razor/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fancy UITabBar Like Tweetie</title>
		<link>http://isagoksu.com/2009/development/iphone/fancy-uitabbar-like-tweetie/</link>
		<comments>http://isagoksu.com/2009/development/iphone/fancy-uitabbar-like-tweetie/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 10:06:26 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[iPhone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[tweetie]]></category>
		<category><![CDATA[uitabbar]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=631</guid>
		<description><![CDATA[It&#8217;s been a while I haven&#8217;t written anything about iPhone :) Anyways, today I added a fancy UITabBar (like in #Tweetie 2) to one of my applications. I thought I would share the code since I saw lots of iPhone Dev folks are looking for this :)

Initially I started googling, then I ended up a [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while I haven&#8217;t written anything about iPhone :) Anyways, today I added a fancy <em>UITabBar</em> (like in <strong>#Tweetie 2</strong>) to one of my applications. I thought I would share the code since I saw lots of iPhone Dev folks are looking for this :)</p>

<p>Initially I started googling, then I ended up a <a href="http://stackoverflow.com/questions/1563701/making-a-thinner-uitabbar">StackOverflow entry</a> says you have to Roll it :) Since my need was just placing an indicator on top of the <em>UITabItem</em>, I didn&#8217;t go for that way.</p>

<p>Here is how I did:</p>

<p>First, I created an <em>UIImageView</em> which has the indicator icon. Then I added this view to my <em>UITabBar</em> as subview.</p>

<p><pre class="sh_csharp">
UIImage *upArrow = [UIImage imageNamed:@"up-arrow.png"];
UIImageView *imageView=[[UIImageView alloc] initWithImage:upArrow];
imageView.tag = ICON_TAG;
[upArrow release];
[self.tabBarController.tabBar addSubview:imageView];
</pre></p>

<p>This wasn&#8217;t quite enough for my need since I needed indicator to be centered. So I did some math :)</p>

<p><pre class="sh_csharp">
int itemCount = [self.tabBarController.tabBar.items count];
CGFloat cellWidth = tabBarController.view.frame.size.width/itemCount;
CGFloat center = (cellWidth / 2) - (INDICATOR_WIDTH / 2);
</pre></p>

<p>Now I could easily use this center as my indicator center. However I noticed that this wasn&#8217;t enough either since I want it to move every time after I tap to the next <em>UITabBarItem</em>. So I did some refactoring and:</p>

<p><pre class="sh_csharp">
&#35;define INDICATOR_WIDTH 10 //u can define st like this
-(void) addIndicatorTo:(int) index {
    int itemCount = [self.tabBarController.tabBar.items count];
    CGFloat cellWidth=tabBarController.view.frame.size.width/itemCount;
    CGFloat center = (index * cellWidth) + (cellWidth / 2) 
                            - (INDICATOR_WIDTH / 2);
    UIImage *upArrow = [UIImage imageNamed:@"up-arrow.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:upArrow];
    imageView.tag = ICON_TAG;
    [upArrow release];
    [self.tabBarController.tabBar addSubview:imageView];
}
// just listen the item index change
- (void)tabBarController:(UITabBarController *)tbController 
        didSelectViewController:(UIViewController *)viewController {
    [self addIndicatorTo:tbController.selectedIndex];
}
</pre></p>

<p>So far so good. Wait a second, this adds new images every time I tap to the next <em>UITabBarItem</em> :S Anyways, so I refactored my code a little more:</p>

<p><pre class="sh_csharp">
&#35;define INDICATOR_WIDTH 10, u can define st like this
&#35;define INDICATOR_WIDTH 9, u can define st like this
&#35;define ICON_TAG 11, u can define st like this
-(UIImageView *) createNewIndicator {
    UIImage *upArrow = [UIImage imageNamed:@"up-arrow.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:upArrow];
    imageView.tag = ICON_TAG;
    [upArrow release];
    return imageView;
}
-(UIImageView *) findIndicator {
    // return existing one
    for (UIView *view in self.tabBarController.tabBar.subviews) {
        if (view.tag == ICON_TAG) {
            return (UIImageView *) view;
        }
    }
    // if not return a new one
    return [self createNewIndicator];
}
-(void) addIndicatorTo:(int) index {
    int itemCount = [self.tabBarController.tabBar.items count];
    CGFloat cellWidth = tabBarController.view.frame.size.width / itemCount;
    CGFloat center = (index * cellWidth) 
                + (cellWidth / 2) - (INDICATOR_WIDTH / 2);
    UIImageView *imageView = [self findIndicator];
    imageView.frame = CGRectMake(
                        indicatorPositionX, 
                        3 - INDICATOR_HEIGHT, 
                        INDICATOR_WIDTH, 
                        INDICATOR_HEIGHT
                      );
    [self.tabBarController.tabBar addSubview:imageView];
}
</pre></p>

<p>This is basically it. So I did some animation too, here is the result:</p>

<p><!-- ProPlayer by Isa Goksu --><div name="mediaspace" id="mediaspace"><div class="pro-player-container" width="480px" height="320px"><div id="pro-player-631pp-single-5346954a67bf4"></div></div></div><script type="text/javascript" charset="utf-8">var flashvars = {width: "480",height: "320",autostart: "false",repeat: "false",backcolor: "111111",frontcolor: "cccccc",lightcolor: "66cc00",stretching: "fill",enablejs: "true",mute: "false",skin: "http://isagoksu.com/wp-content/plugins/proplayer/players/skins/default.swf",logo: "http://isagoksu.com/wp-content/plugins/proplayer/players/watermark.png",image: "http://isagoksu.com/wp-content/plugins/proplayer/players/preview.png",plugins: "",javascriptid: "631pp-single-5346954a67bf4",image: "http://isagoksu.com/wp-content/plugins/proplayer/players/preview.png",file: 'http://isagoksu.com/wp-content/plugins/proplayer/playlist-controller.php?pp_playlist_id=631pp-single-5346954a67bf4&sid=1397134666'};var params = {wmode: "transparent",allowfullscreen: "true",allowscriptaccess: "always",allownetworking: "all"};var attributes = {id: "obj-pro-player-631pp-single-5346954a67bf4",name: "obj-pro-player-631pp-single-5346954a67bf4"};swfobject.embedSWF("http://isagoksu.com/wp-content/plugins/proplayer/players/player.swf", "pro-player-631pp-single-5346954a67bf4", "480", "320", "9.0.0", false, flashvars, params, attributes);</script></p>

<p>If you guys need, I can upload the working source code to somewhere.. Hope this guides a bit.</p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/iphone/fancy-uitabbar-like-tweetie/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Single, Dynamic, Multiple and Double Dispatching</title>
		<link>http://isagoksu.com/2009/development/java/single-dynamic-multiple-and-double-dispatching/</link>
		<comments>http://isagoksu.com/2009/development/java/single-dynamic-multiple-and-double-dispatching/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 10:57:33 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[dispatch]]></category>
		<category><![CDATA[double]]></category>
		<category><![CDATA[languages]]></category>
		<category><![CDATA[Multiple]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[single]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=625</guid>
		<description><![CDATA[Today I was reading couple articles about programming languages and I noticed that there is still some confusion about dispatching. So I&#8217;ll try to explain as much as I can. Everbody is welcome to correct!

What is Dispatching?

This is also just another OOP term. It&#8217;s not valid outside of the OOP context. I&#8217;m not gonna dive [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was reading couple articles about programming languages and I noticed that there is still some confusion about dispatching. So I&#8217;ll try to explain as much as I can. Everbody is welcome to correct!</p>

<h3>What is Dispatching?</h3>

<p>This is also just another OOP term. It&#8217;s not valid outside of the OOP context. I&#8217;m not gonna dive into linguistic details. Basically, it&#8217;s an invocation of a function on a specific type as in <em>object.function(with params)</em>. For more details you can <strong>#wiki</strong> it. There are 3 types of dispatching mechanism:</p>

<ul>
<li>Single/Dynamic Dispatching</li>
<li>Multiple Dispatching</li>
<li>Double Dispatching</li>
</ul>

<p>You might also find 2 other topics related to this subject, but I&#8217;m not gonna cover them today. You can quickly <strong>#wiki</strong> it: <a href="http://en.wikipedia.org/wiki/Monkey_patching">Monkey Patching</a> and <a href="http://en.wikipedia.org/wiki/Duck_typing">Duck Typing</a>. Anyways, so let&#8217;s get back to our subject:</p>

<h3>Single/Dynamic Dispatching</h3>

<p>Although there is a subtle difference between them, I covered these 2 topics under the same title. So basically, when you invoke a function on a type, it&#8217;s called single dispatch as in:</p>

<p><pre class="sh_java">
    class Messenger {
        public void send(String message) { }
    }<br />
    Messenger messenger = new Messenger();
    messenger.send("Hello World");
</pre></p>

<p>If there is no polymorphic structure, compiler knows this at compile time. There can be multiple <em>send</em> functions under different types (classes). Compiler binds them to the correct ones in the compile time:</p>

<p><pre class="sh_java">
    class Messenger {
        public void send(String message) { }
    }<br />
    class SMSGateway {
        public void send(String sms) { }
    }<br />
    Messenger messenger = new Messenger();
    messenger.send("Hello World");<br />
    SMSGateway gateway = new SMSGateway();
    gateway.send("Cya in 10!");
</pre></p>

<p>In above example, compiler bound <em>send(message)</em> to Messenger and <em>send(sms)</em> to SMSGateway types. These are all single dispatch examples. No dynamic dispatching needed so far. However, if you have a polymorphic structure as in:</p>

<p><pre class="sh_java">
    interface Messenger {
        void send(String message);
    }<br />
    class TextMessenger implements Messenger {
        public void send(String message) {
            System.out.println("TEXT: " + message);
        }
    }<br />
    class XMLMessenger implements Messenger {
        public void send(String message) {
            System.out.println("<message>" + message + "</message>");
        }
    }<br />
    class Demo {
        public void useMessenger(Messenger messenger) {
            messenger.send("Which messenger am I using?");
        }
    }
</pre></p>

<p>As you may quickly notice, this requires dynamic dispatching (run-time decision) since compiler cannot decide the actual type of the messenger which <em>Demo.useMessenger</em> uses. Lots of known design patterns are already based on this mechanism (Strategy, Bridge, etc..) Again I&#8217;m not going go into details, you can find more information about this on <strong>#wiki</strong>: <a href="http://en.wikipedia.org/wiki/Single_dispatch">Single/Dynamic Dispatch</a> and <strong>#c2wiki</strong>: <a href="http://c2.com/cgi/wiki?SingleDispatch">Single Dispatch</a> / <a href="http://c2.com/cgi/wiki?DynamicDispatch">Dynamic Dispatch</a></p>

<h3>Multiple Dispatching</h3>

<p>Roughly it is the idea behind overloading in most programming languages. Your type has so many functions with the same name, but they all have different parameters.</p>

<p><pre class="sh_java">
    class Messenger {
        public void send(String message) { }
        public void send(String message, Person to) { }
        public void send(String message, String subject, Person to) { }
    }
</pre></p>

<p>You can figure out how it would work. However multiple dispatching is not just about this. I guess overloading example is misleading too. Anyways, let&#8217;s consider following example:</p>

<p><pre class="sh_java">
    interface Messenger {
        void send(String message);
    }
    class TextMessenger implements Messenger {
        public void send(String message) {
            System.out.println("TEXT: " + message);
        }
    }<br />
    class XMLMessenger implements Messenger {
        public void send(String message) {
            System.out.println("<message>" + message + "</message>");
        }
    }
    class Demo {
        public void useMessenger(Messenger messenger) {
            messenger.send("Which messenger am I using?");
        }
        public void useMessenger(TextMessenger messenger) {
            messenger.send("I'm TextMessenger for sure, but?");
        }
    }
</pre></p>

<p>So what do you think will happen when I try to invoke <em>Demo.useMessenger(TextMessenger)</em>. If your language doesn&#8217;t support true multiple dispatch mechanism, you&#8217;ll always end up invoking <em>useMessenger(Messenger)</em> function no matter what you provide. With true multiple dispatching, you&#8217;ll invoke <em>useMessenger(TextMessenger)</em> when you provide <em>TextMessenger</em> to the function. More information, again use <strong>#wiki</strong> <a href="http://en.wikipedia.org/wiki/Multiple_dispatch">Multiple Dispatch</a> or <strong>#c2wiki</strong>: <a href="http://c2.com/cgi/wiki?MultipleDispatch">Multiple Dispatch</a> BTW, <strong>#Java</strong> doesn&#8217;t support true multiple dispatching, so don&#8217;t cause any bugs while creating overloaded methods.</p>

<h3>Double Dispatching</h3>

<p>Well this one is pretty cool. Some define this as true dispatching :) Anyways, to me all of them are true :) In real world, all relations are actually two-way. It&#8217;s not only you&#8217;re telling somebody about something, he/she is also listening to you. Double dispatching is like this: two-way. Visitor pattern is actually good way of explaining this topic. Let&#8217;s look at the following example:</p>

<p><pre class="sh_java">
    // messenger
    interface Messenger {
        void send(Message message);
    }
    class TextMessenger implements Messenger {
        public void send(Message message) {
            // some custom operations
            message.print(this);
        }
    }
    class XMLMessenger implements Messenger {
        public void send(Message message) {
            // some other custom operations
            message.print(this);
        }
    }
    // and message
    class Message {
        public void print(TextMessenger messenger) {
            // do something
        }
        public void print(XMLMessenger messenger) {
            // do some other thing
        }
    }
</pre></p>

<p>As you can easily see, objects are related to each-other both ways. <em>Message</em> is deciding to do something based on other types.</p>

<p>Hope this clarifies things a bit more.</p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/java/single-dynamic-multiple-and-double-dispatching/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Act Like a Senior Developer &#8211; About Clean Code</title>
		<link>http://isagoksu.com/2009/development/agile-development/act-like-a-senior-developer-about-clean-code/</link>
		<comments>http://isagoksu.com/2009/development/agile-development/act-like-a-senior-developer-about-clean-code/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 09:59:51 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[clean]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[refactoring]]></category>
		<category><![CDATA[smell]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=603</guid>
		<description><![CDATA[Today it was a hard day for me. As usual, I was looking at a mess around our code base. And the worst thing was that the code that I saw today was not a legacy code :S 
It has enough test coverage and moreover the system was working well. The problem was the conditional [...]]]></description>
			<content:encoded><![CDATA[<p>Today it was a hard day for me. As usual, I was looking at a mess around our code base. And the worst thing was that the code that I saw today was not a <em>legacy code</em> :S 
It has enough <u>test coverage</u> and moreover the system was working well. The problem was the conditional logics used all over the place. It is almost impossible to follow what&#8217;s 
happening and where :S Me and my colleague spent 2 whole days trying to understand what the heck was going on. Finally we figured it out and did what we wanted to do initially.</p>

<p>Here, I wanna just stop and speak loudly to all the developers that call themselves <em>senior</em> or <em>EDIT:</em> <em>principal</em> or <em>if (experience != Experiences.JUNIOR)</em>:</p>

<p>People, what&#8217;s wrong with us? How come newly implemented code base is turning into a mess this fast? How come we&#8217;re allowing such a mess when we see it slowly approaching us
like a monster? But of course, when it comes to the interviews, we have to ask candidates questions around design patterns, real-time problem solving skills, test driven design, 
and refactoring. And seriously is this why we were asking these questions? I&#8217;m so emberassed and ashamed of being a <em>senior</em> guy today.</p>

<p>Anyways, long story short, here is a 5 minute crash course about what we forget to foresee:</p>

<h3>1. Evil Ifs</h3>

<p>As a <em>senior</em> guy, you have to be aware of ifs are evil in most cases. For those who forgot, here is a quick do not forget list:</p>

<ul>
<li><em>ALLOW THEM WHEN</em>:</li>
</ul>

<h4>Condition can be expressed without <em>AND</em>, <em>OR</em> operators: i.e</h4>

<p><pre class="sh_java">
if (myContainer.hasItems()) {
    //...
}
</pre></p>

<h4>Condition is about an encapsulated field: i.e</h4>

<p><pre class="sh_java">
if (_isVisible) {
    //...
}
</pre></p>

<h4>Condition is non-float numerical comparison: i.e</h4>

<p><pre class="sh_java">
if (myCertificates.count() > 3) {
    //...
}
</pre></p>

<ul>
<li><em>BE CAUTIOUS</em>:</li>
</ul>

<h4>When there is one or two <em>AND</em>, <em>OR</em> operators: i.e</h4>

<p><pre class="sh_java">
if (_isVisible &amp;&amp; !isParent) {
    //...
}
// SOLUTION: refactor (extract method, extract local variable, etc)
</pre></p>

<h4>When there is negative logic: i.e</h4>

<p><pre class="sh_java">
if (!_iAmSenior) {
    //...
}
// SOLUTION: refactor (make it positive like iAmJunior; 
// positive statements are easy to understand)
</pre></p>

<h4>When there is a very long condition: i.e</h4>

<p><pre class="sh_java">
if (myAwesomeServiceImpl.findExtremelyImportantSomething()
                            .equals(myLocalExtremelyImportantThing)) {
    //...
}
// SOLUTION: refactor (make it short or extract local variable, 
// trust me your application is not at the point where you should 
// worry about memory or CPU cycles)
</pre></p>

<h4>When there is a if/else statement: i.e</h4>

<p><pre class="sh_java">
if (_isVisible) {
    number = getNumberFromMoon();
} else {
    number = 1;
}
// this creates more than 2 execution paths within one method, 
// make sure you force all the possibilities to block above logic
// SOLUTION: get rid of the second part if possible as in:</p>

<p>number = 1;
if (_isVisible) {
    number = getNumberFromMoon();
}
// if it is not this simple, then make sure you created 
// two different executions paths (with different 
// methods/classes) before coming to this point
</pre></p>

<ul>
<li><em>DON&#8217;T ALLOW PLEASE</em>:</li>
</ul>

<h4>When it is a null check:</h4>

<p><pre class="sh_java">
if (item != null) {
    // do something...
}
// SOLUTION: find the cause of null and eliminate it.
</pre></p>

<p>For more information on this topic, please read <a href="http://isagoksu.com/2009/development/java/how-to-avoid-nullpointerexceptions-npe/">my other post</a> about null pointer exceptions.</p>

<h4>When there is more than two <em>AND</em>, <em>OR</em>, <em>NOT</em> operators: i.e</h4>

<p><pre class="sh_java">
if ((_isVisible &amp;&amp; !isParent) || iAmMaster || youCanPassIsSet) {
    // do something...
}
// SOLUTION: For God's sake! you have to refactor this code. 
// The least you can do is extracting a method out of it 
// if you don't know any design patterns to apply. Check below:</p>

<p>if (isValid()) {
    // do something...
}
</pre></p>

<h4>When there is nested if/else statement: i.e</h4>

<p><pre class="sh_java">
if (isThisTrue) {
    if (checkIfHeIsTheMaster() &amp;&amp; !hmmmThisSeemsWeird()) {
        // do something...
    } else {
        // do something else...
    }
} else {
    // this is just ugly...
}
// SOLUTION: Use well known OOP technique called <em>POLYMORPHISM</em>, 
// or if the operator is one of (>, &lt;, ==) then various possible 
// design patterns like Strategy (behavior modification), 
// Visitor (context evaluation) or Specification (item selection). 
// If you're not happy, but you don't know what to do then talk 
// to someone you think he/she might know.
</pre></p>

<p>Also if you are the maintainer of the code base then you might wanna introduce static code analyzers like PMD. They can easily detect <em>cyclomatic complexities</em>.</p>

<p>Anyways, you guys can easily figure it out. You are welcome to introduce new ones. These are just some that I can think of in the middle of the night.</p>

<h3>2. Stupid Loops</h3>

<p>Folks, if you&#8217;re introducing loops to your logic, please make sure that you really need them. Please check the code snippets and the solutions below; I don&#8217;t wanna comment more about this:</p>

<p><pre class="sh_java">
for (int i=0; i &lt; 2; i++) {
    if (i == 0) {
        doThis();
    } else if (i == 1) {
        doThat();
    } 
}
// SOLUTION: how about this? You don't need loop there :S
doThis();
doThat();
</pre></p>

<p>Another one:</p>

<p><pre class="sh_java">
for (int i=0; i &lt; items.size(); i++) {
    if (!isVisible(items.get(i))) {
        continue;
    }
    doThis(); 
}
// SOLUTION: how about this? I stil don't know why you need continue there?
for (int i=0; i &lt; items.size(); i++) {
    if (isVisible(items.get(i))) {
        doThis(); 
    }
}
</pre></p>

<p>One more:</p>

<p><pre class="sh_java">
item = null;
for (int i=0; i &lt; items.size(); i++) {
    if (isVisible(items.get(i))) {
        item = items.get(i);
    }
}
return item;
// SOLUTION: how about this? returning values directly?
for (int i=0; i &lt; items.size(); i++) {
    if (isVisible(items.get(i))) { // EDIT from user comments
        return items.get(i);
    }
}
return null; // if possible even return new NullItem()
</pre></p>

<h3>3. Dependency Injections</h3>

<p>Woov, this one is an advanced topic ah? Everyone loves dependency injection. Spring sort of frameworks are even forcing you to do it this way right? Let me tell you something; 
I believe after go-to statements, this one is the most misinterpreted topic in programming history. We <em>senior</em> guys somehow convinced ourselves to something like this: 
If you can inject it&#8217;s cost free! Man&#8230; just don&#8217;t do this please. Everything has a cost. This is just a way to ease/loose your tight connections with your dependencies. 
Don&#8217;t try to interpret otherwise.</p>

<p>And second thing is the famous <em>setter injection</em>. So if you have a setter injection set up there, it means don&#8217;t worry. It&#8217;s like we can&#8217;t think otherwise :S Opppss. Stop here! 
It is not like that at all if you still couldn&#8217;t figure it out. Setter injection and Constructor injection are 2 well known ways of doing this (there are other ways too). 
Each of them has its own advantages/disadvantages. However, let&#8217;s be honest. Constructor injection is much more declarative than setter injection.</p>

<p>Anyways, it&#8217;a very big debate. I&#8217;m kinda scared :P People are gonna offend me again. I just wanna say that if possible please try to use constructor injection in your custom code. 
If you don&#8217;t believe me, then refer to Martin Fowler&#8217;s <a href="http://martinfowler.com/articles/injection.html#ConstructorInjectionWithPicocontainer">IOC Article</a> or Misko Hevery&#8217;s <em>Clean Code</em> Talks at #Google, such as: <a href="http://www.youtube.com/watch?v=RlfLCWKxHJ0">Don&#8217;t Look For Things</a>.</p>

<h3>4. So Many Dependencies</h3>

<p>Just a tiny comment here. Folks, try reading #SOLID principles, ok. DON&#8217;T CREATE this much dependency :S The class itself is screaming at you: &#8220;I can&#8217;t carry this much!&#8221;, 
&#8220;You won&#8217;t be able to test this&#8221;, &#8220;I&#8217;ve more than 1000 lines&#8221;, &#8220;You can&#8217;t use constructor injection anymore!&#8221;</p>

<p>Bottom line, if you have so many dependencies, please try to find a way to separate concerns.</p>

<h3>5. So Many Parameters</h3>

<p>You have more than 3-4 arguments? Re-consider that code. Probably you don&#8217;t need that. I&#8217;m sure you can pull up something from that method or at least extract and call separately.</p>

<h3>6. Pass What You Need</h3>

<p>This bugs me a lot. Look at this:</p>

<p><pre class="sh_java">
calculateLoanForSomething(Account, Customer, World);</p>

<p>// here is the method
void calculateLoanForSomething(Account a, Customer c, World w) {
    if (w.date.time.hour == 11) {
        // do something here..
    }
}</p>

<p>// Why r u sending God objects everywhere :S
void calculateLoanForSomething(Account a, Customer c, int hour) { }
</pre></p>

<h3>7. Long Classes/Methods</h3>

<p>Here is my rule of thumb:</p>

<ul>
<li>Is it more than 20 lines? THEN: Refactor</li>
<li>Is it more than 10 methods? THEN: Refactor</li>
<li>Is it more than 5 package? THEN: Refactor</li>
<li>Your colleague is coding? Please pair with him/her as much as you can especially if you think he/she is gonna introduce something bad. At least you can teach him/her or prevent things from happening.</li>
</ul>

<p>I don&#8217;t know if you guys are agree with me or not. I was so ashamed today and wanted to write this. It was more like a self relaxation. 
Please don&#8217;t mind if I used a wrong sentence or anything. It&#8217;s almost 2AM and I&#8217;m so tired.</p>

<p>For more deeper information about these topics, please refer to Refactoring Book or <a href="http://refactoring.com">site</a>, <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod">SOLID Principles</a>, Clean Code talks, Clean Code <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">book</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/agile-development/act-like-a-senior-developer-about-clean-code/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>True Liskov Substitution Principle (LSP)</title>
		<link>http://isagoksu.com/2009/development/quotes/true-liskov-substitution-principle-lsp/</link>
		<comments>http://isagoksu.com/2009/development/quotes/true-liskov-substitution-principle-lsp/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 19:59:32 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[Quotes]]></category>
		<category><![CDATA[liskov]]></category>
		<category><![CDATA[lsp]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[principle]]></category>
		<category><![CDATA[quot]]></category>
		<category><![CDATA[substitution]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=587</guid>
		<description><![CDATA[I  know everybody is quoting from #WikiPedia or st, but I guess the true definition of this principle is:

A subtype must require no more and promise no less than its supertype.&#160;



Bertrand Meyer

]]></description>
			<content:encoded><![CDATA[<p>I  know everybody is quoting from #WikiPedia or st, but I guess the true definition of this principle is:</p>

<blockquote>A subtype must require no more and promise no less than its supertype.<br />&nbsp;
</blockquote>

<p>
<strong class="author">Bertrand Meyer</strong>
</p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/quotes/true-liskov-substitution-principle-lsp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Custom Annotations and Using Them</title>
		<link>http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/</link>
		<comments>http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 08:58:25 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[create]]></category>
		<category><![CDATA[element-type]]></category>
		<category><![CDATA[retention]]></category>
		<category><![CDATA[target]]></category>
		<category><![CDATA[use]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=565</guid>
		<description><![CDATA[Okay, here is another topic that I couldn&#8217;t find much information in the Internet :) So I guess I&#8217;m gonna cover it quickly.

How to Create a Custom Annotations?

There are a lot of documentation about this part in the Internet. All you have to do is basically creating an annotation class like below:


public @interface Copyright {
 [...]]]></description>
			<content:encoded><![CDATA[<p>Okay, here is another topic that I couldn&#8217;t find much information in the Internet :) So I guess I&#8217;m gonna cover it quickly.</p>

<h3 id="565_how-to-create-a-cust_1" >How to Create a Custom Annotations?</h3>

<p>There are a lot of documentation about this part in the Internet. All you have to do is basically creating an annotation class like below:</p>

<p><pre class="sh_java">
public @interface Copyright {
    String info() default "";
}
</pre></p>

<p>And that&#8217;s it. Now it&#8217;s ready to use! Now you can put copyright information to your classes :) Since we didn&#8217;t define any <em>@Target</em>, you can use this annotation anywhere in your classes by default. If you want your annotation to be only available for class-wise or method-wise, you should define <em>@Target</em> annotation. Here is a little table of what options are available:</p>

<ul>
<li><strong>@Target(ElementType.PACKAGE)</strong>, package header</li>
<li><strong>@Target(ElementType.TYPE)</strong>, class header</li>
<li><strong>@Target(ElementType.CONSTRUCTOR)</strong>, constructor header</li>
<li><strong>@Target(ElementType.METHOD)</strong>, method header</li>
<li><strong>@Target(ElementType.FIELD)</strong>, for class fields only</li>
<li><strong>@Target(ElementType.PARAMATER)</strong>, for method parameters only</li>
<li><strong>@Target(ElementType.LOCAL_VARIABLE)</strong>, for local variables only</li>
</ul>

<p>If you want your annotation to be available in more than one place, just use array syntax as in:</p>

<p><pre class="sh_java">
@Target({ ElementType.PARAMETER, ElementType.LOCAL_VARIABLE })
</pre></p>

<p>One thing you may already notice is annotations are interfaces, so you don&#8217;t implement anything in them.</p>

<h3 id="565_how-to-make-use-of-y_1" >How to Make Use of Your Custom Annotations?</h3>

<p>Up to here, you can find lots of examples. Okaaay, now let&#8217;s do something useful :) For instance, let&#8217;s re-implement <em>JUnit</em>&#8217;s <em>@Test</em> annotation. As you guys already know, <em>@Test</em> annotation is a marker annotation. Basically it marks the method as test method. If you&#8217;re expecting any exceptions, you would set <em>expect</em> attribute in the annotation. You can try anything here, I&#8217;m just using this example since everyone knows how <em>@Test</em> annotation works.</p>

<p>First let&#8217;s define our annotation:</p>

<p><pre class="sh_java">
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
    Class expected();
}
</pre></p>

<p>You might notice that I used <em>@Retention</em>. This annotation marks our annotation to be retained by JVM at runtime. This will allow us to use Java reflections later on.</p>

<p>Now we need to write our annotation parser class. This class will parse our annotation and trigger some other invocations related to what we want. Keep in mind that if you have more than one custom annotation, then it&#8217;s also wise to have separate parsers for each annotation you define. So I&#8217;ll create one for this! The basic idea behind the annotation parser is using Java reflections to access the annotation information/attributes etc. So here is an example parser for our <em>@Test</em> annotation:</p>

<p><pre class="sh_java">
public class TestAnnotationParser {
    public void parse(Class&lt;?&gt; clazz) throws Exception {
        Method[] methods = clazz.getMethods();
        int pass = 0;
        int fail = 0;</p>

<pre><code>    for (Method method : methods) {
        if (method.isAnnotationPresent(Test.class)) {
            try {
                method.invoke(null);
                pass++;
            } catch (Exception e) {
                fail++;
            }
        }
    }
}
</code></pre>

<p>}
</pre></p>

<p>That&#8217;s all you need. You parser is ready to use too. But wait a minute, we didn&#8217;t implement anything about the annotation attributes. This part is a bit tricky. Because you cannot directly access those attributes from the object graph. Luckily invocation helps us here. You can only access these attributes by invoking them. Sometimes you might need to cast the class to the annotation type too. I&#8217;m sure you&#8217;ll figure out when you see it:) Anyways here is a bit more logic to take our <strong>expected</strong> attribute into account:</p>

<p><pre class="sh_java">
// ...
// this is how you access to the attributes
Test test = method.getAnnotation(Test.class);
// we use Class type here because our attribute type
// is class. If it would be string, you'd use string
Class expected = test.expected();
try {
    method.invoke(null);
    pass++;
} catch (Exception e) {
    if (Exception.class != expected) {
        fail++;
    } else {
        pass++;
    }
}
// ...
</pre></p>

<p>Now everything is ready to use. Below example demonstrates how you use Parser with your test classes:</p>

<p><pre class="sh_java">
public class Demo {
    public static void main(String [] args) {
        TestAnnotationParser parser = new TestAnnotationParser();
        parser.parse(MyTest.class);
        // you can use also Class.forName 
        // to load from file system directly!
    }
}
</pre></p>

<p>Yeah, I hope you enjoyed. Don&#8217;t hesitate to put some comments down if you&#8217;ve a better approach? Thanks! Here is the full parser class implementation:</p>

<p><pre class="sh_java">
public class TestAnnotationParser {
    public void parse(Class&lt;?&gt; clazz) throws Exception {
        Method[] methods = clazz.getMethods();
        int pass = 0;
        int fail = 0;</p>

<pre><code>    for (Method method : methods) {
        if (method.isAnnotationPresent(Test.class)) {
            // this is how you access to the attributes
            Test test = method.getAnnotation(Test.class);
            Class expected = test.expected();
            try {
                method.invoke(null);
                pass++;
            } catch (Exception e) {
                if (Exception.class != expected) {
                    fail++;
                } else {
                    pass++;
                }
            }
        }
    }
}
</code></pre>

<p>}
</pre></p>

<p>
<em>Edit:</em> <i>Also after receiving some emails, I guess I should add a full working example :) So here is one. Just copy paste and run the show :)</i>
</p>

<p><pre class="sh_java">
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Test {
    String info() default "";
}</p>

<p>class Annotated {
    @Test(info = "AWESOME")
    public void foo(String myParam) {
        System.out.println("This is " + myParam);
    }
}</p>

<p>class TestAnnotationParser {
    public void parse(Class<?> clazz) throws Exception {
        Method[] methods = clazz.getMethods();</p>

<pre><code>    for (Method method : methods) {
        if (method.isAnnotationPresent(Test.class)) {
            Test test = method.getAnnotation(Test.class);
            String info = test.info();

            if ("AWESOME".equals(info)) {
                 System.out.println("info is awesome!");
                 // try to invoke the method with param
                 method.invoke(
                    Annotated.class.newInstance(), 
                    info
                 );
            }
        }
    }
}
</code></pre>

<p>}</p>

<p>public class Demo {
    public static void main(String[] args) throws Exception {
        TestAnnotationParser parser = new TestAnnotationParser();
        parser.parse(Annotated.class);
    }
}
</pre></p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Creating Custom Managers For Repetitive Filters</title>
		<link>http://isagoksu.com/2009/development/django/creating-custom-managers-for-repetitive-filters/</link>
		<comments>http://isagoksu.com/2009/development/django/creating-custom-managers-for-repetitive-filters/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 05:37:51 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[manager]]></category>
		<category><![CDATA[model]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=561</guid>
		<description><![CDATA[Today I was trying to do something in Django and I&#8217;ve noticed that I&#8217;m using lots of filter in my views. And most of the filters were same, but for different purposes. Then I felt like DRY principle is screaming at me. So I started to think that maybe there is a way to prevent [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was trying to do something in <strong>Django</strong> and I&#8217;ve noticed that I&#8217;m using lots of <em>filter</em> in my views. And most of the filters were same, but for different purposes. Then I felt like <a href="http://en.wikipedia.org/wiki/DRY" title="Don't repeat yourself - Wikipedia, the free encyclopedia" target="_blank">DRY</a> principle is screaming at me. So I started to think that maybe there is a way to prevent these repetitions. And like all other problems in the world, the solution was just in front of my eyes :)</p>

<p>So let&#8217;s say that we&#8217;ve a model class that represents Employees in the company which includes even retired ones. To reach the all employees, you would use:</p>

<p><br />
<pre class="sh_python">
Employee.objects.all()
</pre></p>

<p>And if you want to work with retired employees:</p>

<p><pre class="sh_python">
Employee.objects.filter(status=Employee.RETIRED)
</pre></p>

<p>This would give you the all retired employees. If you&#8217;re working with this object list frequently, you might want to introduce a custom manager.</p>

<h3 id="561_custom-managers_1" >Custom Managers</h3>

<p>Before going into the custom managers, I&#8217;d like to first explain where this <i>Employee.objects</i> comes from. <em>objects</em> attribute is an instance of a special class called <strong>Manager</strong> (<i>django.db.models.Manager</i>). The basic idea is to provide common db operations via this attribute, e.g <i>all()</i>, <i>filter()</i>, etc.. You can find the full documentation from <a href="http://docs.djangoproject.com/en/dev/topics/db/models/" title="Models" target="_blank">here</a>. If you don&#8217;t specify any custom managers, <strong>Django</strong> automatically adds this default manager to your model class.</p>

<p>Custom managers on the other hand is the extended version of this manager class. And creating a custom manager is fairly easy:</p>

<p><pre class="sh_python">
class MyModel(models.Model):
    myfield = models.CharField(max_length=50)</p>

<pre><code>object_provider = models.Manager()
</code></pre>

<p></pre></p>

<p>So above model&#8217;s <em>object_provider</em> attribute would act exactly same as the default manager since they&#8217;re same. Please check below usages:</p>

<p><pre class="sh_python">
'''
  Below usages would provide same results.
'''
MyModel.objects.all()
MyModel.object_provider.all()
</pre></p>

<p>So how to customize this manager then? Again, very easy. Just extend the <i>django.db.models.Manager</i> class. So let&#8217;s look at the following code:</p>

<p><pre class="sh_python">
class RetiredEmployeeManager(models.Manager):
   def get_query_set(self):
      return super(RetiredEmployeeManager, self).get_query_set().filter(status=Employee.RETIRED)
</pre></p>

<p>From this point, the only thing you need to do is defining this manager as your manager.</p>

<p><pre class="sh_python">
class Employee(models.Model):
    name = models.CharField(max_length=50)</p>

<pre><code>objects = models.Manager()
retired_ones = RetiredEmployeeManager()
</code></pre>

<p></pre></p>

<p>And finally, you can use your new manager in your views:</p>

<p><pre class="sh_python">
Employee.retired_ones.all();
</pre></p>

<p>Hope it helps you to clean up some duplicated code!</p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/django/creating-custom-managers-for-repetitive-filters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating Lorem Ipsums in Django Templates</title>
		<link>http://isagoksu.com/2009/development/django/generating-lorem-ipsums-in-django-templates/</link>
		<comments>http://isagoksu.com/2009/development/django/generating-lorem-ipsums-in-django-templates/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 11:50:19 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[generate]]></category>
		<category><![CDATA[ipsum]]></category>
		<category><![CDATA[lorem]]></category>
		<category><![CDATA[template]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=551</guid>
		<description><![CDATA[When we first attempt create our web applications, most of us use a common printing phrase which starts with Lorem Ipsum words in our templates. Today while I was reading something in the Django documentation, and surprisingly I came across with this very useful module. Honestly, I didn&#8217;t even know Django has such a thing. [...]]]></description>
			<content:encoded><![CDATA[<p>When we first attempt create our web applications, most of us use a common printing phrase which starts with <strong>Lorem Ipsum</strong> words in our templates. Today while I was reading something in the Django documentation, and surprisingly I came across with this very useful <a href="http://docs.djangoproject.com/en/dev/ref/contrib/webdesign/" target="_blank">module</a>. Honestly, I didn&#8217;t even know Django has such a thing. After seeing this module, I again thought about how much I love Django :)</p>

<p>Anyways, the idea is generating this placeholder words in your template by using a template tag. Here is the usage:</p>

<p><pre class="sh_html">
&lt;!-- 
    make sure you're loading webdesign module 
    by writing {% load webdesign %} 
--&gt;
&lt;div id='my-text-area'&gt;
   {% lorem %}
   &lt;!--
       This will be replaced with "Lorem ipsum dolor 
       sit amet, consectetur adipiscing elit..."
   --&gt;
&lt;/div&gt;</p>

<p>&lt;input type='text name='name' value='{% lorem 2 w random %}' /&gt;
&lt;!-- 
    This will be replaced with 
    2 random latin words 
--&gt;</p>

<p>&lt;div id='description'&gt;
   {% lorem 5 p %}
   &lt;!--
       This will be replaced with 
       5 paragraphs of "Lorem Ipsum.." text
   --&gt;
&lt;/div&gt;
</pre></p>

<p>Isn&#8217;t Django awesome :) It has everything you need!</p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/django/generating-lorem-ipsums-in-django-templates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning Site Packages Folder Under OSX</title>
		<link>http://isagoksu.com/2009/development/django/learning-site-packages-folder-under-osx/</link>
		<comments>http://isagoksu.com/2009/development/django/learning-site-packages-folder-under-osx/#comments</comments>
		<pubDate>Sun, 13 Sep 2009 08:21:06 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[folder]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[site-packages]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=542</guid>
		<description><![CDATA[
Today I was browsing couple django extensions to check if there is any new useful stuff around. I saw couple questions in those WiKis/forums about site-packages folder under OSX. For those who don&#8217;t know which site-packages folder is active in your system, you must consider how your system is configured. Especially if you&#8217;re using MacPorts [...]]]></description>
			<content:encoded><![CDATA[<p>
Today I was browsing couple <strong>django</strong> extensions to check if there is any new useful stuff around. I saw couple questions in those WiKis/forums about <u>site-packages</u> folder under OSX. For those who don&#8217;t know which <u>site-packages</u> folder is active in your system, you must consider how your system is configured. Especially if you&#8217;re using <em>MacPorts</em> or any tool like that, your default <u>site-packages</u> folder that is shipped with OS X might be different than what you&#8217;re presuming.
</p>

<p>
Anyways, the best way to learn what&#8217;s your active <u>site-packages</u> folder, you can quickly learn it by typing:
</p>

<p><pre class="sh_sh">
$ python -c \ 
"from distutils.sysconfig import get_python_lib;   \
 print get_python_lib()"
</pre></p>

<p>Or you can create a script like below and place it under your <em>/usr/bin</em> folder for further uses.</p>

<p><pre class="sh_python">
from distutils.sysconfig import get_python_lib;</p>

<p>print get_python_lib()
</pre></p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/django/learning-site-packages-folder-under-osx/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Code More Testable &#8211; Breaking Static Dependencies</title>
		<link>http://isagoksu.com/2009/development/agile-development/test-driven-development/making-code-more-testable-breaking-static-dependencies/</link>
		<comments>http://isagoksu.com/2009/development/agile-development/test-driven-development/making-code-more-testable-breaking-static-dependencies/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 08:07:31 +0000</pubDate>
		<dc:creator>Isa Goksu</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[break]]></category>
		<category><![CDATA[constructor]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[dependency]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[static]]></category>

		<guid isPermaLink="false">http://isagoksu.com/?p=531</guid>
		<description><![CDATA[Hi guys, it&#8217;s been a while that I haven&#8217;t posted anything. I was thinking writing all those technical things sometimes is not enough for the reader to visualize the concept. So I came up with a screencast this time. I&#8217;ll try to create these screencasts once a week and will cover different topics. This series [...]]]></description>
			<content:encoded><![CDATA[<p>Hi guys, it&#8217;s been a while that I haven&#8217;t posted anything. I was thinking writing all those technical things sometimes is not enough for the reader to visualize the concept. So I came up with a screencast this time. I&#8217;ll try to create these screencasts once a week and will cover different topics. This series will contain <strong>Making Code More Testable</strong> talks only. For other topics, I&#8217;ll create different series. Anyways, let&#8217;s get back to the overview :)</p>

<p>In this first screencast I&#8217;ll try to cover how you guys could break the static dependencies in your constructor. Let me give you some brief overview about these dependencies:</p>

<h3 id="531_dependencies_1" >Dependencies</h3>

<p>Dependencies are everywhere in our little world. Every unit, every module is depending on something. Sometimes it&#8217;s another unit, sometimes it&#8217;s another modules, and sometimes it&#8217;s another library. And there are lots of discussions currently going on to make your units, modules more scalable and more isolated! All OSGi, maven, DI (Dependency Injection) and SOLID principles are just for this purpose. To help you to break/isolate/modulate your code base.</p>

<p>In this screencast I&#8217;m gonna talk about only a single part of whole this picture. Static dependencies within your constructors.</p>

<h3 id="531_static-dependencies-_1" >Static Dependencies Within Constructors</h3>

<p>This type of dependencies are very evil when it comes to do unit testing. It could turn into a very big puzzle game sometimes. The basic idea is some developers tend to place their dependent services or non-value objects into the constructor and using  <strong>singleton and/or static methods</strong>. Without being aware of what they&#8217;re doing, they sometimes even place <em>if/else</em>, <em>try/catch</em>, <em>switch/default</em> statements into this tiny part of the code.</p>

<p>So how it happens? Very easy, let&#8217;s consider the following code snippets:</p>

<p><pre class="sh_java">
/** My class. */
public class MyClass {
    private Service service;</p>

<pre><code>/** Default constructor */
public MyClass() {
    // lots of logic that shouldn't be here..
    // and
    this.service = Service.getInstance();
    TimeService.recordTime();
}
</code></pre>

<p>}
</pre></p>

<p><i>(EDIT)</i> As you may clearly see, it&#8217;s very hard to test this unit since it has non-injectable static dependencies. So what do we need to do?</p>

<p>There are couple ways to break these dependencies. Before going into too deep, I want to clarify something here. &#8220;DON&#8217;T EVER DO THIS&#8221;! When you write your code, maybe you don&#8217;t follow TDD or anything. But please consider there will be some people that have to deal with this code after you. Then again, if you&#8217;re selfish.. There is no more word to say!</p>

<h3 id="531_breaking-the-depende_1" >Breaking the Dependencies</h3>

<p>As I said, there are couple ways to break these sort of dependencies.</p>

<p><strong><u>Constructor Delegation</u></strong></p>

<p>First and my favourite is <em>Constructor Delegation</em>. The basic idea for this technique is create another constructor which takes these dependencies for dependency injection and delegate the first constructor to the second one. Please consider following code&#8217;s before/after and usage scenarios:</p>

<p><pre class="sh_java">
// BEFORE 'constructor delegation'
public class LibraryManager {
    private LibraryService service;</p>

<pre><code>public LibraryManager() {
    this.service = LibraryService.getInstance();
}
// more code
</code></pre>

<p>}</p>

<p>// AFTER 'constructor delegation'
public class LibraryManager {
    private LibraryService service;</p>

<pre><code>public LibraryManager() {
    // delegate to the new constructor
    this(LibraryService.getInstance());
}

// new constructor
public LibraryManager(LibraryService service) {
    this.service = service;
}
// more code
</code></pre>

<p>}</p>

<p>// USAGE 'in the test'
LibraryManager manager = new LibraryManager(mockLibraryService);
// ...
// do your assertions
</pre></p>

<p><strong><u>Endo Testing</u></strong></p>

<p>Second technique is from <em>Endo Testing</em>. The technique here is extracting these dependencies to getter equivalents and overriding these methods for returning the mock/stub/fake ones. One thing here is your getter methods should be package private or protected. Please look at the following before/after and usage scenarios again:</p>

<p><pre class="sh_java">
// BEFORE 'endo testing'
public class SmartHitter {
    private Exchange exchange;</p>

<pre><code>public SmartHitter() {
    this.exchange = Exchange.getActiveExchange();
}
// more code
</code></pre>

<p>}</p>

<p>// AFTER 'endo testing'
public class SmartHitter {
    private Exchange exchange;</p>

<pre><code>public SmartHitter() {
    this.exchange = getActiveExchange();
}

protected Exchange getActiveExchange() {
    return Exchange.getActiveExchange();
}
// more code
</code></pre>

<p>}</p>

<p>// USAGE 'in the test'
final Exchange mockExchange = mock(Exchange.class);
SmartHitter hitter = new SmartHitter() {
    @Override
    protected Exchange getActiveExchange() {
         return mockExchange;
    }
};
// ...
// do your assertions
</pre></p>

<p><strong><u>Setter Injection</u></strong></p>

<p>The last one is not applicable to all scenarios, but it&#8217;s another dependency injection mechanism (@see <a href="http://martinfowler.com/articles/injection.html" target="_blank">Dependency Injection</a>). For this one, you basically create a setter method for your dependency and allow test to inject this dependency. Let&#8217;s look at the example:</p>

<p><pre class="sh_java">
// BEFORE 'setter injection'
public class AjaxPriceModifier {
    private CatalogService catalogService;</p>

<pre><code>public AjaxPriceModifier() {
    // initialization..
    this.catalogService = CatalogService(sessionHelper.getStore());
}
// more code
</code></pre>

<p>}</p>

<p>// AFTER 'setter injection'
public class AjaxPriceModifier {
    private CatalogService catalogService;</p>

<pre><code>public AjaxPriceModifier() {
    // initialization..
    this.catalogService = CatalogService(sessionHelper.getStore());
}

public void setCatalogService(CatalogService catalogService) {
    this.catalogService = catalogService;
}
// more code
</code></pre>

<p>}</p>

<p>// USAGE 'in the test'
AjaxPriceModifier modifier = new AjaxPriceModifier();
modifier.setCatalogService(mockCatalogService);
// ...
// do your assertions
</pre></p>

<p>As you may notice, without a getter of that dependency your code still has the dependencies. It&#8217;s very wise to place a getter for that dependency and use that getter (as in Endo Testing) method in the constructor.</p>

<h3 id="531_summary_1" >Summary</h3>

<p>My personal favourite is <strong>Constructor Injection</strong> since it&#8217;s more intuitive when you&#8217;re coding the test. It clearly describes what dependencies you need to test that unit. Okay, now you can watch the screencast. Hope it turns some lights on :) All comments are welcome!</p>

<p><!-- ProPlayer by Isa Goksu --><div name="mediaspace" id="mediaspace"><div class="pro-player-container" width="530px" height="253px"><div id="pro-player-531pp-single-5346954adf945"></div></div></div><script type="text/javascript" charset="utf-8">var flashvars = {width: "530",height: "253",autostart: "false",repeat: "false",backcolor: "111111",frontcolor: "cccccc",lightcolor: "66cc00",stretching: "fill",enablejs: "true",mute: "false",skin: "http://isagoksu.com/wp-content/plugins/proplayer/players/skins/default.swf",logo: "http://isagoksu.com/wp-content/plugins/proplayer/players/watermark.png",image: "http://isagoksu.com/wp-content/plugins/proplayer/players/preview.png",plugins: "",javascriptid: "531pp-single-5346954adf945",image: "http://isagoksu.com/wp-content/plugins/proplayer/players/preview.png",file: 'http://isagoksu.com/wp-content/plugins/proplayer/playlist-controller.php?pp_playlist_id=531pp-single-5346954adf945&sid=1397134667'};var params = {wmode: "transparent",allowfullscreen: "true",allowscriptaccess: "always",allownetworking: "all"};var attributes = {id: "obj-pro-player-531pp-single-5346954adf945",name: "obj-pro-player-531pp-single-5346954adf945"};swfobject.embedSWF("http://isagoksu.com/wp-content/plugins/proplayer/players/player.swf", "pro-player-531pp-single-5346954adf945", "530", "253", "9.0.0", false, flashvars, params, attributes);</script></p>

<p><br /></p>
]]></content:encoded>
			<wfw:commentRss>http://isagoksu.com/2009/development/agile-development/test-driven-development/making-code-more-testable-breaking-static-dependencies/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
<enclosure url="http://isagoksu.com/wp-content/uploads/screencasts/tdd/01.mov" length="37775037" type="video/quicktime" />
		</item>
	</channel>
</rss>
