<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>KakimotOnline</title>
	<atom:link href="http://nandokakimoto.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://nandokakimoto.wordpress.com</link>
	<description>Software development information and IT news</description>
	<lastBuildDate>Tue, 11 Aug 2009 02:32:33 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='nandokakimoto.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/475e7920d5d82506e7b1bb24e9f3391d?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>KakimotOnline</title>
		<link>http://nandokakimoto.wordpress.com</link>
	</image>
			<item>
		<title>Code performance</title>
		<link>http://nandokakimoto.wordpress.com/2009/08/11/code-performance/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/08/11/code-performance/#comments</comments>
		<pubDate>Tue, 11 Aug 2009 02:32:33 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[code performance]]></category>
		<category><![CDATA[optimize code]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=481</guid>
		<description><![CDATA[Code performance is one of the most polemics topics in software development process, addressing a lot of issues, for example:

When to improve code performance?
Should I prioritize legibility or response time?
What part of my code should be improved?

There is a lot of discussion about code performance and one reason for that is due to fast code [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=481&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="text-align:justify;">Code performance is one of the most polemics topics in software development process, addressing a lot of issues, for example:</p>
<ul>
<li>When to improve code performance?</li>
<li>Should I prioritize legibility or response time?</li>
<li>What part of my code should be improved?</li>
</ul>
<p style="text-align:justify;">There is a lot of discussion about code performance and one reason for that is due to <strong>fast code isn’t the best code</strong>. Code optimization generally affects code legibility, which affects code readability, which affects code maintenance, and so on. So, when you realize that is time to look a bit deeper to your code execution time, you must be aware of some trick aspects.</p>
<p style="text-align:justify;">The first one is the <a href="http://en.wikipedia.org/wiki/Pareto_principle">Pareto Principle</a> (also known as the 80-20 rule) which states that, for many events, roughly 80% of the effects come from 20% of the causes. This is exactly what happens in code optimization: 20% of the routines are responsible for 80% of program’s execution time. Sometimes you take the whole afternoon optimizing a loop which seems to be the cause of the slowness of your program. And after using all your optimization skills, the program looks like the old one. To avoid this kind of situations you should first measure your program’s bottleneck using a profiler tool: remember the 80-20 rule. After finding it and re-writing it using some basic optimizations techniques, you will notice that your code will be 80% faster.</p>
<p style="text-align:justify;">Another tip is not relying on what everyone says about code optimization (me included). Have you ever heard about reducing lines of code, optimizing while coding, or this operation should be faster the other? Well, they are all suspicious.</p>
<p style="text-align:justify;">Lot of programmers thinks that writing routines using just one or two lines of code makes a faster program. Take a look at the code below taken from <a href="http://www.cc2e.com/">Code Complete</a> book.</p>
<p>For i = 1 to 10<br />
a[i] = i<br />
end</p>
<p>a[1] = 1; a[2] = 2; a[3] = 3;<br />
a[4] = 4; a[5] = 5; a[6] = 6;<br />
a[7] = 7; a[8] = 8; a[9] = 9;<br />
a[10] = 10;</p>
<p style="text-align:justify;">Both programs do the same thing. Which one do you think is faster? These programs were compared in the book and here is the result:</p>
<p>For loop<br />
- Visual Basic: 8,47s<br />
- Java: 12,6s</p>
<p>Linear code<br />
- Visual Basic: 3,16s<br />
- Java: 3,23s</p>
<p style="text-align:justify;">In this case, the linear code was more than 60% faster than the “for loop”. Does it prove that as longer as your code, faster it will be? No! This proves that numbers of line and code performance does not have any predictable relationship.</p>
<p style="text-align:justify;">Another very common mistake is optimizing your code while writing it. It is almost impossible to find bottlenecks without any specific tool. Without a profiler, you will probably lose time trying to optimize code that really doesn’t matter for your program performance. In addition, optimizing code while programming take you away from the main focus of it, for example user interaction and legibility. Premature code optimization is generally a bad choice.</p>
<p style="text-align:justify;">So, when optimize code? First, concentrate efforts in creating modular, maintainable program, always aware of making things easy for future changes. When it’s done, measure its performance and optimize if necessary, but only if necessary. As small parts of code consumes a considerable percentage of the whole program’s execution time, measure your code before the modifications and just after them, so you can keep track if your changes are really effectives. Just to illustrate the difference between a readable code and an optimized code, see both examples below:</p>
<p style="text-align:justify;">
<pre class="brush: cpp;">
sum = 0;
 for (row = 0; row &lt; rowCount; row++) {
    for ( column = 0; column &lt; columnCount; column++) {
         sum = sum + matrix[row][column];
    }
 }
</pre>
<pre class="brush: cpp;">
 sum = 0;
 elementPointer = matrix;
 lastElementPointer = matrix[rowCount-1][columnCount-1];
 while (elementPointer &lt; lastElementPointer) {
    sum = sum + *(elementPointer++);
 }
</pre>
<p style="text-align:justify;">Both loops calculate the sum of matrix’s elements. However, the second one uses just sum operations when calculating memory address dislocation, while the first loop uses multiplication, much more expensive (don’t rely on me, go ahead and prove it by yourself). Although slower, the first code is much easier to read and modify. So, which code to use? Remember, write readable code first, measure it and, if necessary, optimize it.</p>
<p style="text-align:justify;"><a href="http://www.cc2e.com/">Code complete</a> also comes with an entire chapter dedicated just to code optimization techniques. Next posts I’ll talk about some of them. Hope you like.</p>
<p>See you,</p>
<p>&#8211;<br />
Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/481/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=481&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/08/11/code-performance/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>
	</item>
		<item>
		<title>Singleton (Anti-) Pattern</title>
		<link>http://nandokakimoto.wordpress.com/2009/07/22/singleton-anti-pattern/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/07/22/singleton-anti-pattern/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 03:51:39 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[refactoring]]></category>
		<category><![CDATA[software design]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[anti-pattern]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=444</guid>
		<description><![CDATA[I’ve implemented my first design patterns at college, while creating a web system during the software engineer course. My classmates and I needed a facade class with a single instance of it throughout the system. So, because we’re really smart, we’ve applied the Facade and Singleton pattern. Actually, we’ve implemented the patterns without knowledge of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=444&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I’ve implemented my first design patterns at college, while creating a web system during the software engineer course. My classmates and I needed a facade class with a single instance of it throughout the system. So, because we’re really smart, we’ve applied the <a href="http://en.wikipedia.org/wiki/Facade_pattern">Facade</a> and <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton</a> pattern. Actually, we’ve implemented the patterns without knowledge of the design patterns catalog. For us, it was just a way to get what we need.</p>
<p>This week, while doing my daily work, I realized how dangerous the Singleton pattern is. Well, I would have noticed it before, if I have used <a href="http://en.wikipedia.org/wiki/Test-driven_development">Test-First Programming</a>. Even knowing the benefits of TDD, I decided to write some code in advance, since I don’t have much experience on the platform used and on its supported tests framework.</p>
<p>My task was to create a GPS abstraction and use it in a mobile Navigator module. My first thought was making my GPS abstraction a Singleton class. It looked very obvious for me: a mobile device has only one GPS and different GPS intances will provide the same data set. So, what I need is just a single GPS instance troughout the system.</p>
<p>After some minutes writing code, I’ve created abstractions similar to the Java sample below.</p>
<p><strong>GPSProvider.java</strong></p>
<pre class="brush: java;">
import java.util.List;

public class GPSProvider implements LBSPositionObserver {

 private static GPSProvider INSTANCE = new GPSProvider();
 private Position lastCoordinate;
 private List&lt;GPSListener&gt; listeners;

 private GPSProvider() {
 this.listeners = new ArrayList&lt;GPSListener&gt;();
 }

 //retrive the class instance
 public static GPSProvider GetInstance() {
 return INSTANCE;
 }

 // perform GPS initialization
 public void initGPSService() {
 (...)
 }

 // add a new listener to the gps class
 public void attach(GPSListener listener) {
 this.listeners.add(listener);
 }

 // remove a listener from the class list
 public void dettach(GPSListener listener) {
 this.listeners.remove(listener);
 }

 @Override
 // set lastCoordinate and notify all listeners about the update
 public void positionUpdated(Position position) {
 this.lastCoordinate = position;
 for ( GPSListener listener : this.listeners ) {
 listener.positionUpdated(position);
 }
 }

 @Override
 // notify all listener about the update
 public void setStatus(int status) {
 for ( GPSListener listener : this.listeners ) {
 listener.statusUpdated(status);
 }
 }

 // return the last known coordinate
 public Position getLastCoordinate() {
 return this.lastCoordinate;
 }

}
</pre>
<p><strong>GPSListener.java</strong></p>
<pre class="brush: java;">
public interface GPSListener {

 void positionUpdated(Position position);

 void statusUpdated(int status);

}
</pre>
<p><strong>LBSPositionObserver.java</strong> &#8211; native GPS interface</p>
<pre class="brush: java;">
public interface LBSPositionObserver {

 void positionUpdated(Position position);

 void setStatus(int status);

}
</pre>
<p><strong>Navigator.java</strong></p>
<pre class="brush: java;">
public class Navigator implements GPSListener {

 private NavigatorObserver observer;

 public Navigator(NavigatorObserver observer) {
 this.observer = observer;
 }

 // start navigation by listening to gps updates
 public void navigate(Route route) {
 GPSProvider gps = GPSProvider.GetInstance();
 gps.attach(this);
 }

 // pause navigation by not receiving gps updates
 public void pause() {
 GPSProvider gps = GPSProvider.GetInstance();
 gps.dettach(this);
 }

 @Override
 // everytime the position is updated, the navigator gives directions if needed
 public void positionUpdated(Position position) {
 // navigate user through route.
 int step = this.verifyStepUpdated();
 if ( step != -1 ) {
 this.observer.StepUpdated(step);
 }

 if ( this.achievedDestination() ) {
 this.observer.DestinationAchived(position);
 }
 }

 // calculate if achieved destination
 private boolean achievedDestination() {
 (...)
 }

 // verify is have to change direction
 private int verifyStepUpdated() {
 (...)
 }

 @Override
 public void statusUpdated(int status) {
 // send status to end user.
 }
}
</pre>
<p>Now, since I’ve finished my Navigator module, I want to test it to make sure it’s working correctly. In order to test the Navigator module, I need a GPS data log and a route to walk through it, simulating a person walking and being navigated by the system. The route is not a problem because I pass it as a parameter of &#8220;navigate&#8221; method. However, there is no way to simulate a GPS log with the code above, unless I use some Dependency Injection Framework, which is not the case.</p>
<p>That’s the Singleton disadvantage. I can’t inject a GPS mock in my Navigator module because I always use the native gps implementation represented in my Singleton GPSProvider class. Everytime I need some GPS information, I use the GPSProvider.GetInstance() static method to retrieve the only GPS instance I have access to.</p>
<p>To solve this problem, I found a simple solution: not using Singleton. I removed  the Singleton pattern from GPSProvider and change every class that uses GPSProvider.GetInstance() to receive the current GPS intance. In the Navigator module, I passed the GPS instance through its class&#8217; constructor.</p>
<p><strong>GPSAbstractProvider.java</strong></p>
<pre class="brush: java;">
import java.util.ArrayList;
import java.util.List;

public abstract class GPSAbstractProvider {

 private List&lt;GPSListener&gt; listeners;

 public GPSAbstractProvider() {
 this.listeners = new ArrayList&lt;GPSListener&gt;();
 }

 public abstract void initGPSService();

 public void attach(GPSListener listener) {
 this.listeners.add(listener);
 }

 public void dettach(GPSListener listener) {
 this.listeners.remove(listener);
 }

 public void notifyPositionUpdated(Position position) {
 for ( GPSListener listener : this.listeners ) {
 listener.positionUpdated(position);
 }
 }

 public void notifyStatusUpdated(int status) {
 for ( GPSListener listener : this.listeners ) {
 listener.statusUpdated(status);
 }
 }

}
</pre>
<p><strong>GPSProvider.java</strong></p>
<pre class="brush: java;">
public class GPSProvider extends GPSAbstractProvider implements LBSPositionObserver {
 private Position lastCoordinate;

 private GPSProvider() {
 super();
 }

 @Override
 // perform GPS initialization
 public void initGPSService() {
 (...)
 }

 @Override
 public void positionUpdated(Position position) {
 this.lastCoordinate = position;
 this.notifyPositionUpdated(position);
 }

 @Override
 public void setStatus(int status) {
 this.notifyStatusUpdated(status);
 }

 public Position getLastCoordinate() {
 return this.lastCoordinate;
 }

}
</pre>
<p><strong>Navigator.java</strong></p>
<pre class="brush: java;">
public class Navigator implements GPSListener {

 private NavigatorObserver observer;
 private GPSAbstractProvider gps;

 public Navigator(NavigatorObserver observer, GPSAbstractProvider gps) {
 this.observer = observer;
 this.gps = gps;
 }

 public void navigate(Route route) {
 this.gps.attach(this);
 }

 public void pause() {
 this.gps.dettach(this);
 }

 @Override
 public void positionUpdated(Position position) {
 // navigate user through route.
 int step = this.verifyStepUpdated();
 if ( step != -1 ) {
 this.observer.StepUpdated(step);
 }

 if ( this.achievedDestination() ) {
 this.observer.DestinationAchived(position);
 }
 }

 private boolean achievedDestination() {
 (...)
 }

 private int verifyStepUpdated() {
 (...)
 }

 @Override
 public void statusUpdated(int status) {
 // send status to end user.
 }
}
</pre>
<p>Much better! Notice that I still have just one single instance of my GPS class. All I have to do is creating my GPS at the beginning of the program and pass it through classes that use it.<br />
Doing this, testing my code became very simple. I inject my GPS mock to simulate GPS data in my tests,  just as below.</p>
<p><strong>NavigatorTest.java</strong></p>
<pre class="brush: java;">
import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

public class NavigatorTest extends TestCase implements NavigatorObserver {

 private Navigator navigator;
 private GPSAbstractProvider gps;

 public void testNavigate() throws Exception {
 List&lt;Position&gt; gpsPositions = new ArrayList&lt;Position&gt;();
 this.addPositions(gpsPositions);
 this.gps = new GPSTestProvider(gpsPositions);

 this.navigator = new Navigator(this, this.gps);
 this.navigator.navigate(this.createSimpleRoute());

 gps.initGPSService();

 assert(...);
 assert(...);
 }

 private Route createSimpleRoute() {
 (...)
 }

 private void addPositions(List&lt;Position&gt; gpsPositions) {
 (...)
 }

 @Override
 public void DestinationAchived(Position destination) {
 (...)
 }

 @Override
 public void StepUpdated(int step) {
 (...)
 }

}
</pre>
<p>As you can see, I can use any GPS provider in my tests, making them much more easy and flexible.<br />
In addition to the disavantage presented, <a href="http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/">Alex Miller</a> discuss some points why he hates Singleton pattern.<br />
From here, trying avoiding this pattern in situations like that. Think twice before applying Singleton in your project.</p>
<p>See you</p>
<p>&#8211;<br />
Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/444/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=444&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/07/22/singleton-anti-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>
	</item>
		<item>
		<title>C Arrays and Pointers</title>
		<link>http://nandokakimoto.wordpress.com/2009/07/15/c-arrays-pointers/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/07/15/c-arrays-pointers/#comments</comments>
		<pubDate>Wed, 15 Jul 2009 02:15:14 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[c/c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[c arrays]]></category>
		<category><![CDATA[pointers]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=437</guid>
		<description><![CDATA[Hello guys,
some weeks ago I was reading some questions in StackOverflow and one of them really took my attention. I don&#8217;t have a great experience with C programming language, but I’ve started developing in C++ and Symbian 3 moths ago, which improved my skills in pointers and memory allocation. Even after some moths programming in C++, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=437&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Hello guys,</p>
<p>some weeks ago I was reading some questions in <a href="http://stackoverflow.com/">StackOverflow</a> and <a href="http://stackoverflow.com/questions/381542/in-c-arrays-why-is-this-true-a5-5a">one of them</a> really took my attention. I don&#8217;t have a great experience with C programming language, but I’ve started developing in C++ and Symbian 3 moths ago, which improved my skills in pointers and memory allocation. Even after some moths programming in C++, I could not understand why in C arrays a[5] == 5[a], can you?</p>
<p>To answer this question, we must understand the behavior of C arrays. What happens in memory when writing:</p>
<p>int array[] = {0, 1, 2, 3, 4, 5};</p>
<p>The first thing to have in mind is that this assignment creates 5 memory “slots” with 32bits each one. A single “slot” has its value and its address, just like a pointer. It’s easy to predict the value of each position value:</p>
<p>array[0] == 0;<br />
array[1] == 1;<br />
(…)</p>
<p>Talking about the variable address, imagine the array is located at address 0&#215;0000. As you already know, in a 32bit platform, an integer has 32bits = 4bytes. So we can conclude that to access any array position we can use the following calculation:</p>
<p>address = start_address + (index * size)</p>
<p>&amp;array[0] == (0 + (0 * 4));<br />
&amp;array[1] == (0 + (1 * 4));<br />
(…)</p>
<p>And it’s exactly what the compiler does. So, when you write array[5] it’s the same of *(0 + (5 * 4)) = *(20) = 5. Easy! However, what about 5[a]? Well, the calculation is similar. Remember that C arrays are nothing just pointers, which means that both declarations below are equivalents:</p>
<p>int array[5];<br />
int *array;</p>
<p>And when incrementing an array, you are just going to the array’s next position. Which means:</p>
<p>array[1] == *(array + 1);</p>
<p>Now, if we look back to 5[a], what does it looks like? Similar to what I said, 5[a] = *(5 + a) = *(a + 5) = a[5].</p>
<p>Now, things are making sense.<br />
To read more about it, go to the original question <a href="http://stackoverflow.com/questions/381542/in-c-arrays-why-is-this-true-a5-5a">here</a>.</p>
<p>See you,<br />
Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/437/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=437&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/07/15/c-arrays-pointers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>
	</item>
		<item>
		<title>Basic Data Types</title>
		<link>http://nandokakimoto.wordpress.com/2009/06/27/basic-data-types/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/06/27/basic-data-types/#comments</comments>
		<pubDate>Sat, 27 Jun 2009 14:46:27 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[code complete]]></category>
		<category><![CDATA[data types]]></category>
		<category><![CDATA[magic numbers]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=429</guid>
		<description><![CDATA[I’ve been reading the single most influential book every programmer should read since last month and there is a really nice chapter about basic data types. Actually, when I read the chapter’s title, I thought reading it would be a waste of time, but I was wrong. There are some quick tips that really worth [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=429&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I’ve been reading the <a href="http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read">single most influential book every programmer should read</a> since last month and there is a really nice chapter about basic data types. Actually, when I read the chapter’s title, I thought reading it would be a waste of time, but I was wrong. There are some quick tips that really worth its reading and is about them that we will be talking today.</p>
<p><strong>Magic Numbers</strong></p>
<p>The first tip is avoiding magic numbers, which are literal numbers spread all over the code with no explanation. For example:</p>
<pre class="brush: cpp;">
for ( int i = 0; i &lt; 65; i++) { ... }
</pre>
<p>Does anyone here know what 65 means? So, if your language supports named constants, use them in place of the number itself. If named constants are not supported, you can use global variables too.</p>
<p>Avoiding magic numbers provide tree advantages:</p>
<ul>
<li>Changes can be made in a more confident way.</li>
<li>Changes can be made in a more easy way.</li>
<li>You improve your code legibility.</li>
</ul>
<p>The code above can be improved by using a macro, as shown below:</p>
<pre class="brush: cpp;">
#define MAX_ENTRIES 65
for ( int i = 0; i &lt; MAX_ENTRIES-1; i++) { ... }
</pre>
<p>Remember: the only literal values that should occur in your program are 0 and 1. The others should be placed with a more descriptive name.</p>
<p><strong>Integer Operations</strong></p>
<p>Be careful when dividing two integers. Keep in mind that 7/10 it’s not 0,7. The result is, in most cases, 0 (zero), varying from one language to other. In real world, we’ve learned that 10*(7/10) = (10*7)/10 = 7, which is not that same in integer’s arithmetic: 10*(7/10) = 0 because 7/10 = 0.</p>
<p>Other problem is integer overflows. When operating integers, such as additions and multiplications, you must have in mind the <a href="http://en.wikipedia.org/wiki/Integer_overflow#Origin">biggest possible value</a>. For example, if you multiply 250*300 the result is 75.000, but if the maximum possible value is 65.535, the result is 9.464 due to a integer overflow (75.000 – 65.536 = 9.464).</p>
<p><strong>Float Operations</strong></p>
<p>The main consideration about float numbers is that most decimal fractions can’t be represented with precision, with basically 7 or 15 digits. Because of that, avoid operating float numbers with different sizes. For example, what’s the result of 1.000.000,00 + 0,1? Probably, this operation will return 1.000.000,00 because 32 bits don’t offer significant digits between the interval 1.000.000 and 0,1. The same happens here: 5.000.000,02 – 5.000.000,01 probably will return 0,0.</p>
<p>A classic problem with float numbers is the incremental of 0,1 in a for loop.</p>
<pre class="brush: java;">
double nominal = 1.0;
double sum = 0.0;

for ( int i = 0; i &lt; 10; i++ ) {
    sum += 0.1;
}

if ( nominal == sum ) {
    System.out.println(&quot;Same&quot;);
} else {
    System.out.println(&quot;Different&quot;);
}
</pre>
<p>As you already know, the result is “Different”. After the loop, sum = 0,999999999999999 and the comparison fails. The work around here is using an acceptable precision interval and a boolean function to determine the equality of both numbers.</p>
<pre class="brush: java;">
final double ACCEPTABLE_DELTA = 0.00001;

boolean Equals( double n1, double, n2)  {
    if ( Math.abs ( n1 - n2 ) &lt; ACCEPTABLE_DELTA ) {
        return true;
    }
    return false;
}
</pre>
<p>If you are working with currency values, this solution is not recommended. An alternative is passing float numbers to 64bits integer, by multiplying them for 100. After the operations has completed, pass the values again to float, by dividing them for 100.</p>
<p><strong>Boolean Variables</strong></p>
<p>Boolean variables are useful to document your program. Instead of testing a boolean expression, you can assign it to a variable, making your code easy to read. For example:</p>
<pre class="brush: cpp;">
if ( (elementIndex &lt; 0)
      || (MAX_ELEMENTS &lt; elementIndex)
      || (elementIndex == lastElementIndex) ) { … }
</pre>
<p>This piece of code can be improved by creating local variables, as below:</p>
<pre class="brush: cpp;">
finished = (elementIndex &lt; 0) || (MAX_ELEMENTS &lt; elementIndex);
repeatedEntry = (elementIndex == lastElementIndex);

if ( finished || repeatedEntry) { … }
</pre>
<p>Some languages have a predefined boolean type, such as Java and C++, others don’t. But it’s possible to define your own Boolean type. In C, for example, you may use the code below:</p>
<pre class="brush: cpp;">

typedef int BOOLEAN
enum Boolean {
    True = 1, False = (!True)
};
</pre>
<p><strong>Conclusion</strong></p>
<p>We have covered Integers, Float and boolean variables. In addition, the book chapter also mentions characters and strings, enum types and arrays, but these are topics for a future post.</p>
<p>See you,</p>
<p>&#8211;<br />
Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/429/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=429&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/06/27/basic-data-types/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>
	</item>
		<item>
		<title>Breaking Information Hiding in C++</title>
		<link>http://nandokakimoto.wordpress.com/2009/05/21/breaking-information-hiding-cplusplus/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/05/21/breaking-information-hiding-cplusplus/#comments</comments>
		<pubDate>Thu, 21 May 2009 04:10:08 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[c/c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[information hiding]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=409</guid>
		<description><![CDATA[Almost every object-oriented programmer is familiar with the concept of information hiding. Actually, lots of them get confused with the terms encapsulation and information hiding. So, before we talk about information hiding itself, let me explain the difference of both terms:

Encapsulation is the public interface that defines how an object can be used, and how its [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=409&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Almost every object-oriented programmer is familiar with the concept of information hiding. Actually, lots of them get confused with the terms encapsulation and information hiding. So, before we talk about information hiding itself, let me explain the difference of both terms:</p>
<ul>
<li>Encapsulation is the public interface that defines how an object can be used, and how its data is derived.</li>
<li>Information Hiding is the principle of hiding design decisions, preventing external objects from using the derived data.</li>
</ul>
<p>Now let&#8217;s take a look in a real sample. The code below shows a classic header file, corresponding to a Point class. Note that class&#8217; members are protected against modification, since they are declared as private and no setter methods were provided. The class data is also encapsulated into the Point interface, which defines how Point objects are used, through its constructor and getter methods.</p>
<p><strong>Point.h</strong></p>
<p><img class="alignnone size-full wp-image-413" title="pontoh" src="http://nandokakimoto.files.wordpress.com/2009/05/pontoh.png?w=326&#038;h=325" alt="pontoh" width="326" height="325" /></p>
<p>A very common issue when using a third-party API is the need of changing private members value when running some tests. However, if no setter methods exist, the change can&#8217;t be made, right? Well, in C++ things are pretty different. When using pointers, you&#8217;re working directly with memory addresses. So if we create pointers that make reference to private member’s address, we can manipulate its value. Look at the code below.</p>
<p><strong>main.cpp</strong></p>
<p><img class="alignnone size-full wp-image-419" title="main" src="http://nandokakimoto.files.wordpress.com/2009/05/main1.png?w=422&#038;h=354" alt="main" width="422" height="354" /></p>
<p>Note that I&#8217;m using an integer pointer, which is an array of integers. If we come back to Point class definition, we will see just two integers. Therefore, in respect with memory manipulation Point class is similar to an integer array. In other words, array[0] is the same of point-&gt;x since both read int values (4 bytes in win32 platform). When doing the pointer attribution and the explicit cast, we&#8217;re just pointing the integer array to the first memory address of the object. Changing its value will affect the memory content, it means: the object private member.</p>
<p>I know that this is a little bit weird, but it works perfectly. To looks like more acceptable, we could create a new class, similar to Point class signature, and manipulate its members, but in fact working with the Point class member variables. Here is the code that illustrates this behavior.</p>
<p><strong>MyPoint.h</strong></p>
<p><img class="alignnone size-full wp-image-421" title="mypointh" src="http://nandokakimoto.files.wordpress.com/2009/05/mypointh1.png?w=237&#038;h=256" alt="mypointh" width="237" height="256" /></p>
<p><strong>main.cpp</strong></p>
<p><img class="alignnone size-full wp-image-422" title="mainmypoint" src="http://nandokakimoto.files.wordpress.com/2009/05/mainmypoint.png?w=412&#038;h=443" alt="mainmypoint" width="412" height="443" /></p>
<p>Now, be free to change private members wherever you want.</p>
<p>See you,</p>
<p>[]&#8217;s</p>
<p>Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/409/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=409&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/05/21/breaking-information-hiding-cplusplus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/pontoh.png" medium="image">
			<media:title type="html">pontoh</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/main1.png" medium="image">
			<media:title type="html">main</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/mypointh1.png" medium="image">
			<media:title type="html">mypointh</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/mainmypoint.png" medium="image">
			<media:title type="html">mainmypoint</media:title>
		</media:content>
	</item>
		<item>
		<title>Principles of Package Design</title>
		<link>http://nandokakimoto.wordpress.com/2009/05/15/principles-of-package-design/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/05/15/principles-of-package-design/#comments</comments>
		<pubDate>Fri, 15 May 2009 14:39:58 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[software design]]></category>
		<category><![CDATA[package cycles]]></category>
		<category><![CDATA[package dependency]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=394</guid>
		<description><![CDATA[Agile Software Development is really an incredible book. After reading it, a lot had been talked about the Object-Oriented Principles on this blog (here and here). Today, I&#8217;ll be talking about another section of the book, which introduces principles used to maintain high package cohesion and a desirable package dependency, known as Principles of Package Design.
Packages [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=394&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="text-align:justify;"><a href="http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445">Agile Software Development</a> is really an incredible book. After reading it, a lot had been talked about the Object-Oriented Principles on this blog (<a href="http://nandokakimoto.wordpress.com/2009/03/28/visitor-pattern-and-the-open-closed-principle/">here</a> and <a href="http://nandokakimoto.wordpress.com/2009/03/08/the-principles-of-object-oriented-design/">here</a>). Today, I&#8217;ll be talking about another section of the book, which introduces principles used to maintain high package cohesion and a desirable package dependency, known as Principles of Package Design.</p>
<p style="text-align:justify;">Packages are used to organize larger projects. More than this, they are containers of classes used to manage the development and distribution on software. Package’s goal is separate classes in an application according to some criteria. However, classes often have dependencies on other classes, creating package dependencies relationships. To help manage this situation, some principles were created to govern the creation, interrelationship and use of packages.</p>
<p style="text-align:justify;">The three principles in sequence are related to package cohesion, useful in deciding how to partition classes into packages.</p>
<p><strong>The Reuse-Release Equivalence Principle (REP)</strong>: <em>the granule of reuse if the granule of release</em></p>
<p style="text-align:justify;">REP states that anything that we reuse must also be released and tracked. Reusability is not only the creation. It comes only after there is a track system in place that offers the guarantees of support that reusers will need. Since reusability is based on packages, if some software is going to be reused, then it must be partitioned in a convenient structure for this purpose, so all classes in a package become reusable by the same audience.</p>
<p><strong>The Common-Reuse Principle (CRP)</strong>: <em>the classes in a package are reused together</em></p>
<p style="text-align:justify;">CRP helps in deciding which classes should be placed into a package. This can be determined by reuse characteristics. Classes that tend to be reused together should be placed in the same package. Remember: if you reuse one class in a package, you reuse them all. Although the CRP tells us what classes put together, it also says what classes do <strong>not</strong> put in the same package. If a class depends on another class in a different package, it depends on the entire package. Every time the used package is released, the using package must be revalidated and rereleased, even the change was made in a different class that the using package depends on. Therefore, CRP also says that classes which are not tightly related to each other should not be in the same package, so every time I depend on a package, I depend on every class in that package.</p>
<p style="text-align:justify;"><strong>The Common-Closed Principle (CCP)</strong>: <em>a change that affects a package affects all the classes in that package and no other packages.</em></p>
<p style="text-align:justify;">This is the same as SRP, but applied for the packages context. Such as classes should have just one reason to change, CCP states that packages should not have multiple reasons to change. It&#8217;s preferable that changes occur in just one package rather than distributed along the whole system.</p>
<p>Now, we are going to take a look at principles related to package relationship and dependency.</p>
<p><strong>The Acyclic-Dependencies Principle (ADP)</strong>: <em>allow no cycles in the package-dependency graph.</em></p>
<p style="text-align:justify;">Package cycles create immediate problems, and the most obvious one is when you have to release a package that was modified. In order to release the package, it must be compatible with all other packages that it depends on. A cycle in your package-dependency graph makes release harder since you increase the number of packages that you have to be compatible with. For example, take the Figure 1 and Figure 2. To release package C in the first situation we must be compatible with package E and F. However, in the second case we also must be compatible with package A, B and D. Even worst, if you want to test package C, we must link and build all other packages in the system, instead of just two of them.</p>
<p><img class="alignnone size-full wp-image-402" title="no-cycle" src="http://nandokakimoto.files.wordpress.com/2009/05/no-cycle.png?w=827&#038;h=261" alt="no-cycle" width="827" height="261" /></p>
<p>To break the cycle, two solutions are suggested:</p>
<ol>
<li>apply Dependecy-Inversion Principle.</li>
<li>create a new package between C and A, and move the classes that they both depend on into that new package.</li>
</ol>
<p><strong>The Stable-Dependencies Principle (SDP)</strong>: <em>depend in the direction of stability.</em></p>
<p style="text-align:justify;">Stability has nothing directly to do with frequency of change, but to the amount of work required to make the change. In software, package stability is measured in number of classes inside this package that depend on classes outside this package and number of classes outside this package that depend on classes within this package. Thus, a package is called <strong>instable</strong> if it is <strong>easy to change</strong>, in other words, just a few or none packages have dependency relationship with it. A package is called <strong>s<em>table</em></strong> if it is <strong>hard to change</strong>, or a lot of classes outside this package depend on it. The book also brings a method to calculate stability metrics, but I&#8217;ll not be such detailed. Just have in mind that a good design contains some instable package and some stable package. Instable packages are on top and depend on stable packages at the bottom, just shown below.</p>
<p><img class="alignnone size-full wp-image-400" title="figura1" src="http://nandokakimoto.files.wordpress.com/2009/05/figura1.png?w=325&#038;h=176" alt="figura1" width="325" height="176" /></p>
<p><strong>The Stable-Abstractions Principle (SAP): </strong><em>a package should be as abstract as it is stable.</em></p>
<p style="text-align:justify;">This principle states that a stable package should also be abstract so that its stability does not prevent it from being extended, and an instable package should be concrete since its instability allows the concrete code within it to be easily changed. Thus, stable packages consist of abstract classes and instable packages of implementations classes.</p>
<p><strong>Conclusion</strong></p>
<p style="text-align:justify;">After some posts of OOP, we already know how to create a good class design. However, in big systems, classes are separate into packages which corresponds a very important part of the system&#8217;s release and deploy. So, a new concern is how to divide classes between packages and maintain the system&#8217;s consistency. In this post we introduced six principles explained in Robert Martin book which help us in solve a lot of package design problems. You can find a lot of more information in the book, which I strictly recommend.</p>
<p>See you,</p>
<p>&#8211;<br />
Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/394/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/394/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/394/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/394/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/394/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/394/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/394/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/394/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/394/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/394/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=394&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/05/15/principles-of-package-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/no-cycle.png" medium="image">
			<media:title type="html">no-cycle</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/figura1.png" medium="image">
			<media:title type="html">figura1</media:title>
		</media:content>
	</item>
		<item>
		<title>Generic DAO with NHibernate and Autofac</title>
		<link>http://nandokakimoto.wordpress.com/2009/05/04/generic-dao-nhibernate-autofac/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/05/04/generic-dao-nhibernate-autofac/#comments</comments>
		<pubDate>Mon, 04 May 2009 02:20:43 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software design]]></category>
		<category><![CDATA[autofac]]></category>
		<category><![CDATA[dao]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=374</guid>
		<description><![CDATA[Data access is one of the most important design decisions in software development. Depending on how you design your data access classes, every single modification causes cascading changes throughout your project. Imagine you have a lot of persistent data objects to manage and, for example, you have to change your database. This transition must be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=374&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="text-align:justify;">Data access is one of the most important design decisions in software development. Depending on how you design your data access classes, every single modification causes cascading changes throughout your project. Imagine you have a lot of persistent data objects to manage and, for example, you have to change your database. This transition must be done without modifying the source code of your persistent classes. Other problem happens when you add more persistent data collection classes to the system. Of course, you won’t be happy if every time a new basic class is added, a new CRUD class is needed. The last point is programming in respect with the <a href="http://nandokakimoto.wordpress.com/2009/03/08/the-principles-of-object-oriented-design/">OOP</a>, in other words, programming for the abstractions and not for implementations, with low coupling and high cohesion.</p>
<p style="text-align:justify;">To solve those problems, the project that I&#8217;d worked for the last 8 months (<a href="http://www.onibusrecife.com.br/">Onibus Recife</a>) used a combination of 3 technologies, and this post is about them.</p>
<p><strong>NHibernate</strong></p>
<p style="text-align:justify;">NHibernate is an Object-relational mapping (ORM) solution for the Microsoft .NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. NHibernate&#8217;s primary feature is mapping from .NET classes to database tables. NHibernate generates the SQL commands and relieves the developer from manual data set handling and object conversion, keeping the application portable to most SQL databases, with database portability delivered at very little performance overhead.</p>
<p>NHibernate was used exactly for this purpose: create SQL commands and provide database portability.</p>
<p><strong>Generics</strong></p>
<p style="text-align:justify;">Generics is a programming feature added in the .NET Framework 2.0 which allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code.</p>
<p style="text-align:justify;">Using Generics, our team was able to use one, and just one, repository class for all of the simple persistent entities. Every time a new entity was add to the project, nothing more than its corresponding .hbm file was needed.</p>
<p><strong>Autofac</strong></p>
<p>Autofac is a fresh approach to <a href="http://martinfowler.com/articles/injection.html">IoC</a> in .NET that fits well with C# 3.0.</p>
<p style="text-align:justify;">The Autofac framework enabled us to inject all classes’ dependencies in just one place. So, when dependences changed, just a few lines of code were modified in a single source code file.</p>
<p style="text-align:justify;">To illustrate those techniques, I’ll use them in a sample and small project.<br />
Imagine a simple Contacts project used to keep your friends&#8217; address, phone number and birthday. The abstraction of a contact is shown below.</p>
<p><strong>Contact.cs</strong></p>
<p><strong><img class="alignnone size-full wp-image-379" title="contact" src="http://nandokakimoto.files.wordpress.com/2009/05/contact.png?w=503&#038;h=376" alt="contact" width="503" height="376" /><br />
</strong></p>
<p style="text-align:justify;">In order to persist the Contact class in my SQL Server database, I used NHibernate framework. Due to that, I need an .hbm file for the Contact class and a NHibernate session manager, responsible to manage database access. Because it&#8217;s a small and very simple project, I created a simple session manager, shown below.</p>
<p><strong>NHibernateSessionManager.cs</strong></p>
<p><strong><img class="alignnone size-full wp-image-380" title="sessionmanager" src="http://nandokakimoto.files.wordpress.com/2009/05/sessionmanager.png?w=885&#038;h=1139" alt="sessionmanager" width="885" height="1139" /><br />
</strong></p>
<p style="text-align:justify;">Now, it&#8217;s time for the repository class. Actually, I implemented a repository interface and its implementation. Remember: program for abstractions, not for implementations. Note that they are generic. I did this to provide a single persistent implementation for more than one entity and simplify my life as a programmer. The code of them is listed below.</p>
<p><strong>IRepository.cs</strong></p>
<p><strong><img class="alignnone size-full wp-image-382" title="irepository1" src="http://nandokakimoto.files.wordpress.com/2009/05/irepository1.png?w=366&#038;h=306" alt="irepository1" width="366" height="306" /><br />
</strong></p>
<p><strong>NHibernateRepository.cs</strong></p>
<p><strong><img class="alignnone size-full wp-image-384" title="nhibernaterepository1" src="http://nandokakimoto.files.wordpress.com/2009/05/nhibernaterepository1.png?w=695&#038;h=767" alt="nhibernaterepository1" width="695" height="767" /><br />
</strong></p>
<p>Now, let’s test our code reading data from the database. For that, I used the following piece of code.</p>
<p><strong>TestReadContactById</strong></p>
<p><strong><img class="alignnone size-full wp-image-385" title="getcontact" src="http://nandokakimoto.files.wordpress.com/2009/05/getcontact.png?w=826&#038;h=158" alt="getcontact" width="826" height="158" /><br />
</strong></p>
<p>The test passed, so everything is working.</p>
<p style="text-align:justify;">Now imagine that we need another entity class, for example, a User, to restrict the program access with a username and password. All that I have to do is creating the User.cs abstraction and the User.hbm.xml file. I don’t need a new CRUD class for it. I just use the same generic repository that I used for Contact class, saving me a lot of time. Below is the code that I used to retrieve a user from the database.</p>
<p><strong>TestReadUserById</strong></p>
<p><strong><img class="alignnone size-full wp-image-386" title="getuser" src="http://nandokakimoto.files.wordpress.com/2009/05/getuser.png?w=755&#038;h=157" alt="getuser" width="755" height="157" /><br />
</strong></p>
<p style="text-align:justify;">Note that we must instantiate a new NHibernateRepository with a NHibernateSessionManager as parameter every time we need a new IRepository instance. Probably, in a big project, this line of code will be scattered in a huge number of files and, if that instantiation change for any reason, a lot of files will be modified. That’s what we don’t want. We like when changes are made in just one place and that is the work of Autofac framework.</p>
<p>Take a look of how the same tests are made using Autofac.</p>
<p><strong>AutofacRepositoryTest.cs</strong></p>
<p><strong><img class="alignnone size-full wp-image-387" title="autofactest" src="http://nandokakimoto.files.wordpress.com/2009/05/autofactest.png?w=767&#038;h=868" alt="autofactest" width="767" height="868" /><br />
</strong></p>
<p style="text-align:justify;">The framework will inject all classes’ dependencies in the beginning of the program execution. Later, to instantiate an object, we ask the framework to resolve its type. If its instantiation changed, just the line of code where Autofac register is changed.</p>
<p><strong>Conclusion</strong></p>
<p style="text-align:justify;">In this post, I’ve introduced a combination of NHibernate, Generics and Autofac. With these technologies in hand, I was able to create an extensible persistent layer in a low coupling and high cohesion way as shown in the sample project created.</p>
<p style="text-align:justify;">For more information about this technologies see <a href="http://www.hibernate.org/">Hibernate</a> and <a href="http://code.google.com/p/autofac/">Autofac</a> documentation.</p>
<p>See you.</p>
<p>&#8211;<br />
Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/374/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=374&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/05/04/generic-dao-nhibernate-autofac/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/contact.png" medium="image">
			<media:title type="html">contact</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/sessionmanager.png" medium="image">
			<media:title type="html">sessionmanager</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/irepository1.png" medium="image">
			<media:title type="html">irepository1</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/nhibernaterepository1.png" medium="image">
			<media:title type="html">nhibernaterepository1</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/getcontact.png" medium="image">
			<media:title type="html">getcontact</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/getuser.png" medium="image">
			<media:title type="html">getuser</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/05/autofactest.png" medium="image">
			<media:title type="html">autofactest</media:title>
		</media:content>
	</item>
		<item>
		<title>Google Maps and the MarkerClusterer solution</title>
		<link>http://nandokakimoto.wordpress.com/2009/04/26/google-maps-marker-cluster/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/04/26/google-maps-marker-cluster/#comments</comments>
		<pubDate>Sun, 26 Apr 2009 14:37:33 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[maps]]></category>
		<category><![CDATA[cluster]]></category>
		<category><![CDATA[GMarker]]></category>
		<category><![CDATA[google maps]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=369</guid>
		<description><![CDATA[Hi everyone,
today I&#8217;ll be writing a small post about a problem that most people who write maps application deal with: add thousands of markers in you map. A known solution to manage your marker is GMarkerManager. However, today I read about the MarkerClusterer solution in GeoGoogleDevelopers Blog.
&#8220;MarkerClusterer collects markers into different clusters and displays the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=369&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Hi everyone,</p>
<p>today I&#8217;ll be writing a small post about a problem that most people who write maps application deal with: add thousands of markers in you map. A known solution to manage your marker is <a href="http://code.google.com/intl/pt-BR/apis/maps/documentation/reference.html#GMarkerManager">GMarkerManager</a>. However, today I read about the MarkerClusterer solution in <a href="http://googlegeodevelopers.blogspot.com/2009/04/markerclusterer-solution-to-too-many.html">GeoGoogleDevelopers Blog</a>.</p>
<p>&#8220;<em>MarkerClusterer collects markers into different clusters and displays the number of markers in each cluster with a label, creating new clusters as the map zoom level changes. The clustering algorithm is simple; for each new marker it sees, it either puts it inside a pre-existing cluster, or it creates a new cluster if the marker doesn&#8217;t lie within the bounds of any current cluster</em>.&#8221;</p>
<p>The effect of using MarkerClusterer is shown in the picture below and <a href="http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/examples/simple_example.html">library&#8217;s sample site</a>:</p>
<p><img class="alignnone size-full wp-image-370" title="markerclusterer" src="http://nandokakimoto.files.wordpress.com/2009/04/markerclusterer.png?w=602&#038;h=237" alt="markerclusterer" width="602" height="237" /></p>
<p>The library works like magic. You just have to pass your array of markers to the MarkerClusterer constructor, and it ill take care of the rest. First, we have to import the MarkerClusterer JavaScript implementation file. Later, we create some markers, push into the array and call MarkerClusterer, as shown in the code snippet below.</p>
<p><img class="alignnone size-full wp-image-371" title="marketclusterercode" src="http://nandokakimoto.files.wordpress.com/2009/04/marketclusterercode.png?w=958&#038;h=616" alt="marketclusterercode" width="958" height="616" /></p>
<p>It&#8217;s really awesome and straightfoward. Try it yourself.</p>
<p>See you,</p>
<p>&#8211;<br />
Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/369/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=369&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/04/26/google-maps-marker-cluster/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/04/markerclusterer.png" medium="image">
			<media:title type="html">markerclusterer</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/04/marketclusterercode.png" medium="image">
			<media:title type="html">marketclusterercode</media:title>
		</media:content>
	</item>
		<item>
		<title>C# Extension Methods</title>
		<link>http://nandokakimoto.wordpress.com/2009/04/06/c-extension-methods/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/04/06/c-extension-methods/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 01:29:54 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software design]]></category>
		<category><![CDATA[extension methods]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=359</guid>
		<description><![CDATA[I&#8217;ve been talking about Object-Oriented Principles for a while, and this post will not be different. Here and here, I&#8217;ve introduced OOP and described an elegant solution to comply with Open-Closed Principle using Visitor Pattern, respectively. Today I&#8217;ll be talking about a C# 3.0 feature called extension methods. Maybe you&#8217;re now asking what extension methods [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=359&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="text-align:justify;">I&#8217;ve been talking about Object-Oriented Principles for a while, and this post will not be different. <a href="http://nandokakimoto.wordpress.com/2009/03/08/the-principles-of-object-oriented-design/">Here</a> and <a href="http://nandokakimoto.wordpress.com/2009/03/28/visitor-pattern-and-the-open-closed-principle/" target="_blank">here</a>, I&#8217;ve introduced OOP and described an elegant solution to comply with Open-Closed Principle using Visitor Pattern, respectively. Today I&#8217;ll be talking about a C# 3.0 feature called <strong>extension methods. </strong>Maybe you&#8217;re now asking what extension methods and OOP have in common. That is what this post is about.</p>
<p style="text-align:justify;"><!--[if gte mso 9]&gt;  Normal 0   21   false false false  PT-BR X-NONE X-NONE              MicrosoftInternetExplorer4              &lt;![endif]--><!--[if gte mso 9]&gt;                                                                                                                                            &lt;![endif]--><!--  /* Font Definitions */  @font-face 	{font-family:"Cambria Math"; 	panose-1:2 4 5 3 5 4 6 3 2 4; 	mso-font-charset:1; 	mso-generic-font-family:roman; 	mso-font-format:other; 	mso-font-pitch:variable; 	mso-font-signature:0 0 0 0 0 0;} @font-face 	{font-family:Calibri; 	panose-1:2 15 5 2 2 2 4 3 2 4; 	mso-font-charset:0; 	mso-generic-font-family:swiss; 	mso-font-pitch:variable; 	mso-font-signature:-1610611985 1073750139 0 0 159 0;}  /* Style Definitions */  p.MsoNormal, li.MsoNormal, div.MsoNormal 	{mso-style-unhide:no; 	mso-style-qformat:yes; 	mso-style-parent:""; 	margin-top:0cm; 	margin-right:0cm; 	margin-bottom:10.0pt; 	margin-left:0cm; 	line-height:115%; 	mso-pagination:widow-orphan; 	font-size:11.0pt; 	font-family:"Calibri","sans-serif"; 	mso-ascii-font-family:Calibri; 	mso-ascii-theme-font:minor-latin; 	mso-fareast-font-family:Calibri; 	mso-fareast-theme-font:minor-latin; 	mso-hansi-font-family:Calibri; 	mso-hansi-theme-font:minor-latin; 	mso-bidi-font-family:"Times New Roman"; 	mso-bidi-theme-font:minor-bidi; 	mso-fareast-language:EN-US;} p 	{mso-style-priority:99; 	mso-margin-top-alt:auto; 	margin-right:0cm; 	mso-margin-bottom-alt:auto; 	margin-left:0cm; 	mso-pagination:widow-orphan; 	font-size:12.0pt; 	font-family:"Times New Roman","serif"; 	mso-fareast-font-family:"Times New Roman";} .MsoChpDefault 	{mso-style-type:export-only; 	mso-default-props:yes; 	mso-ascii-font-family:Calibri; 	mso-ascii-theme-font:minor-latin; 	mso-fareast-font-family:Calibri; 	mso-fareast-theme-font:minor-latin; 	mso-hansi-font-family:Calibri; 	mso-hansi-theme-font:minor-latin; 	mso-bidi-font-family:"Times New Roman"; 	mso-bidi-theme-font:minor-bidi; 	mso-fareast-language:EN-US;} .MsoPapDefault 	{mso-style-type:export-only; 	margin-bottom:10.0pt; 	line-height:115%;} @page Section1 	{size:595.3pt 841.9pt; 	margin:70.85pt 3.0cm 70.85pt 3.0cm; 	mso-header-margin:35.4pt; 	mso-footer-margin:35.4pt; 	mso-paper-source:0;} div.Section1 	{page:Section1;} --><!--[if gte mso 10]&gt; &lt;!   /* Style Definitions */  table.MsoNormalTable 	{mso-style-name:"Table Normal"; 	mso-tstyle-rowband-size:0; 	mso-tstyle-colband-size:0; 	mso-style-noshow:yes; 	mso-style-priority:99; 	mso-style-qformat:yes; 	mso-style-parent:""; 	mso-padding-alt:0cm 5.4pt 0cm 5.4pt; 	mso-para-margin-top:0cm; 	mso-para-margin-right:0cm; 	mso-para-margin-bottom:10.0pt; 	mso-para-margin-left:0cm; 	line-height:115%; 	mso-pagination:widow-orphan; 	font-size:11.0pt; 	font-family:"Calibri","sans-serif"; 	mso-ascii-font-family:Calibri; 	mso-ascii-theme-font:minor-latin; 	mso-fareast-font-family:"Times New Roman"; 	mso-fareast-theme-font:minor-fareast; 	mso-hansi-font-family:Calibri; 	mso-hansi-theme-font:minor-latin;} --> <!--[endif]-->Extension methods enable you to &#8220;add&#8221; methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.</p>
<p>Therefore, extension methods are an optional technique to extend classes functionalities without modifying it. This makes me remember the Open-Closed Principle which states that software entities should be open for extension, but closed for modification. By using extension methods, your software tends to be less difficult to change, to not impact in dependent modules and even more important, changes are achieved by adding new code, not by changing old code that already exists.</p>
<p style="text-align:justify;">Extension methods are defined as static methods in static classes, but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the <span style="color:#000080;"><strong>this</strong></span> modifier. The following example shows extension methods for C# string class.</p>
<p style="text-align:justify;"><strong>StringExtension.cs</strong></p>
<p style="text-align:justify;"><img class="alignnone size-full wp-image-361" title="em1" src="http://nandokakimoto.files.wordpress.com/2009/04/em1.png?w=554&#038;h=458" alt="em1" width="554" height="458" /></p>
<p style="text-align:justify;">Extension methods are only in scope when you explicitly import the namespace into your source code with a <strong><span style="color:#000080;"><span class="input">using</span></span></strong> directive. They are used as if they were instance methods and are visualized in VS intellisense, as show below:</p>
<p style="text-align:justify;"><img class="alignnone size-full wp-image-362" title="em2" src="http://nandokakimoto.files.wordpress.com/2009/04/em2.png?w=669&#038;h=273" alt="em2" width="669" height="273" /></p>
<p style="text-align:justify;">Here is the test class for <strong>StringExtension.cs</strong> class showing how to invoke extension methods in C#.</p>
<p style="text-align:justify;"><strong>TestExtensionMethods.cs</strong></p>
<p style="text-align:justify;"><strong><img class="alignnone size-full wp-image-363" title="em3" src="http://nandokakimoto.files.wordpress.com/2009/04/em3.png?w=545&#038;h=780" alt="em3" width="545" height="780" /><br />
</strong></p>
<p style="text-align:justify;">As you could see, this feature enables you to extend the string class, which is a <span style="color:#000080;"><strong>sealed</strong></span> class, same as <strong><span style="color:#800000;">final </span></strong><span style="color:#800000;"><span style="color:#000000;">class</span></span> in Java, and implossible to inherit it. This helps you to extend and maintain code in a really elegant way. So, remeber using extension methods when find similar problems in you code.</p>
<p style="text-align:justify;">See you,</p>
<p style="text-align:justify;">&#8211;<br />
Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/359/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/359/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/359/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/359/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/359/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/359/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/359/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/359/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/359/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/359/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=359&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/04/06/c-extension-methods/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/04/em1.png" medium="image">
			<media:title type="html">em1</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/04/em2.png" medium="image">
			<media:title type="html">em2</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/04/em3.png" medium="image">
			<media:title type="html">em3</media:title>
		</media:content>
	</item>
		<item>
		<title>Visitor Pattern and the Open-Closed Principle</title>
		<link>http://nandokakimoto.wordpress.com/2009/03/28/visitor-pattern-and-the-open-closed-principle/</link>
		<comments>http://nandokakimoto.wordpress.com/2009/03/28/visitor-pattern-and-the-open-closed-principle/#comments</comments>
		<pubDate>Sat, 28 Mar 2009 15:55:14 +0000</pubDate>
		<dc:creator>nandokakimoto</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[software design]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[object-oriented design]]></category>
		<category><![CDATA[visitor]]></category>

		<guid isPermaLink="false">http://nandokakimoto.wordpress.com/?p=324</guid>
		<description><![CDATA[A few weeks ago, I described here the Open-Closed Principle, which says that software entities should be open for extension, but closed for modification. Now, imagine you are facing with the following design problem:
You need to add a new functionality to a hierarchy of classes, but the act of adding it will be painful or [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=324&subd=nandokakimoto&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="text-align:justify;">A few weeks ago, I described <a href="http://nandokakimoto.wordpress.com/2009/03/08/the-principles-of-object-oriented-design/" target="_blank">here</a> the <strong>Open-Closed Principle</strong>, which says that software entities should be open for extension, but closed for modification. Now, imagine you are facing with the following design problem:</p>
<p style="text-align:justify;"><em>You need to add a new functionality to a hierarchy of classes, but the act of adding it will be painful or damaging to your design.</em></p>
<p style="text-align:justify;">I&#8217;ll use here the example of <a href="http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445">Robert C. Martin&#8217;s book</a>: suppose you have a hierarchy of <em>Modem</em> objects. The base class has the generic methods common to all modems, and the derivatives represent the drivers for many different modem manufactures and types. Suppose also that you have a requirement to add a new method, named <em>configureForUnix, </em>to the hierarchy. This method will configure the modem to work with the UNIX operating system, corresponding to a different implementation in each modem derivative.</p>
<p style="text-align:justify;">The real problem is not adding the new <em>configureForUnix </em>method, but what about the others operating systems? Must we really add a new method to the <em>Modem </em>hierarchy for every new operating system? Adding methods to the hierarchy of classes obviously violates the OCP because we&#8217;ll never be able to close the <em>Modem </em>interface.</p>
<p style="text-align:justify;">The VISITOR pattern helps solving this kind of problems. As it definition says: VISITOR lets you define a new operation without changing the classes of the elements on which it operates. To do that, VISITOR use a technique called dual dispatch, which evolves two polymorphic dispatches.</p>
<p style="text-align:justify;">The figure below shows the UML diagram create by VS2008.</p>
<p style="text-align:justify;"><a href="http://nandokakimoto.files.wordpress.com/2009/03/uml.png"><img class="alignnone size-full wp-image-325" title="uml" src="http://nandokakimoto.files.wordpress.com/2009/03/uml.png?w=707&#038;h=403" alt="uml" width="707" height="403" /></a></p>
<p style="text-align:justify;">Now, let&#8217;s create the code necessary to implement the VISITOR pattern in the Modem problem.</p>
<p style="text-align:justify;"><strong>Modem.cs</strong></p>
<pre><a href="http://nandokakimoto.files.wordpress.com/2009/03/modem.png"><img class="alignnone size-full wp-image-342" title="modem" src="http://nandokakimoto.files.wordpress.com/2009/03/modem.png?w=373&#038;h=274" alt="modem" width="373" height="274" /></a></pre>
<p><strong>ModemVisitor.cs</strong></p>
<p><a href="http://nandokakimoto.files.wordpress.com/2009/03/modemvisitor1.png"><img class="alignnone size-full wp-image-344" title="modemvisitor1" src="http://nandokakimoto.files.wordpress.com/2009/03/modemvisitor1.png?w=393&#038;h=241" alt="modemvisitor1" width="393" height="241" /></a><a href="http://nandokakimoto.files.wordpress.com/2009/03/modemvisitor.png"></a></p>
<p><strong>HayesModem.cs</strong></p>
<p><a href="http://nandokakimoto.files.wordpress.com/2009/03/hayes.png"><img class="alignnone size-full wp-image-345" title="hayes" src="http://nandokakimoto.files.wordpress.com/2009/03/hayes.png?w=482&#038;h=427" alt="hayes" width="482" height="427" /></a></p>
<p><strong>ZoomModem.cs</strong></p>
<pre><a href="http://nandokakimoto.files.wordpress.com/2009/03/zoom.png"><img class="alignnone size-full wp-image-346" title="zoom" src="http://nandokakimoto.files.wordpress.com/2009/03/zoom.png?w=432&#038;h=443" alt="zoom" width="432" height="443" /></a></pre>
<p><strong>ErnieModem.cs</strong></p>
<p><a href="http://nandokakimoto.files.wordpress.com/2009/03/earnie.png"><img class="alignnone size-full wp-image-347" title="earnie" src="http://nandokakimoto.files.wordpress.com/2009/03/earnie.png?w=441&#038;h=442" alt="earnie" width="441" height="442" /></a></p>
<p><strong>UnixModemConfigurator.cs</strong></p>
<pre><a href="http://nandokakimoto.files.wordpress.com/2009/03/unixmodem1.png"><img class="alignnone size-full wp-image-349" title="unixmodem1" src="http://nandokakimoto.files.wordpress.com/2009/03/unixmodem1.png?w=512&#038;h=443" alt="unixmodem1" width="512" height="443" /></a></pre>
<p>And here is the test code.</p>
<p><strong>TestModemVisitor.cs</strong></p>
<pre><a href="http://nandokakimoto.files.wordpress.com/2009/03/testemodem1.png"><img class="alignnone size-full wp-image-351" title="testemodem1" src="http://nandokakimoto.files.wordpress.com/2009/03/testemodem1.png?w=698&#038;h=667" alt="testemodem1" width="698" height="667" /></a><a href="http://nandokakimoto.files.wordpress.com/2009/03/testemodem.png"></a></pre>
<p>Having built this structure, new operation system configuration can be added just by creating new derivatives of <em>ModemVisitor </em>without changing the <em>Modem </em>hierarchy. Another pattern that accomplishes this is the DECORATOR pattern, but this is a talk for other post.</p>
<p>See you,</p>
<p>&#8211;<br />
Fernando</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nandokakimoto.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nandokakimoto.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nandokakimoto.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nandokakimoto.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nandokakimoto.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nandokakimoto.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nandokakimoto.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nandokakimoto.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nandokakimoto.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nandokakimoto.wordpress.com/324/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nandokakimoto.wordpress.com&blog=2881717&post=324&subd=nandokakimoto&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://nandokakimoto.wordpress.com/2009/03/28/visitor-pattern-and-the-open-closed-principle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">nandokakimoto</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/03/uml.png" medium="image">
			<media:title type="html">uml</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/03/modem.png" medium="image">
			<media:title type="html">modem</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/03/modemvisitor1.png" medium="image">
			<media:title type="html">modemvisitor1</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/03/hayes.png" medium="image">
			<media:title type="html">hayes</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/03/zoom.png" medium="image">
			<media:title type="html">zoom</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/03/earnie.png" medium="image">
			<media:title type="html">earnie</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/03/unixmodem1.png" medium="image">
			<media:title type="html">unixmodem1</media:title>
		</media:content>

		<media:content url="http://nandokakimoto.files.wordpress.com/2009/03/testemodem1.png" medium="image">
			<media:title type="html">testemodem1</media:title>
		</media:content>
	</item>
	</channel>
</rss>