SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
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:

Contenu connexe

Tendances

Integrating react in django while staying sane and happy
Integrating react in django while staying sane and happyIntegrating react in django while staying sane and happy
Integrating react in django while staying sane and happyFröjd Interactive
 
Spring-batch Groovy y Gradle
Spring-batch Groovy y GradleSpring-batch Groovy y Gradle
Spring-batch Groovy y GradleAntonio Mas
 
LibreTime: a web-based automation system for radio - presentation at Ohio Li...
LibreTime:  a web-based automation system for radio - presentation at Ohio Li...LibreTime:  a web-based automation system for radio - presentation at Ohio Li...
LibreTime: a web-based automation system for radio - presentation at Ohio Li...Robb Ebright
 
Developing Cross Platform Applications with Golang
Developing Cross Platform Applications with GolangDeveloping Cross Platform Applications with Golang
Developing Cross Platform Applications with GolangErhan Yakut
 
Come With Golang
Come With GolangCome With Golang
Come With Golang尚文 曾
 
Extract Method Refactoring Workshop (2016)
Extract Method Refactoring Workshop (2016)Extract Method Refactoring Workshop (2016)
Extract Method Refactoring Workshop (2016)Peter Kofler
 
Paving the way with Jakarta EE and Apache TomEE - itkonekt 2020
Paving the way with Jakarta EE and Apache TomEE - itkonekt 2020Paving the way with Jakarta EE and Apache TomEE - itkonekt 2020
Paving the way with Jakarta EE and Apache TomEE - itkonekt 2020César Hernández
 
Golang Channels use cases
Golang Channels use casesGolang Channels use cases
Golang Channels use casesErhan Yakut
 
Angular Vienna - Use React tools for better Angular apps
Angular Vienna - Use React tools for better Angular appsAngular Vienna - Use React tools for better Angular apps
Angular Vienna - Use React tools for better Angular appsMartin Hochel
 
How to approach building GUIs using PyQT
How to approach building GUIs using PyQTHow to approach building GUIs using PyQT
How to approach building GUIs using PyQTJerlyn Manohar
 
Code Quality Control in a PHP project. GeekTalks, Cherkassy 2020
Code Quality Control in a PHP project. GeekTalks, Cherkassy 2020Code Quality Control in a PHP project. GeekTalks, Cherkassy 2020
Code Quality Control in a PHP project. GeekTalks, Cherkassy 2020Andrew Yatsenko
 
Golang from Scala developer’s perspective
Golang from Scala developer’s perspectiveGolang from Scala developer’s perspective
Golang from Scala developer’s perspectiveSveta Bozhko
 
Geb+spock: let your functional tests live long and prosper
Geb+spock: let your functional tests live long and prosperGeb+spock: let your functional tests live long and prosper
Geb+spock: let your functional tests live long and prosperEsther Lozano
 
Basics of Open Source Contribution - WWCodeMobile
Basics of Open Source Contribution - WWCodeMobileBasics of Open Source Contribution - WWCodeMobile
Basics of Open Source Contribution - WWCodeMobileVui Nguyen
 
Coding Dojo: Bank OCR Outside-In (2015)
Coding Dojo: Bank OCR Outside-In (2015)Coding Dojo: Bank OCR Outside-In (2015)
Coding Dojo: Bank OCR Outside-In (2015)Peter Kofler
 

Tendances (20)

Integrating react in django while staying sane and happy
Integrating react in django while staying sane and happyIntegrating react in django while staying sane and happy
Integrating react in django while staying sane and happy
 
Spring-batch Groovy y Gradle
Spring-batch Groovy y GradleSpring-batch Groovy y Gradle
Spring-batch Groovy y Gradle
 
LibreTime: a web-based automation system for radio - presentation at Ohio Li...
LibreTime:  a web-based automation system for radio - presentation at Ohio Li...LibreTime:  a web-based automation system for radio - presentation at Ohio Li...
LibreTime: a web-based automation system for radio - presentation at Ohio Li...
 
Developing Cross Platform Applications with Golang
Developing Cross Platform Applications with GolangDeveloping Cross Platform Applications with Golang
Developing Cross Platform Applications with Golang
 
Come With Golang
Come With GolangCome With Golang
Come With Golang
 
Groovy android
Groovy androidGroovy android
Groovy android
 
Extract Method Refactoring Workshop (2016)
Extract Method Refactoring Workshop (2016)Extract Method Refactoring Workshop (2016)
Extract Method Refactoring Workshop (2016)
 
Go lang
Go langGo lang
Go lang
 
Jedi knight
Jedi knightJedi knight
Jedi knight
 
Paving the way with Jakarta EE and Apache TomEE - itkonekt 2020
Paving the way with Jakarta EE and Apache TomEE - itkonekt 2020Paving the way with Jakarta EE and Apache TomEE - itkonekt 2020
Paving the way with Jakarta EE and Apache TomEE - itkonekt 2020
 
Hack Rio/OS
Hack Rio/OSHack Rio/OS
Hack Rio/OS
 
