27 February 2016

Descriptive names

We've all been through our initial programming lessons, creating for loops as for(int i = 0; i<10; ++i) and so on. float s = d / t.

Variable names didn't matter much then.

The confusion begins, when you enter the professional world, write large programs, forget about them and months later, look at the code and wonder what in the world you had written long back. Class names, variable names and function names don't make any sense at all!!!
If you took care to write comments, then they are a saving grace, but only for a while.

Which of these would make more sense to you?

//check if customer age is equal to threshold
void check(double v
{
   if (val == v) {print("yes");} else {print("no");}
}

or

void checkIfCustomerAgeIsEqualToAgeThreshold(double customerAge
{
   if (ageThreshold == customerAge) {print("yes");} else {print("no");}
}

See the difference? No need of comments. No confusion. You understand what the function and variables are there for, just by looking at the code.

The other big advantage is that if you decided to do some refactoring, you wouldn't have to bother changing any comments, because the class/function/variable name itself is the comment!

Same goes with macros.
I see a lot of C++ programmers using...

#if 0
//some code
#endif

...to temporarily deactivate some code. If these programmers get hit by a bus or even if they look at the code many years later, they won't have a clue of why the code was deactivated and whether it is ok to simply delete it.

What if they used this instead:

#ifdef YEAR_CALCULATION_CODE_TEMPORARILY_DEACTIVATED_DONT_DELETE
//some code
#endif

or

#ifdef CODE_FOR_DEBUGGING_DELETEME_ANYTIME

or

#ifdef SWITCH_ON_COLOR_OUTPUT


Same goes with class names. Which makes more sense?:

class Filter{}
class MicroFilter extends Filter {}

or

class AirFilterSuperclass {}
class SpecializedMicroFilterOfCompanyABC extends AirFilterSuperclass {}


  • It makes a world of a difference to the person who maintains the code.
  • It makes another world of a difference to the person who reviews your code.
  • And it makes an entirely different world of a difference to the business that profits because developers, tech leads and QA teams spent lesser time figuring out the code and spent more time in being able to create a splendid product!

No comments: