<?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>Gridshore &#187; software design</title>
	<atom:link href="http://www.gridshore.nl/tag/software-design/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gridshore.nl</link>
	<description>A weblog about software engineering, Architecture, Technology an other things we like.</description>
	<lastBuildDate>Tue, 13 Dec 2011 15:36:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>The power of immutability in a Rich Domain Model</title>
		<link>http://www.gridshore.nl/2009/04/06/the-power-of-immutability-in-a-rich-domain-model/</link>
		<comments>http://www.gridshore.nl/2009/04/06/the-power-of-immutability-in-a-rich-domain-model/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 19:00:00 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[domain model]]></category>
		<category><![CDATA[software design]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=696</guid>
		<description><![CDATA[<p>As many other developers, I’ve been used to the fat service layer and the anemic domain model of the transaction script pattern. In that programming model, immutability is pretty much as rare as a Dodo. However, I have been investigating the rich domain model pattern lately (as you can read in my previous post) [...]]]></description>
			<content:encoded><![CDATA[<p>As many other developers, I’ve been used to the fat service layer and the anemic domain model of the <a href="http://martinfowler.com/eaaCatalog/transactionScript.html" target="_blank">transaction script</a> pattern. In that programming model, immutability is pretty much as rare as a <a href="http://en.wikipedia.org/wiki/Dodo" target="_blank">Dodo</a>. However, I have been investigating the rich domain model pattern lately (as you can read in my <a href="http://www.gridshore.nl/2009/01/27/injecting-domain-objects-with-spring/">previous post</a>) and more importantly, a good migration path for “<a href="http://martinfowler.com/eaaCatalog/transactionScript.html" target="_blank">transaction script</a>” developers to get acquainted with the rich <a href="http://martinfowler.com/eaaCatalog/domainModel.html" target="_blank">Domain Model</a>, a design pattern that has been heavily underrated (and misunderstood) by many.</p>
<p>In this post, I will explain some of the advantages that immutable domain objects bring us, while showing that some of the seemingly problematic side effects aren’t really that problematic.</p>
</p>
<p> <span id="more-696"></span>
</p>
<p>A practical example is often the easiest way to explain these kind of things. Since the banking world has received enough discredit in these times, I will use another example than the infamous “withdrawal” example. Instead, we will use the almost-as-infamous product and order example.</p>
<p>Imagine an application where you can browse trough products and place an order for one or more of those products. Our simple domain will contain three entities: product, order and order line. A UML class diagram for this domain is shown below.</p>
<p><img title="power_of_immutability_class_diagram_1" style="border-top-width: 0px; display: block; border-left-width: 0px; float: none; border-bottom-width: 0px; margin-left: auto; margin-right: auto; border-right-width: 0px" height="216" alt="power_of_immutability_class_diagram_1" src="http://www.gridshore.nl/wp-content/uploads/power-of-immutability-class-diagram-12.jpg" width="323" border="0" /></p>
<h3>The anemic approach</h3>
<p>A commonly seen approach to implement this domain model is the following. The Order is implemented containing some delivery details and a list of order lines. The Order exposes getters and setters to modify each of those properties, including a getter that provides access to the list of order lines. The implementation of the OrderLine class is similar; it might contain a reference to a Product instance as well as a property to indicate the quantity ordered, resulting in the following code:</p>
<pre>
<pre class="brush: java; title: ; notranslate">
public class OrderLine {
    private Product product;
    private int quantity; 

    public Product getProduct() {
        return product;
    } 

    public void setProduct(final Product product) {
        this.product = product;
    } 

    public int getQuantity() {
        return quantity;
    } 

    public void setQuantity(final int quantity) {
        this.quantity = quantity;
    }
}
</pre>
</pre>
<p>This code has a few problems, some functional and some technical</p>
<ul>
<li>What happens if the price of the product changes? Invoices will probably show the new price (which is always higher, for some reason). </li>
<li>It’s no longer possible to delete a product, since you won’t be able to see what somebody ordered </li>
<li>You allow every other class in your application to modify the OrderLine at will. What if you have a discount for customers that order for a certain amount? Each time an order line was modified, your code would have to call a <code>calculateDiscount</code> in your order </li>
<li>If you want to calculate the total price of an order, you would have to iterate through all OrderLine and Product instances. </li>
</ul>
<p>Of course, each of those problems can be solved some way or another, but whatever you do to solve them, it only adds to the complexity already there.</p>
<h3>The immutable approach</h3>
<p>Making the OrderLine immutable will solve some of the problems outlined above. The state of immutable objects is exclusively set in the constructor, meaning that both the Product and quantity will have to be passed as constructor parameters.</p>
<p>To solve the problem of the Product changing state, we can copy some of the important fields into the OrderLine. Good candidates for copying are the product identifier, the product name and its price. In fact, we don’t need any reference to the original Product instance at all after the OrderLine has been constructed.</p>
<p>The implementation of the immutable OrderLine is then changed into the following:</p>
<pre>
<pre class="brush: java; title: ; notranslate">
public class OrderLine {

    private final String productIndentifier;
    private final String productName;
    private final Price itemPrice;
    private final Price totalPrice;
    private final int amount;

    public OrderLine(Product product, int amount) {
        this.productIndentifier = product.getIdentifier();
        this.productName = product.getName();
        this.itemPrice = product.getPrice();
        this.totalPrice = itemPrice.multiply(amount);
        this.amount = amount;
    }

    /* getters not shown for brevity */
}
</pre>
</pre>
<p>All problems solved? Well, no, not really. For starters, the last two problems enumerated above are still not solved. And then there is persistence. I use hibernate for nearly every project that requires persistence. Hibernate and immutable objects are not the best friends possible. Hibernate requires a non-private default constructor. Doesn’t seem like a problem, just add a no-argument constructor to you class. But then the <code>final</code> keyword ruins the game. You’ve got no other choice than to remove it. This removed the guaranteed visibility when your class is accessed by different threads at the same time. Solving that is a totally different ballgame and would carry me way off topic.</p>
<h3>Using an aggregate root</h3>
<p>We still have the problem that our discount is not updated when OrderLine instances are added or removed from an order. Making an order immutable in the same fashion would solve the problems. But let’s assume that a user is allowed to update and modify his orders as long they haven’t been processed by the system.</p>
<p>Exposing the list of OrderLine entries inside an order is not a good way to go, since your order is not in charge of its own lifecycle. If you take a close look at the UML diagram above, you will notice there is a composite relationship between the Order and OrderLine classes. This means that the Order class is responsible for the lifecycle of the OrderLine items that belong to it. In Domain Model terms, this means that Order is the <a href="http://domaindrivendesign.org/discussion/messageboardarchive/Aggregates.html" target="_blank">Aggregate Root</a> of these components.</p>
<p>The order would then be implemented as follows:</p>
<pre>
<pre class="brush: java; title: ; notranslate">
public class Order {

    private final List&lt;orderline&gt; orderLines = new ArrayList&lt;orderline&gt;();
    private final Customer customer;
    private Address shippingAddress;
    private Price totalAmount;

    public Order(Customer customer) {
        this.customer = customer;
    }

    public List&lt;orderline&gt; getOrderLines() {
        return Collections.unmodifiableList(orderLines);
    }

    public void addToOrder(Product product, int amount) {
        removeFromOrder(product);
        final OrderLine orderLine = new OrderLine(product, amount);
        orderLines.add(orderLine);
        totalAmount = totalAmount.add(orderLine.getTotalPrice());
        calculateDiscount();
    }

    public void removeFromOrder(Product product) {
        // implementation left to your imagination
    }

    /* rest of implementation left out for brevity */
}
</pre>
</pre>
<p>As you can see, a high level of encapsulation has been applied. It is now impossible to change any state of the Order or OrderLine without the Order knowing it. The list of OrderLine items that the Order exposes is made immutable using the utility method in the Collections class.</p>
<p>With this implementation, it the latter two of the problems enumerated above have been solved. Since the order is in charge of making the changes to its own state, it is rather easy to discover state changes that might impact applicable discounts or change the total amount of the order. Now, getting access to the amount of the order is as easy as returning the <code>totalAmount</code> property from the Order.</p>
<h3>Conclusion</h3>
<p>In this post, I’ve introduced a very powerful concept to manage the state of complex domain models: immutability. By preventing the application to change state directly, you gain more control over the the actions that need to be taken when the state changes. Especially in aggregates, immutability reduces the complexity of state management.</p>
<p>However, when using Hibernate, it is impossible to make an entity completely immutable using the final keywords. In that case it is sufficient to create a default constructor with package visibility and removing the final keywords.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F04%2F06%2Fthe-power-of-immutability-in-a-rich-domain-model%2F&amp;title=The%20power%20of%20immutability%20in%20a%20Rich%20Domain%20Model&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/04/06/the-power-of-immutability-in-a-rich-domain-model/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Bring some stability to your architecture</title>
		<link>http://www.gridshore.nl/2008/10/30/bring-some-stability-to-your-architecture/</link>
		<comments>http://www.gridshore.nl/2008/10/30/bring-some-stability-to-your-architecture/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 20:44:56 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[software design]]></category>
		<category><![CDATA[stability]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2008/10/30/bring-some-stability-to-your-architecture/</guid>
		<description><![CDATA[<p>Applications have to run in high-consequence environments. They have to serve hundreds of thousands of users 24 / 7. Our clients spend millions in hard- and software and highly depend on the revenue generated by these applications. Unnecessary outage of these application is fatal.</p> <p>Software Architects play an important role in setting up an [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/circuitbreaker.jpg" alt="circuitbreaker" hspace="5" vspace="5" width="90" height="89" align="left" />Applications have to run in high-consequence environments. They have to serve hundreds of thousands of users 24 / 7. Our clients spend millions in hard- and software and highly depend on the revenue generated by these applications. Unnecessary outage of these application is fatal.</p>
<p>Software Architects play an important role in setting up an architecture that can cope with these high demands. At the JAOO, <a href="http://www.michaelnygard.com">Michael Nygard</a>&#8216; had a talk, &#8220;<a href="http://jaoo.dk/aarhus-2008/tracks/show_track.jsp?trackOID=187">Failure comes in Flavors</a>&#8220;, that gave very good insight in the risks and opportunities of today&#8217;s application. The talk was was divided into two sessions. The first session covered the bad news: the stability threats. He discussed several situations that pose a threat to the long and happy life of an application. The second session was a happier one. It covered the patterns that should be applied to the application architecture to prevent these threats.</p>
<p>In this post, I will elaborate on some of the stability threats and pick one specific pattern to resolve them: the circuit breaker.</p>
<p><span id="more-384"></span></p>
<p><strong>Stability</strong></p>
<p>Before we go on about the stability threats, we need a common understanding about what stability is.</p>
<p>Michael Nygard defines stability as &#8220;the consistent, long-term availability of features&#8221;, and can be divided into four different qualities:</p>
<ul>
<li>Severability; instead of crashing completely, only loose the functional area&#8217;s that are struck by failure</li>
<li>Resilience; automatically recover from failures</li>
<li>Recoverability; make sure only crashed components need to be restarted, not the entire application</li>
<li>Tolerance; absorb shocks from other components instead of propagating them</li>
</ul>
<p>Note that stability doesn&#8217;t mean that nothing will ever go wrong. It just states that when something does go wrong, only the features of the applications directly related to the struck component become unavailable, and only until the component comes up again.</p>
<p><strong>Stability threats</strong></p>
<p>The life of a web application developer is interesting. We build applications that are hosted in the most hostile environment imaginable: the internet. People can travel at light speed, nearly invisible and have all the power to bring your application down, willingly or accidentally. In fact, more application crash because of accidental abuse than of hackers.</p>
<p>This brings us to the first threat: the <em><span style="text-decoration: underline;">user</span></em>. Unfortunately, the user pays for our client&#8217;s income (and ours too). We&#8217;ll have to deal with them.</p>
<p>Several aspects of the users behavior pose a threat for our application:</p>
<ul>
<li>Users don&#8217;t wait. If a page doesn&#8217;t show up quickly enough, he&#8217;ll push the link again, starting two threads to work for him, only wonderings the situation</li>
<li>Users write about cool stuff and come to your site after reading that stuff. This may cause a sudden burst of users, possibly overloading your site</li>
<li>Buyers will use all integration points, causing traffic in every little corner of your application</li>
<li>Some users aren&#8217;t actually users, but bots, and may cause unused sessions to be created for them</li>
<li>Users only visit your site when they&#8217;re awake, causing traffic surges at daytime, while your processors wait for orders at night.</li>
</ul>
<p>A threat briefly mentioned above is the <span style="text-decoration: underline;"><em>integration point</em></span>. This is the point where your application meets another. An example of this is the database or an external payment provider.</p>
<p>Integration points are dangerous for a couple of reasons:</p>
<ul>
<li>External systems typically have to be reached over a network connection, making the integration dependent of ever more components</li>
<li>Ever had the problem of a firewall dropping your packets? It&#8217;s a nice way of not being able to set up a connection without getting any feedback about why this happens.</li>
<li>Some external systems just keep you waiting. If your payment provider is busy, they&#8217;ll be happy to keep you waiting. But will your user wait? How many threads will clog up and the integration point, waiting for a response?</li>
</ul>
<p>I could go on for a long time, but these are the two threats that I want to cover in this post. If you want more, read Michael Nygard&#8217;s book &#8220;Release It&#8221;.</p>
<p><strong>Stability patterns</strong></p>
<p>Fortunately, there is a series of patterns that can be applied to increase an application stability. One of these patterns is the <span style="text-decoration: underline;"><em>circuit breaker</em></span>. You&#8217;re most likely familiar with the electrical circuit breaker. When you have an electricity leak or high power throughput, the circuit breaker will open and stop the electrical current. You&#8217;ll be in the dark, but at least your television, washing machine and music installation are saved from destruction.</p>
<p>Now, imagine your database has a hard time keeping up with your amount of requests. It will probably take longer to process each request, causing even more requests to pile up. In the end, your database server might break, taking your application with it. That is the time where we need a circuit breaker to stop the current from going to our database. I&#8217;m talking about digital current here, not electricity. Let&#8217;s keep that fans turning on the hardware!</p>
<p>A software circuit breaker should do a few things. Most important is that is should monitor each call performed on a specific backend. When a certain amount of calls fail or take too long, the circuit breaker opens, blocking the current. Each request coming in when the circuit breaker is opened will result in an immediate failure, throwing the last exception that was received from the last call. This has two positive effects: your thread returns more quickly and the load on the external system is relieved, allowing it to recover.</p>
<p>After a certain period of time, the circuit breaker will let a single request pass through to the backend. If that call fails, nothing changes. If the call succeeds, the circuit breaker will close, allowing the requests to pass through to the external system.</p>
<p>The number of use cases for a circuit breaker is most likely limited by our imagination. A nice one I could think of was to limit functionality when load becomes too high. Typically, this would be the functionality that is &#8220;nice to have&#8221;, but not essential to your application. To do this, your code would have to inspect the state of the circuit breaker when deciding which options are made available to your user. Do keep in mind though, that limiting functionality might cause your circuit breaker to sit and wait for requests which don&#8217;t come, never closing it. You&#8217;ll need another mechanism for detecting when it can be closed.</p>
<p><strong>Implementing the circuit breaker</strong></p>
<p>I&#8217;ve been playing around with a small circuit breaker implementation. You can find the code in our <a href="http://gridshore.googlecode.com/svn/trunk/StabilityPatterns/" target="_blank">code repository</a>. It&#8217;s really small, but seemed really powerful.</p>
<p>There are 2 main components in the application.</p>
<ul>
<li>The interceptor is responsible for intercepting calls to the external system and sending the requests and responses to the circuit breaker [<a title="AnnotatedMethodCircuitBreakerInterceptor.java" href="http://gridshore.googlecode.com/svn/trunk/StabilityPatterns/circuitbreaker/src/main/java/nl/gridshore/stability/circuitbreaker/AnnotatedMethodCircuitBreakerInterceptor.java" target="_blank">see code</a>]</li>
<li>The circuit breaker itself decides if requests should be sent and what should happen when responses are received [<a title="SimpleCircuitBreaker.java" href="http://gridshore.googlecode.com/svn/trunk/StabilityPatterns/circuitbreaker/src/main/java/nl/gridshore/stability/circuitbreaker/TimedSpringJmxCircuitBreaker.java" target="_blank">see code</a>]</li>
</ul>
<p>To find out if a circuit breaker is actually useful, I&#8217;ve done a few load tests. I&#8217;ve ran these tests against the same application twice. Once with circuit breaker and once without. The results are promising.</p>
<p>When activated, the circuit breaker will cause failures to append a lot faster than when there is none. This means threads are released much faster, allowing the next unfortunate user to receive the error. Of course, it doesn&#8217;t help your user much, but at least you&#8217;ll be able to tell him something is wrong instead of giving him a timeout after 30 seconds.</p>
<p>Don&#8217;t believe me? Have a look at the screen shots of the meter tests below:</p>
<p align="center"><a href="http://www.gridshore.nl/wp-content/uploads/250threads_target_throughput_50.png" target="_blank"><img src="http://www.gridshore.nl/wp-content/uploads/250threads-target-throughput-50-small.jpg" alt="250threads target throughput 50" hspace="5" vspace="5" width="225" height="137" /></a><br />
250 concurrent threads with a targeted throughput of 50 requests per second. The circuit breaker variant doesn&#8217;t have any failed calls, while the normal implementation has more than 40% failures.</p>
<p align="center"><a href="http://www.gridshore.nl/wp-content/uploads/250threads_target_throughput_100.png" target="_blank"><img src="http://www.gridshore.nl/wp-content/uploads/250threads-target-throughput-100-small.jpg" alt="250threads target throughput 100" hspace="5" vspace="5" width="225" height="137" /></a><br />
250 concurrent threads with a targeted throughput of 100 requests per second. This is where the circuit breaker variant seems to have it&#8217;s first failures.</p>
<p align="center"><a href="http://www.gridshore.nl/wp-content/uploads/1000thread_burst.png" target="_blank"><img src="http://www.gridshore.nl/wp-content/uploads/1000thread-burst-small.png" alt="1000thread burst" hspace="5" vspace="5" width="225" height="61" /></a><br />
And finally, a 1000 thread burst, just to see what happens if you spam tomcat with 1000 concurrent, continuously refreshing users. It&#8217;s 80% failure against 32% for the circuit breaker.</p>
<p><strong>Conclusion</strong></p>
<p>In this post, I&#8217;ve covered two of the stability threats that can be prevented by a correct implementation of the circuit breaker pattern. Our <a title="Gridshore SVN repository - Stability Patterns" href="http://gridshore.googlecode.com/svn/trunk/StabilityPatterns/" target="_blank">svn code repository</a> contains example code of an implementation of a circuit breaker. And finally, I&#8217;ve shown some unit test results to demonstrate the advantage of applying a circuit breaker to your architecture.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F10%2F30%2Fbring-some-stability-to-your-architecture%2F&amp;title=Bring%20some%20stability%20to%20your%20architecture&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/10/30/bring-some-stability-to-your-architecture/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Dihydromonoxide: what&#8217;s in a name?</title>
		<link>http://www.gridshore.nl/2008/08/06/dihydromonoxide-whats-in-a-name/</link>
		<comments>http://www.gridshore.nl/2008/08/06/dihydromonoxide-whats-in-a-name/#comments</comments>
		<pubDate>Wed, 06 Aug 2008 21:29:01 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[software design]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2008/08/06/dihydromonoxide-whats-in-a-name/</guid>
		<description><![CDATA[<p>Does the name dihydromonoxide sound in any way familiar to you? It should (really, it should). Try googling it (here, I&#8217;ll make it easy for you). If and when you do google it, you will be informed by all sorts of sites of the various properties and dangers of this chemical compound. This one, [...]]]></description>
			<content:encoded><![CDATA[<p>Does the name <em>dihydromonoxide</em> sound in any way familiar to you? It should (really, it should). Try googling it (here, I&#8217;ll <a href="http://www.google.com/search?hl=en&amp;q=dihydromonoxide&amp;btnG=Google+Search&amp;meta=">make it easy for you</a>). If and when you do google it, you will be informed by all sorts of sites of the various properties and dangers of this chemical compound. <a href="http://www.gumbopages.com/fridge/dmho.html">This one</a>, for instance, covers all the dangers of dihydromonoxide (or DHMO) in great and completely accurate detail.</p>
<p>Of course dihydromonoxide and the many warnings against it are all based on a clever use of words. Seen in that light dihydromonoxide is a wonderful example of something I was taught by a professor of mine at university (and reminded of a couple of times today): Shakespeare may have prattled on about <a href="http://en.wikiquote.org/wiki/Romeo_and_Juliet#Act_II">roses by any other name</a>, but in reality notation is absolutely everything in our business.</p>
<p> <span id="more-180"></span>
<p>Here&#8217;s (another) example of the importance of notation: derivation. Derivation as in calculus, which you were taught in highschool. I&#8217;m sure everybody remembers doing endless sums about calculating the derivative function <em>f &#8216;(x)</em> of a given function <em>f(x)</em>, quickly followed by the second derivative <em>f &#8221;(x)</em> and possibly even the third derivative <em>f<sup>(3)</sup>(x)</em> and fourth derivative <em>f<sup>(4)</sup>(x)</em>. And I&#8217;ll bet most of you never even knew (or cared) about the fact that there are a number of different notations in use for a derivative. But there are; and of these, the three most well-known are the Newton notation (which indicated derivation against a function by placing one or more dots above the functor), the Lagrange notation (the notation with the primes used most often for first and second derivative) and the most commonly used of all, the Leibniz notation (which a number in parentheses, an analog to the power-of or exponent notation). Of these, the Leibniz notation is most often used in mathematics. And the reason is simple: once you get beyond second derivatives, the other notations get to be very cumbersome.</p>
<p>Notation is an important factor in our work as computing scientists and software engineers. It often makes the difference between making a piece of software easy to use or cumbersome and unusable. Sometimes it also makes the difference between making a problem easy to solve and difficult. Back in university, for instance, there were a number of courses where we derived solutions to problems from a formal specification. This process involved using <a href="http://en.wikipedia.org/wiki/Predicate_Calculus">predicate calculus</a>, which is very powerful but often cumbersome. However, introducing a useful notation and proving some simple properties of this notation could often greatly reduce the burden of proof in these exercises.</p>
<p>Another example of notation making life easier is a pattern that I&#8217;ve employed quite often over the past few years when applying the <a href="http://en.wikipedia.org/wiki/Strategy_pattern">strategy pattern</a>: in order to select the correct strategy for a specific case, instead of using a gigantic pile of <code>if</code>-statements, I prefer to put instances of all my different strategies in a hashtable using a representative for each case (like a <code>Class</code> instance) as the key. The result looks a little like this:</p>
<p>
<pre class="brush: java; title: ; notranslate">
private Map strategyMap = ...; // Instantiate this somehow 

public void applyStrategyToASpecificCase(final Object theCase)
{
     strategyMap.get(theCase.getClass()).applyTo(theCase);
} </pre>
</p>
<p>One of the reasons I like this, by the way, is that it also mixes well with dependency injection frameworks like <a href="http://www.springframework.org/">Spring</a>.</p>
<p>Like I already said, I was reminded by my professor&#8217;s wise lesson a number of times today, both in the positive and in the negative sense. One such reminder occurred when I was working on some <a href="http://www.uml.org/">UML</a> diagrams using <a href="http://www.sparxsystems.com/products/ea/">Enterprise Architect</a> (which is a horror I hope you will all be spared). This series of diagrams includes a certain construct which occurs a large number of times in many different places. I quickly found myself wishing there was a simple way to create a shorthand notation for this construct. I was however pleasantly surprised to find that you can embed diagrams in other diagrams (both as embedded images and as symbolic links) and can drill down to them. This allows you to define subactivities for your activity diagrams, for instance. Now if only you could actually include the subactivity within the overall activity as an activity, rather than having to include an activity and put the diagram link next to that (but not connected to the diagram)&#8230;.</p>
<p>A second example I ran into is related to the definition of a web service interface that is currently being defined. This interface must provide for the inclusion of one or more pieces of configuration data that are retrieved from other XML documents. A very generic solution was chosen by defining a repeatable element called <code>Item</code>, which contains an <code>XMLElement</code> element and a <code>FieldValue</code> element. This solution certainly works, but I think that names like <code>ConfigurationItem</code>, <code>ConfigurationItemName</code> and <code>ConfigurationItemValue</code> are a bit more expressive and therefore make it easier to understand how to use the service.</p>
<p>Notation is one of those subtle little things that I think are too easily overlooked in software engineering, especially given the huge role it can play in making or breaking your system. Notation means the difference between an easily usable API and an airline terminal (ask a travel agent about it, if you&#8217;ve never seen one used). It means the difference between self-documenting, maintainable code and unmaintainable code. It can mean the difference between an easily comprehensible and codable solution and a solution that hurts your head just to come up with. It can aid you in achieving separation of concerns (if only by ordering your thoughts). It can even be the key to better-performing code for some problems.</p>
<p>The importance of notation in API design is one of the reasons I am quite enamoured of the notion of a <a href="http://www.martinfowler.com/bliki/FluentInterface.html">Fluent API</a>, by the way. This interface style promises to make APIs a lot easier to use and a lot less error prone albeit at the cost of requiring more thought on the part of the development team. One of my current projects is experimenting with Fluent APIs right now; I&#8217;ll dedicate a future blog to the outcome.</p>
<p>Whether the fluent style will work out or not, I can confirm right now that a clear and expressive interface is always a good idea: two of the projects I am involved with are moving from very generic, &#8220;you can put any parameter and value you want in this key-value pair list&#8221;-style of interfaces to interfaces that are very explicit about what is needed, what is allowed and what the effect and outcome will be; both projects are reporting far less aggravation in the implementation of their new services than they had previously. Note that the type of data that can be passed through the interface has not changed; just the way the interface forces the client to present this data. Like my professor said, notation is everything.</p>
<p>By the way, in case you were worried: dihydromonoxide (or H<sub>2</sub>O) is more commonly referred to as water&#8230;.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F08%2F06%2Fdihydromonoxide-whats-in-a-name%2F&amp;title=Dihydromonoxide%3A%20what%27s%20in%20a%20name%3F&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/08/06/dihydromonoxide-whats-in-a-name/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

