Principles of Clean Code

Clean code?

Why do we need clean code?

What can we do to have clean code?

Warning: these are my personal opinions :-)

Keep your code simple

Write code that looks familiar

Always follow the language conventions


Avoid deep-nesting

The more levels of nesting, the harder code is to read

        function myFunc(foo, bar) {
            if(foo) {
                if(bar) {
                   // body of function
                }
            }
        }
    

VS

        function myFunc(foo, bar) {
            if(!foo || !bar)
                return;

            // body of function
        }
    

Keep variable names short but descriptive

Don't do too much in a single line

modules

Design systems as a series of modules

cohesion

Maintain high cohesion within modules

loose coupling

Write loosely coupled code

Write functions that required as little to run as possible

        function func(manager) {
            var id = manager.info.getId();
            return store.get(id);
        }
    

VS.

        function func(id) {
            return store.get(id);
        }
    

Use globals sparingly - they are EVIL!

Global variables have no locality

Global variables have no access control

Global variables lead to namespace pollution

DIE

Avoid spaghetti code

CRUD
paging

Always page your data

test

Write specs for your code

document

Comment all public APIs (e.g. javadoc)

/* Code Commenting */

// A comment should explain WHY a piece of code is like it is, not what it does.

// Don't summarize what a block of code does, rewrite it!

Iterate quickly

Refactor ruthlessly

Rewrite bravely

Source

Rouben Meschian

rmeschian@gmail.com