zoode.org

Homo mundus minor  



:: contents

projects
about

:: logs

March 2004
MonTueWedThuFriSatSun
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31     

:: log archives

March 2004
February 2004
January 2004
December 2003
November 2003
October 2003
September 2003
August 2003
July 2003
June 2003
May 2003
April 2003
March 2003
February 2003
January 2003
December 2002
November 2002
October 2002
September 2002
August 2002

:: log categories

A.I.
ActionScript
C#
CSS
General
Java
JavaScript
JScript .NET
Math
SVG
XHTML
XML
XPath
XQuery
XSLT

:: search logs



:: search zoode.org








03.03.04

log   Command Pattern or The Menu Item Who Knew Too Much  -  at 09:25:41

Graphical User Interface applications handle user interaction using an event driven programming model. The user clicks a button, or presses a key, or activates a menu item and something cool happens. Different environments and programming languages manage event handling by using function pointers, callbacks, delegates, listeners or similar mechanics. But above that low level event handling issue, there lies a higher level problem: how to handle user requests, how to execute operations based on those requests?
For example, let's assume we are writing a desktop application. After that the user clicks a menu item for opening a file, how do we match "open file" request with the "open file" operation?
Here is some sample code in C#; the user clicks on fileOpenMenuItem and we open a file:
//...
this.fileOpenMenuItem.Click += new System.EventHandler(this.fileOpenMenuItem_Click);

private void fileOpenMenuItem_Click(object sender, EventArgs e) 
{
	// a lengthy method follows
}
Now, imagine we want to do the same thing (opening a file) once the user clicks a button too. The first reflex would be to use "Extract Method" refactoring technique and write a method for opening files, so that we can reuse that method many times.
private void fileOpenMenuItem_Click(object sender, EventArgs e) 
{
	OpenDocument();
}
public bool OpenDocument() 
{
      // place your code here    
}
Now, assuming that an average application will have around 50 menu items (just an average number), we may end with 50 methods like above. After writing a few methods, we may ask ourselves if we need to move methods to the classes they belong (yes, "Move Method" refactoring technique). We may come up with a few classes (like one for handling file I/0 operations, etc).
Even if we create extra classes and move methods to those classes, still our application design is not object oriented. We solve the problem using procedural programming methodologies (just write functions and invoke them when needed). What do we need? We need an extra level of indirection.
At this stage, the menu item (the object which receives the request) is *tightly coupled* with the class which executes the operation. The menu item knows the receiver of the request, but it shouldn't know.
Enter Command Design Pattern.
Command pattern introduces an interface for executing an operation and *decouples* the invoker (menu item) from the object which performs the operation. So we can write an interface or an abstract class named Command, and create concrete classes which will implement this interface or extend this abstract class. For example, the FileOpenCommand will create a binding between the *receiver* object and the file open operation. The client (in our case, the Forms application) will create a FileOpenCommand and sets its receiver (for example FileIOManager class). The menu item will just ask the Command to carry out the request, but will not know the details about the receiver object (which actually performs the operation).
At its basic form, we can define an abstract class like this:
public abstract class Command
{
	public abstract void Execute();
	public abstract void UnExecute();
}
By abstracting commands as first-class objects, we have new possibilities such as developing an undo/redo system, hence the UnExecute method. We can keep a history list of commands and offer an arbitrary level of undo/redo operations (Memento pattern can be key to create such a system).
Our concrete command class may look like this:
public class FileOpenCommand : Command
{
	public Receiver receiver;

  	public FileOpenCommand()
  	{
  	}

  	public override void Execute()
  	{
    		receiver.DoAction();
  	}
}
And, at last, the menu item can be decoupled in a nice way. We just set its related command object, and when it receives the request, it passes the request to the related command object, and it doesn't know anything about the rest.
//..
FileOpenCommand foc = new FileOpenCommand();
fileOpenMenuItem.command = foc;

private void fileOpenMenuItem_Click(object sender, EventArgs e) 
{
	command.Execute();
}
In Catalog of Non-Software Examples of Design Patterns, Michael Duell offers an analogy between an order in a restaurant and the Command pattern: the customer is the client, the order is the command, the waitress is the invoker and the cook is the receiver.

22.02.04

log   Refactoring: An Old Tale  -  at 10:08:00

What is refactoring in the Object Oriented Programming discipline?
Here is a short explanation. You have written a program (or you have inherited one), and it works as expected. You make a post-mortem analysis of the code, you find out that the structure of the application is not that robust, it is hard to maintain and it is difficult to add new functionalities. It works, but you can do much better. So what do you do? You start *refactoring*, you re-write some parts of your code, you make step-by-step alterations in the structure of your program. Those transformations shouldn't affect the behavior of the application, they are just enhancements of the internal structure of the program. After some hard work, you end up with a much better and robust design. This is refactoring. Informally, it's also called "cleaning up the code".
Refactoring doesn't have to be done after writing the entire code of a program, it can be done during the development phase too. It's better if one can refactor earlier. Also let's remember the famous motto: "If it ain't broke, don't fix it". The management (the *suits*) won't let you to do re-writes after shipping the product anyway.
Here, a chess analogy can be made: you analyze your own games or the games of others. You find out the traps layed out for you (and you find out the stupid mistakes too), at the end, you learn to avoid those traps in the next match.
The concept of refactoring has been known for decades, but in the OOP world, it is mostly associated with Martin Fowler, who has written the definitive book on the subject. On the refactoring site maintained by Fowler, you can find the alpha list of most common refactoring techniques. This list and the book are very useful in this field.
When we write code, we have to be able to see most common and basic traps, so that we can avoid Fool's Mate and alike while coding.

Here are some alerters for us:
  • Extensive use of conditionals (if-else if-else or switch statements). Those are good candidates for extracting methods or to use design patterns such as Strategy or State.
  • Comments. Fowler says that comments have a *smell*. We comment something which is not clear or too complex. Can it be simplified?
  • Strings, algorithms based on values of strings. Hardcoded strings. Classes or enumerations can be used instead.
  • Duplicated code (of course).
  • Extensive use of static methods and Singleton classes. This is a sign of procedural programming in an OOP language.
  • Unnecessary subclasses. @see Liskov substitution principle.
  • Unclear names (like "GTUrx.grvtzcx()"). Rename methods, classes, properties, everything in an intelligible way.
  • Methods which are in the wrong class. Recheck if the method really belongs to its class, if not, move it.
Of course, every developer will have his/her own favorite refactoring techniques, but I can guess that extracting methods and extracting classes should be two of the most popular ones.
In his blog, Jay Bazuzi has posted some good articles on refactoring.

zoode log is powered by b2

view this weblog as RSS

copyright © 2001-2003 Ahmet Zorlu