Thursday 7 January 2010

UI Code Don'ts

It's important to keep code quality in check constantly in UI classes probably more than others as it typically seems to get out of hand more quickly.  Here are some observations, they hopefully do not fall into the micro-optimisation category but I definitely feel they are bad to have around.

  • Images or other memory hungry objects/resources marked with static.  These objects will never be garbage collected even if they are never used.  A shared object should store these images short term or SoftReferences should be used to store the images for a greater time without the danger of memory leaks.
  • Style information spread out across the whole program.  Especially Font objects, this seems to be the first thing to change and if it is spread out across the whole project then its going to be a mess.
  • Creating new Color objects in setters.  This causes a couple of problems, you're creating new Color objects all over the place which is only a minor problem but still pointless.  The other problem is understandability, it's hard to see what that colour is from the RGB constructor.
  • Magic numbers.  Not much need to explain why this is bad, please name them.  If there are too many then create a separate class to house them, you can even use a static import to keep code readable.
  • Too many anonymous classes.  Anonymous classes are useful buf too many look ugly (I don't like the syntax noise) and can cause memory leaks as the reference isn't explicit.
  • SwingTimer.  Please no!  Even if you know the memory leak pitfall, it's still too easy to fall into it.  Just avoid.

    This is just a short list off the top of my head, I'll update it if I think of anymore.

    No comments: