SlideShare une entreprise Scribd logo
1  sur  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
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:
- victorrentea@gmail.com
- www.VictorRentea.ro
-
- @victorrentea
2
Who am I ?
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Functions
Classes
Formatting & Comments
Contents
Agenda
3
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 Stroustrup
inventor of C++
Grady Booch
inventor of UML
Michael Feathers
author of Working Effectively with Legacy Code
Martin Fowler
author of Refactoring
Ward Cunningham
inventor of Wiki, coinventor of eXtreme Programming
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 WRITE
Do 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
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Functions
Classes
Formatting & Comments
Contents
Agenda
6
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Packages, namespaces
Classes, interfaces
Functions
Variables, parameters
Class fields
Constants, enums, ...
 We do a lot of naming, so we must be good at it
Names
We name everything
7
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Packages – 1 word
Classes, interfaces
Functions
Variables, parameters
Class fields
Constants
enum values ≈constants
customer.service
Customer, OrderService
placeOrder()
customerName
age, phoneNumber
CUSTOMER_PAGE_SIZE
{SINGLE, MULTIPLE}
Names
The JavaCaseConventions
8
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Functions are verbs
getName(), sendEmail(), execute(), placeOrder()
- Boolean functions should answer yes/no
isGoldClient(), hostsAreValid()
Classes are nouns
Customer, OrderLine, SpecialSalesOffer, OrderFacade
- Iron out as much domain concepts ASAP
- Avoid meaningless prefixes or suffixes:
ICustomerService, OrderInfo, OrderData, OrderServiceImpl
Names
“Well Written Prose”
9
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
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Pronounceable
int getinvcdtlmt() vs. int getInvoiceableCreditLimit()
- Avoid abbreviations ! (except a fundamental business concept)
Consistent
DAO.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 confuse
When 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
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Provide Meaningful Context
Order.customerFirstName
- But don't repeat yourself: Order.orderCreationDate
Sort nicely at CTRL-SPACE
- Related classes should begin similarly
CustomerService, CustomerDAO, Customer, CustomerExporter
Think positive about booleans
isActive() instead of isInactive() or isNotActive()
- Read this: !isInactive() :-S
Names: Several Guidelines
Names Should…
12
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++) { ... }
}
}
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Functions
Classes
Formatting & Comments
Contents
Agenda
14
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
"A function should do one thing, it should do it well
and it should do it ONLY"[UBob]
They should be
Small
in order not to surprise us
- Principle of Least Astonishment
Functions
Functions
15
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
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 much
Its name can then tell you everything
Functions
Functions Should be Small !!
16
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 author
But 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
if
for
if
if
if
for
else
if
for if
if
for
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
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 names
that guide the reader
Functions
Act Professional
19
sendActivation
EmailToCustomer()
removeAllPast
CancelledOrders
OfConsumer()
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);
?!
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
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
By continuous refactoring to clean up the code
You 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
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 possible
Into 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
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;
}
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();
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
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
1.A Query doesn't have side effects
and returns a result
getState():State, isLoggedIn():boolean, findCustomer():Customer
2.A Command changes the system state
and returns void
processOrder(Order), consumeMessage(Message), setName(String)
Avoid doing both in the same method
processOrder(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
?
!
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
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Functions
Classes
Formatting & Comments
Contents
Agenda
29
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() {…}
}
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
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;
}
≈
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
=hide implementation details from your client
Expose operations rather than data
car.startEngine() instead of car.setEngineStarted(true)
or car.engineStarted=true
- Data is concrete, it's an implementation detail
Try to minimize the object's observable state
Expose data as abstract as possible
car.getPercentageFuelLeft() instead of getGasolineInLiters()
Objects vs. Data Structures
True Encapsulation
34
car.getEstimatedRemainingKm()
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
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 Demeter
A 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")
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();
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 switch
e.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
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 B
import B;
b.method()
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 B
import
I
.method()
import
= abstractions should not depend on details, details should depend on abstractions
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Functions
Classes
Formatting & Comments
Contents
Agenda
41
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
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 screen
Indentation: 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();
{
}
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
=they compensate for our inability to express in code
Always before dropping a comment
And 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
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;
}
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 JavaDocs
Non-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!
}
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Intent: WHY?(what?)
- When the code just can't say it
specific algorithms/calculus
bug workarounds
- An URL link can explain it all
Clarifications
To 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!
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
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
49
Special Thanks to
Ionuţ Chereji
Laurenţiu Carată
Victor Bucuţea
Florin Diaconu
Ionuţ Scutaru
Leonard Giura
50
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Clean Code
Robert C. Martin (aka Uncle Bob), 2008
Clean Coders videos
http://www.cleancoders.com/ : Uncle Bob
Refactoring
Martin 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

