Code-OCD

Thameena S
2 min readJul 25, 2020

How does your room look when you have all your things cluttered on your table/shelf? How long will it take to find things from the heap of dump?

Image: The Art of Programming by Geek & Poke

Thats exactly how a codebase written with more than 25 lines of code in a function and methods not at the right place will look like.
The code might run without errors and you might very well understand the code you wrote.
But the quality of code you write should be determined by how well another developer can understand your code.

When it comes to object oriented programming, maintaining a clean codebase, is analogous to keeping your house clean. A few things, if taken care, can help in leaving the codebase as a better place for other developers.

Keeping Your Functions Short

Keeping very few things on your table/shelf without dumping things on it, will make your room look cleaner.

Like your room, just 5–6 lines of code in a function, with one function doing just one thing, helps in keeping clean classes.

Meaningful Function Names

The habit of arranging your belongings into small boxes and labelling each box, helps in finding things easily. You don’t have to open each box to know whats inside it.

Being able to understand what a function does without having to go through the lines of code in that function, helps in better code readability. With short functions, the name itself acts as a label and will tell you what that function does.

Putting Things At The Right Place

Everything in the house has a designated place for it. The stove goes in the kitchen and not in the bedroom.

Similarly, every field and method should be in the class that they belong to. Think twice before you write a method in a class. It might have a better place to be in.

Tell-Don’t-Ask Principle

You use your stove for cooking, but that happens from the kitchen. You don’t take your stove to your bedroom to cook.

This is what the ‘Tell Don’t Ask’ principle talks about. Instead of asking a class for its data and then doing manipulations on that data, you should tell that class what to do and then get the result from it. Any manipulations on the fields of a class, should happen from inside the class.

An obsessive compulsion to keep your code clean could possibly be a trait a programmer needs to have. I’ll call it code-OCD!

--

--