clean code

50
Enterprise Java Training © Copyright Victor Rentea P.F.A. 2015 www.VictorRentea. ro The Art of Clean Code Victor Rentea March 23, 2016 @ Bucharest Java User Group Voxxed Days Bucharest 2016

Upload: victor-rentea

Post on 12-Jan-2017

1.120 views

Category:

Software


2 download

TRANSCRIPT

Page 1: Clean Code

Enterprise Java Training

© Copyright Victor Rentea P.F.A. 2015

www.VictorRentea.ro

The Art of

Clean Code

Victor RenteaMarch 23, 2016

@

Bucharest Java User Group

Voxxed Days Bucharest 2016

Page 2: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

About Me Victor Rentea, PhD(CS)

- Technical Team Lead, Senior Java Engineer at IBM Romania

- Independent Trainer PFA:

- [email protected] www.VictorRentea.ro - - @victorrentea

2

Who am I ?

Page 3: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

IntroductionNamesFunctionsClassesFormatting & Comments

Contents

Agenda

3

Page 4: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Clean Code ……does one thing well…reads like well written prose ...looks like it was written by someone who cares ...is when each method you read turns out to be pretty much

what you expected

[The Principle of Least Astonishment]

anyone can write code that a computer understands, but few programmers know how to write code that a human can understand

Introduction

What is Clean Code ?

4

Bjarne Stroustrupinventor of C++

Grady Boochinventor of UML

Michael Feathersauthor of Working Effectively with Legacy Code

Martin Fowlerauthor of Refactoring

Ward Cunninghaminventor of Wiki, coinventor of eXtreme Programming

Page 5: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

The true cost of software = its maintenance- 80% of the total cost+effort of software is in maintenance. Why ?- Because we get slower and slower,

as the code gets dirtier and begins to ROT

We READ 10x more time than we WRITEDo your best to increase readability, even if it makes writing harder Always check in cleaner code than you found (Boy scout rule)

Introduction

Why Clean Code ?

5

Page 6: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

IntroductionNamesFunctionsClassesFormatting & Comments

Contents

Agenda

6

Page 7: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Packages, namespacesClasses, interfacesFunctions

Variables, parametersClass fieldsConstants, enums, ... We do a lot of naming, so we must be good at it

Names

We name everything

7

Page 8: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Packages – 1 wordClasses, interfacesFunctions

Variables, parametersClass fieldsConstantsenum values ≈constants

customer.service Customer, OrderService

placeOrder() customerName age, phoneNumber

CUSTOMER_PAGE_SIZE {SINGLE, MULTIPLE}

Names

The JavaCaseConventions

8

Page 9: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Functions are verbsgetName(), sendEmail(), execute(), placeOrder()

- Boolean functions should answer yes/no isGoldClient(), hostsAreValid()

Classes are nounsCustomer, OrderLine, SpecialSalesOffer, OrderFacade

- Iron out as much domain concepts ASAP

- Avoid meaningless prefixes or suffixes:ICustomerService, OrderInfo, OrderData, OrderServiceImpl

Names

“Well Written Prose”

9

Page 10: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Why it exists? What it does? How it's used?You should NOT need:

1. an /* explanatory comment */2. to descifer its implementation, or 3. to hunt down the code using it

Make the name speak for itself !!Just go back and rename it whenever you feel so

- Your team will be grateful! And even you will, in 3 months!- With an IDE, it's a matter of seconds with almost no risk

Names should…

Names Explain Intent

10

Page 11: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Pronounceableint getinvcdtlmt() vs. int getInvoiceableCreditLimit()

- Avoid abbreviations ! (except a fundamental business concept)

ConsistentDAO.findXyz() .fetchXyz() or .getXyz() – pick one but stick to it

- When you add code, choose names that preserve consistency(read some code to understand the de facto naming conventions)

Unique: Synonyms are bad, they confuseWhen referring to a customer, don't also use buyer or client in code

- Use ubiquitous language: customer if that’s the prevalent business term

Names: Several Guidelines

Names Should be …

11

Page 12: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Provide Meaningful ContextOrder.customerFirstName

- But don't repeat yourself: Order.orderCreationDate

Sort nicely at CTRL-SPACE- Related classes should begin similarlyCustomerService, CustomerDAO, Customer, CustomerExporter

Think positive about booleansisActive() instead of isInactive() or isNotActive()