Contenu connexe

Tendances

Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupVictor Rentea
 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Victor Rentea
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next ChapterVictor Rentea
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixVictor Rentea
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityVictor Rentea
 
Don't Be Mocked by your Mocks - Best Practices using Mocks
Don't Be Mocked by your Mocks - Best Practices using MocksDon't Be Mocked by your Mocks - Best Practices using Mocks
Don't Be Mocked by your Mocks - Best Practices using MocksVictor Rentea
 
The Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring FrameworkThe Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring FrameworkVictor Rentea
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfVictor Rentea
 

Tendances (20)

Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User Group
 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next Chapter
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Clean code
Clean code Clean code
Clean code
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
Clean code
Clean codeClean code
Clean code
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
 
Don't Be Mocked by your Mocks - Best Practices using Mocks
Don't Be Mocked by your Mocks - Best Practices using MocksDon't Be Mocked by your Mocks - Best Practices using Mocks
Don't Be Mocked by your Mocks - Best Practices using Mocks
 
The Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring FrameworkThe Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring Framework
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
 

Similaire à Clean Code

Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principlesEdorian
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++Mohamed Essam
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java PlatformSivakumar Thyagarajan
 
Architecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons LearnedArchitecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons LearnedJoão Pedro Martins
 
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...Codemotion
 
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...Codemotion
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and ToolsBob Paulin
 
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons LearnedITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons LearnedJoão Pedro Martins
 
XPDays Ukraine: Legacy
XPDays Ukraine: LegacyXPDays Ukraine: Legacy
XPDays Ukraine: LegacyVictor_Cr
 
Ncrafts.io - Refactor your software architecture
Ncrafts.io - Refactor your software architectureNcrafts.io - Refactor your software architecture
Ncrafts.io - Refactor your software architectureJulien Lavigne du Cadet
 
Create first android app with MVVM Architecture
Create first android app with MVVM ArchitectureCreate first android app with MVVM Architecture
Create first android app with MVVM Architecturekhushbu thakker
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style GuidesMosky Liu
 
Web performance
Web  performance Web  performance
Web performance Major Ye
 
OOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptxOOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptxMohamed Essam
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programmingThang Mai
 

Similaire à Clean Code (20)

Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
Enterprise TypeScript
Enterprise TypeScriptEnterprise TypeScript
Enterprise TypeScript
 
DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
Java 10 - Key Note
Java 10 - Key NoteJava 10 - Key Note
Java 10 - Key Note
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java Platform
 
Architecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons LearnedArchitecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons Learned
 
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
 
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
Erik Wendel - Beyond JavaScript Frameworks: Writing Reliable Web Apps With El...
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
 
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons LearnedITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
 
XPDays Ukraine: Legacy
XPDays Ukraine: LegacyXPDays Ukraine: Legacy
XPDays Ukraine: Legacy
 
Ncrafts.io - Refactor your software architecture
Ncrafts.io - Refactor your software architectureNcrafts.io - Refactor your software architecture
Ncrafts.io - Refactor your software architecture
 
Create first android app with MVVM Architecture
Create first android app with MVVM ArchitectureCreate first android app with MVVM Architecture
Create first android app with MVVM Architecture
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style Guides
 
Web performance
Web  performance Web  performance
Web performance
 
OOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptxOOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptx
 
Domain driven design
Domain driven designDomain driven design
Domain driven design
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 

Plus de Victor Rentea

Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Victor Rentea
 
Distributed Consistency.pdf
Distributed Consistency.pdfDistributed Consistency.pdf
Distributed Consistency.pdfVictor Rentea
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteVictor Rentea
 
Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfVictor Rentea
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxVictor Rentea
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxVictor Rentea
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java ApplicationVictor Rentea
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxVictor Rentea
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing ArchitecturesVictor Rentea
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hintsVictor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor Rentea
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the DomainVictor Rentea
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021Victor Rentea
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicVictor Rentea
 
Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzVictor Rentea
 
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021Victor Rentea
 
Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow oneVictor Rentea
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Victor Rentea
 

Plus de Victor Rentea (20)

Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24
 
Distributed Consistency.pdf
Distributed Consistency.pdfDistributed Consistency.pdf
Distributed Consistency.pdf
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
 
Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdf
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptx
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptx
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
 
Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX Mainz
 
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
 
Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow one
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021
 
TDD Mantra
TDD MantraTDD Mantra
TDD Mantra
 

Dernier

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 

