SlideShare a Scribd company logo
1 of 33
Download to read offline
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:

More Related Content

What's hot

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
 

What's hot (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)
 

Similar to Improving Java code design

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
 

Similar to Improving Java code design (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
 

Recently uploaded

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Recently uploaded (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

Improving Java code design

  • 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