KakimotOnline

February 21, 2009

Refactoring to Command Pattern

Filed under: programming, refactoring, software design — Tags: , , — nandokakimoto @ 1:29 am

I’ve spent the last two weeks reading another refactoring famous reference. After Refactoring, I decided to read Refactoring to Patterns, which is also very good, and today I’ll share one sample of book’s refactoring catalog: Replace Conditional Dispatcher with Command. In this example, you will be able to see some of book’s approach and how this practice improves code quality.

“Conditional logic is used to dispatch requests and execute actions. Create a Command for each action. Store the Commands in a collection and replace the conditional logic with code to fetch and execute Commands.”

A lot of systems receive and manipulate requests, which in some cases are processed by conditional statements. There is no problem if your conditional mecanisn is small and treats just a few number of requests. However, if your if-else’s start growing, it’s time to search for betters solutions. A good option is change from conditional statements to the Command pattern, providing runtime flexibility and avoiding inflated code.

To implement the pattern, you just separate each block of the conditional dispatcher in a separated command class with a common execute method responsable for executing a specific encapsulated logic. So, besides of calling different routines depending on the received request, you will now just call the excute method for all of them.

Benefits

  • provide a simple mecanism to execute different behaviors in a common way.
  • allow runtime changes in which requests are manipulated and how they are manipulated.
  • easy implementation with trivial code.

Disavantage

  • complicates a project when a conditional statement it’s enough.

Now, let’s examine a real-life example. Imagine you have the code below:

image12

In this example, the RequestHandler class is responsable for manipulating requests depending on its actionName parameter in a big conditional statement. It isn’t a good approach at all,  so let’s start refactoring it. The first step is apply extract method on each conditional body. This step will result in the following code.

image21

I compile and test to make sure that I didn’t break anything.

The next step creates concrete commands for each existing if-else block. So, we will add two new classes to the project: ErrorHandler and SuccessHandler, and later apply move method to the existing methods in the RequestHandler class. That’s is the result.

image31

image4

image5

Again I compile and test.

With the concrete commands created, it’s time to create the command interface. Note that both commands have different methods name and we still use the conditional statement to instantiate the correct concrete command.  Let’s use a Handler interface with an execute method to manipulate the requests. In addition I used move method in getMessage and preparedEmail because, at this moment, they are specific to its respectively concrete handler. Here is how the code looks like after this changes.

image6

image7

image8

image9

Compile and test one more time.

To complete this refactor we must call Handler.execute() for all requests, independently of its type. This is possible by creating a factory method, which returns the correct handler depending on the request’s actionName. However, the conditional statement will continue making part of the code. So, I’ll use a different solution. To define which concrete handler instatiate, I will make use of a Map of actionName, mapping the name of the request to the correct handler. The final result is shown below.

image10

Now, the code is much more clean, extensible and readable.

This is just a little of what Refactoring to Patterns addresses. There is a lot more funny things there.
If you got interedted, you can find the whole refactorings catalog here. Enjoy it.

See you,


Fernando

February 10, 2009

Google Maps API: Rendering GPolylines and GSteps

Filed under: ASP.NET, google, programming, web — Tags: , , — nandokakimoto @ 3:26 am

Hello everybody,

due to the success of the last 2 posts (here and here) related to ASP.NET and Google Maps API, I decided to dedicated one more post to this topic. Today, we are going to work on GRoute, GPolyline and GStep objects for creating customized maps. Maybe you are going to say that this objects was already covered by others posts, however we will use a different approach. Instead of rendering google result and instructions automatically, we are going to do this by ourselves. That’s how it works.

First of all, I will start with an application similar to that created in later posts. So, we have a map, 2 text fields and a button. After the button ‘onclick’ event, the route is displayed on the map and the instructions on the left panel, as shown the picture below:

image1

Note that the map route and the driving directions were rendered just like magic. All you have to do is passing the map’s and panel’s container to the GDirections constructor and the API works for you. Here is the code used:

code1

Unfortunately, you want to customize the directions result or to change route markers, just like the project that I’m working on in the last months. How use this kind of approach? The first thing is using the deafult GDirections constructor, and do not pass any parameters for it. This will avoid your map and direction’s panel from being populated. Later, you will need to include two options in GDirections.load() function: getPolyline and getSteps. Here is how the new rederPolyline function looks like.

code2

Now, the result comes with all route’s data. For printing driving directions you should use GDirections.getRoute(i) and GRoute.getStep(i) functions, which return each single direction. For printing the route on the map, you should use GDirection.getPolyline() and GMap2.addOverlay(polyline) functions. Here is my default implementation just to demonstrate the use of the API.

code3

In this piece of code I created a ‘ul’ element and added each direction as a new ‘li’ element and add new markers to the map ilustrating route’s origin and destination. The result is shown below:

image2

Now it’s up to you. Use your hability and imagination for creating customized and personal maps.
For more information about the Google Maps API, visit Google Maps API Documentation.

See you.


Fernando

February 1, 2009

Refactoring: write code that humans can understand

Filed under: programming, refactoring — Tags: , — nandokakimoto @ 6:04 pm

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

This is a famous phrase from Martin Fowler and one of the most relevant motivations for refactoring. Martin defines refactoring as “a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior”. However, why should I change my piece of code if it’s perfectly running?

Well, refactoring has four main motivations:

  1. Refactoring improve software project: Without refactoring, your software’s project start deteriorating. As more as people change it, more damaged and more difficult to understand it is. Refactoring is like putting things in their right place and helps to keep code’s quality.
  2. Refactoring makes software easier to understand: programming is like talking with computers. When you are programming you’re telling computers what to do. However, if you talk in a difficult language, which just computers understand, the future programmer will lost a precious time trying to decode what you are telling before start creating code. Refactoring helps keeping your code more readable.
  3. Refactoring helps finding bugs: while refactoring you’re working on code comprehension and structure. With a better code comprehension, it’s easier to look at assumptions you’ve made before and find that they were wrong.  
  4. Refactoring helps programming faster: the other three motivations result in this last one: refactoring makes you create code faster. Refactoring your code frequently makes your code ease to understand and change. So, if you have to add new functionalities, you will not need to lose time trying to figure out what that piece of code means. You go straightforward and make what have to be done quickly.

As I’ve said on the motivations, refactoring must be a programming habit. Every time you change your code, you have the responsibility to deliver it better than when you got it. So do refactoring every time you add new functions, fix a bug or review the code.

Now that you know why refactoring, you need to know how to do it. The essential thing is: have solid tests. Remember that refactoring alters program internal structure without changing its external behavior, which means you must refactor without adding new bugs. One way to guarantee that you’re not adding bugs to your project is running your tests every time you do a refactoring in your code. So, change, compile and test. Tests give you the confident to refactoring and, most of times, give you the agility to write code right and simple.

To know more about refactoring, I recommend reading Martin Fowler’s book Refactoring: Improving the Design of Existing Code. The book comes with a refactoring catalog which shows you a lot of refactoring techniques and samples; it’s really a very good reading. Now, it’s up to you.

See you,


Fernando

Blog at WordPress.com.