<?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>henko.net &#187; Design</title>
	<atom:link href="http://henko.net/category/imperfection/design/feed/" rel="self" type="application/rss+xml" />
	<link>http://henko.net</link>
	<description>Home of a human being and software developer</description>
	<lastBuildDate>Wed, 21 Dec 2011 11:12:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Separate class for each id type</title>
		<link>http://henko.net/imperfection/separate-class-for-each-id-type/</link>
		<comments>http://henko.net/imperfection/separate-class-for-each-id-type/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 11:12:15 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/?p=1007</guid>
		<description><![CDATA[The code I&#8217;ve been looking at recently has quite some problems with managing various ids. The ids in the system are confusing on many levels, both syntactically and semantically. To begin with, there are a lot of them. They are represented using a mix of ints, longs and strings. Even the same id may be [...]]]></description>
			<content:encoded><![CDATA[<p>The code I&#8217;ve been looking at recently has quite some problems with managing various ids. The ids in the system are confusing on many levels, both syntactically and semantically.</p>

<ul>
<li>To begin with, there are a lot of them.</li>
<li>They are represented using a mix of ints, longs and strings. Even the same id may be represented using different data types in different places.</li>
<li>We&#8217;ve had bugs where an object with multiple ids has been put into a map using one of its ids as key and someone else tries to get it out using another id as key.</li>
<li>Their names are sometimes confusingly similar.</li>
<li>The same id may have multiple names, used intermixed.</li>
</ul>

<p>Therefore, we&#8217;ve discussed various ways of getting a grip on the situation. One of the alternatives, which I think sounds rather good, is to use a separate class to represent each type of id.</p>

<p>For example, a <code>User</code> class doesn&#8217;t have a <code>int userId</code> field, but a <code>UserId userId</code> field. How <code>UserId</code> internally represents the id (perhaps as a long or string), is up to that class.</p>

<p>Some of the pros of this solution, from a Java perspective, are:</p>

<ul>
<li>When the id is used &#8220;out of context&#8221;, you don&#8217;t have to rely on variable naming to convey its meaning, you will get static type checking to help you.</li>
<li>If you want to change the internal representation (int, long, etc), you only need to change a rather limited number of places instead of all over the system.</li>
<li>You get an opportunity to create a suitable <code>toString()</code>, <code>hashCode()</code>, and or <code>equals()</code> implementation.</li>
<li>You get a natural place for common convenience methods regarding the id, reducing the need for various &#8220;util classes&#8221; (which really are <a href="/imperfection/private-static-methods-might-be-a-smell/" title="more procedural than object oriented">more procedural than object oriented</a>).</li>
</ul>

<p>The primary drawback that I can think of is that it generates a lot more small objects which may increase memory usage. But until it has been proven to be an actual problem in a specific case, I think that is a reasonable cost for the benefits above.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/separate-class-for-each-id-type/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Two types of design</title>
		<link>http://henko.net/imperfection/two-types-of-design/</link>
		<comments>http://henko.net/imperfection/two-types-of-design/#comments</comments>
		<pubDate>Wed, 02 Nov 2011 21:09:18 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>

		<guid isPermaLink="false">http://henko.net/?p=997</guid>
		<description><![CDATA[Lately, I&#8217;ve been thinking about two ways to design a system. I&#8217;m having trouble with figuring out which one I actually prefer. I&#8217;ll try to describe them below. If you would like to read through the description and leave a comment or two I would be very grateful! Feel free to just add a comment [...]]]></description>
			<content:encoded><![CDATA[<p>Lately, I&#8217;ve been thinking about two ways to design a system. I&#8217;m having trouble with figuring out which one I actually prefer. I&#8217;ll try to describe them below.</p>

<p>If you would like to read through the description and leave a comment or two I would be very grateful! Feel free to just add a comment or two in this document.</p>

<p>I’m using a fictional weather service as example. It does something along the lines of fetching the current weather data from a web service, parse it and extract relevant data, fetch some information about the current geographical location, and finally analyze them to provide the user with some interesting information about the weather.</p>

<h3>Design A</h3>

<p>The system is designed with the majority of the code as a set of completely independent modules which are joined together with a small amount of glue code.</p>

<p style="text-align: center"><a href="/wp-content/uploads/2011/11/design-a.png"><img src="http://henko.net/wp-content/uploads/2011/11/design-a-300x196.png" alt="Example of Design A" title="Example of Design A" width="300" height="196" class="aligncenter size-medium wp-image-999" /></a></p>

<p>Classes and modules tend to send primitive data or value objects to each other rather than intelligent classes. Modules tend to have none or very few dependencies. Re-use of modules is simplified because they can be used independently of each other.</p>

<p>Modules tend to be stateless with any state kept in the caller/glue code. External dependencies are kept as shallow as possible in the call/dependency tree.</p>

<p>The sequence of calls needed to perform something is encoded in the glue code rather than spread out in the system. It is up to the caller needs to know in which order to call modules. It delegates the execution of each step to the modules, but keeps control. The call stack will always remain rather short.</p>

<p>Each module can be unit tested in isolation and internal classes inside the modules do not have separate tests. The glue code is tested through integration tests that run end-to-end to verify that the system works. Unit tests often become easier to write because there is no need for mocking dependencies.</p>

<p>This approach is more &#8220;functional&#8221; in nature as modules tend to be stateless, get all required data as input and return the result as output.</p>

<h3>Design B</h3>

<p>The system is designed as a set of interacting, often stateful, modules which are joined together in a graph of dependencies.</p>

<p style="text-align: center"><a href="http://henko.net/wp-content/uploads/2011/11/design-b.png"><img src="http://henko.net/wp-content/uploads/2011/11/design-b.png" alt="Example of Design B" title="Example of Design B" width="420" class="aligncenter size-medium wp-image-1000" /></a></p>

<p>One module often calls another module without providing all information necessary to complete a task, secure in the knowledge that the other module can obtain it. This is typically performed through injection of dependencies. Modules therefore often have multiple dependencies.</p>

<p>Modules are often stateful or depends on objects which are. External dependencies are often pushed as deep down the dependency tree as possible.</p>

<p>The sequence of calls needed to perform something is often spread out over a set of modules and partially encoded in the dependency setup. The caller can often call one or a few modules knowing they will in turn call others. The caller delegates not only the execution of tasks but also control to a large degree. The call stack will in the middle of execution be rather deep.</p>

<p>Each module is unit tested, typically with any dependencies replaced with stub/mock/fake instances. Integration tests ensure that the wiring of the modules is correct and that the system works together. There is little fundamental difference between tests on different levels.</p>

<p>This approach is perhaps more &#8220;object oriented&#8221; in nature where the system is divided into a set of stateful, intelligent objects that cooperate in generating the output.</p>

<h3>Questions</h3>

<p>I would appreciate any comments or input, such as your thoughts about:</p>

<ul>
<li>Which alternative you prefer? Which one do you most often use? Perhaps a hybrid?</li>
<li>Under which circumstances is one better than the other?</li>
<li>Are they good at different levels? E.g. method, class, component, or system level.</li>
<li>Is there a &#8220;OO vs functional&#8221; difference, as I suggest?</li>
<li>Is either of them easier to maintain than the other?</li>
<li>Can they be described more clearly? What are they called?</li>
<li>Have I gotten anything or everything completely wrong?</li>
</ul>

<p>Feel free to enter any feedback or comments below.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/two-types-of-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Name classes for content, not usage</title>
		<link>http://henko.net/imperfection/name-classes-for-content-not-usage/</link>
		<comments>http://henko.net/imperfection/name-classes-for-content-not-usage/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 06:51:30 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/?p=988</guid>
		<description><![CDATA[To make a class as universally usable as possible, name it after its content, not its intended usage. After all, the usage might change, and you may find a new area of use for the class which you didn&#8217;t foresee. Example In the project I&#8217;m working on, I had a class called SelectedInstalledBase which represented [...]]]></description>
			<content:encoded><![CDATA[<p>To make a class as universally usable as possible, name it after its content, not its intended usage. After all, the usage might change, and you may find a new area of use for the class which you didn&#8217;t foresee.</p>

<h3>Example</h3>

<p>In the project I&#8217;m working on, I had a class called <code>SelectedInstalledBase</code> which represented the subset of products in a customer&#8217;s &#8220;installed base&#8221; selected by the user. (An &#8220;installed base&#8221; is this domain is all the products a customer has bought.)</p>

<p>That was fine until I wanted an inverted version of the selection, i.e. the installed base not selected (the &#8220;remaining installed base&#8221;). Then, it suddenly didn&#8217;t make much sense to create a <em>remaining</em> installed base of type <code>SelectedInstalledBase</code>. It also didn&#8217;t make sense to create a clone of <code>SelectedInstalledBase</code> named <code>RemainingInstalledBase</code> as they would be identical apart from the name.</p>

<p>The solution the problem was renaming <code>SelectedInstalledBase</code> to <code>InstalledBaseIdentifier</code> (because it represented the ids of the selection made by the user) and naming the variables to reflect the different cases, such as <code>InstalledBaseIdentifier selectedInstalledBase</code> and <code>InstalledBaseIdentifier remainingInstalledBase</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/name-classes-for-content-not-usage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What I learned from Kent Beck</title>
		<link>http://henko.net/imperfection/what-i-learned-from-kent-beck/</link>
		<comments>http://henko.net/imperfection/what-i-learned-from-kent-beck/#comments</comments>
		<pubDate>Thu, 08 Sep 2011 18:16:20 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/?p=976</guid>
		<description><![CDATA[This is a summary of what learned from a &#8220;Mastering TDD&#8221; course with Kent Beck. Given he is the creator of JUnit, I guess his thoughts on unit testing are worth considering. In some cases I might have rewritten, changed, extended or simply misunderstood what he was saying, but these were my notes from the [...]]]></description>
			<content:encoded><![CDATA[<p>This is a summary of what learned from a &#8220;Mastering TDD&#8221; course with Kent Beck. Given he is the creator of JUnit, I guess his thoughts on unit testing are worth considering. <img src='http://henko.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>

<p>In some cases I might have rewritten, changed, extended or simply misunderstood what he was saying, but these were my notes from the course, nevertheless.</p>

<ul>
<li>Doing TDD is like losing weight. You like having lost some weight, but not actually losing it.</li>
<li>Taking really, really small TDD steps is useful when you&#8217;re unsure/confused about the code you are writing. That way you are at least moving forward.</li>
<li>What kills productivity isn&#8217;t doing something slowly, but not doing it. I.e. when you switch to reading email, surfing the web, etc instead of working.</li>
<li>Implementing a piece of code <em>inside</em> a test keeps your options open if you&#8217;re not sure about the future interface.</li>
<li>Start writing the test which you expect to learn the most from.</li>
<li>Most important, according to Kent: Writing a test is really telling a story about the code. Having that mindset helps you work out many other problems with testing.</li>
<li>Deleting tests comes down to story telling &#8211; which tests do we need to tell the story about this code. (There is also a technical/coverage aspect, but it is of lower importance).</li>
<li>When unsure about whether to clean something up or not &#8211; think about the amount of leverage it will give you. Worth it?</li>
<li>When coding exploratory (without TDD), start TDD:ing when/if you don&#8217;t expect the code to die anymore, or when you think you&#8217;ve learned the most important lessons.</li>
<li>In many cases: The more discussion, the less important the decision. Everyone agrees about the really important ones.</li>
<li>Write code in a functional style, as it is more suitable for testing.</li>
<li>Consider not using dependency injection as it makes TDD harder by encouraging a design where dependencies are spread out over the system. Instead, design many stand-alone modules which are unit tested individually without the need for mocked dependencies, then join them together in other classes which are tested through integration tests.</li>
<li>Avoid abstact superclasses for unit test classes as they make the individual test classes harder to read.</li>
<li>Duplication is often more okay in tests than in the production code because readability of tests is so important.</li>
<li>For infrastructure-related setup code, @Rule can be used instead of inheritance in many cases.</li>
<li>Write tests on the high and low level, but be weary of too many tests on the mid level. They tend to be more of a problem than help when refactoring.</li>
<li>Kent: &#8220;I try not to have more tests than I need&#8221;</li>
<li>Use one test class per fixture (i.e. set of test data). Name the classes after the fixture. That is how JUnit is designed and intended to be used.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/what-i-learned-from-kent-beck/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Two kinds of interfaces</title>
		<link>http://henko.net/imperfection/two-kinds-of-interfaces/</link>
		<comments>http://henko.net/imperfection/two-kinds-of-interfaces/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 08:00:35 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/?p=910</guid>
		<description><![CDATA[An interface is a point of interaction between two systems and they are used extensively within the Java world. While the mechanics of interfaces always are the same, the semantics may differ. There are (at least) two rather distinct types of uses for interfaces in Java. One type of interface, which we might call separation [...]]]></description>
			<content:encoded><![CDATA[<p>An interface is a point of interaction between two systems and they are used extensively within the Java world. While the mechanics of interfaces always are the same, the semantics may differ. There are (at least) two rather distinct types of uses for interfaces in Java.</p>

<p>One type of interface, which we might call <em>separation interface</em>, aims to separate different components. In this case, a component only exposes interfaces for its functionality but not the actual classes to make sure that clients aren&#8217;t too tightly coupled with the implementation. In this scenario, there is typically ever only a single implementation of the interface and both the interface and the implementation have the same author(s). Whenever you see a <code>Interface</code>/<code>InterfaceImpl</code> pair, you are most likely looking a this kind of interface use. This pattern is considered a best practice between components and systems, but rarely useful inside cohesive modules where classes naturally are more tightly coupled.</p>

<p>The other type of interface, let&#8217;s call it <em>extension interface</em>, is intended to represent an <em>ability</em> than an object can have. Here, multiple implementations of the interface exists and the client can choose the implementation that best suites his or her needs. A component often defines an interface on which it depends in order to allow implementations to be added at a later time. Often, the author of the interface is not even the same as the ones who create the implementations. This type of interfaces (together with regular inheritance) are the foundation of polymorphism. <code>Iterable</code> or <code>Comparator</code> are typical examples.</p>

<p>Quite possibly, there are other types of interfaces as well. Feel free to comment on the issue. <img src='http://henko.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/two-kinds-of-interfaces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t peek</title>
		<link>http://henko.net/imperfection/dont-peek/</link>
		<comments>http://henko.net/imperfection/dont-peek/#comments</comments>
		<pubDate>Mon, 26 Apr 2010 08:00:29 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>

		<guid isPermaLink="false">http://henko.net/?p=815</guid>
		<description><![CDATA[When I talked to Michael Feathers about why constraints are good, he also mentioned an example of where he thought things were going wrong. Some people who use test-driven development, also use tools that allow the to peek into classes and read private variables. That is an efficient way to ensure that some method altered [...]]]></description>
			<content:encoded><![CDATA[<p>When I talked to Michael Feathers about why <a href="http://henko.net/imperfection/constraints-are-good/" title="Constraints are good">constraints are good</a>, he also mentioned an example of where he thought things were going wrong.</p>

<p>Some people who use test-driven development, also use tools that allow the to peek into classes and read private variables. That is an efficient way to ensure that some method altered the state of the object in the expected way.</p>

<p>However, as Michael pointed out, by doing so they miss the point of test-driven development. Test-driven development adds constraints. It does that in order to force developers to design their code better. (TDD is about design, not testing &#8212; remember?) By peeking into classes, one effectively removes one constraint added by TDD, and thereby removing much of the benefit of TDD.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/dont-peek/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exception Handling Policy &#8211; Catching Exceptions</title>
		<link>http://henko.net/imperfection/exception-handling-policy-catching-exceptions/</link>
		<comments>http://henko.net/imperfection/exception-handling-policy-catching-exceptions/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 20:17:06 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/?p=666</guid>
		<description><![CDATA[This is the third installment in my series on sensible exception handling and will cover when and how to catch exceptions. To quickly summarize, the series looks as follows: Throwing Exceptions Using Assertions Catching Exceptions (this one) Logging Exceptions The information in this post is divided into two parts: when to catch, and how to [...]]]></description>
			<content:encoded><![CDATA[<p>This is the third installment in my series on sensible exception handling and will cover when and how to catch exceptions.</p>

<p>To quickly summarize, the series looks as follows:</p>

<ol>
<li><a href="http://henko.net/imperfection/exception-handling-policy-throwing-exception/" title="Exception Handling Policy - Throwing Exceptions">Throwing Exceptions</a></li>
<li><a href="http://henko.net/imperfection/exception-handling-policy-using-assertions/" title="Exception Handling Policy - Using Assertions">Using Assertions</a></li>
<li><strong>Catching Exceptions</strong> (this one)</li>
<li><a href="http://henko.net/imperfection/exception-handling-policy-logging-exceptions/" title="Exception Handling Policy - Logging Exceptions">Logging Exceptions</a></li>
</ol>

<p>The information in this post is divided into two parts: when to catch, and how to catch.</p>

<h3>When to catch</h3>

<p>Here are some guidelines on when to catch exceptions and when to let them propagate up through the call stack.</p>

<h4>Catch only exceptions you know how to handle, and be specific</h4>

<div style="margin-left: 2em;">

<p>If you don&#8217;t know ahead of time what the exception is going to be, you don&#8217;t know how to handle it, and you should send it up the stack.</p>

<p>Catching top-level exception means trying to deal with the really exceptional case, which by definition you can&#8217;t plan for.</p>

</div>

<h4>Provide a general catch-all</h4>

<div style="margin-left: 2em;">

<p>Ensure that all exceptions are caught and reported at some point
This is especially important in a multi-threaded environment, where a thread&#8217;s death may otherwise go unnoticed.</p>

<p>In languages which also have other error mechanisms, such as PHP, make sure that warnings, errors, fatals etc don&#8217;t go unnoticed.</p>

</div>

<h3>How to catch</h3>

<p>When you catch an exception, make sure to do it the right way.</p>

<h4>Do not suppress or ignore exceptions</h4>

<div style="margin-left: 2em;">

<p>NEVER! EVER! Don&#8217;t even while testing. It is not only undisciplined, but you <em>will</em> forget to &#8220;deal with it later&#8221;.</p>

</div>

<h4>Always clean up after yourself</h4>

<div style="margin-left: 2em;">

<p>Finally is usually recommended to guarantee resource cleanup, however you should yourself guarantee that finally never fails. In general, ensure finally never eats up your original exception.</p>

</div>

<h4>Declarative exception handling</h4>

<div style="margin-left: 2em;">

<p>Handling exceptions is an dynamic concern, the right way to handle an exception can easily change. Therefore, use a flexible framework to manage this.</p>

<p>For example Struts allows user defined <code>ExceptionHandlers</code> to be associated on a local or global scope using configuration instead of code. In other words, responses to exceptions should not only based on type but also on context in where they are called.</p>

</div>

<p>Next week, the final episode of the series will be published, so be sure to check back. If you have any comments, please provide them below!</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/exception-handling-policy-catching-exceptions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exception Handling Policy &#8211; Using Assertions</title>
		<link>http://henko.net/imperfection/exception-handling-policy-using-assertions/</link>
		<comments>http://henko.net/imperfection/exception-handling-policy-using-assertions/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 06:00:18 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/?p=700</guid>
		<description><![CDATA[This is the second part in a series of four on exception handling and it focuses on an area related to exceptions &#8212; assertions. A quick summary of posts in this series: Throwing Exceptions Using Assertions (this one) Catching Exceptions Logging Exceptions Guidelines for assertions An assertion is code that&#8217;s used during development that allows [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second part in a series of four on exception handling and it focuses on an area related to exceptions &#8212; assertions.</p>

<p>A quick summary of posts in this series:</p>

<ol>
<li><a href="http://henko.net/imperfection/exception-handling-policy-throwing-exception/" title="Exception Handling Policy - Throwing Exceptions">Throwing Exceptions</a></li>
<li><strong>Using Assertions</strong> (this one)</li>
<li><a href="http://henko.net/imperfection/exception-handling-policy-catching-exceptions/" title="Exception Handling Policy - Catching Exceptions">Catching Exceptions</a></li>
<li><a href="http://henko.net/imperfection/exception-handling-policy-logging-exceptions/" title="Exception Handling Policy - Logging Exceptions">Logging Exceptions</a></li>
</ol>

<h3>Guidelines for assertions</h3>

<p>An <a href="http://en.wikipedia.org/wiki/Assertion_(computing)" title="assertion">assertion</a> is code that&#8217;s used during development that allows a program to check itself as it runs. They are used much in the same spirit as unit tests, but spread out in the actual program code. It is a statement placed to indicate that the developer thinks that some predicate is always true at that place.</p>

<h4>Use assertions for conditions that should never occur</h4>

<div style="margin-left: 2em;">

<p>If an assertion is fired for an anomalous condition, the corrective action is not merely to handle an error gracefully — the corrective action is to change the program&#8217;s source code, recompile, and release a new version of the software.</p>

<p>Use assertions to document and verify preconditions and postconditions.</p>

</div>

<h4>Use a barricades to distinguish between assertions and exceptions</h4>

<div style="margin-left: 2em;">

<p>Routines that are outside the barricade should use error handling because it isn&#8217;t safe to make any assumptions about the data. Routines inside the barricade should use assertions, because the data passed to them is supposed to be sanitized before it&#8217;s passed across the barricade. If one of the routines inside the barricade detects bad data, that&#8217;s an error in the program rather than an error in the data.</p>

</div>

<h4>Don&#8217;t put executable code into assertions.</h4>

<div style="margin-left: 2em;">

<p>Doing so raises the possibility that the compiler will eliminate the code when you turn off the assertions. Instead, only put boolean conditions with no side effects in your assertions.</p>

</div>

<h4>For highly robust code, assert and then handle the error any way</h4>

<div style="margin-left: 2em;">

<p>Better safe than sorry, they say.</p>

</div>

<h3>Assertions in Java</h3>

<p>For those unfamiliar with assertions, I&#8217;ll give a quick summary. Java provides the keyword <code><a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html" title="assert">assert</a></code> since version 1.4. It throws a <code>java.lang.AssertionError</code> when it fails, and has the following syntax:</p>

<pre><code>assert expression : "error message shown if expression is false";
</code></pre>

<p>Where <code>expression</code> is any boolean expression which should always be true at the point of the assertion. For example, this variable should always be greater than 0, or that collection should always be empty.</p>

<p>To enable assertions when running a program, use the Java VM <code>-ea</code> (or <code>-enableassertions</code>) switch. Assertions are always compiled in, but without this switch, the assertions are ignored by the virtual machine.</p>

<p>Tune in next week for guidelines for catching exceptions! And please do write any comments or questions you might have below.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/exception-handling-policy-using-assertions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exception Handling Policy &#8211; Throwing Exceptions</title>
		<link>http://henko.net/imperfection/exception-handling-policy-throwing-exception/</link>
		<comments>http://henko.net/imperfection/exception-handling-policy-throwing-exception/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 12:06:23 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/?p=662</guid>
		<description><![CDATA[This is the first post in a series of four on exception handling. The series will cover what I think is a good and sound strategy for handling exceptions and errors in your application. It is written with Java in mind, but is applicable to most languages which feature exceptions. This first issue will go through the art of throwing exceptions.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/mbiskoping/510673513/"><img src="http://henko.net/wp-content/uploads/2009/06/exception.jpg" alt="An exception" title="An exception (Copyright by [martin])" width="240" height="234" class="alignright size-full wp-image-695" /></a>This is the first post in a series of four on exception handling.</p>

<p>The series will cover what I think is a good and sound strategy for handling exceptions and errors in your application.</p>

<p>It is written with Java in mind, but is applicable to most languages which feature exceptions.</p>

<p>A quick summary of the coming posts:</p>

<ol>
<li><strong>Throwing Exceptions</strong> (this one)</li>
<li><a href="http://henko.net/imperfection/exception-handling-policy-using-assertions/" title="Exception Handling Policy - Using Assertions">Using Assertions</a></li>
<li><a href="http://henko.net/imperfection/exception-handling-policy-catching-exceptions/" title="Exception Handling Policy - Catching Exceptions">Catching Exceptions</a></li>
<li><a href="http://henko.net/imperfection/exception-handling-policy-logging-exceptions/" title="Exception Handling Policy - Logging Exceptions">Logging Exceptions</a></li>
</ol>

<p>Let&#8217;s get started!</p>

<h3>General</h3>

<p>First, we&#8217;ll go through some things which apply to all types of exceptions.</p>

<h4>Always preserve the stack trace</h4>

<div style="margin-left: 2em;">

<p>Make sure that the stack trace of a wrapped exception is captured and preserved. The single worse thing one can do after eating your exceptions is to to capture it but throw away all the essential details.</p>

<p>Be careful with distributed systems, as simplistic use of Java serialization requires the Exception classes be available in all tiers.</p>

<p>Also, pre JDK 1.4 Exceptions do not preserve the stacktrace.</p>

</div>

<h4>Never use exceptions for flow control</h4>

<div style="margin-left: 2em;">

<p>Exceptions are meant for exceptional events &#8211; when things go wrong. Don&#8217;t build your system based on that something goes wrong.</p>

<p>Also, exceptions are slow, so heavy use of them might lead to performance problems.</p>

</div>

<h4>Provide enough context</h4>

<div style="margin-left: 2em;">

<p>Include information and methods in the exception which help the client deal with the exception.</p>

<p>When defining a new exception don&#8217;t just add a new error message, provide enough context for a catcher to gracefully handle the exception. If an existing exception class doesn&#8217;t have essential context, create a custom one.</p>

</div>

<p>Next, we&#8217;ll discuss checked and unchecked exceptions, and when to use them.</p>

<h3>Checked exceptions</h3>

<p>A checked exception is a Java concept which means an exception which is specified in a method&#8217;s signature. It is a way for the designer to tell the client of a method what might go wrong, so that the client can prepare accordingly.</p>

<h4>Throw a checked exception if a method can&#8217;t fulfill it&#8217;s contract</h4>

<div style="margin-left: 2em;">

<p>Either that, or don&#8217;t promise things you cannot keep.</p>

</div>

<h4>Make your exceptions part of your contract</h4>

<div style="margin-left: 2em;">

<p>Throw an exception which is meaningful in terms of the method&#8217;s contract.</p>

<p>Declare unchecked exceptions in the throws clause &#8211; make it easy for programmers and the IDE to discover the RuntimeExceptions that may be thrown by your method.</p>

<p>Document exceptions in Javadoc.</p>

</div>

<h4>Never let implementation-specific exceptions escalate to the higher layers</h4>

<div style="margin-left: 2em;">

<p>If the client code cannot do anything about a implementation-specific checked exception, convert it to a unchecked exception.</p>

<p>If you are confident that the business layer can take some recovery action when the implementation-specific exception occurs, convert it into a more meaningful checked exception.</p>

</div>

<h3>Unchecked exceptions</h3>

<p>Unchecked exceptions are all other exceptions, which are &#8220;unforeseen&#8221;.</p>

<h4>Prefer unchecked exceptions for all programming errors</h4>

<div style="margin-left: 2em;">

<p>If method parameters are invalid or preconditions not met, throw a unchecked exception. A client shouldn&#8217;t add exception handling code for providing invalid parameters, it should provide valid parameters!</p>

<p>Unchecked exceptions have the benefit of not forcing the client API to explicitly deal with them. They propagate to where you want to catch them, or they go all the way out and get reported.</p>

</div>

<h4>If the client cannot do anything useful, then make the exception unchecked</h4>

<div style="margin-left: 2em;">

<p>No sense in forcing the client to handle an exception it does not know how to deal with.</p>

</div>

<p>Feel free to provide any comments or thoughts below, and check back in a week for the next episode!</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/exception-handling-policy-throwing-exception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Common Conception Of Agile Missing The Point?</title>
		<link>http://henko.net/imperfection/common-conception-of-agile-missing-the-point/</link>
		<comments>http://henko.net/imperfection/common-conception-of-agile-missing-the-point/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 07:00:53 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Process]]></category>

		<guid isPermaLink="false">http://henko.net/?p=607</guid>
		<description><![CDATA[This is a bit of a rant, but I just gotta get it out of my system. I&#8217;m getting frustrated by people I talk to who seem to misunderstand the whole point of agile software development (IMHO). Different ways of reducing risk The point with agile, as far as I understand, is to reduce risk [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/gibbons/2171091952/"><img alt="Missing the mark" src="http://farm3.static.flickr.com/2193/2171091952_b281d3ec41_m.jpg" title="Missing the mark (Copyright 2008 by Bah Humbug)" class="alignright" width="240" height="161" /></a>This is a bit of a rant, but I just gotta get it out of my system.</p>

<p>I&#8217;m getting frustrated by people I talk to who seem to misunderstand the whole point of agile software development (IMHO).</p>

<h3>Different ways of reducing risk</h3>

<p>The point with agile, as far as I understand, is to reduce risk and thereby costs by <a href="http://henko.net/imperfection/minimizing-irreversible-actions/" title="Minimizing Irreversible Actions">postponing decisions</a> until we have as much information as possible. In older waterfall processes, pretty much everything was decided upfront. That wasn&#8217;t because people thought it was so much fun to decide everything up front, but because they believed it to be the best way to reduce risk and cost. Because a bug found just before delivery <em>is</em> <a href="http://www.agilemodeling.com/essays/costOfChange.htm" title="much more costly">much more costly</a> than one found earlier.</p>

<p>Agile, on the other hand, tries to use development practices which enable us to postpone decisions, practices which makes the system easy to change even later in the development process. Thus, the code you write should have two qualities:</p>

<ul>
<li>doesn&#8217;t force you into making unnecessary decisions, and</li>
<li>be easy to change.</li>
</ul>

<h3>How to reduce risk the agile way</h3>

<p>Quotes such as &#8220;<a href="http://c2.com/xp/YouArentGonnaNeedIt.html" title="You Ain't Gonna Need It">You Ain't Gonna Need It</a>&#8221; (YAGNI) and &#8220;<a href="http://c2.com/xp/DoTheSimplestThingThatCouldPossiblyWork.html" title="Do The Simplest Thing That Could Possibly Work">Do The Simplest Thing That Could Possibly Work</a>&#8221; (DTST) emphasize the first part &#8212; not making premature decisions. But while you can typically find people talking about the second part too, it doesn&#8217;t nearly get as much attention in people minds as the first one. Most likely simply because it&#8217;s not included in the name, in the mantra. I guess &#8220;You Aren&#8217;t Gonna Need It, But Do Not Forget To Make Sure Your Code Is Flexible&#8221; just doesn&#8217;t stick as easily.</p>

<p>Actually ensuring that your code is easy to change requires some work &#8212; especially while trying to avoid making premature decisions! It means using things like table driven code and putting abstractions in code an meta-data in configuration. It means thinking about what things are likely to change, and what things are not. It means not assuming too much, since you never know how things are going to be used in the future.</p>

<h3>Where many people misunderstand agile</h3>

<p>Rules and practices are good, but they are just the means to an end. I find that too many people interpret the agile mantras of YAGNI and DTST too literally. They create solutions which are &#8220;simple&#8221; and &#8220;works&#8221; and only includes &#8220;what&#8217;s needed&#8221;.</p>

<p>However, the next day, or next month, when requirements and expectations have changed (as they no doubt will) these solutions prove to be hard to adapt to the new situation. That&#8217;s because their developers forgot about the second part, making the system easy to change! And I believe forgetting that is forgetting the very core of what agile is about!</p>

<p>You agree? Got another opinion? How do you ensure you&#8217;re code is easy to change?</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/common-conception-of-agile-missing-the-point/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Constructors and Creation Methods</title>
		<link>http://henko.net/imperfection/constructors-and-creation-methods/</link>
		<comments>http://henko.net/imperfection/constructors-and-creation-methods/#comments</comments>
		<pubDate>Sat, 22 Sep 2007 12:53:36 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>

		<guid isPermaLink="false">http://henko.net/imperfection/constructors-and-creation-methods/</guid>
		<description><![CDATA[Sometimes a constructor doesn't communicate intention very effectively. This could be because instantiating the class in question isn't as straight-forward as "creating a new object", or because there are many alternative constructors. In those circumstances it might be useful to use well-named static or non-static methods to create instances of the class instead.]]></description>
			<content:encoded><![CDATA[<p>Sometimes a constructor doesn&#8217;t communicate intention very effectively. This could be because instantiating the class in question isn&#8217;t as straight-forward as &#8220;creating a new object&#8221;, or because there are many alternative constructors. In those circumstances it might be useful to use well-named static or non-static methods to create instances of the class instead.</p>

<p><a href="http://industriallogic.com/xp/refactoring/constructorCreation.html" title="Joshua Kerievsky introduced">Joshua Kerievsky introduced</a> the term <em>Creation Method</em> for these kinds of methods. The GOF pattern <a href="http://en.wikipedia.org/wiki/Factory_method" title="Factory Method">Factory Method</a> is similar as it includes a subset of all possible <em>Creation Method</em>s.</p>

<p>So, how does a <em>Creation Method</em> differ from a constructor, semantically? When should one use one or the other?</p>

<h3>Is computation required?</h3>

<p>I tend to use a <em>Creation Method</em>s when the instance creation requires much computation. In one sense, it is very similar to when to use properties and when to use Get-methods in VB/C#.</p>

<p>Possibly, a <em>Creation Method</em> which does a lot should be seen as a separate responsibility and moved to a a separate <em>Factory</em> class. This is similar to what Joshua Kerievsky discusses in <a href="http://www.industriallogic.com/xp/refactoring/classesWithFactory.html" title="Encapsulate Classes with Factory">Encapsulate Classes with Factory</a>, that some developers might not like having a class which has a <em>Factory</em> responsibility as well as its normal responsibility. In the end, I guess it&#8217;s a matter of taste.</p>

<h3>Do you actually get a <em>new</em> object?</h3>

<p>A <em>Creation Method</em> may be used when there is a finite set of possible objects to create. In such a case, a well named <em>Creation Method</em> may indicate that you cannot actually create a <em>new</em> object, but rather get one of the already defined.</p>

<p>An example would be the Java class <a href="http://java.sun.com/javase/6/docs/api/java/nio/charset/Charset.html" title="Charset">Charset</a>. There is a limited number of possible charsets (or at least number of charsets the system will understand), and therefore it does not provide a public constructor, but rather uses the method <code>forName(String)</code>. You would use the following code to create a <code>Charset</code> object.</p>

<pre><code>Charset c = Charset.forName("ISO-8859-1");
</code></pre>

<h3>Other reasons</h3>

<p>Another reason to use a <em>Creation Method</em> could be to hide the fact that it&#8217;s actually a (private) subclass which is being instantiated. In other words, that the <em>Creation Method</em> is actually a true <em>Factory Method</em>. See for instance the Money example in Kent Beck&#8217;s <a href="http://www.amazon.com/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530" title="Test-Driven evelopment">Test-Driven evelopment</a>.</p>

<p>You&#8217;ve got more ideas on what differs <em>Creation Method</em>s and constructors? Post a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/constructors-and-creation-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testability vs coupling</title>
		<link>http://henko.net/imperfection/testability-vs-coupling/</link>
		<comments>http://henko.net/imperfection/testability-vs-coupling/#comments</comments>
		<pubDate>Fri, 13 Jul 2007 09:45:19 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>

		<guid isPermaLink="false">http://henko.net/imperfection/testability-vs-coupling/</guid>
		<description><![CDATA[I want to describe a situation I came across where designing for testability seems to be in conflict with the always-valuable principle of loose coupling.]]></description>
			<content:encoded><![CDATA[<p>I want to describe a situation I came across where designing for testability seems to be in conflict with the always-valuable principle of loose coupling.</p>

<h3>Summary of coupling</h3>

<p><a href="http://stevemcconnell.com/" title="Steve McConnell">Steve McConnell</a> in <a href="http://cc2e.com/" title="Code Complete">Code Complete</a> describes coupling as follows.</p>

<blockquote>
  <p>Coupling describes how tightly a class or routine is related to other classes or routines. The goal is to create classes and routines with small, direct, visible, and flexible relations to other classes and routines, which is known as &#8220;loose coupling&#8221;.</p>
</blockquote>

<p>McConnell furthermore lists a number of different types of coupling, some of which are better than other.</p>

<ul>
<li><em>Simple-data-parameter coupling</em>: All data passed between <em>A</em> and <em>B</em> are of primitive data types and passed through parameter lists. This kind of coupling is normal and acceptable.</li>
<li><em>Simple-object coupling</em>: <em>A</em> instantiates an object of type <em>B</em>. This kind is also fine.</li>
<li><em>Object-parameter coupling</em>: <em>A</em> requires <em>B</em> to send it an object of type <em>C</em>. This type is tighter since it requires <em>B</em> to know of <em>C</em>.</li>
<li><em>Semantic coupling</em>: <em>A</em> makes use of, not some syntactic element of <em>B</em>, but knowledge of its inner workings. Should be avoided.</li>
</ul>

<h3>Dependency injection to simplify testing</h3>

<p>So, loose coupling is definitely good as it makes the system easier to work with. However, when I read one of <a href="http://codebetter.com/blogs/jeremy.miller/archive/2006/03/09/140465.aspx" title="Jeremy Miller's excellent posts">Jeremy Miller's excellent posts</a> I started thinking. He suggests using dependency injection to simplify testing in some cases, which to me seems to be creating tighter coupling within the system.</p>

<p>More specifically, the problem he describes is as follows. A class <code>ClassUnderTest</code> internally creates an object of type <code>Dependency</code>. However, if it is hard to create a new instance of <code>Dependency</code> equal to the first one (e.g. a datetime object representing &#8220;now&#8221;), <code>ClassUnderTest</code> becomes very difficult to test.</p>

<p>When the unit test wants to create a copy of the the hard-to-reproduce-object <code>Dependency</code> to compare with <code>ClassUnderTest</code>&#8216;s <code>Dependency</code> instance, a non-equal instance is created (the system clock has changed) and the test fails.</p>

<p>The solution is to provide the object under test with either:</p>

<ul>
<li>the <code>Dependency</code> object in question itself, or </li>
<li>an object which provides <code>ClassUnderTest</code> with the wanted <code>Dependency</code> instance.</li>
</ul>

<p>I agree with this completely. In fact, I&#8217;ve had the problem a number of times myself, and solved it successfully this very way.</p>

<h3>In terms of coupling</h3>

<p>With respect to coupling, the case is that before we add the test (let&#8217;s assume we&#8217;re testing legacy code) we have <em>simple-object coupling</em>, since <code>ClassUnderTest</code> creates another object <code>Dependency</code>. However, when we test <code>ClassUnderTest</code> we want to create another object of the same type as <code>Dependency</code> equal to the one <code>ClassUnderTest</code> created.</p>

<p>As noted above, the solution is dependency injection &#8212; to provide <code>ClassUnderTest</code> with <code>Dependency</code>, either directly or indirectly. That way, we have the possibility to get hold of <code>Dependency</code> to perform the assertion in question. In terms of coupling however, this changes the coupling to be of type <em>object-parameter coupling</em> which is considered tighter than the type of coupling we had before.</p>

<h3>A counter argument</h3>

<p>Thinking about this, I thought that maybe the key here is that to test <code>ClassUnderTest</code> in the first case, the test would need to be <em>semantically coupled</em> to <code>ClassUnderTest</code> because it would have to know what kind of <code>Dependency</code> object it created internally (&#8220;now&#8221; vs any other datetime) and try to recreate it in some clever way. So we actually replace semantic coupling with object-parameter coupling &#8212; an improvement.</p>

<p>The counter argument (to the counter argument) is that without the test code, we would have no need to create such an object and there would be no semantic coupling in the first place. Thus, writing the test tightens the coupling in the system.</p>

<h3>The question</h3>

<p>Am I missing anything, or is this an example of where designing for testability actually leads to worse (as in more complex and more tightly coupled) design? Or am I just getting lost completely in theory? Maybe this slightly tighter coupling is nothing compared to what we gain from having a good and simple unit test in place.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/testability-vs-coupling/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Slightly different and even simpler</title>
		<link>http://henko.net/imperfection/slightly-different-and-even-simpler/</link>
		<comments>http://henko.net/imperfection/slightly-different-and-even-simpler/#comments</comments>
		<pubDate>Mon, 11 Jun 2007 12:24:28 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>

		<guid isPermaLink="false">http://henko.net/imperfection/slightly-different-and-even-simpler/</guid>
		<description><![CDATA[I'm constantly trying to become better at estimating how long a development task will take. As one step in this process I decided to create a simple web-based timer which I could use to measure time. Shouldn't be too hard, I just needed a simple stop watch &#8212; the simplest thing that that could possibly work. That's what I thought at least.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m constantly trying to become better at estimating how long a development task will take. As one step in this process I decided to create a simple web-based timer which I could use to measure time. Shouldn&#8217;t be too hard, I just needed a simple stop watch &mdash; the simplest thing that that could possibly work. That&#8217;s what I thought at least.</p>

<p>The problem was that instead of thinking about what functionality I actually needed, I just assumed that since I was going to measure time I needed a regular stop watch. Thus, the first version of my timer had the operations <code>start</code>, <code>pause</code>, <code>stop</code> and <code>reset</code>, where <code>reset</code> was only available when the timer was stopped.</p>

<p>After a while I realized I was pressing the sequence <code>stop</code>-<code>reset</code>-<code>start</code> a lot of times. I did it every time a task was finished and I was about to start with a new one. So to make my life easier I added <code>restart</code> which did just that.</p>

<p>After using it even more I realized that <code>restart</code> now actually was the only button I was pushing. Therefore, I simply removed all other buttons than <code>restart</code> (which was renamed <code>reset</code>).</p>

<p>The result is a very simple timer. It auto-starts and is then always running. Thus, no need for <code>start</code> or <code>stop</code>. That&#8217;s great for measuring time while working, because real time doesn&#8217;t stop. I always spend time doing <em>something</em>. The only thing I can do with my time is divide it into chunks of time which I spend doing different tasks. That is exactly what my <code>reset</code> button allows me to do &mdash; tell where one such chunk ends and the next starts.</p>

<p>I&#8217;m actually very satisfied with the result. What is rather funny about this whole thing is that although I first thought I needed &#8220;just a simple stop watch&#8221;, my need was in fact slightly different and <em>even simpler</em>.</p>

<p>P.S. If you want to use the timer, it&#8217;s available at <a href="http://timer.henko.net/" title="http://timer.henko.net/">http://timer.henko.net/</a>. However, it currently assumes Central European Time (+1). Time is also only shown in hours, since that is how I enter time in my time reporting tool.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/slightly-different-and-even-simpler/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Do design, just not Big and Up Front</title>
		<link>http://henko.net/imperfection/do-design/</link>
		<comments>http://henko.net/imperfection/do-design/#comments</comments>
		<pubDate>Thu, 08 Feb 2007 13:38:20 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>

		<guid isPermaLink="false">http://henko.net/imperfection/do-design/</guid>
		<description><![CDATA[While evolving a design is good and nice one has to remember that even though big design <em>up front</em> might not be a good idea, all the hard design work still needs to be done at some point. Otherwise you'll just end up with a big piece of garbage. Therefore, while starting with a story, <em>do</em> take time and think it through and answer a couple of the following questions for yourself.]]></description>
			<content:encoded><![CDATA[<p>The term <a href="http://c2.com/xp/BigDesignUpFront.html" title="Big Design Up Front">Big Design Up Front</a> (BDUF) is used in the Agile community as a derogatory word for the practice of doing all (or most of) the design before starting coding. Agilists agree on the fact that BDUF is not the way to go, but rather to let the design evolve as coding is done.</p>

<p>While evolving a design is good and nice one has to remember that even though big design <em>up front</em> might not be a good idea, all the hard design work still needs to be done at some point. Otherwise you&#8217;ll just end up with a big piece of garbage. Therefore, while starting with a story or use case, <em>do</em> take time and think it through and answer a couple of questions for yourself (not an exhaustive list).</p>

<ul>
<li>What is the goal of the story?</li>
<li>In what ways can we solve this?</li>
<li>How does these solutions fit into the current system?</li>
<li>What are the pros and cons of these solutions?</li>
<li>What are the larger problems (if any)?</li>
</ul>

<p>However, while thinking about all this, don&#8217;t try to work <em>all</em> the details out, they will sort themselves out while coding. More importantly, don&#8217;t <em>commit</em> to any of the design alternatives you come up with. The important part is thinking the problem through thoroughly. A quote from David Eisenhower sums this up nicely:</p>

<blockquote>
  <p>In preparing for battle I have always found that plans are useless, but planning is indispensable.</p>
</blockquote>

<p>Steve McConnell in the second edition of <a href="http://cc2e.com/" title="Code Complete">Code Complete</a>, describes how while he was writing the first edition, design zealots argued for BDUF, and as he was writing the second, some software swamis instead argued for no initial design at all. He says:</p>

<blockquote>
  <p>In ten years the pendulum has swung from &#8220;design everything&#8221; to &#8220;design nothing&#8221;. But the alternative to BDUF isn&#8217;t no design up front, it&#8217;s a Little Design Up Front (LDUF) or Enough Design Up Front — ENUF.</p>
</blockquote>

<p>Another take on this is to make the decision in the <em>Last Responsible Moment</em>, described by Jeremy Miller in <a href="http://codebetter.com/blogs/jeremy.miller/archive/2006/01/18/136648.aspx" title="one of his articles">one of his articles</a>.</p>

<blockquote>
  <p>The key is to make decisions as late as you can responsibly wait because that is the point at which you have the most information on which to base the decision. In software design it means you forgo creating generalized solutions or class structures until you know that they’re justified or necessary.</p>
</blockquote>

<p>However, one might not use this advice to justify not designing at all. The key here is that you don&#8217;t <em>commit</em> to a certain design (i.e. make the decision) until the last possible minute, but you still <em>consider the alternatives</em> — which of course requires you to research and actually think about them!</p>

<div class="modifications">

<p>Modifications:</p>

<ul>
<li>2007-02-08: Original post.</li>
<li>2007-07-12: Added the paragraphs on ENUF.</li>
<li>2007-07-13: Added the paragraphs on Last Responsible Moment.</li>
</ul>

</div>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/do-design/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Non-obvious duplication</title>
		<link>http://henko.net/imperfection/non-obvious-duplication/</link>
		<comments>http://henko.net/imperfection/non-obvious-duplication/#comments</comments>
		<pubDate>Mon, 28 Aug 2006 12:22:09 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>

		<guid isPermaLink="false">http://henko.net/imperfection/non-obvious-duplication/</guid>
		<description><![CDATA[I just wanted to describe what for me became an "eye-opener" regarding Test-Driven Development; that when you remove duplication, you should look for not only duplication of logic, but also duplication of data.]]></description>
			<content:encoded><![CDATA[<p>I just wanted to describe what for me became an &#8220;eye-opener&#8221; regarding <a href="http://en.wikipedia.org/wiki/Test_driven_development" title="Test-Driven Development">Test-Driven Development</a>. Let&#8217;s begin with a quick recap on TDD.</p>

<ol>
<li>It says that while all tests pass, you&#8217;re not allowed to add new functionality. To do that, you have to add a new test which fails because of the lack of the wanted functionality.</li>
<li>Then you make that test pass in the simplest way you can imagine. In fact, while you have a test which fails, you&#8217;re allowed to do practically anything (possibly except cardinal sins) to make it pass. </li>
<li>After you&#8217;ve made it pass, you can refactor all you want to clean up the existing code, including the lines you just wrote.</li>
</ol>

<p>This is the rhythm of TDD, which is often called red/green/refactor, as a reference to the color of the progress bar most unit testing interfaces use when test fail and pass.</p>

<p>Anyway, back to the eye-opening experience. As an example, lets use the following test, asserting that a method for calculating the sum of two integers is correct.</p>

<pre><code>public void testSum() {
    assertEquals(8, sum(3, 5));
}
</code></pre>

<p>The simplest way I can imagine to make this test pass is the following code is just faking the implementation.</p>

<pre><code>public int sum(int augend, int addend) {
    return 8;
}
</code></pre>

<p>Now, this really feels bad. We know that returning 8 is not a correct solution for all possible parameter values. On the other hand, the test is passing, which is my proof of that the program works. Nevertheless, just faking out the implementation feels like cheating. No matter how many more tests we write for this function we could always just continue faking it by making another special case, ending up with a gigantic <code>switch</code> statement rather than the real and much simpler function (I leave finding the correct function as an exercise for the reader <img src='http://henko.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ).</p>

<p>Now comes what for me was an eye-opener. <a href="http://c2.com/cgi/wiki?KentBeck" title="Kent Beck">Kent Beck</a> in his book <a href="http://www.awprofessional.com/bookstore/product.asp?isbn=0321146530" title="Test-Driven Development">Test-Driven Development</a> describes how to solve this problem nicely. He notices that there is duplication between the test and the implementation; not duplication of logic, but duplication of data. The duplication is also not explicit, but implicit. What <code>return 8;</code> really stands for is <code>return 3+5;</code>. And it is rather obvious to us that <code>3</code> and <code>5</code> really are the same numbers which are given as parameters to the <code>sum()</code> function in the test. In other words, the numbers <code>3</code> and <code>5</code> are duplicated.</p>

<p>To avoid this and remove the duplication, we have to make the function somehow reference the values in the test. In our case, this turns out to be very simple, as they are given to the method as parameters. We refactor the method as follows, and the duplication is gone.</p>

<pre><code>public int sum(int augend, int addend) {
    return augend + addend;
}
</code></pre>

<p>Now look and behold. By removing the duplication, we also made the function work as we wanted.</p>

<p>Lets think again about the rhythm of TDD. Since the test passed with our first <code>return 8;</code> implementation, we were at green bar (all tests passed). And when we&#8217;ve got a green bar, TDD only allows us to refactor the code, not add new functionality. Now, one can argue that the change made to the implementation (changing <code>8</code> to <code>augend + addend</code>) wasn&#8217;t a semantics preserving refactoring at all, but rather adding new functionality. To answer this, let&#8217;s recap on perhaps the most well known definition of refactoring, namely from <a href="http://www.martinfowler.com/" title="Martin Fowler">Martin Fowler</a>s book <a href="http://martinfowler.com/books.html#refactoring" title="Refactoring">Refactoring</a>.</p>

<blockquote>
  <p>A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its
  observable behavior.</p>
</blockquote>

<p>So, in fact, practically all refactorings change the exact behavior of the code, just not the type we are interested in which is <em>observable behavior</em>. And when we&#8217;re talking Test-Driven Development, what you don&#8217;t have tests for, you can&#8217;t observe. Thus, the modification we made was not changing any observable (i.e. tested) behavior, just untested and therefore invisible behavior.</p>

<p>This might seem to you as either fooling oneself, or as an elegant solution to the problem. I put my vote on the latter.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/non-obvious-duplication/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing equals()</title>
		<link>http://henko.net/imperfection/implementing-equals/</link>
		<comments>http://henko.net/imperfection/implementing-equals/#comments</comments>
		<pubDate>Thu, 18 May 2006 22:15:26 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>

		<guid isPermaLink="false">http://henko.net/software-engineering/implementing-equals/</guid>
		<description><![CDATA[Among Java developers, there exist different ideas about how to implement the <code>equals()</code> method. The disagreement is about whether to allow subclasses to be considered equal or not. I quickly describe the difference between the two alternatives and give my take on the problem.]]></description>
			<content:encoded><![CDATA[<p>Among Java developers, there exist <a href="http://www.artima.com/intv/bloch17.html" title="different ideas">different ideas</a> about how to implement the <code><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals(java.lang.Object)" title="equals">equals</a>()</code> method. The disagreement is about whether to allow subclasses to be considered equal or not.</p>

<h3>Two ways to see it</h3>

<p>Some say that it should be done using the <code>instanceof</code> operator, like this.</p>

<pre><code>public boolean equals(Object obj) {
    if (obj instanceof MyClass) {
        MyClass that = (MyClass) obj;
        // compare this and that
    } else {
        return false;
    }
}
</code></pre>

<p>Other says that it should be done by comparing the exact classes of the two objects, like this.</p>

<pre><code>public boolean equals(Object obj) {
    if (obj != null &amp;&amp; obj.getClass() == this.getClass()) {
        MyClass that = (MyClass) obj;
        // compare this and that
    } else {
        return false;
    }
}
</code></pre>

<p>The difference lies in how they treat subclasses. As <code>instanceof</code> returns <code>true</code> if <code>obj</code> is of the same class <em>or any subclass</em>, it will allow subclasses to be considered semantically identical to their superclasses. Comparing the result of <code>getClass()</code> on both objects will require that they are of exactly the same class. Using that method, no subclass can ever be semantically equal to its superclass.</p>

<p>To understand why this difference matters, it is important to remember one of the requirements Java has on any implementation of <code>equals()</code>; the equality relation must be symmetrical. In other words, for any objects <code>a</code> and <code>b</code> the expression <code>a.equals(b)</code> may return <code>true</code> <em>if and only if</em> <code>b.equals(a)</code> also does.</p>

<p>Because of this, the <code>getClass()</code> camp argues that since we can&#8217;t predict how subclasses might want to implement <code>equals()</code>, we better implement <code>equals()</code> in such a way that it only compares objects of the same class. That way a subclass can safely override and implement <code>equals()</code> any way they want. For example, a subclass might have additional fields which it wants to use in the equality comparison. Otherwise we might end up in a situation where e.g. the superclass says that is equal to the subclass but not the other way around.</p>

<p>The argument from the <code>instanceof</code> proponents is that not allowing a subclass to be considered equal breaks the notion of <a href="http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming" title="polymorphism">polymorphism</a>. It also violates the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" title="Liskov substitution principle">Liskov substitution principle</a> as well as the <a href="http://en.wikipedia.org/wiki/Principle_of_least_astonishment" title="principle of least astonishment">principle of least astonishment</a>.</p>

<h3>How I see it</h3>

<p>Okay, enough with the summary. Now I&#8217;ll throw my own two cents in.</p>

<p>I think this whole question pretty much falls apart if we just make a better distinction between interface and implementation. An interface decides <em>what</em> a method is supposed to do, while a particular implementation knows <em>how</em> to do it. In other words, it is up to the interface to define what equality means for that interface. Being separated from its implementation(s), the interface must therefore define <code>equals()</code> in terms of comparisons of its own members. Thus, it cannot require the other object to &#8220;be of the same class&#8221; without having inappropriate knowledge about at least one of its implementations.</p>

<p>One problem is that a class in Java is somewhat ambiguous as it both has an interface and provides an implementation for it. This makes the interface more implicit. If you think it makes things clearer, extract an interface from your superclass and let it define (through documentation and unit tests) the exact behavior of the implementation. Then implement that exact behavior in any way you see fit in your class.</p>

<h4>Example: Collections in Java</h4>

<p>A good example of how things should work is the collections framework in Java. If we look at the documentation for the <code>equals()</code> method of e.g. the <code><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Set.html" title="Set">Set</a></code> interface, we see the following. Pay special attention to the last sentence.</p>

<blockquote>
  <p>Returns true if the specified object is also a set, the two sets have the same size, and every 
  member of the specified set is contained in this set (or equivalently, every member of this set 
  is contained in the specified set). This definition ensures that the equals method works 
  properly across different implementations of the set interface.</p>
</blockquote>

<p>This behavior is defined by the interface <code><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Set.html" title="Set">Set</a></code>. It is then implemented in the abstract class <code><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractSet.html" title="AbstractSet">AbstractSet</a></code> which is in turn extended by <code><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html" title="HashSet">HashSet</a></code> and <code><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeSet.html" title="TreeSet">TreeSet</a></code>. None of the two subclasses override <code>equals()</code>.</p>

<h4>Example: Employees and Managers</h4>

<p>In a blog entry, Cay Horstmann uses <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=4744" title="another example">another example</a>. However, he is arguing for using <code>getClass()</code> rather than <code>instanceof</code>. His example includes a class hierarchy where we have an <code>Employee</code> class as the base and then a <code>Manager</code> class which extends <code>Employee</code> by adding a <code>bonus</code> field. Expressing the example in code, it would look something like below.</p>

<pre><code>public Employee {
    public boolean equals(Object other) {
        if (!(other instanceof Employee)) return false;
        // cast other to Employee and compare fields
        // ...
    }
}

public Manager extends Employee {
    public boolean equals(Object other) {
        if (!super.equals(other)) return false;
        // cast other to Manager and compare fields
        return bonus == ((Manager)other).bonus;
    }
}
</code></pre>

<p>In other words, the subclass <code>Manager</code> changes the meaning of equality it inherited from its superclass <code>Employee</code>. Is this a sensible thing to do? As you might guess, I would say no. We (hopefully) decided when we wrote <code>Employee</code> that there was a given way to uniquely identify any specific employee. That might have been an employee id, combination of first name and last name, or any other combination of <code>Employee</code> members. For sake of discussion, let us say we compare the values of the function <code>getId()</code>. Being an <code>Employee</code> itself, what reason would <code>Manager</code> have to change this definition? To check if two <code>Manager</code> objects have the same id but different values for the field <code>bonus</code>? Well, if we do have two such objects, then <em>that</em> is the problem. We shouldn&#8217;t have allowed them exist at the same time. The job of <code>equals()</code> is not to guard us from having corrupt data in our model!</p>

<h4>Final thoughts</h4>

<p>If a subclass truly has to override <code>equals()</code> to provide a semantically different implementation of <code>equals()</code> it might instead be a sign of that the subclass perhaps should not be a subclass after all. A subclass is supposed to extend or alter the behavior of a superclass or implement the behavior of an interface, but always doing so within the boundaries of all inherited interfaces.</p>

<p>One way to make sure subclasses does not break the contract is to make the <code>equals()</code> method in the superclass <code>final</code>. However, I think that is just overly protective. There could be a valid reason for wanting to override the <code>equals()</code> and still preserve its semantics. Performance optimization could be one such reason.</p>

<p>Thus, in my humble opinion, the correct way to implement <code>equals()</code> is as follows.</p>

<pre><code>public boolean equals(Object obj) {
    if (obj instanceof MyInterface) {
        MyInterface that = (MyInterface) obj;
        // compare public members of this and that
    } else {
        return false;
    }
}
</code></pre>

<p>However, my opinion might not be the same as yours, and your opinion might not be the same as mine (for symmetry purposes <img src='http://henko.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ). If you happen to have another opinion, feel free to comment or trackback!</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/implementing-equals/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Simplicity in Software Design</title>
		<link>http://henko.net/imperfection/simplicity-in-software-design/</link>
		<comments>http://henko.net/imperfection/simplicity-in-software-design/#comments</comments>
		<pubDate>Sun, 30 Apr 2006 09:50:35 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Imperfection]]></category>

		<guid isPermaLink="false">http://www.viskos.org/~henko/henko.net/test/?p=5</guid>
		<description><![CDATA[Not many people would argue that a complex and difficult-to-understand solution is better than a simple and easy-to-understand one. And still, we often tend to end up with more complex solutions than we need and/or would wish for. This is generally for two reasons. Either we think to little, or too much.]]></description>
			<content:encoded><![CDATA[<p>Not many people would argue that a complex and difficult-to-understand solution is better than a simple and easy-to-understand one. And still, we often tend to end up with more complex solutions than we need and/or would wish for. This is generally for two reasons. Either we think to little, or too much.</p>

<h3>Thinking to little</h3>

<p>To some degree, programming is just mechanical work. We know what we want the computer to do, and we just need to write down the instructions. However, although we normally know what we want the computer to do, we don&#8217;t necessarily know the best way to do it. Figuring out a good way to do this is what programming is all about.</p>

<p>Unfortunately, the simplest solution is not necessarily the first one that comes into our minds. In fact, there seems to be an inverse proportionality between the complexity of a solutions and the time it took to reach it. Thus, simple solutions tend to take longer time and require more thought to find.</p>

<p>That makes it all seem very simple, right? The more you think, the better chance you have of reaching a good solution. Perfect! Then you could stop reading right now, and just spend some more time thinking. Right?</p>

<h3>Thinking too much</h3>

<p>Well, not quite. This is the time where programmers tend to get carried away. They get too eager, too ambitious. Programmers like to write complex code. They want to create the Perfect System™, reach design nirvana. There is something very satisfying in designing those perfect systems; extremely flexible with intricate interaction, beautiful class hierarchies, perfect cohesion and so little coupling that you have to use a magnifying glass to see it.</p>

<p>Not only that, W.E. Boebert, designer of an autopilot that ran for 15+ years without an in-flight anomaly, suggested that education also is a factor in programmers desire for design complexity.</p>

<blockquote>
  <p>I laid full blame […] on CS faculty who either knew nothing other than operating systems or held OS designs up as the ultimate paradigm of software. So CS students and new grad software engineers came out thinking that an autopilot should look like Unix.</p>
</blockquote>

<p>So when you recognize those feelings inside you, it is time to stop and take a deep breath.</p>

<div class="images"><img src="http://henko.net/wp-content/uploads/2006/04/DSC_0044.JPG" alt=" (Picture is taken 2006 by Karin Röhsman.)" title=" (Picture is taken 2006 by Karin Röhsman.)" /></div>

<h3>Doing the right thing</h3>

<p>Most likely what we need right now is not the Perfect System™. Most likely we need a simpler, less complex system. While this might sound boring, it is pretty much almost the truth. I&#8217;m sorry. For some inspiration, read those words of wisdom from <a href="http://en.wikipedia.org/wiki/Queen_Kristina" title="Queen Christina">Queen Christina</a> of Sweden, freely translated by me:</p>

<blockquote>
  <p>Greatness lies not in doing what one wants, but wanting what one should.</p>
</blockquote>

<p>But come on you might say, why not build the perfect system? After all, if we do build a perfect system, it&#8217;s not that anyone is going to complain, right? Well, no. Chances are however that you&#8217;re not going to reach the perfect system. It is much more likely that we end up with a system which is not quite what you intended, overly complex with a class hierarchy with more levels than a Nintendo game. And while it can handle any future change you could ever anticipate, still doesn&#8217;t do exactly that we need right now. Without doubt you have spent way more time than can be justified and it still doesn&#8217;t work. Of cause, there are exceptions, and I might be exaggerating just a bit, but you get the general idea.</p>

<p><a href="http://www.extremeprogramming.org/" title="Extreme Programming">Extreme Programming</a> stresses among other good habits the importance of, and time gain one gets from, not writing an overly complex solution in their <a href="http://www.extremeprogramming.org/rules/simple.html" title="first design rule">first design rule</a>:</p>

<blockquote>
  <p>Always do the simplest thing that could possibly work.</p>
</blockquote>

<h3>Benefits of simplicity</h3>

<p>The saying goes that &#8220;less is more&#8221;, and this is very true when it comes to software design. By keeping our system as simple as we can we gain one very important quality; it makes our system easier to understand. Kernighan and Plauger wrote in 1978 as the first rule in their classic programming book <a href="http://www.amazon.com/gp/product/0070342075/sr=8-1/qid=1146189252/ref=sr_1_1/002-4377899-6721631?%5Fencoding=UTF8" title="Elements of Programming Style">Elements of Programming Style</a> something which still, thirty years later is as true as ever.</p>

<blockquote>
  <p>Write clearly – don&#8217;t be too clever.</p>
</blockquote>

<p>Actually, as long as it is syntactically correct, a computer has no problem figuring out what you mean no matter how the code is structured. The same is certainly not true for humans, however. Therefore, don&#8217;t write code for computers, they don&#8217;t care how it looks anyway. Write code for yourself and for your fellow co-developers – they certainly do care. And believe it or not, most of us actually have a limitation for how many layers of abstraction and indirection we can handle before exploding.</p>

<p>Another good reason to avoid complex solutions is that it generally is harder to debug programs than to write them. So, put somewhat jokingly, if you are as smart as you ever can when you write the code, how can you have any hope of ever being able to debug it?</p>

<p>I&#8217;ll sum up with the words of C. A. R. Hoarse, brittish computer scientist, perhaps most famous for developing the quicksort algorithm.</p>

<blockquote>
  <p>There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.</p>
</blockquote>

<p>Which way are you constructing your designs?</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/simplicity-in-software-design/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

