The Holy Grail of good code

The Holy Grail of good code
Reading Time: 6 minutes

Like all things related to beauty, the measure of good code is in the eye of the beholder. There is no clear and limited set of guidelines that would, in theory, result in The Best Code Ever™. However, there is some consensus regarding a few best practices that highly improve readability and clarity. I will try to present some of these practices, and run through a set of examples that you can easily apply. But first… why even bother?

Why good code matters


Most developers will immediately say that good code is for the sake of the team, i.e. if one of your co-workers needs to help out on a larger feature, they will benefit from the readability and clarity, and therefore they will have an easier job. But it’s more than that. In my opinion, qualitative code is a reflection of its writer. An asset of for their own testing and debugging skills. By the way, every best practice around is somehow related to code quality: TDD (Test Driven Development), documenting,  estimation, open-source and collaboration are all much easier on good, modular and self-explanatory code. Interviewing for developer jobs? I won’t even go there with this article, but we do talk about it in our Interview Tips article.
For more details about such best practices and how they intertwine, I recommend Uncle Bob’s book “Clean Code”. The entire toolset of the modern developer is beyond the scope of this article, so let’s focus on some simple recipes for good code. You can also have a look at our book recommendations for developers.

Recipes for good code


Suggestive naming

When using a framework, stick to the principles it offers: name files and folders using consistent casing and always organise everything into clearly delimited folders. For a classical MVC framework, I recommend the following minimal folder structure:

  • Models
  • Repositories
  • Observers (if necessary)
  • Services
  • Tests

I also suggest having a few Exceptions folders, but not necessarily at the first level, e.g. it is better to group your exceptions around certain services like Services/PaymentServices/Exceptions .
Inside each folder, you should label classes in a clear fashion. Code to interfaces. A lot. Prefer the -able  naming for interfaces (Searchable , Editable ), but if it sounds weird, use the -Interface  naming instead (CustomListInterface , PaymentInterface ). The same goes for using other concepts, like Mixins in Python or Traits in PHP: label them accordingly, using the name of the concept as part of the filename.
Variables and functions are another clear target of this best practice. Even if it sounds too long, it’s preferable to name your variables partialPaymentAmount , fullPaymentAmount , totalAmount  etc. rather than a  or amt . It is a more “human” naming. With functions, proper naming also suggests some improvement possibilities. Using the word “and” inside the name of a function is usually an indicator that it doesn’t apply the Single Responsibility Principle and can be broken down into separate functions. Don’t shy away from prefixing functions: getters should be named like getPaymentAmount , validators like validatePayment , creators like createPaymentLineItems , setters… well, you get the point.

Coding standards

Always adhere to a Coding Standard as recommended by the framework you are using, or otherwise by a large part of your programming language’s community. We’ve covered PHP, Python, NodeJS and Angular when writing articles, and, as you might have seen, each coding standard is different. What is important is to keep spacing and braces consistent with your chosen coding standard. Another couple of things which are staples in our company’s projects:

  • having an empty line before return statements
  • always surrounding blocks with braces, even if they contain just one instruction
  • empty lines between import/use/include statements and the body of the source code file
  • empty lines between different blocks of code (e.g. if statements follow a longer foreach )

Apply Occam’s Razor

If you look at your code and it seems complicated, remember there is always a simpler way. That simpler way may involve breaking down functionality into more functions, or otherwise detangling it. To avoid complicated, nested if  structures, I recommend this short guide I’ve written on Medium.

To comment or not to comment?

When talking about code quality, most people will refer to it as self-documenting. Indeed, there shouldn’t be many comments in your code, simply because adhering to strong coding principles will provide the code with most of the needed documentation. However, there is an important exception to this rule. When using an approach which might seem odd to you or your co-workers, I encourage you to comment and explain in 1-2 lines why you chose that implementation. Here’s an example from my own codebase:

// this initial filtering done for performance reasons, to avoid lengthy database calls
// max Contracts per Parcel is 5, so worst case will be iteration over
// C{1}{5} + C{2}{5} + C{3}{5} + C{4}{5} + C{5}{5} = 5 + 10 + 10 + 5 + 1 = 31
// still better than running the query in the entire database
[ ... code ... ]

Also, when commenting out functionality, it is best practice to also comment on why those lines weren’t elliminated altogether, e.g. //commented out because functionality is not yet merged from the develop branch .

Hunting for “bad” code


By this point you’re probably thinking: “OK, but *my* code is not bad.”. Or “OK, but how do I know where to start exercising these practices?”. I won’t go into much detail about this, since it is another one of those things beyond the scope of this article. However, I will enumerate some possible indicators to “bad” code, which should help you identify where you can start with the application of these practices:

  • do you find it difficult to write unit tests? Very often difficulty testing is due to coupled and tangled code.
  • do you have long classes (over 200 lines for Services, 100 for Controllers) and methods (over 20 lines)? It might be the case that you bundled up too much functionality in the same class and/or method.
  • do you swear by your code that it respects all SOLID principles? Good code should respect the most respected industry standards.
  • advanced: does your code… uhm, smell? Code smells are symptoms indicating deeper technical problems, and some of them you might be familiar with: duplicated code, too many parameters in methods, classes that do everything but the kitchen sink etc.

Keep on growing

A joke in my country is that “The smart person thinks they’re stupid, it’s the stupid ones who think they are smart!”. This applies to programming as well, in the sense that being aware of code problems does not mean you are a bad developer. By all means, it is the exact opposite: conscious and continuous improvement of our skills is what makes us good. After all, practice makes perfect.

We transform challenges into digital experiences

Get in touch to let us know what you’re looking for. Our policy includes 14 days risk-free!

Free project consultation