- Read this: !isInactive() :-S

Names: Several Guidelines

Names Should…

12

Page 13: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Variables: big scope long descriptive name- For loop variables can be 1 letter- Method variables: 1+ word- Method parameters: 1++ word

Documentation: are shown by the IDE- Fields: a bit longer- Constants: self-explanatory names

Functions & Classes: big scope short name- public names should be convenient: short and easy to remember- private functions should have long descriptive names

Names

Name Length

13

public class AClass { public final static int CONST_WITH_EXPLANATORY_NAME; private String instanceField;

public void myMethod(String parameter) { String variable; for (int i = 0; i < 100; i++) { ... } }}

Page 14: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

IntroductionNamesFunctionsClassesFormatting & Comments

Contents

Agenda

14

Page 15: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

15

"A function should do one thing, it should do it well and it should do it ONLY"[UBob]

They should be

Smallin order not to surprise us

- Principle of Least Astonishment

Functions

Functions

Page 16: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

16

How small ?- 4 lines is best; 5 is ok; 6 is already too much- By any means, keep your functions smaller than a page of your IDE !

Why so small ?!To be sure that they do only 1 THING

In a few lines, you can’t do muchIts name can then tell you everything

Functions

Functions Should be Small !!

Page 17: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

The layout of a long function is like a landscape- Humans, are good at memorizing landscape

This landscape is familiar to the authorBut for the rest of the team,

this function is completely unknown, it's like wilderness

Functions

Why do small functions scare us?

Function Landscape

17

iffor

if

if

if

for

else

if

for if

if

for

Page 18: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Instead of a familiar landscape

- in which only you (the author) orient very well

You're now swimming in a sea of small functions- You're not so comfortable anymore,- But it's to the end good of the entire team !

Choose long descriptive names - They will act as signposts guiding you and your team- The reader will now be able to quickly understand your code

Functions

Why do small functions scare us?

A Sea of Small Functions

18

(the author)

else for if

Page 19: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

This is why we want to leave landmarks behind;

we split long functions into many small functions

with carefully chosen long namesthat guide the reader

Functions

Act Professional

19

sendActivation EmailToCustomer

()

removeAllPastCancelledOrdersOfConsumer()

Page 20: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Same Goal: the code should speak for itself- The reader shouldn't have to look at the function definition nor to its usages

Max 2 parameters- For ≥ 3 parameters, it's hard to read: their order becomes a problem group them in a Parameter Object/DTO

Avoid output parameters- The caller may be surprised that an argument changed

No flag parameters (boolean, enum) = laziness/fear

- It shouts that the function does more than one thing ! Split it into smaller functions

customer.setLoggedIn(true);

Functions

Function Signature (1)

20

myBadMethod("John","Michael", "Paris","St. Albergue");

checkCustomer(customer, order);

removeOrders(customer, false, true);

params.setStreet("Paris");…myBadMethod(params);

?!

Page 21: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

No nullable parameters- It's like a boolean split that function in 2: one for null, one for not-null- Thoroughly check parameters at boundaries (=defensive programming)

Don’t return null- Null is the worst mistake in IT [dzone]

Consider Optional<> / throw exception / Null Object Pattern

Unchecked Exceptions won !- No more try/throws/empty catch(); no return status codes- Runtime Exceptions don’t annoy the caller

Can be handled uniformly in a transparent layer at the entry points Can hold enum error codes for (i18n) user messages Define custom exception sub-types for recoverable errors (selective catch)

Functions

Function Signature (2)

21

Page 22: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

By continuous refactoring to clean up the codeYou are not done when the code starts working!

It is then when you should clean up your code !!- IDEs help you a lot - But only rigorous unit tests can guarantee that you don't break anything

Test-Driven Development

Functions - Techniques

How to write such Functions ?

22

Page 23: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

You Extract Till You Drop: [UBob]

Try to extract as many functions as possibleInto methods that tell what they do

- by their long nice name- (you document your code this way making it easier to understand)

… until you simply cannot extract any more [opt]

- (when extracting again would basically duplicate a method)= Extreme

Functions - Techniques

Split Your Functions !

23

Page 24: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Reduces the number of indentations- Max number of TABs can be restricted: Readability ++

Functions - Techniques

Function body : Early returns

24

public List<Integer> stringsToInts( List<String> strings) { if (strings != null) { List<Integer> integers = new ArrayList<>(); for (String s : strings) { integers.add(Integer.parseInt(s)); } return integers; } else { return null; }}

