<?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>The Shyam &#187; code smells</title>
	<atom:link href="http://theshyam.com/tag/code-smells/feed/" rel="self" type="application/rss+xml" />
	<link>http://theshyam.com</link>
	<description>Ramblings from the Real Shyam; You know, unlike those other fake Shyams!</description>
	<lastBuildDate>Sun, 08 Jan 2012 13:07:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Separation anxiety ?</title>
		<link>http://theshyam.com/2009/07/separation-anxiety/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=separation-anxiety</link>
		<comments>http://theshyam.com/2009/07/separation-anxiety/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 07:57:19 +0000</pubDate>
		<dc:creator>shyam</dc:creator>
				<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[Technique]]></category>
		<category><![CDATA[code smells]]></category>
		<category><![CDATA[constructor]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Law of Demeter]]></category>
		<category><![CDATA[refactoring]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://assertionfailed.wordpress.com/?p=70</guid>
		<description><![CDATA[We all have separation anxiety. Its a human tendency. We love inertia, and we don&#8217;t like change. But why should your code have separation anxiety ? Its not human (even though it might try and grow a brain of its own at times)! I bring this up because I got the chance to work with [...]]]></description>
			<content:encoded><![CDATA[<p>We all have separation anxiety. Its a human tendency. We love inertia, and we don&#8217;t like change. But why should your code have separation anxiety ? Its not human (even though it might try and grow a brain of its own at times)!</p>
<p>I bring this up because I got the chance to work with someone who had some questions on how to test UI code. Fairly innocuous question, and in most cases, my response would have been, keep the UI code simple and free of any logic, and don&#8217;t worry too much about it. Or you could write some nice end to end / integration tests / browser based tests. So with that response set in mind, I set off into the unknown. Little was I to know was that was the least of my concerns. As I sat down to look at the code, I saw that there were already tests for the code. I was optimistic now, I mean, how bad could things be if there are already tests for it ?</p>
<p>Well, I should remember next time to actually look at the tests first. But anyways, there were tests, so I was curious what kinds of tests they wanted to write and what kind of help I could provide, if any. So it turns out, the class was some sort of GUI Component, which basically had some fields, and depending on whether they were set of not, displayed them as widgets inside of it. So there were, say, 5 fields, and differing combinations of what was set would produce different output. The nice thing was that the rendered data was returned as a nice Java object, so you could easily assert on what was set, and get a handle on the widgets inside of it, etc. So the method was something along the following lines :</p>
<pre><span style="color:#333333;">public RenderedWidgetGroup render() {
</span><span style="color:#333333;">    </span><span style="color:#333333;">RenderedWidgetGroup group =
        createWidgetGroup(this.componentId,
                          this.parent);</span>
<span style="color:#333333;">    if (this.name = null) {</span><span style="color:#333333;">
</span><span style="color:#333333;">        return group;</span><span style="color:#333333;">
</span><span style="color:#333333;">    } </span><span style="color:#333333;">
</span><span style="color:#333333;">    group.addWidget(new TextWidget(this.name));</span><span style="color:#333333;">
</span><span style="color:#333333;">    group.addWidget(
        new DateWidget(
            this.updatedTimestamp == null ?
                 this.createdTimestamp : this.updatedTimestamp));
</span><span style="color:#333333;">    </span><span style="color:#333333;">return group;</span><span style="color:#333333;">
</span><span style="color:#333333;">}</span></pre>
<p>So far, so good, right ? Nice, clean, should be easy to test if we can set up this component with the right fields. After that, it should just be a few tests based on the different code paths defined by the conditionals. Yeah, thats what I thought too. So, me, being the naive guy that I was, said, yeah, that  looks nice, should be easy to test. I don&#8217;t see the problem.</p>
<p>Well, then I was taken to the tests. The first thing I see is a huge test. Or atleast thats what I think it is. Then I read it more closely, and see its a private method. It seems to take in a bunch of fields (Fields with names that I distinctly remembered from just a while ago) and churn out a POJO (Plain Old Java Object). Except this POJO was not the GUI Component object I expected. So obviously, I was curious (and my testing sensors were starting to tingle).  So I followed through to where it was called (which wasn&#8217;t very hard, it was a private method) and lo and behold, my worst fears confirmed.</p>
<p>The POJO object generated by the private method was passed in to the constructor of the GUI component, which (on following it further down the rabbit hole) in its constructor did something like the following :</p>
<pre><span style="color:#333333;">public MyGUIComponent(ComponentId id,
                      Component parent,
                      MyDataContainingPOJO pojo) {
    super(id, parent);
    readData(pojo); 
} </span></pre>
<p>And of course, <strong>readData</strong>, as you would expect, is a :</p>
<ul>
<li>Private method</li>
<li>Looks through the POJO</li>
<li>If it finds a field which is not null then it sets it in the Gui Component</li>
</ul>
<p>And of course, without writing the exact opposite of this method in the unit test, it just wasn&#8217;t possible to write unit tests. And sudddenly, it became clear why they were having trouble unit testing their Gui Components. Because if they wanted to test render (Which was really their aim), they would have to set up this POJO with the correct fields (which of course, to make things more interesting / miserable, had sub POJOs with sub POJOs of their own. Yay!) to be exercised in their test.</p>
<p>The problem with this approach is two fold :</p>
<ol>
<li>I need tests to ensure that the parsing and reading from the POJO logic is sound, and that it correctly sets up the GUI Component.</li>
<li>Every time I want to test the render logic, I end up testing (unintentionally, and definitely unwantedly) the parsing logic.</li>
</ol>
<p>This also adds, as I saw, obviously complicated pre test setup logic which should not be required to test something completely different. This is a HUGE <strong>code smell</strong>. Unit testing a class should not be an arduous, painful task. It should be easy as setting up a POJO and testing a method. The minute you have to perform complicated setup to Unit test a class (Note, the keyword is unit test. You can have integration tests which need some non trivial setup.), stop! There is something wrong.</p>
<p>The problem here is that there is a mixing of concerns in the MyGuiComponent class. As it turns out, MyGuiComponent breaks a few fundamental rules of testability. One, it does <strong>work in the constructor</strong>. Two, it violates the <strong>law of demeter</strong>, which states that the class should ask for what it needs, not what it doesn&#8217;t need to get what it needs (Does that even make sense ?). Thirdly, it is <strong>mixing concerns</strong>. That is, it does too much. It knows both how to create itself as well as do the rendering logic. Let me break this down further :</p>
<h3>Work in the constructor</h3>
<p>If you scroll back up and look at the constructor for MyGuiComponent, you will see it calling <strong><em><span style="color:#808080;">readData(pojo)</span></em></strong>. Now, the basic concept to test any class is that you have to create an instance of the class under test (unless it has static methods. Don&#8217;t get me started on that&#8230;). So now, every time you create an instance of MyGuiComponent, guess what ? <strong><em><span style="color:#808080;">readData(pojo)</span></em></strong> is going to get called. <strong>Every. Single. Time</strong> ! And it cannot be mocked out. Its a private method. And god forbid if you really didn&#8217;t care about the pojo and passed in a null. Guess what ? It most probably will blow up with a NullPointerException. So suddenly, that innocuous method in the constructor comes back to haunt you when you write yours tests (You are, aren&#8217;t you ?).</p>
<h3>Law of Demeter</h3>
<p>Furthermore, if you look at what <strong><em><span style="color:#808080;">readData(pojo)</span></em></strong> does, you would be even more concerned. At its base, MyGuiComponent only cares about 6 fields which it needs to render. Depending on the state of each of these fields, it adds widget. So why does the constructor ask for something totally unrelated ? This is a fundamental violation of the Law of Demeter. The Law of Demeter can be summed up as &#8220;Ask for what you need. If you need to go through one object to get what you need, you are breaking it.&#8221;. A much more fancier definition can be found on the web if you care, but the minute you see something like A.B().C() or something along those lines, there is a potential violation.</p>
<p>In this case, MyGuiComponent doesn&#8217;t really care about the POJO. It only cares about some fields in the POJO, which it then assigns to its own fields. But the constructor still asks for the POJO instead of directly asking for the fields. What this means is that instead of just creating an instance of MyGuiComponent with the required fields in my test, I now have to create the POJO with the required fields and pass that in instead of just setting it directly. Convoluted, anyone ?</p>
<h3>Mixing Concerns</h3>
<p>Finally, what could be considered an extension of the previous one, but deserves a rant of its own. What the fundamental problem with the above class is that it is mixing concerns. It knows both how to create itself as well as how to render itself once it has been created. And the way it has been coded enforces that the creation codepath is executed every single time. To provide an analogy for how ridiculous this is, it is like a a Car asking for an Engine Number and then using that number to create its own engine. Why the heck should a car have to know how to create its engine ? Or even a car itself ? Similarly, why should <strong>MyGuiComponent</strong> know how to create itself ? Which is exactly what is happening here.</p>
<h3>Solution</h3>
<p>Now that we had arrived at the root of the problem, we immediately went about trying to fix it. My immediate instinct was to pull out MyGuiComponent into the two classes that I was seeing. So we pulled out a MyGuiComponentFactory, which took up the responsibility of taking in the POJO and creating a GuiComponent out of it. Now this was independently testable. We also added a builder pattern to the MyGuiComponent, which the factory leveraged.</p>
<pre><span style="color:#333333;">class MyGuiComponentFactory {</span><span style="color:#333333;">
</span><span style="color:#888888;"><span style="color:#333333;">    MyGuiComponent createFromPojo(ComponentId id,
                                  Component parent,
                                  MyDataContainingPOJO pojo) {
      // Actual logic of converting from pojo to
      // MyGuiComponent using the builder pattern
     }
}</span></span>
<span style="color:#333333;">class MyGuiComponent {</span><span style="color:#333333;">
</span><span style="color:#333333;">    public MyGuiComponent(ComponentId id,
                          Component parent) {
        super(id, parent);
    }</span><span style="color:#333333;">
</span><span style="color:#333333;">    public MyGuiComponent setName(String name) {
        this.name = name;
        return this;
    }</span><span style="color:#333333;">
</span><span style="color:#333333;">} </span></pre>
<p>And now, suddenly (and expectedly, I would like to add), the constructor for MyGuiComponent becomse simple. There is no work in the constructor. The fields are set up through setters and the builder pattern. So now, we started writing the unit tests for the render methods. It took about a single line of setup to instantiate MyGuiComponent, and we could test the render method in isolation now. Hallelujah!!</p>
<p>Disclaimer :<br />
No code was harmed / abused in the course of the above blog post. There were no separation issues whatsoever in the end, it was a clean mutual break!</p>
]]></content:encoded>
			<wfw:commentRss>http://theshyam.com/2009/07/separation-anxiety/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>My code&#8217;s untestable !!</title>
		<link>http://theshyam.com/2008/09/my-codes-untestable/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=my-codes-untestable</link>
		<comments>http://theshyam.com/2008/09/my-codes-untestable/#comments</comments>
		<pubDate>Thu, 04 Sep 2008 21:53:33 +0000</pubDate>
		<dc:creator>shyam</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[Technique]]></category>
		<category><![CDATA[code smells]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[refactoring]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://assertionfailed.wordpress.com/?p=56</guid>
		<description><![CDATA[I have frequently heard this complaint, from some really great engineers in the past year. My code&#8217;s untestable, there&#8217;s no way i can test this, the only way to test my code is to write a full on end to end test. And in some cases, it was actually true. But the thing is, it [...]]]></description>
			<content:encoded><![CDATA[<p>I have frequently heard this complaint, from some really great engineers in the past year. My code&#8217;s untestable, there&#8217;s no way i can test this, the only way to test my code is to write a full on end to end test. And in some cases, it was actually true. But the thing is, it doesn&#8217;t need to be that way. There are always ways to twist and turn the untestable code into testable code, in other words refactor.</p>
<p>But before you get excited, and go aha, thats what I am going to do, hold your horses for a second. What are you going to go refactor ? Well, don&#8217;t scratch your heads, there are a few things to look out for. Similar to the code smells we had, there are similar smells we can look for, which indicate that the code is untestable. And there are a few standard ways to tackle them, and make your classes testable. So without further adieu, lets take a look at the more common and annoying testability smells.</p>
<ol>
<li><strong>Constructor doing work :</strong><br />
This is one of the biggest things preventing a class from being testable. There are many names to this smell, including constructor doing work,  Breaking the law of demeter, etc. but all it comes down to is the constructor doing more than just assigning stuff to local variables. For example, something like :</p>
<p>XPathConvertor() {<br />
this.xpathDatabase = XPathDatabaseFactory.getDatabase();<br />
XPathMapper mapper = new SimpleXPathMapper(&#8220;Simple Mapper&#8221;);<br />
this.xpathTranslator = XPathTranslatorFactory.getTranslator(this.xpathDatabase, mapper);<br />
}</p>
<p>While the above may seem a contrived example, or too simple, it exhibits what is at the centre of most bad constructors. One, its a default constructor. Then it goes out, grabs a database out from ether (Static factory method call), and then creates a mapper, and then passes those two to get a XpathTranslator object. Now, take my word for it, but the XPathConvertor only needs xpathTranslator. SO what is it doing with the darn database and the mapper. This is breaking the law of demeter, which states that &#8220;The constructor should only ask for what it needs, and nothing else.&#8221;</p>
<p>Why is this bad ? Well, for one, if the thing your constructor is creating is a heavy piece of service like a database or something, there&#8217;s a huge hit in your test. Your test is no longer a unit test, but an integration test. Each call now has to travel to the DB and back, and just makes everything slower. Secondly, there are some cases in which it picks up a service which you just can&#8217;t work with in a test. Something which either needs the whole production setup, or just doesn&#8217;t work in a unit test. And since it reaches into static factories to get that, there&#8217;s no way for you to slip in your mock.</p>
<p>So instead, start passing in what is needed to your constructor. This forms the basis of Dependency Injection, or slipping in a fake, or whatever you want to call it. Basically, your constructor takes in what it needs, and all it does is assign stuff to local variables. No work is done there. So the above code becomes something like :</p>
<p>XPathConvertor(XPathTranslator translator) {<br />
this.xpathTranslator = translator;<br />
}</p>
<p>So much cleaner, and only has what it needs. So in our test, you can create a translator and pass it in which uses a mock db, or pass in a fake translator or whatever. The point is, testing becomes easier.</li>
<li><strong>Global State :<br />
</strong> The second biggest complaint with untestable code. It usually has to do with Global state. Or as some people like to call it, putting things in and pulling things out of ether. This might be anything from using global static singletons to static method calls inbetween your method.</p>
<p>How is this bad ? Consider some method you are testing. What if it suddenly reaches out into the ether, and grabs some object and uses it to perform its calculations. You say, ok, I can somehow add a setter which allows me to set its state. Now what if there are multiple tests running in parallel&#8230;. Yes, exactly. Not good. Furthermore, you can&#8217;t mock a static method, which makes life miserable.</p>
<p>Consider this question then, why does it need to be static ? What benefit are you getting, other than the fact that you don&#8217;t need to create an object ? Is it really worth making code untestable in order to reduce one line of code of creating an object ? The answer 9 times out of 10, I find, is no.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://theshyam.com/2008/09/my-codes-untestable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Your code smells!!!</title>
		<link>http://theshyam.com/2008/08/your-code-smells/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=your-code-smells</link>
		<comments>http://theshyam.com/2008/08/your-code-smells/#comments</comments>
		<pubDate>Mon, 11 Aug 2008 00:58:50 +0000</pubDate>
		<dc:creator>shyam</dc:creator>
				<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[Technique]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code smells]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[refactoring]]></category>

		<guid isPermaLink="false">http://assertionfailed.wordpress.com/?p=35</guid>
		<description><![CDATA[I was planning to talk about Dependency Injection or the difference between Mocks, Stubs and Fakes, but I think I would prefer to get this one out first. For those of you who haven&#8217;t heard the term before, a code smell is something that indicates there is something wrong with the source code, be they [...]]]></description>
			<content:encoded><![CDATA[<p>I was planning to talk about Dependency Injection or the difference between Mocks, Stubs and Fakes, but I think I would prefer to get this one out first. For those of you who haven&#8217;t heard the term before, a <strong>code smell</strong> is something that indicates there is something wrong with the source code, be they design problems or signs that the code needs refactoring. So in this post, I would like to mention a few common code smells, their identifying patterns and how to fix them. So without any further delay, lets start :</p>
<ol>
<li><strong>Too many comments</strong><br />
<strong>The Problem</strong> : Lets start with the easiest to identify code smell. Comments are good, if they are describing a class or a method. But when you start having comments in your code explaining what a particular block of code does, you know you are in trouble.<br />
<strong>The Fix </strong>: If there is a block of code which does some complicated stuff, and you feel you need to comment it to make it easily understood, pull it out into a well named method, and let the method name describe what it does.<br />
.</li>
<li><strong>Long Class / Method<br />
The Problem :</strong> These two code smells actually are similar. If you have a method which goes beyond 10 &#8211; 15 lines, then you have a long method. While there is nothing technically wrong with long methods, its not as easy to comprehend as a nice small method, and can make maintenance a pain in the rear. Long classes also are similar, having too many things that its trying to do. If you generally try describing a class and have to use <strong>ands</strong> and <strong>ors</strong>, then you have a long class.<br />
<strong>The Fix : </strong>Pull out parts of the long method into smaller well named methods. The advantage is two fold. One, your method is much more readable now. And two, you can now test individual methods you have pulled out, making testing a much easier task than one giant method. Same with classes, break it up into multiple smaller easily testable classes.<br />
.</li>
<li><strong>Primitive Obsession<br />
The Problem :</strong> How many times have you had to write a class which takes in, say a phone number ? And how many times have you passed in a String or a long to the class which asks for the phone number ? If you raised your hand, then congrats, you have a code smell known as primitive obsession. This happens when instead of creating an object, you pass around primitives, and write functions to operate and convert that primitive from one form to another. So you might have to create utility classes which give you a phone number with brackets from a string, and so on and so forth.<br />
<strong>The Fix :</strong> Just give the poor thing a class. If you operate on phone numbers, create a PhoneNumber class which has methods to operate on the number. Makes it easier for anyone using the class as well, and of course, its testable <img src='http://theshyam.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> .<br />
.</li>
<li><strong>Feature Envy / Inappropriate Intimacy<br />
The Problem :</strong> Feature Envy is when a method on a class is more interested in other classes than the class to which it belongs. The reason for this could be as simple as the method being in the wrong class to something more non trivial. Inappropriate intimacy is when two classes are so tightly coupled that one depends on the other to work a particular way for it to work.<br />
<strong>The Fix :</strong> For feature envy, just move the method to where it belongs. If it does work solely on some other class, then maybe it belongs on that class instead of where it is currently. For inappropriate intimacy, you need to figure out if the problem is something simple or something more complicated. It might be that the interfaces weren&#8217;t selected appropriately, or you might need to introduce a layer to keep the coupling loose, or even refactor the code to make sure it does not depend on another tightly coupled class.<br />
.</li>
<li><strong>Lazy class / Dead code / Duplicate code / Speculative Generality<br />
The Problem</strong> : All of the above are usually simple code smells which indicate you have code which you don&#8217;t need. Lazy class is when a class doesn&#8217;t do enough to justify its existence. Dead code is obvious, code which is not used or dead. Duplicate code, duh, Its duplicated. Speculative generality is the most interesting of the lot. Its when you write some code for something which you don&#8217;t need yet, but may need at some point in the future.<br />
<strong>The Fix</strong> : For the first three code smells, the fix is trivial. Delete it. Dont even think about it, just blindly delete it. Duplicate code is a pain to maintain as well, pull it out into a method and then delete the duplicates. Speculative generality is one thing people don&#8217;t realize they are doing or feel they need to do it now since otherwise, it might become difficult to do in the future. The interesting thing is that the feature they added speculatively is rarely ever used. Its an additional overhead to maintain and test for something you never use. Don&#8217;t do it. If you can implement it now, you can implement it when you need it. Just delete that darn code.</li>
</ol>
<p>There are a lot more code smells than I could list out here, but these are a few of the most common ones you should keep a lookout for. Google search Code smells if you want to learn more about these insidious creations <img src='http://theshyam.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> . Next time, before I start dependency injection, I think I will rant about things which make code untestable. So in a sense, Testability code smells.</p>
]]></content:encoded>
			<wfw:commentRss>http://theshyam.com/2008/08/your-code-smells/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

