Defensive programming complements patch programming. It is a must for those who want to enjoy life outside of programming and not climb the programmer ladder.
Below I'll unfold a short initiation session, so read on when ready ...
Let's start with the basics, I'll give you your motto: An extra safety net can't hurt. It's the salute that a defensive programmer uses to greet other defensive programmers. At the time of this writing, it is not known that defensive programmers have a special dress code, so you'll need to learn the salute by heart, and as a safety net, keep a paper with some sample code of yours at all times with you. This way you can easily prove your membership to the group and you won't be taken as an undesirable TDD- or refactoring-programmer.
A good practitioner of defensive programming requires that you:
1. Extensively use safety nets like if (obj != null) sometimes right after the object is created, so you'll never be responsible for a NPE again.
2. Add extensive comments explaining why you did what you did in the way you did instead of refactoring the code. This way, if somebody does not understand your code, it's completely their fault.
3. Clone an object both when you set it in its container and when you return the object back from the container; this way you'll be extremely sure that nobody will modify the initial object.
4. When creating a class with similar functionality to an existing one, copy and paste the old class; better yet, even if your class will deprecate / replace the old class, leave it there in case someone takes pleasure in investigating obsolete code.
5. When extending a class, to make sure that an inherited method is called, override it and merely call the super version; who knows what happens with the dynamic dispatch mechanism in the JVM and your method won't be called.
Far from being exhaustive, this list should have given you a good picture of this programming style. As a final advice, take some rhetoric classes: they will teach you how to convince the rest of the team that those bugs in your list ... aren't actually yours.
Thursday, February 26, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment