Easy to maintain code


Created by Jeroen De Dauw for Wikimedia Deutschland
Licensed CC BY-SA 3.0


bit.ly/econ-cleancode

Collection of pointers

We want to go fast

Tradable quality hypothesis

Write code for humans

Software craftsmanship

Naming

Reveal intent

usrsbscr ➜ userSubscription

Avoid disinformation

Use one word per concept

Don't try to be clever/cute

Complexity

Cyclomatic complexity, NPath complexity

Minimize scope, minimize state


function onFirstPost() {
    $messageText = $this->getWelcomeMessageBody();
    if ($this->addFooter()) {
        $messageText.= $this->getWelcomeMessageFooter();
    }
    $this->emailer->send($messageText);

    foreach ($this->getReviewers() as $reviewer) {
        $this->reviewerNotifier->notify( $reviewer );
    }
}
                    

function onFirstPost() {
    $this->sendWelcomeMessage();
    $this->notifyReviewers();
}
                    

Functions

  • Small, few ELOC
  • One level of abstraction
  • Little nesting
  • Single functional area
  • Minimize parameters
  • Command query separation

public boolean set( String attributeName, String value );
                   

if ( set( "username", "NyanCat" ) )
                    

Minimize coupling

  • Number of classes bound to
  • Avoid inheritance
  • Program against "interfaces"

Avoid global state


public function doStuff() {
    FilesystemLogger::log( 'doing stuff on Caturday is madness' );
    DataStore::getInstance()->saveObject( $object );
}
                        

function __construct( Logger $logger, DataStore $dataStore ) {
    $this->logger = $logger;
    $this->dataStore = $dataStore;
}
                            

public function doStuff() {
    $this->logger->log( 'doing stuff on Caturday is madness' );
    $this->dataStore->saveObject( $object );
}
                            

YAGNI

You Aren't Gonna Need It

  • cost of creation
  • cost of delay
  • cost of maintenance
  • cost of correction

Applies to features, not ease of modification

Simple design is not simple

I'm sorry I had to write you such a long letter,
but I did not have time to write you a short one

-- Blaise Pascal

SOLID principles

  • SRP: one responsibility per class
  • OCP: classes doing their job should not need change
  • LSP: able to provide a subtype instead of the type
  • ISP: client specific interfaces rather than general ones
  • DIP: program against "interfaces"

Design patterns

Reusable solution to common problem

Communication tool

Layered design

Source: The Clean Architecture, Robert C Martin

Tests

Testable code and good design go hand in hand

Avoid dogma

Trade-offs

Transcend the rules






Questions?




bit.ly/econ-cleancode