<= Home

Self Documenting Code

Posted about over 2 years ago

Long before Martin Fowler’s recent post on CodeAsDocumention I have been advocating it as what I call Self Documenting Code (SDC). I originally preferred the term “Self Describing code” but that confuses some developers because they think first of attributes/meta data when hearing that.

The benefits of applying SDC are enormous and the effort is usually minimal. Unfortunately the most beneficial tenets are what I usually see least applied:

MethodsVsCodeFragments – My personal rule of thumb is if the code is longer then 25 lines then most likely it needs to be refactored. I have been challenged many times that the 25 lines maximum as too impractical but I have found that usually 19 out of every 20 methods that contain more then 25 lines of code could be effectively refactored into smaller more explicit methods.

DeclareVariablesAtFirstUse – It’s hard to read code when all the variables used are declared at the beginning of a function. (Residual Bonus: Abiding by this will reduce the lines of code in your method.)

PolymorphismVsSelectionIdiom – The switch/select case keywords are almost just as evil as static members. :)

MeaningfulName

TightGroupOfClasses

SeparateInterfacesFromImplementation

There are a many more at Ward’s wiki. My personal favorite I almost never see applied is NamedConditions.

NamedConditions – Assign conditional operations to a meaningfully named boolean variable.

NamedCondtions favors

bool accountLimitReached = account.Balance >= account.MaximumLimit;

if(accountLimitReached) {

SendNotification();

}

Over

if(account.Balance >= account.MaximumLimit) {

//Send notification when the acount limit is reached

SendNotification();

}