lunedì, febbraio 19, 2007

Code Gallery: defensive coding!

Nothing frights more a developer than a NPE! A C# reporting app, period: year 2007:
public AReport generateReport(...)
    //do somethig
    AReport report= new AReport(...);
    if ( report != null )
      return report;
      return null; //!!!!
Comment: how to smartly avoid a (brrr!) feared NPE! Here's the clever algorithm, stated after long mumble numble the author:
1- instantiate an object with a new Something()
2- don't rely on "new"! what if it doesn't work? (what if the moon crashes on hearth, I'd reply...)
3- test the newly instantiated object: is it null?
4- if yes... That's the unexpected case, I think! our man had to be in real trouble: what to do NOW? Here comes the artist touch and sensibility, if it is null... well... simply... return null!

A great little cameo: how to look busy and fill of dust a 3 lines method.

2 commenti:

Luigi Viggiano ha detto...


Luigi Viggiano ha detto...

I think you should use my code colorer tool ;)