KEMBAR78
Improving your code design using Java | PDF
Improving your code design using Java
Melhorando o design do seu código Java
Speaker
Roan Brasil
@roanbrasil
Senior Engineer
+ JCP-Member
+ Open Source Contributor
+ Book and blog writer
+ Teacher
Ugly Code?
Ugly Code?
What your code looks like?
Refactoring?
"A change made to the internal structure of software
to make it easier to understand and cheaper to
modify without changing its observable behavior"
- Martin Fowler
Refactoring?
"Business is well served by continuous refactoring,
yet the practice of refactoring must coexist
harmoniously with business priorities"
- Joshua Kerievsky
Without Refactoring
Productivity decreases:
● Thousands of duplicated code
● Any new implementation or logic become complex
● Maintenance is hard to be done because the code is not easily understandable
Why is there this kind of problem?
● Small experience from who wrote the code
● Lazy coding
● Small deadlines
Low Code Quality High
Junior Mid-level Senior
Boy Scout Rule:
● Always leave the campground cleaner than you found it.
Reasons to clean your code
● Easier and faster to keep changing the code
When you shouldn't clean your code
● You cannot execute or run your code
● If this change results in gold-plating
● Deadlines must be met
Code Smell
● A surface indication that usually corresponds to a deeper problem in the system
https://martinfowler.com/bliki/CodeSmell.html
Bloaters
Very large methods and classes that are hard to work with. Bloaters usually
accumulate over time as software evolves.
● Method Bloaters
○ Up to 10 lines is perfect
○ 10-20 lines is still often OK
○ More than 20 lines - consider refactoring
● Class Bloaters
○ Single responsibility principle
○ 2+ Responsibilities - consider refactoring
Bloaters
● Long parameter list
● Long method
● Contrived Complexity
● Primitive obsession
● Data clumps
● Large class
Long Parameter List
● Method 4 or more parameters
● Maximum 3 parameters
Problems:
● Difficult to understand the code spending many hours trying to understand
● Difficult to remember the position of each argument
● Acts like a magnet for even more arguments and code
Example: private BigDecimal calculateTax(25, true, "Brasil", new Order());
Long Methods
● A method contains hundreds or/and thousands lines of code
Problems:
● Hard to change
● Can create BUG easily
● Act like a magnet, attracting more lines of code
Example: calculateAmount(){
// sum up amount, apply discount, add or not delivery fee
}
Contrived Complexity
There is code that achieves an objective but is too complex. Hard to understand. There
are many ways to do a elegant code to achieve the same goal.
Problems:
● Hard to change or even understand
● Can create BUG easily
Benefits:
● Shorter and easier to understand
● Easy to change
https://ducmanhphan.github.io/2020-01-11-Refactoring-with-splitting-bloaters/#:~:text=The%20contrived%20complexity%20means%20that,to%20do%20the%20same%20thing.
Contrived Complexity
https://ducmanhphan.github.io/2020-01-11-Refactoring-with-splitting-bloaters/#:~:text=The%20contrived%20complexity%20means%20that,to%20do%20the%20same%20thing.
Before
List<Double> prices = new ArrayList<>();
for(Item item : items){
prices.add(item.price());
}
for(double price : prices){
baseTotal = baseTotal + price;
}
After
for(Item item : items) {
baseTotal += item.price();
}
Primitive Obsession
Use of primitives instead of complex objects
Problems:
● Mostly causes of long parameter lists
● Code duplication
● Not type safe and probably to have errors
○ findCountryByName("Fance");:
How to fix ?
1. Create an object,
2. Move the primitives there
3. Pass in the object
Primitive Obsession
https://ducmanhphan.github.io/2020-01-11-Refactoring-with-splitting-bloaters/#:~:text=The%20contrived%20complexity%20means%20that,to%20do%20the%20same%20thing.
Before
String name = customer.getName();
String email = customer.getEmail();
String zipCode = customer.getAddress()
.getZipCode();
double calculateTotal(name, email, zipCode){
…
}
After
double calculateTotal(customer){
String name = customer.getName();
String email = customer.getEmail();
String zipCode =customer.getAddress()
.getZipCode();
}
Data Clumps
A group of variables which are passed around together (in a clump) throughout
various parts of the program
Problems:
● Major cause of long parameter lists
● Code duplication
Data Clumps
Before
Order {
String address;
}
deliverTo(address);
After
Order {
Customer customer;
}
deliverTo(customer.getAddress());
Large Class
A class that has more than one responsibility (doing many things). It is a class that
does almost everything known as "God Object"
Problems:
● Hundreds and thousands line of code to maintain
● Violates the Single Responsibility Principle
Object-oriented Abusers
Code that doesn't follow object-oriented programming principles.
Types:
● Conditional complexity
● Refused bequest
● Temporary field
● Alternative classes with different interfaces
Conditional Complexity
Complex switch operator or a sequence of if-statements
What is:
● Missing domain objects
● Not using polymorphism
● Not using inheritance
Problems:
● Starts simple, but becomes hard to change and understand
● High likelihood of breaking
● Breaks the Open/Closed Principle
Conditional Complexity - Example
Refused Bequest
Subclass inherits fields and methods it doesn't need
Problems:
● Objects inherit behavior that doesn't belong to them
● Makes coding confusing
● Leads to unexpected behavior
Dog
getPtName()
bark()
Cat
Temporary Field
Fields that have values only under certain circumstances and needed by only certain
methods. They are empty the rest of the time.
Problems:
● Why is this field null half of the time?
● Indicates low class cohesion
How to solve it?
● Replace Method with Method Object
https://blog.ploeh.dk/2015/09/18/temporary-field-code-smell/
Alternative Classes with Different Interfaces
Two or more methods exist across multiple classes that do the same thing.
Problems:
● Not DRY (Don't Repeat Yourself) - code is duplicated with just minor variations
● Can cause problems if one place is updated, but not the other
Interface
Class1
convertT(a1, a2)
Class2
convert(a1)
I will not write any more bad code
Let's code
Q & A:

Improving your code design using Java

  • 1.
    Improving your codedesign using Java Melhorando o design do seu código Java
  • 2.
    Speaker Roan Brasil @roanbrasil Senior Engineer +JCP-Member + Open Source Contributor + Book and blog writer + Teacher
  • 3.
  • 4.
  • 5.
    What your codelooks like?
  • 6.
    Refactoring? "A change madeto the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior" - Martin Fowler
  • 7.
    Refactoring? "Business is wellserved by continuous refactoring, yet the practice of refactoring must coexist harmoniously with business priorities" - Joshua Kerievsky
  • 8.
    Without Refactoring Productivity decreases: ●Thousands of duplicated code ● Any new implementation or logic become complex ● Maintenance is hard to be done because the code is not easily understandable
  • 9.
    Why is therethis kind of problem? ● Small experience from who wrote the code ● Lazy coding ● Small deadlines Low Code Quality High Junior Mid-level Senior
  • 10.
    Boy Scout Rule: ●Always leave the campground cleaner than you found it.
  • 11.
    Reasons to cleanyour code ● Easier and faster to keep changing the code
  • 12.
    When you shouldn'tclean your code ● You cannot execute or run your code ● If this change results in gold-plating ● Deadlines must be met
  • 13.
    Code Smell ● Asurface indication that usually corresponds to a deeper problem in the system https://martinfowler.com/bliki/CodeSmell.html
  • 14.
    Bloaters Very large methodsand classes that are hard to work with. Bloaters usually accumulate over time as software evolves. ● Method Bloaters ○ Up to 10 lines is perfect ○ 10-20 lines is still often OK ○ More than 20 lines - consider refactoring ● Class Bloaters ○ Single responsibility principle ○ 2+ Responsibilities - consider refactoring
  • 15.
    Bloaters ● Long parameterlist ● Long method ● Contrived Complexity ● Primitive obsession ● Data clumps ● Large class
  • 16.
    Long Parameter List ●Method 4 or more parameters ● Maximum 3 parameters Problems: ● Difficult to understand the code spending many hours trying to understand ● Difficult to remember the position of each argument ● Acts like a magnet for even more arguments and code Example: private BigDecimal calculateTax(25, true, "Brasil", new Order());
  • 17.
    Long Methods ● Amethod contains hundreds or/and thousands lines of code Problems: ● Hard to change ● Can create BUG easily ● Act like a magnet, attracting more lines of code Example: calculateAmount(){ // sum up amount, apply discount, add or not delivery fee }
  • 18.
    Contrived Complexity There iscode that achieves an objective but is too complex. Hard to understand. There are many ways to do a elegant code to achieve the same goal. Problems: ● Hard to change or even understand ● Can create BUG easily Benefits: ● Shorter and easier to understand ● Easy to change https://ducmanhphan.github.io/2020-01-11-Refactoring-with-splitting-bloaters/#:~:text=The%20contrived%20complexity%20means%20that,to%20do%20the%20same%20thing.
  • 19.
    Contrived Complexity https://ducmanhphan.github.io/2020-01-11-Refactoring-with-splitting-bloaters/#:~:text=The%20contrived%20complexity%20means%20that,to%20do%20the%20same%20thing. Before List<Double> prices= new ArrayList<>(); for(Item item : items){ prices.add(item.price()); } for(double price : prices){ baseTotal = baseTotal + price; } After for(Item item : items) { baseTotal += item.price(); }
  • 20.
    Primitive Obsession Use ofprimitives instead of complex objects Problems: ● Mostly causes of long parameter lists ● Code duplication ● Not type safe and probably to have errors ○ findCountryByName("Fance");: How to fix ? 1. Create an object, 2. Move the primitives there 3. Pass in the object
  • 21.
    Primitive Obsession https://ducmanhphan.github.io/2020-01-11-Refactoring-with-splitting-bloaters/#:~:text=The%20contrived%20complexity%20means%20that,to%20do%20the%20same%20thing. Before String name= customer.getName(); String email = customer.getEmail(); String zipCode = customer.getAddress() .getZipCode(); double calculateTotal(name, email, zipCode){ … } After double calculateTotal(customer){ String name = customer.getName(); String email = customer.getEmail(); String zipCode =customer.getAddress() .getZipCode(); }
  • 22.
    Data Clumps A groupof variables which are passed around together (in a clump) throughout various parts of the program Problems: ● Major cause of long parameter lists ● Code duplication
  • 23.
    Data Clumps Before Order { Stringaddress; } deliverTo(address); After Order { Customer customer; } deliverTo(customer.getAddress());
  • 24.
    Large Class A classthat has more than one responsibility (doing many things). It is a class that does almost everything known as "God Object" Problems: ● Hundreds and thousands line of code to maintain ● Violates the Single Responsibility Principle
  • 25.
    Object-oriented Abusers Code thatdoesn't follow object-oriented programming principles. Types: ● Conditional complexity ● Refused bequest ● Temporary field ● Alternative classes with different interfaces
  • 26.
    Conditional Complexity Complex switchoperator or a sequence of if-statements What is: ● Missing domain objects ● Not using polymorphism ● Not using inheritance Problems: ● Starts simple, but becomes hard to change and understand ● High likelihood of breaking ● Breaks the Open/Closed Principle
  • 27.
  • 28.
    Refused Bequest Subclass inheritsfields and methods it doesn't need Problems: ● Objects inherit behavior that doesn't belong to them ● Makes coding confusing ● Leads to unexpected behavior Dog getPtName() bark() Cat
  • 29.
    Temporary Field Fields thathave values only under certain circumstances and needed by only certain methods. They are empty the rest of the time. Problems: ● Why is this field null half of the time? ● Indicates low class cohesion How to solve it? ● Replace Method with Method Object https://blog.ploeh.dk/2015/09/18/temporary-field-code-smell/
  • 30.
    Alternative Classes withDifferent Interfaces Two or more methods exist across multiple classes that do the same thing. Problems: ● Not DRY (Don't Repeat Yourself) - code is duplicated with just minor variations ● Can cause problems if one place is updated, but not the other Interface Class1 convertT(a1, a2) Class2 convert(a1)
  • 31.
    I will notwrite any more bad code
  • 32.
  • 33.