Clean Code Cheat Sheet

The last time I read the book Clean Code by “Uncle” Bob Martin, I jotted down these notes. For a while, I had these next to me at my desk at work. I figured I would share…

If you haven’t read the book, I highly encourage you to. It is a great read, and pretty short, so it doesn’t take a lot of time. But there is a wealth of information in there. Most of it is obvious once you read it, but then quickly realize you probably don’t actually follow the advice given on a day to day basis.

So here it is, my Clean Code cheat sheet:

Chapter 2

Avoid “noise” words in variable names. Instead of ProductInfo or ProductData, just use Product. “Info” and “Data” don’t provide real meaning or anything more specific.

Use pronounceable names.

Think about the “search friendliness” of a name. If you had to come back in 6 months and find this code, what would you search for? Using constants instead of numbers can also help. For example,

if(crt.size > 100)
    full = true;

is not as good as:

const int MAX_CART_SIZE = 100;
if(cart.size > MAX_CART_SIZE)
    cartIsFull = true;

Class Names should usually be Nouns.
Method names should usually be Verbs.

Chapter 3

Methods should strive for 0 arguments, and almost never have more than 3.
Otherwise, testing every permutation becomes impossible.
This can often be fixed by inverting the method location:

CalculateSalary(employee);

Can become:

employee.CalculateSalary();

Avoid methods with side-effects. Side effects produce temporal coupling.

Functions should Do something or answer something, not both.

Extract try/catch to their own functions to clean up code.

try {
    delete();
} catch {
    logError();
}

Error handling is ‘one thing’ and functions should only do one thing (error handling should take Single Responsibility Principal into account).

Chapter 5

Declare variables as close to their usage as possible.
Local variables: top of function.
Control variables: within loop statement.
Instance variables: Top of class.

Chapter 6

Procedural = Easy to add functions.
Object Oriented = Easy to add classes.

Law of Demeter – module should not know about the innards of the objects it manipulates.

Try to keep calls to a nesting of 1. Don’t chain calls on method returns (side-note, I actually disagree with this one. Linq is a perfect example of where chaining works well. And most functional languages will do better with chaining.)

Chapter 7

If a method can return multiple Exception types, it can be easier to wrap to 1.

Instead of:

try {
    port.open();
} catch (DeviceResponseException dre) {
    // ...
} catch (NullException ne) {
    // ...
}

Try to do:

try {
    port.open();
} catch (PortException ex) {
    // ...
}

public class port {
    public void open() {
        try {
            openInternal();
        } catch (DeviceResponseException dre) {
            throw new PortException(dre);
        } catch (NullException ne) {
            throw new PortException(ne);
        }
    }
}

Avoid passing and returning null.

Chapter 8

Wrap general / broad APIs or interfaces to just what you need. For example, if you need a read-only collection, don’t use IList or ICollection. Think Liskov’s Substitution Principle.

Isolate your code from boundaries. Especially 3rd party boundaries. Use Adapter Pattern to map from 3rd party interfaces to your own.

Chapter 9

Strive for 1 Assert per test, but enforce 1 concept per test.

Refactor common test setups and asserts into methods that compose a special testing domain-specific language.

Chapter 10

Classes should have few instance variables. (unless they are simple data-transfer objects).

Class methods should use many of the instance variables. If an instance variable is not highly cohesive (not used many places) that could indicate a dividing point to refactor out a smaller class.

Classes should follow the Single Responsibility Principle and have only 1 reason to change.

Use inheritance to fix Open / Closed Principle violations.

Chapter 11

Systems should separate the ‘start-up’ process, when objects are constructed and wired together, from the run-time logic. This plays into the Dependency Inversion Principle, and having a single composition root where things are wired together.

Use domain-specific language to move the code closer to the business, to narrow the communication gap.

Chapter 12

Use the Template Method pattern to reduce duplication. This is done by making common bits into an abstract base class and extending it, instead of one class with similar methods.

Use standard pattern names. For example if you make a factory, name it “ProductFactory”, not something like “ProductMaker”. If it is an adapter, name it “DistributedCacheAdapter”, not “DistributedCacheTranslator”, etc.

Advertisements
Tagged with:
Posted in Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

CodingWithSpike is Jeff Valore. A professional software engineer, focused on JavaScript, Web Development, C# and the Microsoft stack. Jeff is currently a Software Engineer at Virtual Hold Technologies.


I am also a Pluralsight author. Check out my courses!

%d bloggers like this: