Clean Code – Antoine Vernois – Ludovic Pradel



Clean Code – Antoine Vernois – Ludovic Pradel

5 1


prez-clean_code


On Github avernois / prez-clean_code

Clean Code

Antoine Vernois

Software Anarchist

twitter: @avernois

Ludovic Pradel

Continuous Learner

twitter: @ludopradel

Why code in an agile conf?

on m'a posé la question une fois. l'agilité c'est pas un truc de gestion de projet, ni de manager à l'origine c'est des dev. Kent beck : XP = changement social

Why clean code?

il y en a qui ont déjà démarré un projet du départ ?
démarage de projet, tout va bien et puis, rapidement ça dérape. Pourquoi on ralentit ?
Quick and dirty / métaphore de la fenêtre brisé. On essaie.

What is a clean code ?

Clean code is not about beautifullness, it's about goodness.
Rebecca Wirfs-Brock
j'ai cru esthétique, c'était une erreur.

measuring cleanness?

Sonar mouhahaha toujours un moyen d'atteindre le chiffre sans faire le taf Michael Feathers - Written by someone who cares

What can we do?

make it readable

unreadable

public List<int[]> getFlg() {
  List<int[]> list1 = new ArrayList<int[]>();
  for (int[] x : theList ) {
    if (x[0] == 4)
      list1.add(x);
  }
	
  return list1;
}
exemple tirer de Clean Code de Robert "Uncle Bob" Martin parler au business. Yep il faut parler au gens

much better!

public List<Cell> getFlaggedCells() {
  List<Cell> flaggedCells = new ArrayList<Cell>();
  for (Cell cell : gameBoard ) {
    if (cell.isFlagged())
      flaggedCells.add(cell);
  }
		
  return flaggedCells;
}
le processus de nommage n'est pas simple, c'est ok de commencer avec un nom mauvais et raffiner ensuite. travailler pour que changer soit simple

unreadable

public RGBColor readCurrentColor(BlinkLed led) {
    device.sendCommand(new ReadColorRequest(led));
    
    byte[] response = device.readResponse();

    int red = response[2] >= 0 ? response[2] : response[2] + 256;
    int green = response[3] >= 0 ? response[3] : response[3] + 256;
    int blue = response[4] >= 0 ? response[4] : response[4] + 256;
        
    return new RGBColor(red, green, blue);
}

extract code

niveau d'abstraction différent

much better!

public RGBColor readCurrentColor(BlinkLed led) {
    device.sendCommand(new ReadColorRequest(led));
    byte[] response = device.readResponse();
    
    return extractColor(response);
}
private RGBColor extractColor(byte[] response) {
    int red = convertToPositiveInt(response[2]);
    int green = convertToPositiveInt(response[3]);
    int blue = convertToPositiveInt(response[4]);

    return new RGBColor(red, green, blue);
}
private int convertToPositiveInt(byte byt) {
    return byt >= 0 ? byt : byt + 256;
}

Comments

false good idea

comments in real life

/*
* A comment to please checkstyle
*/
/*
* Set the port
*
* @params port
*/
public void setPort(Port port) {this.port=port}
...
        } /* end for */
        dao.flush();
      default : 
        break;  
      } /* end switch */
    } /* end if */
  } /* end if */
} catch ...
évidemment, il y a en d'autres, des pas à jours, des faux, des inutiles. et le code commenté (mort), c'est pas comme si on avait des systèmes de gestion de version pour ça.
Comments are always failure
Uncle Bob
Don't comment bad code. Rewrite it.
Brian W. Kernighan, P.J. Plaugher
Elements of programing style, 1974 !

Comments : the exception

explain the Why!

Comments

Tests tells me What

Code tells me How

Comment, if needed, tells me why

Tests

They give you confidence to change the code.

A test should tell you a story

one test, one assert

tests document your code

Tests are first class citizens!

by the way

Test everything!

il n'y a pas de code trop simple pour ne pas mériter un test le niveau d'une équipe est inversement proportionnel à sa capacité à utiliser un débugger

coupling

this is bad

il y a des couplages classiques, découpage en couche, etc... d'autres auquels on pense moins.
la mise en abyme avec le commentaire :)
a.getB().getC().doThings(); // this is bad
instead
a.doThings();

Demeter's Law

don't talk to strangers
public class Client {
  private Service service;

  public Client() {
    this.service = new ServiceExample();
  }

  public String greet() {
    return "Hello " + service.getName();
  }
}

bad

enfer pour les tests. Exemple B/C = envoie de mail/SMS

Dependency Injection

public class Client {
  private Service service;

  public Client(Service service) {
    this.service = service;
  }

  public String greet() {
    return "Hello " + service.getName();
  }
}

better

= IoC applique a la gestion des dependances,

Dependency injection frameworks

they can be dangerous

Spring, I'm looking at you! on injecte tout et n'importe quoi. classe = 24 trucs injectés.

coupling with external libraries

or technical stuff

like frameworks

don't.

really. Please.

don't let them go inside your business

use abstractions

or facades

try wishfull design

and you can do that for you whole application!

maybe, you should :)

some smells

  • Singleton
  • Tight coupling
  • Untestable
  • Premature Optimisation
  • Indescriptive naming
  • Duplication

lots of other good stuff

  • SOLID principles are good for you
  • never ever return null
  • do not check exceptions
  • do not always think inheritance, think composition
  • do not think if/switch, think polymorphism
  • avoid singletons
  • ...

a clean code

  • is tested !
  • has no duplication
  • reveals its intention
  • easy to read
B. Stroustrup, R. Jeffries, K. Beck, M. Feathers, W. Cunningham, ...
Continuous attention to technical excellence and good design enhances agility.
Agile Manifesto

Read list

Thanks!

For questions, we'll be there the whole day, just come and talk to us. Slides will be available here very soon:http://avernois.github.io/prez-clean_code/

Credits

Plastics Injection Factory by Renee PrisbleBillard 03 by Ghislain MaryA sonar image by Tuukritööde OÜ (Muinsuskaitseamet) via Wikimedia CommonsLED by Nao. FujitaChained by Jamie BradwayChains by John KenedyChains by Rubèn RicoWistful Wishes by Julie Jablonsky143 by Tobias Myrstrand LeanderRefinery by Glenn EulothSweets by Lyrical LemongrassGotta clean myself by Lucia Sanchezthe big net by popofatticusJosé Vasconcelos Library by Rossa MenkmanOne by Lazy Librarian
Clean Code Antoine Vernois Software Anarchist twitter: @avernois Ludovic Pradel Continuous Learner twitter: @ludopradel