Thursday, May 14, 2015

The relationship between DRY and Coupling

I think that the DRY principle is a subset of* "Low Coupling".

DRY & Coupling:

If one rule is expressed in two places in your code (violating DRY), and you want to change the rule, you must edit both places. This is coupling.

byte[] OpenFile(string fileName)
    // Is it our file type?
    if (fileName.Extension == ".foo") ...

void AutoSaveFile(byte[] contents)
    path = Path.Combine(directory, DateTime.Now.ToString("dd_MM_yyyy") + ".foo");

If we decide to change our file extension to the much more reasonable ".bar", then we must edit both.

*possibly equivalent to

The Prime Refactoring

I used to believe that the two most important refactorings were Extract Method and Rename. The way they deliver value and the way they are used are quite different, so it's hard to compare, so I figured they had equal value.

Recently I've decided that Rename is slightly more urgent, if not more important. It is the first refactoring to learn; the first to teach; the first to apply. (Just slightly)

The problem is code that lies to you. It says it's doing one thing, but actually it's doing another. You either have to think really hard to figure that out (slow) or you misunderstand the code and write bugs.

Fix that first. It may lack cohesion, have tight coupling, and lots of duplication, but first introduce good names. Rename to make the code stop lying to you.

(Soon afterwards, start using Extract Method to give you more things to name.)