Montag, 20. Februar 2012

Clean Code #1: Don't repeat yourself

I started this series with my first post and some statements but without real techniques. This series is about applying clean code in the real world. I will use the clean code developer rules simply because i think they gather it up pretty well. The page is in german, but I'll explain the topics I'm talking about.
So, this series starts with some very basic advice: Don't repeat yourself. The DRY principle is why there are procedures, functions, methods... To reuse code. If you copy code and past it to another part of your software, you should stop immediatly. Are you copying one statement? Ok, but is it a complex statement like the check for some kind of status. I mean the
if customer.orderStatus = 1 AND customer.WantRecieveNewsletter AND customer.email NOT NULL
kind of statement. This is dangerous, because if you check for this condition in three different parts of your application and then decide that you want to also check for status 2, you have to change it everywhere. Make it a method and use it like this:
if customer.sendNewsletter

Of course this also applies to bigger stuff involving more lines of code. My approach to this is: If I copy something and it's more than one statement, I think really hard. Most of the time, I end up removing the dublication by creating some kind of method, class or whatever usefull in the specific case.

Is it usefull? Let me say this: Most of the time I have to change our system because of a change request, I have to apply the change in one place. I don't have to search source code, I don't have to worry about forgetting any place. I can test more easily because I can isolate the behaviour and test it on it's own. It's worth the effort!

Up next: KISS!

Keine Kommentare:

Kommentar veröffentlichen