Dernier (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 

Clean Code

  • 1. 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
  • 2. 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: - victorrentea@gmail.com - www.VictorRentea.ro - - @victorrentea 2 Who am I ?
  • 3. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 3
  • 4. 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 Stroustrup inventor of C++ Grady Booch inventor of UML Michael Feathers author of Working Effectively with Legacy Code Martin Fowler author of Refactoring Ward Cunningham inventor of Wiki, coinventor of eXtreme Programming
  • 5. 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 WRITE Do 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
  • 6. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 6
  • 7. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Packages, namespaces Classes, interfaces Functions Variables, parameters Class fields Constants, enums, ...  We do a lot of naming, so we must be good at it Names We name everything 7
  • 8. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Packages – 1 word Classes, interfaces Functions Variables, parameters Class fields Constants enum values ≈constants customer.service Customer, OrderService placeOrder() customerName age, phoneNumber CUSTOMER_PAGE_SIZE {SINGLE, MULTIPLE} Names The JavaCaseConventions 8
  • 9. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Functions are verbs getName(), sendEmail(), execute(), placeOrder() - Boolean functions should answer yes/no isGoldClient(), hostsAreValid() Classes are nouns Customer, OrderLine, SpecialSalesOffer, OrderFacade - Iron out as much domain concepts ASAP - Avoid meaningless prefixes or suffixes: ICustomerService, OrderInfo, OrderData, OrderServiceImpl Names “Well Written Prose” 9
  • 10. 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
  • 11. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Pronounceable int getinvcdtlmt() vs. int getInvoiceableCreditLimit() - Avoid abbreviations ! (except a fundamental business concept) Consistent DAO.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 confuse When 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
  • 12. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Provide Meaningful Context Order.customerFirstName - But don't repeat yourself: Order.orderCreationDate Sort nicely at CTRL-SPACE - Related classes should begin similarly CustomerService, CustomerDAO, Customer, CustomerExporter Think positive about booleans isActive() instead of isInactive() or isNotActive() - Read this: !isInactive() :-S Names: Several Guidelines Names Should… 12
  • 13. 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++) { ... } } }
  • 14. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 14
  • 15. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group "A function should do one thing, it should do it well and it should do it ONLY"[UBob] They should be Small in order not to surprise us - Principle of Least Astonishment Functions Functions 15
  • 16. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group 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 much Its name can then tell you everything Functions Functions Should be Small !! 16
  • 17. 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 author But 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 if for if if if for else if for if if for
  • 18. 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
  • 19. 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 names that guide the reader Functions Act Professional 19 sendActivation EmailToCustomer() removeAllPast CancelledOrders OfConsumer()
  • 20. 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); ?!
  • 21. 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
  • 22. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group By continuous refactoring to clean up the code You 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
  • 23. 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 possible Into 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
  • 24. 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; }
  • 25. 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();
  • 26. 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
  • 27. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group 1.A Query doesn't have side effects and returns a result getState():State, isLoggedIn():boolean, findCustomer():Customer 2.A Command changes the system state and returns void processOrder(Order), consumeMessage(Message), setName(String) Avoid doing both in the same method processOrder(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 ? !
  • 28. 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
  • 29. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 29
  • 30. 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() {…} }
  • 31. 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
  • 32. 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; } ≈
  • 33. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group =hide implementation details from your client Expose operations rather than data car.startEngine() instead of car.setEngineStarted(true) or car.engineStarted=true - Data is concrete, it's an implementation detail Try to minimize the object's observable state Expose data as abstract as possible car.getPercentageFuelLeft() instead of getGasolineInLiters() Objects vs. Data Structures True Encapsulation 34 car.getEstimatedRemainingKm()
  • 34. 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
  • 35. 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 Demeter A 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")
  • 36. 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();
  • 37. 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 switch e.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
  • 38. 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 B import B; b.method()
  • 39. 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 B import I .method() import = abstractions should not depend on details, details should depend on abstractions
  • 40. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 41
  • 41. 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
  • 42. 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 screen Indentation: 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(); { }
  • 43. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group =they compensate for our inability to express in code Always before dropping a comment And 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
  • 44. 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; }
  • 45. 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 JavaDocs Non-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! }
  • 46. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Intent: WHY?(what?) - When the code just can't say it specific algorithms/calculus bug workarounds - An URL link can explain it all Clarifications To 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!
  • 47. 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
  • 48. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group 49 Special Thanks to Ionuţ Chereji Laurenţiu Carată Victor Bucuţea Florin Diaconu Ionuţ Scutaru Leonard Giura
  • 49. 50
  • 50. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Clean Code Robert C. Martin (aka Uncle Bob), 2008 Clean Coders videos http://www.cleancoders.com/ : Uncle Bob Refactoring Martin 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