public List<Integer> stringsToInts2( List<String> strings) { if (strings == null) { return null; } List<Integer> integers = new ArrayList<>(); for (String s : strings) { integers.add(Integer.parseInt(s)); } return integers;}

Page 25: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

= how to refactor God Methods into shiny new classes ?

Functions - Techniques

Extract Method Object refactor

25

public String aLongMethod(String text) { Set<String> words = new HashSet<String>(); int totalWords = 0; int totalPhrases = 0; StringTokenizer tokenizer = … while (tokenizer.hasMoreTokens()) { String nextToken = tokenizer.nextToken(); … if (…) { for (…) {…} … } else { … } }}

public class ExtractedMethodCommand { private final String text; private Set<String> words = new HashSet<>(); private int totalWords = 0; private int totalPhrases = 0; private StringTokenizer tokenizer;

public ExtractedMethodCommand(String text) { this.text = text; tokenizer = new StringTokenizer(text, " "); }

public String execute() {…}

}

Extracting this block as a method require lots of parameters, output parameters

or may even be impossible These methods use instance fields, and take no/fewer arguments

String result = aLongMethod(”bla”);

String result = new ExtractedMethodCommand(”bla”).execute();

Page 26: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

= when a function changes the state of the system- e.g. loginUser(), openConnection(), persistCustomer(), checkUser()

A necessary evil: they can surprise us- and break the Least Astonishment Principle

Explain them- checkUserAndInitializeHisSession(User)

Functions – Advanced Topics

Side Effects

26

Page 27: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

1. A Query doesn't have side effectsand returns a resultgetState():State, isLoggedIn():boolean, findCustomer():Customer

2. A Command changes the system stateand returns voidprocessOrder(Order), consumeMessage(Message), setName(String)

Avoid doing both in the same methodprocessOrder(Order):boolean (that returns false if it failed)

(It forces the caller to check the result right away. Prefer exceptions instead!)

Functions – Advanced Topics

Command / Query Separation

27

?

!

Page 28: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

A consequence of side effects Open the DB connection do stuff close DB connection

Leads to mysterious code- “Hack!! No one told me that I should have called .initialize() first !!"

Can be partially avoided by passing a block- Execute on connection ( set_of_instructions )

Spring’s JdbcTemplate, RestTemplate, …- Java8 lambdas make it a lot easier ()->{stuff;}

Functions – Advanced Topics

Temporal Coupling

28

Page 29: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

IntroductionNamesFunctionsClassesFormatting & Comments

Contents

Agenda

29

Page 30: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

The member order: [Standard Java Conventions]

1. Fields

2. Constructors

3. Methods- Start with the public methods - That call private methods

That call private methods down... etc

The reader should search down

Classes

Basic Shape

30

public class ExtractedMethodCommand { private static final String MY_CONST=“val”; private Set<String> words = new HashSet<String>(); private int totalWords = 0; private int totalPhrases = 0; private StringTokenizer tokenizer;

public ExtractedMethodCommand(String text) {… }

public String execute() {…} private void doInternalVeryUsefulStuff() {…}

}

Page 31: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Define a constant in the class that uses it the most- Even in a domain entity class- DO NOT create a dreadful 4000-lines Constants class !

The same for enums - Next to that class or even nested inside

Classes

Constants

32

Page 32: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

=classes that expose all their internal state- to external procedures that manipulate them- These classes don't usually hold much functionality

Objects vs. Data Structures

Data Structures (≈ C struct)

33

Getters/setters exposing all private fields

is NOT encapsulation !

public class PhoneBookEntryDTO { private String firstName; private String lastName; private String phoneNumber;

public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; }

public String getLastName() { … } public void setLastName(…) { … }

public String getPhoneNumber() { … } public void setPhoneNumber(…) { … }}

public class SimpleImmutableStruct { private final String firstName; private final String lastName;

public SimpleImmutableStruct( String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; }

public String getFirstName() { return firstName; } public String getLastName() { return lastName; }

}

Why we Immutable Objects:- Preserve their consistency after

creation- Thread safe- Safe for sort-/hash-based collections

public class PhoneBookEntryDTO { public String firstName; public String lastName; public String phoneNumber;}

Page 33: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

=hide implementation details from your clientExpose operations rather than data

