How to write Clean Code?

Lessons Learned from Robert C. Martin

Luan Nguyen
Dec 17, 2018 · 6 min read
Photo by rawpixel

Table of Contents:

Overview

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

About the Author

What is Clean Code?

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.

“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.”

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.

Meaningful Names

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

Naming things is hard

Should:

Use intention-revealing Names

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

# good
today = Date.today

Use Pronounceable Names

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

Class Names

Method Names

Pick One Word per Concept

Should NOT:

Encodings

Mental Mapping

Pun

Functions

Small

Do One Thing

Function Arguments

Don’t Repeat Yourself (DRY)

Use a Descriptive Names

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

Comments

“Don’t comment bad code — rewrite it.”

— Brian W. Kernighan and P. J. Plaugher

Unit Tests

Test code is just as important as production code.

The Cycles ofTDD by Uncle Bob

Conclusion

References:

HackerNoon.com

#BlackLivesMatter

HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Luan Nguyen

Written by

🚀 Software Engineer at ITviec — Interested in Ruby, Python, Design Pattern, Clean Code, TDD, Performance, Scalability — https://fullstackrubyonrails.com

HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean