<?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; Implementation</title>
	<atom:link href="http://henko.net/category/imperfection/implementation/feed/" rel="self" type="application/rss+xml" />
	<link>http://henko.net</link>
	<description>Home of a human being and software developer</description>
	<lastBuildDate>Wed, 16 Jun 2010 20:32:13 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Exception Handling Policy &#8211; Logging Exceptions</title>
		<link>http://henko.net/imperfection/exception-handling-policy-logging-exceptions/</link>
		<comments>http://henko.net/imperfection/exception-handling-policy-logging-exceptions/#comments</comments>
		<pubDate>Mon, 13 Jul 2009 06:00:32 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/?p=667</guid>
		<description><![CDATA[This is the last part of my series on exception handling which will deal with logging exceptions and other noteworthy events.

A summary of the series:


Throwing Exceptions
Using Assertions
Catching Exceptions
Logging Exceptions (this one)


General guidelines

We&#8217;ll start off with a few general guidelines for logging.

Always include the exception message in the log



Make sure you know what actually went wrong, [...]]]></description>
			<content:encoded><![CDATA[<p>This is the last part of my series on exception handling which will deal with logging exceptions and other noteworthy events.</p>

<p>A summary of the 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><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><strong>Logging Exceptions</strong> (this one)</li>
</ol>

<h3>General guidelines</h3>

<p>We&#8217;ll start off with a few general guidelines for logging.</p>

<h4>Always include the exception message in the log</h4>

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

<p>Make sure you know what actually went wrong, not just that something went wrong.</p>

</div>

<h4>Never lose a stack trace!</h4>

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

<p>And not only do you want to know what went wrong, you want to know where! An exception without a stack trace is like a person with no memory.</p>

</div>

<h3>Debug levels</h3>

<p>A summary of the typical severity levels used when logging and guidelines on when to use them.</p>

<h4>Info, Debug, or Trace</h4>

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

<p>Informational messages that highlight the progress of the application at various levels of granularity.</p>

<p>Use logging levels <code>INFO</code>, <code>DEBUG</code>, <code>TRACE</code>.</p>

</div>

<h4>Warnings</h4>

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

<p>Potentially harmful situations, such as invalid requests which could be some form of attack. It could also be a client (developer) in need of help.</p>

<p>Use logging level <code>WARN</code>.</p>

</div>

<h4>Errors</h4>

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

<p>Error events that might still allow the application to continue running. For example, uncaught exceptions in your &#8220;catch all&#8221; exception handler.</p>

<p>Use logging level <code>ERROR</code>.</p>

</div>

<h4>Fatal errors</h4>

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

<p>Very severe error events that will presumably lead the application to abort. Examples include <a href="http://henko.net/imperfection/exception-handling-policy-using-assertions/" title="Exception Handling Policy - Using Assertions">all fired assertions</a>. They should not happen &#8212; they are bugs! Also, all &#8220;errors&#8221; in the Java sense (out of memory etc).</p>

<p>Use logging level <code>FATAL</code>.</p>

</div>

<p>I hope this quick four part series on sensible exception handling has been interesting. Be sure to read the previous installments (see summary at top) and please feel free to add your comments below! Any and all comments are very welcome!</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/exception-handling-policy-logging-exceptions/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 catch.

When to catch

Here are some guidelines [...]]]></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 a program to check itself as it [...]]]></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>Scope control</title>
		<link>http://henko.net/imperfection/scope-control/</link>
		<comments>http://henko.net/imperfection/scope-control/#comments</comments>
		<pubDate>Thu, 21 Jun 2007 14:30:18 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/imperfection/scope-control/</guid>
		<description><![CDATA[Again, the book <em>Test-Driven Development: By Example</em> by Kent Beck provides me with an eye-opening experience. It explains how test-driven development is useful for scope control when developing.]]></description>
			<content:encoded><![CDATA[<p><a href="http://henko.net/imperfection/non-obvious-duplication/" title="Non-obvious duplication">Again</a>, the book <a href="http://www.awprofessional.com/bookstore/product.asp?isbn=0321146530&amp;rl=1" title="Test-Driven Development: By Example">Test-Driven Development: By Example</a> by Kent Beck provides me with an eye-opening experience. It explains how test-driven development is useful for scope control when developing.</p>

<blockquote>
  <p>Programmers are good at imagining all sorts of future problems. Starting with one concrete example and generalizing from there prevents you from prematurely confusing yourself with extraneous concerns. You can do a better job of solving the immediate problem because you are focused. When you go to implement the next test case, you can focus on that one, too, knowing that the previous test is guaranteed to work.</p>
</blockquote>

<p>I&#8217;ve found this to be very true. Before starting to think this way, I way to often started writing a test (or even started implementing some feature), only to stray away to a number of different tasks; adding guard clauses for the function, writing a helper function that I might need, refactoring a related method, and so on. By writing a simple test and implement that piece of functionality (and only that), then write a new test and implement that, and so on, my coding has become much more focused and I move forward noticeably faster.</p>

<p>However, this doesn&#8217;t mean you should just ignore thoughts on potential related problems. Write them down to look at later — but don&#8217;t let them grab your attention for longer time than that. Keep pen and paper ready at all times.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/scope-control/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Refactoring vs performance optimization</title>
		<link>http://henko.net/imperfection/refactoring-vs-performance-optimization/</link>
		<comments>http://henko.net/imperfection/refactoring-vs-performance-optimization/#comments</comments>
		<pubDate>Wed, 30 Aug 2006 08:56:23 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/imperfection/refactoring-vs-performance-optimization/</guid>
		<description><![CDATA[The thought popped up into my mind a while ago, that there is actually a striking similarity between refactoring and performance optimization.]]></description>
			<content:encoded><![CDATA[<p>The thought popped up into my mind a while ago, that there is actually a striking similarity between refactoring and performance optimization. Both of them&#8230;</p>

<ul>
<li>are meant to make the program better.</li>
<li>preserve semantics of the program (hopefully).</li>
<li>should be driven by a real and provable need.</li>
<li>can be harmful when premature/speculative.</li>
</ul>

<p>In fact, they have the same goal as well. They are both meant to to make the program easier to interpret. The only difference is that refactoring tries to make it easier for the developer, and performance optimization for the computer.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/refactoring-vs-performance-optimization/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Full statement coverage</title>
		<link>http://henko.net/imperfection/full-statement-coverage/</link>
		<comments>http://henko.net/imperfection/full-statement-coverage/#comments</comments>
		<pubDate>Tue, 15 Aug 2006 12:22:05 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/imperfection/full-statement-coverage-using-test-driven-development/</guid>
		<description><![CDATA[When I read Ron Jeffries Soduko articles, I was wondering why he was writing such sloppy unit tests. He didn't seem to test even half of the code he wrote. A short email conversation later I had realized that he of course wasn't sloppy, but rather just much more clever than I was (not that surprising, really). ;-)]]></description>
			<content:encoded><![CDATA[<p>When I read <a href="http://www.xprogramming.com/" title="Ron Jeffries">Ron Jeffries</a> <a href="http://search.atomz.com/search/?sp-q=sudoku&amp;sp-a=sp01062000&amp;sp-advanced=1&amp;sp-p=any&amp;sp-w-control=1&amp;sp-d=custom&amp;sp-date-range=-1&amp;sp-start-month=0&amp;sp-start-day=0&amp;sp-start-year=&amp;sp-end-month=0&amp;sp-end-day=0&amp;sp-end-year=&amp;sp-x=title&amp;sp-c=10&amp;sp-m=1&amp;sp-s=0" title="Soduko articles">Soduko articles</a>, I was wondering why he was writing such sloppy unit tests. He didn&#8217;t seem to test even half of the code he wrote. A short email conversation later I had realized that he of course wasn&#8217;t sloppy, but rather just much more clever than I was (not that surprising, really). <img src='http://henko.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>

<p>If a test exercises method <code>a()</code> which in turn calls <code>b()</code>, then both <code>a()</code> and <code>b()</code> are in fact tested. If <code>b()</code> is changed (in an incorrect way) there is a test which will fail. In other words, he was writing the least amount of test code necessary to get full statement coverage. Pretty smart, if you ask me.</p>

<p>I guess there is nothing wrong in doing extensive testing, besides perhaps that the development moves forward more slowly (at least in a short perspective). TDDers like to say, test until fear turns to boredom. So apparently I wasn&#8217;t bored enough by writing the tests yet.</p>
]]></content:encoded>
			<wfw:commentRss>http://henko.net/imperfection/full-statement-coverage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why Doing Nothing May Crash Your Program</title>
		<link>http://henko.net/imperfection/why-doing-nothing-may-crash-your-program/</link>
		<comments>http://henko.net/imperfection/why-doing-nothing-may-crash-your-program/#comments</comments>
		<pubDate>Tue, 21 Jun 2005 18:41:25 +0000</pubDate>
		<dc:creator>Henrik Jernevad</dc:creator>
				<category><![CDATA[Imperfection]]></category>
		<category><![CDATA[Implementation]]></category>

		<guid isPermaLink="false">http://henko.net/2005/11/16/visual-basic-real-world/</guid>
		<description><![CDATA[Visual Basic 6 programmers are protected from the "real world". The upside is that VB programmers really can get much more useful things done in less time, the downside is that there are limits for what you can do in VB... and the fact that VB's behavior sometimes can be really, really strange.]]></description>
			<content:encoded><![CDATA[<p><em>Please note, that what is describe in this article may at some times be a very simple version of how things really work. Also, please forgive me for generalizing a little bit. <img src='http://henko.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </em></p>

<p>Visual Basic 6 programmers are protected from the &#8220;real world&#8221;. The real world contains dangerous things like the Windows <acronym title='Application Programming Interface'>API</acronym>, <acronym title='Component Object Model'>COM</acronym>, <acronym title='Active Template Library'>ATL</acronym>, <acronym title='Microsoft Foundation Classes'>MFC</acronym> and other scary stuff. To make contact with the real world, one often has to use <code>Declare</code> statements, which no VB6 programmer really likes. And by the way, what does these &#8220;memory leaks&#8221; people are talking about all the time mean anyway? Ok, I&#8217;m exaggerating, but you get the picture. VB programmers are protected, for good and for bad. The upside is that VB programmers really can get much more useful things done in less time, the downside is that there are limits for what you can do in VB&#8230; and the fact that VB&#8217;s behavior sometimes can be really, really strange.</p>

<p>Even though VB programmers do not have to care about all those weird things &#8220;out there&#8221;, Visual Basic itself lives in the same world as any other program. Therefore, it has to do all the nasty stuff, but it will (try to) hide it from the programmers so we don&#8217;t have to care. Well, at least as long as we stay away from those <code>Declare</code> statements. We kind of expect weird things to happened when we use them, don&#8217;t we? Therefore, we often try to stay clear form the Windows API. I mean, if we&#8217;re only using VB&#8217;s own class modules we&#8217;re safe, right? Well, unfortunately not. At least not when using the <code>Implements</code> keyword.</p>

<h3>What the heck is &#8220;Implements&#8221;?</h3>

<p>Perhaps you&#8217;ve never encountered the keyword <code>Implements</code> before. It is one of the few object oriented features in the Visual Basic language, and it is a darn useful thing. If you feel that you need to learn more about it, take a look at the Visual Basic <a href="http://www.henko.net/link?http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconinheritancepolymorphismallthat.asp" title="Programmer's Guide">Programmer's Guide</a>. For now, I&#8217;ll just try to give a short explanation of it.</p>

<p>The <code>Implements</code> statement is used to separates the <em>interface</em> of an object from its <em>implementation</em>. This means that many different objects with different implementations and behavior can all called through a single interface which they all implement. The interface can be seen as a contract between the caller and the callee (the object being called), that says &#8220;I, the callee, promise to answer nicely (even though you don&#8217;t know me directly) if you only call the methods defined in this interface which I implement.&#8221; The caller can then handle objects of different classes which implement a common interface as being objects of the common interface type, and don&#8217;t care about exactly what kind of object it is actually calling.</p>

<p>The <code>Implements</code> keyword is used in the declaration area (at the top) of a class module. In the following example, the class module implements the interface <code>ISomeInterface</code> (interfaces are often prefixed by the letter <code>I</code> in Windows programming).</p>

<pre><code>Implements ISomeInterface
</code></pre>

<p>The interface <code>ISomeInterface</code> is another class module (called <code>ISomeInterface</code>) which contains any number of subroutines, functions and properties but with no real implementation. That is, all method bodies are empty.</p>

<h4>Example</h4>

<p>The result is that we can write code like this.</p>

<pre><code>' Class FileLogger implements interface ILogger
' and knows how to write a string to a normal file
' on a hard drive
Dim fl As New FileLogger
' Class NetworkLogger implements interface ILogger 
' and knows how to send a string to a server
Dim nl As New NetworkLogger

Public Sub Main
    ' You can send any of these two objects to
    ' the function SetLogger
    SetLogger nl ' Could as well have been fl
End Sub

Public Sub SetLogger(logger As ILogger)
    ' Do something useful with the logger we are
    ' given...
End Sub
</code></pre>

<p>The nice thing here is that we may change between the <code>FileLogger</code> and the <code>NetworkLogger</code> at any time during runtime. The whole point is that a piece of code can use an object without knowing (or caring) exactly what type of object it is, as long as it knows what it can do.</p>

<p>In this example, the code for the <code>Logger</code>-classes and the <code>ILogger</code> interface was not provided, se the <a href="http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconinheritancepolymorphismallthat.asp" title="Programmers' Guide">Programmers' Guide</a> mentioned above for more detailed examples.</p>

<p>This could also be done by simply setting the argument type to <code>Object</code>, but that would not be as good as we inside the <code>SetLogger</code> procedure would have no guarantee that the given object actually was a logger.</p>

<h3>Looking at some code</h3>

<p>So, now that we know something about interfaces and the <code>Implements</code> keyword, what was the this article&#8217;s title all about? Since when can doing nothing make the program crash? Easy now, I&#8217;ll come to that, and in order to do so, I need to create a small example.</p>

<p>Let&#8217;s create a class module called <code>MyClass</code> which implements the interface <code>ISomeInterface</code> (which is another class module). The interface <code>ISomeInterface</code> can completely empty or define as many functions as you like, it does not matter for this example. The class <code>MyClass</code> looks as follows:</p>

<pre><code>' This means that we promise to implement all
' methods and properties defined in ISomeInterface
Implements ISomeInterface

' Code for any methods defined in ISomeInterface...

' This property is not defined in the interface,
' it exists only in MyClass
Public Property Get ClassProperty() As String
    ClassProperty = "Inside ClassProperty()!"
End Property
</code></pre>

<p>So, with these two classes (or one class and one interface, if you prefer), let&#8217;s take a look at the program&#8217;s <code>Main</code> subroutine.</p>

<pre><code>Private Sub Main()
    Dim c As MyClass
    Set c = New MyClass
    Test c
End Sub

Private Sub Test(o As Object)
    MsgBox o.ClassProperty
    MsgBox o.ClassProperty
End Sub
</code></pre>

<p>This really isn&#8217;t anything fancy. We just create an object and sends it into a function which will call a property on it two times. It is rather obvious what the result will be; it will show two message boxes with the text &#8220;Inside ClassProperty()!&#8221;.</p>

<p>As a side note, I might mention that at this point, a programmers used to more traditional object oriented languages such as e.g. Java might be a bit puzzled. In a more strict world, it would not be possible to access <code>ClassProperty</code> inside the <code>Test</code> method because we do not know that <code>o</code> is of type <code>MyClass</code>. VB&#8217;s <code>Object</code> type is rather forgiving though and automatically tries to cast the object. A runtime error will be generated if that function did not exist.</p>

<p>Back to Visual Basic land. Now, let&#8217;s modify the situation slightly. We create a new subroutine called <code>DoNothing</code> which simply does not do anything (although we will se later, it is not totally innocent). In <code>Test</code>, we also add a call to this routine into which we send our object <code>o</code> (which we know actually is an object of type <code>MyClass</code>). We add the call between the two <code>MsgBox</code> calls. (Obviously, in real life, it would be rather unnecessary to create a method which does not do anything. In this case, I make it empty just to prove that the actual code in the function has nothing to do with the problem we soon will see.)</p>

<pre><code>Private Sub Test(o As Object)
    MsgBox o.ClassProperty
    DoNothing o
    MsgBox o.ClassProperty
End Sub

Private Sub DoNothing(i As ISomeInterface)
End Sub
</code></pre>

<p>We see now that the function <code>DoNothing</code> takes the argument as a <code>ISomeInterface</code>. That is okay with us however, since our object is of type <code>MyClass</code> which implements <code>ISomeInterface</code>. So, if we would run the code again now, surely we would get the same result as last time we run it? Well, no, we don&#8217;t. It would crash! To understand this, we will have to make another digression. It&#8217;s time to take a look at the empty space between the <code>(</code> and the <code>i</code> in the <code>DoNothing</code> function definition.</p>

<h3>Would you like your object by value or by reference?</h3>

<p>To understand what&#8217;s going wrong, we will have to understand the difference between sending an argument <em>by value</em> and <em>by reference</em>.</p>

<h4>Primitive data types</h4>

<p>We&#8217;ll start by looking at how primitive types such as <code>Integer</code> or <code>Double</code> are handled using the following example.</p>

<pre><code>Public Sub Main()
    Dim x As Integer
    x = 1
    DoSomething(x)
End Sub

Public Sub DoSomething(ByVal y As Integer)
    y = 2
End Sub
</code></pre>

<p>When dealing with primitive data types there really is no problem. In the case above, where <code>y</code> is sent by <em>value</em>, the value in <code>y</code> will be a <em>copy</em> of the value in <code>x</code>. That means that no matter what you do to the variable <code>y</code> inside the function <code>DoSomething</code>, the variable <code>x</code> will not change.</p>

<p>If we change the code so that the argument <code>y</code> is sent <em>by reference</em> using the <code>ByRef</code> keyword the situation will be different. In that case, the variable <code>y</code> will contain the <em>reference</em> to the value of <code>x</code>. This means that any changes made to <code>y</code> inside the function <em>will</em> also happened to the variable <code>x</code> on the outside. This is because both the variable <code>x</code> and <code>y</code> references the <em>same</em> value.</p>

<p>In other languages, such as C++, these references are called pointers. Some believe that pointers are God&#8217;s gift to man, while other tend to think that they are not to be trusted. Once again, we come back to the fact that VB programmers are protected from the &#8220;real world&#8221;; Visual Basic manages quite well to hide the difference between a value and a pointer to a value. Very well, to be honest. To recapitulate, if a method accepts an argument <code>ByVal</code>, you will get a copy of the actual <code>value</code> whereas if the argument is defined <code>ByRef</code> you actually get a <code>pointer-to-value</code>. Ok?</p>

<h4>Objects</h4>

<p>Now, in a nice world, variables containing objects would have worked in the same way. Unfortunately, we do not live in a nice world. The problem is that objects tend to be much larger in terms of memory than ordinary primitive data types. Because Visual Basic does not want to shuffle around large blocks of memory all the time, it just shuffles around a <em>pointer</em> to the object in question. This means, that at any time, you never really store an <code>object</code> in your variables but rather a <code>pointer-to-object</code>.</p>

<p>Let&#8217;s take a look at the a piece of code with variables containing objects.</p>

<pre><code>Public Sub Main()
    Dim x As MyClass
    Set x = New MyClass
    x.ClassProperty = 1
    DoSomething(x)
End Sub

Public Sub DoSomething(ByVal y As MyClass)
    y.ClassProperty = 2
    Set y = someOtherMyClassObject
End Sub
</code></pre>

<p>In this example, <code>y</code> will contain a copy of the <code>pointer-to-object</code> which was sent in (i.e. <code>x</code>). However, this does not mean that any changes (such as <code>y.ClassProperty = 2</code>) made to the object <code>y</code> holds does not also happened to the object which <code>x</code> holds, because like in the case with <code>ByRef</code> for primitive data types what we&#8217;ve got is a that <code>x</code> and <code>y</code> are actually referencing the very same object. The last line in <code>DoSomething</code> will not affect <code>x</code> however, only <code>y</code>.</p>

<p>As you might imagine, the really interesting part is objects sent by reference. If you do this (which you probably do all the time), <code>y</code> will actually contain a <code>pointer-to-pointer-to-object</code>. Phew! That means that not only can you still change the object which both variables (indirectly) are pointing to, but you can also change the <em>pointer</em> <code>x</code>. In other words, by pointing <code>y</code> to another object, you also change what object <code>x</code> is pointing to.</p>

<h4>By reference is default</h4>

<p>In C++ sending the values themselves is the &#8220;normal&#8221; way of doing things and you will have to specifically show the compiler that you want to send a pointer to something instead. However, in Visual Basic the situation is the opposite. This means that if you do not write either <code>ByVal</code> or <code>ByRef</code> with your arguments, they will be sent by reference. Specifying <code>ByRef</code> is therefore strictly speaking not necessary though it is a good idea to do it anyway, since the intent will become more clear.</p>

<h3>Why doing nothing may crash the program</h3>

<p>Let&#8217;s go back to the code. As we just learned, <code>ByRef</code> is the default way of sending arguments in Visual Basic. Therefore the method <code>DoNothing</code> could be written the following way instead.</p>

<pre><code>Private Sub DoNothing(ByRef i As ISomeInterface)
End Sub
</code></pre>

<p>This means, that when we think we are sending the object <code>o</code> to <code>DoNothing</code>, we are actually sending a <code>pointer-to-pointer-to-MyClass</code> along with it. However, the <code>DoNothing</code> method expects a <code>pointer-to-pointer-to-ISomeInterface</code> as argument. Well, no problem says VB, I&#8217;ll just convert it for you since I know that <code>MyClass</code> implements <code>ISomeInterface</code>. This is where things go wrong.</p>

<p>You see, we&#8217;re dealing with two pointers; the first one which points to a <code>pointer-to-MyClass</code> and the second one which points to the <code>MyClass</code> interface of the actual object we&#8217;re referreferring. The first pointer comes from the fact that we passed our object by reference. The second one comes from the fact that VB never sends actual objects between functions but rather pointers to objects. This is the very same pointer which was stored in <code>o</code>.</p>

<p>So, what happens when VB converts the argument from <code>MyClass</code> to <code>ISomeInterface</code> is that it modifies the <em>second</em> pointer to be a <code>pointer-to-ISomeInterface</code> instead. That means that we also change the pointer which was stored in <code>o</code>. In other words, after the call to the <code>DoNothing</code> method, the reference on the outside has changed to become a <code>pointer-to-pointer-to-ISomeInterface</code> although it was a <code>pointer-to-pointer-to-MyClass</code> before we entered <code>DoNothing</code>. And because <code>ISomeInterface</code> does not contain the property <code>ClassProperty</code>, the code will crash on the second <code>Msgbox</code> call.</p>

<h3>How to not crash the program</h3>

<p>Now we just need to figure out what to do in order to make the program act as we expected (i.e. not crash). We only need to make a small modification; make sure that the object is sent by value rather than by reference. That way, the <code>pointer-to-ISomeInterface</code> which is stored in <code>y</code> will only be a copy of the pointer stored in <code>x</code>. Any changes to it that VB does will therefore not affect <code>x</code>.</p>

<pre><code>Private Sub DoNothing(ByVal i As ISomeInterface)
End Sub
</code></pre>

<p>And now, the method <code>Test</code> will show two message boxes with the string &#8220;Inside MyClass()!&#8221;, just as we initially wanted.</p>

<h3>Other solution</h3>

<p>Note that there is also another way of solving this problem. In fact, the whole problem arises because of sloppy programming. The person who wrote the <code>Test</code> procedure should have defined the argument <code>x</code> as being of type <code>MyClass</code>, because that is what we use it as.</p>

<p>But in case you haven&#8217;t noticed, there are actually times where you do have to handle code which is in a less-than-perfect state. <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/why-doing-nothing-may-crash-your-program/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.613 seconds -->