Golang Channels use cases
Golang Channels use casesGolang Channels use cases
Golang Channels use cases
 
Angular Vienna - Use React tools for better Angular apps
Angular Vienna - Use React tools for better Angular appsAngular Vienna - Use React tools for better Angular apps
Angular Vienna - Use React tools for better Angular apps
 
Perl wants you
Perl wants youPerl wants you
Perl wants you
 
How to approach building GUIs using PyQT
How to approach building GUIs using PyQTHow to approach building GUIs using PyQT
How to approach building GUIs using PyQT
 
Code Quality Control in a PHP project. GeekTalks, Cherkassy 2020
Code Quality Control in a PHP project. GeekTalks, Cherkassy 2020Code Quality Control in a PHP project. GeekTalks, Cherkassy 2020
Code Quality Control in a PHP project. GeekTalks, Cherkassy 2020
 
Golang from Scala developer’s perspective
Golang from Scala developer’s perspectiveGolang from Scala developer’s perspective
Golang from Scala developer’s perspective
 
Geb+spock: let your functional tests live long and prosper
Geb+spock: let your functional tests live long and prosperGeb+spock: let your functional tests live long and prosper
Geb+spock: let your functional tests live long and prosper
 
Basics of Open Source Contribution - WWCodeMobile
Basics of Open Source Contribution - WWCodeMobileBasics of Open Source Contribution - WWCodeMobile
Basics of Open Source Contribution - WWCodeMobile
 
Coding Dojo: Bank OCR Outside-In (2015)
Coding Dojo: Bank OCR Outside-In (2015)Coding Dojo: Bank OCR Outside-In (2015)
Coding Dojo: Bank OCR Outside-In (2015)
 

Similaire à Improving your code design using Java

Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCefalo
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code cleanBrett Child
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeyCefalo
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeValerio Maggio
 
PHP South Coast - Don't code bake, an introduction to CakePHP 3
PHP South Coast - Don't code bake, an introduction to CakePHP 3PHP South Coast - Don't code bake, an introduction to CakePHP 3
PHP South Coast - Don't code bake, an introduction to CakePHP 3David Yell
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin Vasil Remeniuk
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your codePascal Larocque
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility PrincipleBADR
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012cobyst
 
From Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerFrom Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerKaterina Trajchevska
 
Keeping business logic out of your UIs
Keeping business logic out of your UIsKeeping business logic out of your UIs
Keeping business logic out of your UIsPetter Holmström
 
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesEpisode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesJitendra Zaa
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - TalkMatthias Noback
 
Test-Driven Development.pptx
Test-Driven Development.pptxTest-Driven Development.pptx
Test-Driven Development.pptxTomas561914
 
PHP Berkshire October 2015
PHP Berkshire October 2015PHP Berkshire October 2015
PHP Berkshire October 2015David Yell
 

Similaire à Improving your code design using Java (20)

Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code clean
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit Dey
 
Clean Code
Clean CodeClean Code
Clean Code
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
 
PHP South Coast - Don't code bake, an introduction to CakePHP 3
PHP South Coast - Don't code bake, an introduction to CakePHP 3PHP South Coast - Don't code bake, an introduction to CakePHP 3
PHP South Coast - Don't code bake, an introduction to CakePHP 3
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
 
API Design
API DesignAPI Design
API Design
 
CQRS recepies
CQRS recepiesCQRS recepies
CQRS recepies
 
From Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerFrom Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developer
 
Rails data migrations
Rails data migrationsRails data migrations
Rails data migrations
 
Keeping business logic out of your UIs
Keeping business logic out of your UIsKeeping business logic out of your UIs
Keeping business logic out of your UIs
 
DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
 
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesEpisode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Test-Driven Development.pptx
Test-Driven Development.pptxTest-Driven Development.pptx
Test-Driven Development.pptx
 
PHP Berkshire October 2015
PHP Berkshire October 2015PHP Berkshire October 2015
PHP Berkshire October 2015
 

Dernier

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 

Dernier (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

Improving your code design using Java

  • 1. Improving your code design 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
  • 5. What your code looks like?
  • 6. 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
  • 7. Refactoring? "Business is well served 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 there this 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 clean your code ● Easier and faster to keep changing the code
  • 12. 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
  • 13. Code Smell ● A surface indication that usually corresponds to a deeper problem in the system https://martinfowler.com/bliki/CodeSmell.html
  • 14. 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
  • 15. Bloaters ● Long parameter list ● 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 ● 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 }
  • 18. 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.
  • 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 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
  • 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 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
  • 23. Data Clumps Before Order { String address; } deliverTo(address); After Order { Customer customer; } deliverTo(customer.getAddress());
  • 24. 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
  • 25. Object-oriented Abusers Code that doesn't follow object-oriented programming principles. Types: ● Conditional complexity ● Refused bequest ● Temporary field ● Alternative classes with different interfaces
  • 26. 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
  • 28. 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
  • 29. 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/
  • 30. 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)
  • 31. I will not write any more bad code