<?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>Alexandre Martins &#187; Design Patterns</title>
	<atom:link href="http://blog.m.artins.net/tag/design-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.m.artins.net</link>
	<description>On Agile Software Development</description>
	<lastBuildDate>Thu, 12 Aug 2010 20:09:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Seeking code quality</title>
		<link>http://blog.m.artins.net/seeking-code-quality/</link>
		<comments>http://blog.m.artins.net/seeking-code-quality/#comments</comments>
		<pubDate>Fri, 21 Sep 2007 21:23:11 +0000</pubDate>
		<dc:creator>Alexandre Martins</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Object-Oriented Programming]]></category>

		<guid isPermaLink="false">http://blog.m.artins.net/?p=17</guid>
		<description><![CDATA[This week, during another refactoring session, I had the idea that every time I come across code that needs to be modified to conform to one of the principles of best practices for software development, I'll modify it and share the solution through this blog, exploring its drawbacks, benefits gained by conforming to the principle [...]]]></description>
			<content:encoded><![CDATA[<p><img id="image42" src="http://m.artins.net/wp-content/uploads/2007/09/ideal.jpg" width="116" height="136" align="left" style="margin:4px; align:left;" />This week, during another refactoring session, I had the idea that every time I come across code that needs to be modified to conform to one of the principles of best practices for software development, I'll modify it and share the solution through this blog, exploring its drawbacks, benefits gained by conforming to the principle and also providing a brief explanation of it. Starting now with the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">OCP - Open-Closed Principle</a>.</p>
<h3>The Open-Closed Principle</h3>
<p>This principle is the foundation for building code that is maintainable and reusable. Modules that conform to this principle are, at the same time, <strong>"open for extension"</strong>, so that they can behave in different ways, as the requirements of the application are modified or as new ones are added. And <strong>"closed for modification"</strong>, which means that the module implementation cannot be violated, nobody can modify its source code.</p>
<p>The description above may seem quite contradictory, since to extend a module functionality, a code modification needs to be done. Therefore, we deduce that a functionality that cannot be modified is given as fixed. How could we deal with this conflict? The best way is to show it up through an example.</p>
<p>In my current project, there's a task manager module, which is responsible for executing asynchronous tasks queued up by its clients. Basically it iterates over all the elements in a pending tasks list and executes each of them, respecting the order they appear. The excerpt below shows how this class was implemented, it's a bit different from the original version, making it easier to understand.</p>
<pre name="code" class="java">
public class TaskManager {

    public List<Task> pendingTasks;

    public void executePendingTasks() {
        for (Task task : pendingTasks) {

            switch (task.type()) {
            case computeTrophies:
                engine.computeTrophies();
                break;

            case computeStatistics:
                engine.computeStatistics();
                break;

               // .... and so on ....
            }
        }
    }
}
</pre>
<p>The method <em>executePendingTasks()</em> doesn't conform to the Open-Closed Principle, because it cannot be closed against new task implementations. If your client suddenly comes up, asking you to extend the task manager module, to start handling a new task -- <em>this is always happening and since we're all agile, we're ready to handle it eh?</em> -- so this method will always have to be modified to support a new task. This can be easily done by inserting a new <em>case</em> statement, but it's far from an elegant solution. </p>
<p>Unfortunately most of developers follow this approach, the easier one (seemingly), specially when dealing with legacy code, when the solution is already "thought". All they have to do is follow the way the implementation has been done, not assessing it. Eventually, the code ends up with a huge number of lines (eighteen <em>case</em> statements in my case) and at that time, luckily, maybe a sensible developer will realize the code oddity and will try to improve its quality.</p>
<p>In the following excerpt, I'm showing the solution I gave to the problem, conforming to the OCP. Summarizing, the <em>Task</em> class is now abstract and I included an abstract method called <em>execute()</em>. Following this approach, ALL new tasks being created will be derivatives of this abstract class, providing their implementations of the <em>execute()</em> method.</p>
<pre name="code" class="java">
public class abstract Task {
    public abstract void execute();
}
</pre>
<pre name="code" class="java">
public class ComputeTrophiesTask extends Task {
    public void execute() {
        // logic to compute trophies...
    }
}
</pre>
<pre name="code" class="java">
public class ComputeStatisticsTask extends Task {
    public void execute() {
        // logic to compute statistics...
    }
}
</pre>
<p>And from now on, to our task manager, executing the pending tasks has became much easier. All it has to do is go through each of them and invoke their <em>execute()</em> method, resulting a cleaner, decoupled and non-intrusive code.</p>
<pre name="code" class="java">
public class TaskManager {

    public List<Task> pendingTasks;

    public void executePendingTasks() {
        for (Task task : pendingTasks) {
            task.execute();
        }
    }
}
</pre>
<p>Now if we want to extend <em>executePendingTasks()</em> to start executing any other new task, all we need to do is create a new derivative of the <em>Task</em> class. This method is now conforming to the Open-Closed Principle. Its behaviour can be extended but its implementation doesn't change.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.m.artins.net/seeking-code-quality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
