Friday, December 24, 2004

Use the patterns, Luke

Patterns are good. Everyone agrees with that...which doesn't mean that everyone uses patterns. But even worse than not using patterns is using them wrong. Let's imagine you want to create a Singleton, but you implement it wrong. Because it's stated that it is a pattern we assume it is right...we know what it does. This makes it hard to find the problem...the same way we don't test if Sun's API is right, we assume the pattern is correct. And probably it will take some time till someone finally finds it.

An innovative approach to help in this problem is PEC (Pattern Enforcing Compiler). What it does is check if your implementation of the Design Pattern (Singleton, for example) is correct, at compile time. It's very easy to use. You only need to add the following to your code (copied from website):

  1. Add "import pec...*;", e.g. "import pec.compile.Singleton.*;"
  2. Add "implements ", e.g. "implements Singleton"
  3. Compile with PEC
If your code doesn't implement a correct Singleton (for example) a compile error is shown (the error messages are normally very good explaining what is missing in the pattern). I think this is a good idea and may prevent a few headaches. But there is a catch...there is no magic here...not only you need to implement the Singleton right, you have to implement Singleton the way PEC thinks it should be implemented. I'm not saying that PEC doesn't "enforce" a good Singleton pattern, but there are always different ways of implementing a pattern. For example, in PEC a Singleton must have a static method called "instance" to retrieve the Object instance (no other name). However, if you adhere to PEC guidelines, you gain a powerful tool against those nasty-hard-to-find-bugs. The good news is that PEC is extensible. You can add your patterns, either new ones, or different implementations of those supplied by PEC.
So, in conclusion this can be a handy tool if you adhere to PEC's implementation of patterns or you have the time to extend PEC and create your patterns.

0 comentários: