Friday, June 12, 2009

When adding enhancements and new features, I prefer using existing mechanisms when I can.

There have been a number of instances in which I had added a general mechanism to support some new feature, so that future extensions could make use of them, only to see specific hacks reimplementing my general mechanism put in when extensions were needed. It doesn't bother me too much, though. As long as the code works, I won't touch it. Plus, I've often been guilty of doing the same, simply due to ignorance of the existing mechanism.

But when existing mechanisms can be used, the solutions tend to be simpler and cleaner.

Here's a really good recent example that I ran into. I had some code that returned some text to be shown on some web page. Now, it also needed to return some shorter version of that text appropriate to be shown on a mobile phone. I imagine the solution would probably have been to pass a new parameter through multiple layers of code to select the desired version of text.

However, I had just localized all the code, so I knew that the locale was an existing mechanism with which different versions of the text could be selected. In particular, the locale variant could be used to select the text for the mobile phone. From the Locale javadoc:

The variant argument is a vendor or browser-specific code. For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX. Where there are two variants, separate them with an underscore, and put the most important one first. For example, a Traditional Spanish collation might construct a locale with parameters for language, country and variant as: "es", "ES", "Traditional_WIN".


So, the only changes needed were adding the mobile phone variants to the localization resource bundles, and for the calling code to specify a locale with a mobile phone variant.

No comments:

Post a Comment