Clean Code

Clean Code: Principles and Tips

"Life is very simple, but we insist on complicating it."

Confucius

What is Clean Code?

We can always improve our code. Nothing is perfect, although there will always be flaws, but you, as a professional developer, can strive to make the code as "clean" as possible. That's why here we'll look at some quick points to help you understand all the factors involved in making your code "clean code"...

  • Clean Code is a code that is easy to read, like a book where every word is transformed into an image and you can actually visualize everything. Like watching a movie, in short, it should be human readable.
  • The code must be easy to change.
  • The code does only one thing at a time.
  • The person writing the code is genuinely concerned about who reads and/or maintains it.
  • The logic is simple and leaves no room for errors to appear. It does not tempt others to modify it, which will make the code worse.
  • The code is focused on each function, the classes exhibit the responsibility they have, and this remains completely independent of the surrounding classes/functions.
  • The code must have unit tests.
  • The code makes the programming language look like it was made to solve the particular problem.

These are the Clean Code principles you should know.

"Dirty code is hard to understand, more complex than it should be, not easy to test, and causes other developers to be filled with frustration. While it may take longer to write clean code in the short term, it is more than proven that writing clean code will save everyone time and effort, this means less money in the long run."

It is also important to clarify that clean code is not based on language-specific rules. Instead, it is based on language-independent principles agreed upon by the developer community.

 Universal principles to be followed:

In this previous article, Dario takes a more extensive look at the 5 principles that every programmer should know in order to expose the SOLID principles.

  • You aren't going to need it. "You aren't gonna need it" A developer should not add functionality unless they feel it is necessary. YAGNI

\Clean

Let's talk a little about the rules for names:

  • Use names that can be pronounced well.
  • Choose descriptive and clear names.
  • Use searchable names.
  • Make it easy to remember them.
  • Use names according to the context.
  • Use names that are consistent with each other. For example, it is confusing to have " search" and "get" as equivalent methods in different classes.
  • Use the same language in the names of variables, functions: English, French, etc. In our case, cecropians prefer to use English because it is a standard.
  • Avoid coding and do not add prefixes or write information.

\Clean

How to make comments:

  • Code is the best documentation.
  • Comments are difficult to maintain and do not tell the truth about the code, so try to avoid them. They are almost always out of date.
  • Do not be redundant. Avoid unnecessary comments.
  • Use them only as a clarification of the code.

...And what about the design rules?

  • Declare instance variables at the top of the class.
  • Declare local variables as close as possible to their use.
  • Constants must be declared at the top of the class or in a constants-only class.
  • Follow the Demeter's Law: a class must know only its direct dependencies.
  • Coding is like writing; trying to express the programmer's purpose and the code.
  • Use dependency injection (DIP).
  • If you use third-party libraries, wrap them, so that if they change, only the implementation of your wrapper should change.
  • It is a good idea to separate the concepts vertically.
  • Place the methods in a top-down direction.

Code readability:

  • Avoid files that are too long.
  • Good files have a header, put the main functions first and the utilities or details later.
  • Although we now have large screens and high resolution, avoid making the lines too long (80 to 140 characters is perfect, in my case 120). You will get used to be more concise and your code will be more readable.
  • Be consistent, keep the same rules throughout your team.

Classes:

  • Classes should be small.
  • Classes must have a single responsibility and a single reason for change(SRP).

\Clean

  • Keep utility methods and variables private, except in some cases for testing purposes.
  • Correctly use the package levels: public, protected or package.

Objects and Data Structures:

  • Hide internal structure.
  • If you can, call only the methods of your class, of the objects you have created, and avoid calling methods that are accessible through these objects (Demeter's Law).
  • Improve object decoupling.
  • Variables must be private and must be manipulated by getters and setters, but remember that it is not necessary to add getters/setters to each variable to expose them as public.
  • The base class must not know anything about its derivatives.
  • Objects expose behavior and hide data. In contrast, data structures expose data and lack (meaningful) behavior.

Exception handling:

  • Using exceptions to throw errors makes the code cleaner than checking status values throughout the code.
  • Provide sufficient meaning to determine the cause and location of an error.
  • Wrap third-party library APIs to remap your exceptions as needed.

Concurrency management:

  • Concurrency, while it can improve program performance, is difficult, so use it wisely and only when necessary.
  • Keep concurrency control separate from other code.
  • Know basic concepts and basic programming models such as mutual exclusion, starvation or deadlocks.
  • Create small closed sections.

Unit Tests:

  • Fast: Unit tests must be fast and executed in a short time.
  • Independent: tests should not depend on each other.
  • Repeatable: tests must be reproducible in any environment.
  • If you have code covered by tests, you won't be afraid to modify and break it.
  • TDD: build your software using tests to guide your development.

\Clean

Keep an eye out for our next posts, we will have a more developed article on unit testing.

Let's draw some conclusions, in this summary, I will leave a little "more of the same" but it is worth repeating, and these are some of the things that have helped me in my career. I am sure you will be able to read them very quickly, but applying them, is another thing, it may well take you a lifetime. I've been developing applications for over 20 years, and still, sometimes, I have to stop and think about them as part of the essential parts of this profession.

  • Take the code and break large pieces of code into small functions.
  • If you have not solved the problem by the time you leave work. Turn off the computer and leave it for the next day. Don't think about the problem anymore.
  • Principle YAGNIDon' t code more than you've been asked to code. Don't anticipate the future, just create something that works as soon as possible. Code only the parts needed to solve the current problem.
  • You don't need to know everything, nor all the existing frameworks. The most important thing is to have a good base. Know the language in depth before starting with a Framework.
  • KISS: \ "Keep it simple, stupid" or "keep it stupidly simple" is a design principle that states that most systems work better if they are kept simple rather than complicated. And while this is logical, it is sometimes difficult to achieve.
  • Don't overthink it.
  • If you are too long with a problem or error, walk away and come back to it later. Often, the best solutions to problems occur to me on my way from my office to the bathroom. It's also advisable to take a walk when you're angry with a client or co-worker, especially if you want to keep your job.
  • First solve the problem and then write the code. Don't start coding without knowing what to do.
  • If you want to learn something, practice. Make examples and make them work because reading about something is not enough.
  • Never give up, in the end, one way or another you will work it out. There are bad days, but they will pass.
  • Rest, rest and rest. The best way to solve a problem is to have a calm mind.
  • Learn how to use Software design patterns. Design patterns are solutions to common problems in software design. Each pattern is like a model that can be customized to solve a common design problem in your code. (Don't reinvent the wheel)
  • Ask for help when you need it. Don't waste your time.
  • Practice makes perfect.
  • Learn how to reuse components.
  • Follow documented standards.
  • Users are not technical people. Think about that when developing your user interface.
  • Always use a source code control system such as Github or bitbucket and make small, frequent git commits.
  • And finally, have patience and love for what you do.

I am sure that if you are starting as a developer, these lines will help you a lot in your way, also, if you are an experienced developer surely they have helped you to refresh some recommendations that we all know, but sometimes we forget, take the ones that interest you and ask if you need the rest.

\"\"

Carlos Villaronga

Technical Lead

Scroll to Top