car.startEngine() instead of car.setEngineStarted(true) or car.engineStarted=true

- Data is concrete, it's an implementation detailTry to minimize the object's observable state

Expose data as abstract as possiblecar.getPercentageFuelLeft() instead of getGasolineInLiters()

Objects vs. Data Structures

True Encapsulation

34

car.getEstimatedRemainingKm()

Page 34: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

=classes that hide their state behind abstractions- and expose functionality as public methods, so that- their caller works with them without knowing their implementation

Objects vs. Data Structures

True Objects (as in OOP)

35

public class Car { private double remainingGasoline; private double reservoirCapacity; public double getRemainingGasolineInLiters() { return remainingGasoline; } public double getReservoirCapacityInLiters() { return reservoirCapacity; }

public double getRemainingFuelRatio() { return remainingGasoline/reservoirCapacity; }} structs OOP

Page 35: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

void m(P p) {

memberF();

field.fieldF();

p.parameterF();

new Obj().f();

Math.sqrt(4);

Don’t ask the state of other objects, instead,tell them what to do

1. Encapsulation- Keep behavior next to state

2. Low coupling- Less knowledge about other objects

Avoid Train Wrecks:- getRoot().getManager().getMessageWidget().showMessage("blah")

Classes

Tell, Don’t Ask Principle

36

The Law of DemeterA function m() of ClassX should call only methods of:• ClassX • a field of ClassX• m()'s parameters• objects created within m()• globals(in short: "use only one dot")

Suggestion

Page 36: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

=code that works with too much data of another class…probably belongs inside that other class

- This refactoring usually simplifies the code- Did you thought about the Law of Demeter ? - Is the envy gone from our example ?

Classes

Feature Envy

37

public class Rental { private MovieCopy movieCopy; … public String getStatement() { return "\t" + movieCopy.getMovie().getTitle() + "\t" + movieCopy.getMovie().getPrice() + "\n"; }}

public class MovieCopy { private Movie movie; public String getStatement() { return "\t" + movie.getTitle() + "\t" + movie.getPrice() + "\n"; }}

return movieCopy.getStatement();

Page 37: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Conditionals over Polymorphic Data Structures Objects

Easy to add functions+1 type-specific functionality

= a new switche.g. getMaxLoanDays()

Dangerous to add types+1 type = a new case in all

the existing switches

abstract methods need to be defined by each concrete type

Safe to add types- Java forces us to implement all

the necessary methods More artifacts: + 3 classes

38

Objects vs. Data Structures: Replace Conditionals with Polymorphism

VS

switch (movie.getType()) { case NEW_RELEASE: … break; case REGULAR: … break; case CHILDRENS: … break;}

public class NewReleaseMovie extends Movie { @Override public double func(…) { … }}

Movie#func()

RegularMovie

ChildrensMovie

Page 38: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Runtime dependency usually goes the same way as source code dependency

- Class A imports the class B (source code dependency)- …so that A can then invoke a method in B (runtime dependency)

With OO, we can inverse the source code dep.

Classes

Best of OOP:[UBob]

The Plugin Model

39

Module 2Module 1

A Bimport B;

b.method()

Page 39: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Make A depend on an interface I- That contains the method(s) that need to be invoked in B

Make B implement I- It thus must have code source dependency on I

A needs an instance of type I give it a B instance- Easily done using an dependency injection framework (EJB, Spring, Guice)- At runtime, A still invokes B (), but Module 1 does not depend on Module 2 anymore

Classes

The Plugin Model: Dependency Inversion

40

Module 2Module 1

A Bimport

I.method()

import

= abstractions should not depend on details, details should depend on abstractions

Page 40: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

IntroductionNamesFunctionsClassesFormatting & Comments

Contents

Agenda

41

Page 41: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

It's all about communication- Communication is the most important activity of a professional developer

Don't ignore the formatting rules,Nor follow them blindly

- The purpose is to express your intent in code as clearly as possible

Have the IDE help you

Formatting

Code Formatting

42

Page 42: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

< 100-120 chars/line < 100-200 lines/file, never > 500 < 5-10 lines/method, never > 1 screenIndentation: Team

2-3-4 chars or TAB ? Egyptian-style or not ? ...- Establish a team style and follow it [+stylesheet?]- Never reformat the entire file using your IDE – only several selected lines

Manual formatting can be more expressive: We just merge conflicts at commit, don’t we

Don't collapse: { return 0; } or if (cond) doStuff();

Formatting

Several Suggestions

43

Customer customer = new Customer.Builder() .withName("John Doe") .withAddress(new Address.Builder() .withStreetName("Viorele") .build()) .build();

{}

Page 43: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

=they compensate for our inability to express in codeAlways before dropping a commentAnd see whether you can express it in code

Why should we hate comments ?Because they usually LIE !

- As they immediately fall out of sync with the code

Comments

Comments are Failures

44

Page 44: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

public List<int[]> getFlaggedCells(){ List<int[]> flaggedCells = new A…L…<…>(); for (int[] cell : gameBoard) { boolean isFlagged = cell[STATUS_VALUE] == FLAGGED; if (isFlagged) flaggedCells.add(x); } return flaggedCells;}

public List<Cell> getFlaggedCells(){ List<Cell> flaggedCells = new A…L…<Cell>(); for (Cell cell : gameBoard) { if (cell.isFlagged()) flaggedCells.add(cell); } return flaggedCells;}

Constants - Instead of magic numbers

Explanatory variables- Locals that store intermediary results

Explanatory methods- To name a given computation- "Encapsulate Conditionals"

Split the code- into many small private functions with long descriptive names, remember?

This is how to document your code !

Comments

Code Expressiveness ++

45

public List<int[]> getCells(){ List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) { if (x[0] == 4) list1.add(x); } return list1;}

