Thursday 24 July 2008

Some excellent OO programming tips (and discussion)

Some classy advice from munificent on a proggit thread:
  • Do not copy and paste. Move code around, but don't duplicate it. Disabling Ctrl-C on IDEs would improve the world's programming better than anything I can think of.
  • Decouple decouple decouple. Of all of the things you can do to improve code, reducing coupling will, by far, have the greatest impact at making your life better.
  • Don't store what you can calculate. The fewer member variables, the better. Avoid storing any redundant data unless you want to fix synchronization bugs forever.
  • Make classes immutable when possible. It's easiest to use something you can't break.
  • Don't get too excited about inheritance. If you aren't using polymorphism, you probably don't need to use inheritance.
  • Use all of the features of your language. Delegates (function pointers), static (i.e. non-member) functions, etc. are just as useful with OOP as within straight procedural.
  • If you have a hard time naming a class, it's poorly defined. That being said, don't let lack of a name stop you, you can always find and replace later. Likewise, rename classes if their purpose changes over time.
  • Never call anything "FooManager". Objects are supposed to manage themselves. Get rid of the manager and put the code in Foo.
  • Don't be afraid to make little classes. Making a class just to bundle a couple of function args is perfectly fine. A few months later you'll find you've all sorts of other usefulness to it.
  • Refactor constantly. Coding without refactoring is gardening without weeding and pruning. You can't just keep packing new plants into your yard.
There is some good further discussion and qualifications in the sub-comments.

No comments: