DEV Community

Daniel
Daniel

Posted on

Tips for writing highly readable code

What is readable code

You are writing for humans. Not the machine.

The above should always be at the forefront of a developers mind when designing a system. Assuming your are writing syntactically correct code that functions the machine could not care less about how it is structured, but the developers who work on it later (and that could still be you) certainly will!

"Good code" is highly subjective because whats constitutes as such varies from developer to developer, project to project and year to year. That being said there are still common strategies and guidelines we can adhere to make our lives easier in the future.

I'll go through some more specific examples below but in general:

  • Follow the project style guidelines (if it doesn't have any, suggest some)
  • Write testable code
  • Think SOLID
  • Use common design patterns (where appropriate)
  • Be consistent with file/class naming.

Some examples

Be descriptive

This example is extremely basic and I expect most people write like this by default.

First off - be descriptive with your class, method names and variables. Don't have vars called $i or $model.

Becomes

Abstract (complex) conditionals

Complex conditionals are hard to read and "break the flow" when reading through code.

Consider the following example:

Becomes

I am actually a fan of abstracting conditionals wherever possible. Even if they are relatively simple. They help make your code more testable and by naming your method appropriately you convey the purpose of the conditional in a really nice succinct way.

No magic numbers

Magic numbers are hard coded values that implicitly define logic. Not only does it require us to investigate the code-base to see what the value represents it could also change over time. If a magic numbers value changes we will be required to change it in multiple locations which can lead to inconsistencies.

Becomes

Review

It's easy to over complicate your code but as long as we remember we are writing for humans we can make a much nicer code-base for everyone.

Top comments (2)

Collapse
 
luisfp1986 profile image
Luis Peixoto • Edited

Simple, but highly important tips. Many developers doesn't do this, especially the abstraction part (not only in conditionals, but also in chunks of code that can be reused).

Collapse
 
msamgan profile image
Mohammed Samgan Khan

that magic no. thing is a life saver.