Page 45: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Mumbling- Unclear- Rush/lazy

Redundant

Mandated or Noise

/** Default constructor. */

Position Markers//////// Accessors //////

Commented-out Code- Don't read it. Just DELETE IT! - (You SCM rocks !)

HTML JavaDocsNon-local Information

- Comment code on that line (±1)

Comments

Bad Comments

46

/** * Returns the day of the month. * * @return the day of the month. */ public int getDayOfMonth() { return dayOfMonth; }

DUH !!

stream.close();} catch (IOException e) { // Oh! Give me a break!}

Page 46: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Intent: WHY?(what?)

- When the code just can't say itspecific algorithms/calculusbug workarounds

- An URL link can explain it all

ClarificationsTo explain calls to an external API (if its usage is strange)

Warning of consequences- that might not be obvious

TODOs// TODO vrentea Fetch the order

- Assume ownership

Public API JavaDocs- for libraries/frameworks you write

Legal// Copyright (C) 2013, …

Comments

Good Comments

47

SimpleDateFormat sdf = new SimpleDateFormat(…); // Not thread-safe. Keep it local!

Page 47: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

48

Names Choose descriptive names Unambiguous names, no synonyms Use an ubiquitous language if possible Use long variable names for long scopes Make side-effects clear Avoid encodings (e.g. m_...)

Functions Too many arguments Output arguments Flag arguments Dead function (no callers) Functions should do one thing Function names should say what they do

Comments Redundant Comment Obsolete Comment Commented-out code

General Duplication: DRY Multiple languages in one source file Incorrect behavior at the boundaries Clutter: default constructor, unused code, … Feature Envy Avoid transitive navigation(Law of Demeter) Hidden temporal couplings Follow standard conventions Use explanatory variables and functions Extract magic numbers as constants Encapsulate conditionals Avoid negative conditions

Tests Insufficient tests: use a test coverage tool Don't skip trivial tests Test boundary conditions Exhaustively test near bugs Tests should be fast !

Summary – Code Smells and Heuristics & Part2Part1

Page 48: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

49

Special Thanks toIonuţ Chereji

Laurenţiu CaratăVictor BucuţeaFlorin DiaconuIonuţ ScutaruLeonard Giura

Page 49: Clean Code

50

Continuously refactor

FUNCTIONSBe consistent

Comments lie !Care for your reader

WRITE SMALLACT like a pro !

Don’t cODE,COMMUNICATE

Page 50: Clean Code

Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015

Bucharest Java User Group

Clean CodeRobert C. Martin (aka Uncle Bob), 2008

Clean Coders videoshttp://www.cleancoders.com/ : Uncle Bob

RefactoringMartin Fowler, 1999

NULL – the worst mistake in IT- https://dzone.com/articles/the-worst-mistake-of-computer-science-1

The Clean Architecture: - http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html

Some Programming Jargon- http://blog.codinghorror.com/new-programming-jargon/

Want to dig more ?

References

51