Clean Code

David Losert

Passionate Software Engineer

& Aspiring Craftsman

 

              Fullstack Developer at

              Virtual Identity 

 

              Co Organizer of

              JSCraftCamp
 

 

 

david.losert@gmx.de

david.losert@virtual-identity.com

Clean Code

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.  

Martin Fowler

Overview Clean CODE

  1. What is it?
  2. Why do we need it?
  3. How to write it?
  4. Practice time!

1. What is it?

Clean code always looks like it was written by someone who cares.”

Michael Feathers

You know you are working on clean code when each routine you read turns out to be pretty much what you expected.“

Ward Cunningham

Clean Code

=

Code that is easy to understand

2. Why do we need it?

Do you write your code like this...?

...or more like this?

Truths about coding:

  • time reading > time writing
  • you forget your own code quickly
  • your team members think differently
  • the only constant is change

 

=> CLEAN CODE SAVES TIME

=> CLEAN CODE IS BUSINESS CRITICAL

3. How to write it?

take your time

  • refactor frequently 
  • after it works: look at your code and improve it
  • take baby steps (TDD helps!)
  • have no fear to throw things away
if((e.startDate <= new Date() || e.endDate >= new Date())) {
    // do something
}
if(eventIsToday(e))) {
    // do something
}

// ...

const today = new Date();
const eventIsToday = (event) => 
    event.startDate <= today && event.endDate >= today

vs

Tip #1: Show Intent

function eventHandler() {
    if(!$(this).hasClass(('ext')){
       $(this).animate({width: 120};
    }
 }
function enlargeLink() {
    let linkElement = $(this);
    if(!isExtended(linkElement)){
       enlarge(linkElement);
    }
 }

const isExtended = (element) => element.hasClass('ext')
const enlarge = (element) => element.animate({width: 120})

vs

Tip #2: Use revealing names

TiP #3: Let a function do one thing only

function login(username, password) {
    fetch('/login', {
        method: post,
        body: {
            username,
            password
        }
    }).then(() => {
        window.location = '/app';
        
    }).catch(() => {
        window.location = '/error';
    })
 }
function login(username, password) {
    requestToken(username, password)
        .then(redirectToApp)
        .catch(redirectToError);
 }

const requestToken = (username, password) => 
    fetch('/login', { method: 'POST', body: {username, password} });

const redirectToApp = () => window.location = '/app';
const redirectToError = () => window.location = '/error';

vs

TiP #4: Remove code duplication

function enlargeOrShrink(button) {
    if(button.hasClass('ext')) {
        button.animate({width: 20, speed: 200, type: 'slide'});
    } else {
        button.animate({width: 120, speed: 200, type: 'slide'});
    }
 }
function enlargeOrShrink(button) {
    if(button.hasClass('ext')) {
        expandTo(button, 20);
    } else {
        expandTo(button, 120);
    }
 }

const expandTo = (element, width) =>
    element.animate({width: width, speed: 200, type: 'slide'});
function enlargeOrShrink(button) {
    let width = button.hasClass('ext') ? 20 : 120;
    expandTo(button, width);
 }

const expandTo = (element, width) =>
    element.animate({width: width, speed: 200, type: 'slide'});

vs

vs

TiP #5: Avoid comments

// If event is today
if((e.startDate <= new Date() || e.endDate >= new Date())) {
    // do something
}
if(eventIsToday(e))) {
    // do something
}

// ...

const today = new Date();
const eventIsToday = (event) => 
    event.startDate <= today && event.endDate >= today

vs

TiP #6: SerIously: Avoid comments - they tend to lie!

/**
 * The following code filters the all documents of a project by 
 * providing the type as a argument to the signature.
 * Test with unstrict operators as the type is a number and it can also be a number in a string
 */
function filterByDocType(project, docType) {
    let allDocs = project.documents;
    return allDocs.filter(doc => doc.type === docType);
}
Commit 8f2fee4 David Losert <david.losert@virtual-identity.com>:
Message: "Adjusted docType to always be a string"

From Version Control:

TiP #7: Make it read like a book

function login(username, password) {
    fetch('/login', {
        method: post,
        body: {
            username,
            password
        }
    }).then(() => {
        window.location = '/app';
        
    }).catch(() => {
        window.location = '/error';
    })
 }
function login(username, password) {
    requestToken(username, password)
        .then(redirectToApp)
        .catch(redirectToError);
 }

const requestToken = (username, password) => 
    fetch('/login', { method: 'POST', body: {username, password} });

const redirectToApp = () => window.location = '/app';
const redirectToError = () => window.location = '/error';

vs

TiP #8...n: READ THE BOOK

4. Practice TIME

Easy start:

More sophisticated:

Clean Code Presentation

By Dave L.

Clean Code Presentation

My first presentation on a meetup about my favorite topic: Clean Code!

  • 4,714