Saturday, November 29, 2008

Finding Patterns in how things work


I've recently been getting exposed to various techniques or patterns used by programmers to solve specific problems, and have wondered if there could have been better ways of designing it. TOday I lay my hands on some material on design patterns and it brought back to me the thrill of solving puzzles and problems! Sometimes when you're looking into the nitty gritty details you lose sight of the wonderful bigger picture. These design patterns have been evolved from years of learning of one's own and others' mistakes and successes, and most existing problems already have a suitable design pattern ready to be used. For most usecases, designing the software can become as simple as fitting the requirements to an available design pattern.

Composition is better than inheritance.
I was going to take an example of a Strategic design pattern, but decided against it as I didn't want my blog to read like a textbook! Essentially, the difference between using inheritance to 'implement' a property, and composing the object with it, is that in the first case, the implementation function has to be defined in the base class itself. In the second case, the design is cleaner and more maintanable, in a separate class.

This Strategic pattern is very commonly seen in code. Whether you use design patterns during the design phase or implementation phase will only depend on how good you are at anticipating/recognizing common functionality!

Do we really need to know design patterns to be a good programmer? What you see in any of the design patterns is basically, solid OO design. Given an existing system, knowing design patterns will help us understand them real quick, as they inevitably implement one of the design patterns or its variations. If you are building a new system too, this knowledge can prevent you from re-inventing the wheel and improve your productivity!
'Write once, run anywhere!'

2 comments:

deostroll said...

I like the abstract factory pattern. Don't know why yet?

Zeba said...

Perhaps because it's a solution to several common problems?

It's exciting to read more about patterns that you have actually seen used, because you know some of the benefits of having used it, but not all!

Also, understanding the pattern behind the API classes makes them easy to remember! I remember I used to HATE the input/output classes in java.io for having badly named classes. Everytime you want to use any class, you need to look up reference. But once I realized I need to treat these classes as wrappers around each other, it became a piece of cake! Thumbs up, decorator pattern!