Luan Nguyen

@luanotes

How to write Clean Code?

Lessons Learned from Robert C. Martin

Photo by rawpixel

Table of Contents:

  • Overview of the Clean Code book — Robert C. Martin(Uncle Bob)
  • What is Clean Code?
  • Tips to write Meaningful Names in software.
  • The rules to make a Function easy to read and understand.
  • Comment code, should you comment on bad code or rewrite it?
  • The benefit of Unit Test, Test Driven Development (TDD)

Overview

“Master programmers think of systems as stories to be told rather than programs to be written” — Uncle Bob.

Clean Code — A Handbook of Agile Software Craftsmanship is a must-read book for developers, especially when you want to be a better software developer. This book explains what is the clean code and best practices to help you write clean code.

It helps me enhance coding skills and make remarkable in my career path. And through this article, I want to share my lessons learned and summarize the key points of the book, I think it very useful to you.

About the Author

Robert C. Martin, commonly called Uncle Bob, has been a software professional since 1970 and author of many famous books as The Clean Coder, Clean Architecture and more.

What is Clean Code?

Have many definitions about Clean Code by well-known and deeply experienced programmers asked by authors, they thought what?

Bjarne Stroustrup, inventor of C++ and author of The C++ Programming Language:

I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.

Grady Booch, author of Object Oriented Analysis and Design with Applications:

“Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”

“Big” Dave Thomas, founder of OTI, godfather of the Eclipse strategy:

Clean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. It provides one way rather than many ways for doing one thing. It has minimal depen- dencies, which are explicitly defined, and pro- vides a clear and minimal API. Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.

Based on the above definitions and my coding experience, main Characteristics of Clean Code includes:

  • Elegant: Clean code is pleasing to read, should make you smile.
  • Readability: Clean code should read like well-written prose.
  • Simple: Do one thing with the Single Responsibility Principle (SRP).
  • Testable: Run all the tests.

In the next section, I’ll share about how to write Clean Code.

Meaningful Names

Everything in an application has a name, from variables, functions, arguments, classes, modules, to packages, source file, directories.

Naming things is the most common problem of every developer. As Phil Karlton said that:

“There are only two hard things in Computer Science: cache invalidation and naming things” — Phil Karlton
Naming things is hard

Names are the powerful way you communicate your code’s intent to developers who read your code, including yourself. Choosing good names takes time but make your code better and cleaner. It makes your code easy to read by other developers, as well as yourself in the future.

And in this book, Uncle Bob share some simple rules to create good names:

Should:

Use intention-revealing Names

That means choosing names that reveal intent, the name should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent. It makes your code easier to understand and change later.

# bad 
t = Date.today # the name t reveals nothing.

# good
today = Date.today

Use Pronounceable Names

Humans are good at words and words are, by definition, pronounceable.

If you can’t pronounce it, you can’t discuss it without sounding like an idiot. This matters because programming is a social activity.

# bad 
ymdhms = Time.current # date, year, month, day, hour, minute, second
# good
today_timestamp = Time.current

Class Names

Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info in the name of a class.

A class name should not be a verb.

Method Names

Methods should have a verb or verb phrase names. Examples: createUser, deletePhoto or save

Pick One Word per Concept

One and the same concept in your application should have the same name. For example, it’s confusing to have fetch, retrieve, and get as equivalent methods of different classes.

Using the same word per concept will help developers more easy to understand the code.

Should NOT:

Encodings

Encoded names are seldom pronounceable and are easy to mistype.

Mental Mapping

Readers shouldn’t have to mentally translate your names into other names they already know. This problem generally arises from a choice to use neither problem domain terms nor solution domain terms. 
One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand.

Pun

Avoid using the same word for two purposes. Using the same term for two different ideas is essentially a pun.

Functions

How do you make a function communicate its intent? There are some best practices help you write good functions easy to read and change.

Small

The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that.

Do One Thing

Functions should do one thing. They should do it well. They should do it only.

Follow the Single Responsibility Principle (SRP)

Function Arguments

Functions should have < 3 arguments.

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification — and then shouldn’t be used anyway.

Don’t Repeat Yourself (DRY)

Duplication is a problem in software. Many principles and best practices have been created to reduce duplication code.

Use a Descriptive Names

Same with rule meaningful names which explained in the above section.

“Master programmers think of systems as stories to be told rather than programs to be written” — Uncle Bob.

If you apply well these above rules, your functions are readable, easy to understand, nicely organized and to tell the story of the system.

Comments

“Don’t comment bad code — rewrite it.”
— Brian W. Kernighan and P. J. Plaugher

Comments do not make up for bad code.

Say NO with comment code !!!

Unit Tests

Test code is just as important as production code.

The Test Driven Development (TDD): is a software development process that relies on the repetition of a very short development cycle: requirements are turned into very specific test cases, then the software is improved to pass the new tests, only.

Uncle Bob describes TDD with 3 laws:

  • First Law: You may not write production code until you have written a failing unit test.
  • Second Law: You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
  • Third Law: You may not write more production code than is sufficient to pass the currently failing test.
The Cycles ofTDD by Uncle Bob

Tests are very important to an application as the production code is, because it makes your code is clean, flexible and maintainable. If you have tests, you do not fear change to the code and reduces bugs.

Unit tests help me get more deep sleep!

Conclusion

In this article, I shared with you about useful lessons learned about Clean Code from Robert C. Martin(Uncle Bob). It’s very essential for every developer who wants to be remarkable in the career path.

References:

More by Luan Nguyen

Topics of interest

More Related Stories