0% found this document useful (0 votes)
12 views19 pages

Java Code Smells and Refactoring Guide

Uploaded by

tuan.vuhai
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views19 pages

Java Code Smells and Refactoring Guide

Uploaded by

tuan.vuhai
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Code Smell Examples and Refactoring in Java

Code Quality Report

November 16, 2025

Contents

1 Bloaters (Bloated Code) 2


1.1 Long Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Primitive Obsession . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Data Clumps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Large Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Long Parameter List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Object-Orientation Abusers 6
2.1 Alternative Classes with Different Interfaces . . . . . . . . . . . . . . . . . . . . . 6
2.2 Refused Bequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4 Temporary Field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

3 Change Preventers 9
3.1 Divergent Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2 Parallel Inheritance Hierarchies . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3 Shotgun Surgery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

4 Dispensables 12
4.1 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.2 Duplicate Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.3 Data Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.4 Dead Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.5 Lazy Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.6 Speculative Generality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

5 Couplers 16
5.1 Feature Envy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.2 Inappropriate Intimacy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.3 Incomplete Library Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.4 Middle Man . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.5 Message Chains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

1
1 BLOATERS (BLOATED CODE) 2

1 Bloaters (Bloated Code)


Bloaters are code, methods, and classes that have increased to such gargantuan proportions
that they are hard to work with. Usually these smells do not crop up right away, rather they
accumulate over time as the program evolves.

1.1 Long Method


A method contains too many lines of code and performs too many tasks, making it difficult to
read, understand, test, and maintain.
Code with Smell:
1 public class Calculator {
2 public void calculate ( int a , int b , String operation ) {
3 if ( operation . equals ( " add " ) ) {
4 int result = a + b ;
5 System . out . println ( " Result : " + result ) ;
6 } else if ( operation . equals ( " subtract " ) ) {
7 int result = a - b ;
8 System . out . println ( " Result : " + result ) ;
9 } else if ( operation . equals ( " multiply " ) ) {
10 int result = a * b ;
11 System . out . println ( " Result : " + result ) ;
12 }
13 }
14 }

Refactored Code:
1 public class Calculator {
2 public void calculate ( int a , int b , String operation ) {
3 int result = performOperation (a , b , operation ) ;
4 printResult ( result ) ;
5 }
6
7 private int performOperation ( int a , int b , String operation ) {
8 if ( operation . equals ( " add " ) ) return a + b ;
9 if ( operation . equals ( " subtract " ) ) return a - b ;
10 if ( operation . equals ( " multiply " ) ) return a * b ;
11 return 0;
12 }
13
14 private void printResult ( int result ) {
15 System . out . println ( " Result : " + result ) ;
16 }
17 }

Solution: Break down the method into smaller methods, each performing a single respon-
sibility.

1.2 Primitive Obsession


Using primitive data types (int, string, bool) instead of creating appropriate classes/objects,
leading to lack of abstraction and difficulty in maintenance.
Code with Smell:
1 public class Person {
2 private String email ;
3
4 public void setEmail ( String email ) {
5 if ( email == null || ! email . contains ( " @ " ) ) {

Code Smell Examples and Refactoring in Java


1 BLOATERS (BLOATED CODE) 3

6 throw new I ll e g al A r gu m e nt E x ce p t io n ( " Invalid email " ) ;


7 }
8 this . email = email ;
9 }
10 }

Refactored Code:
1 public class Email {
2 private final String value ;
3
4 public Email ( String email ) {
5 if ( email == null || ! email . contains ( " @ " ) ) {
6 throw new I ll e g al A r gu m e nt E x ce p t io n ( " Invalid email " ) ;
7 }
8 this . value = email ;
9 }
10
11 public String getValue () {
12 return value ;
13 }
14 }
15
16 public class Person {
17 private Email email ;
18
19 public void setEmail ( Email email ) {
20 this . email = email ;
21 }
22 }

Solution: Create value objects to represent domain concepts instead of using primitives.

1.3 Data Clumps


Groups of data that frequently appear together but are not organized into a single unit, leading
to code duplication and maintenance difficulties.
Code with Smell:
1 public class UserService {
2 public void createUser ( String firstName , String lastName ,
3 String street , String city ) {
4 }
5
6 public void updateUser ( String firstName , String lastName ,
7 String street , String city ) {
8 }
9 }

Refactored Code:
1 public class Name {
2 private String firstName ;
3 private String lastName ;
4
5 public Name ( String firstName , String lastName ) {
6 this . firstName = firstName ;
7 this . lastName = lastName ;
8 }
9 }
10
11 public class Address {
12 private String street ;

Code Smell Examples and Refactoring in Java


1 BLOATERS (BLOATED CODE) 4

13 private String city ;


14
15 public Address ( String street , String city ) {
16 this . street = street ;
17 this . city = city ;
18 }
19 }
20
21 public class UserService {
22 public void createUser ( Name name , Address address ) {
23 }
24
25 public void updateUser ( Name name , Address address ) {
26 }
27 }

Solution: Group related data into classes or structs to reduce parameter lists and improve
maintainability.

1.4 Large Class


A class has too many attributes, methods, and responsibilities, violating the Single Responsibility
Principle.
Code with Smell:
1 public class Student {
2 private String name ;
3 private int age ;
4 private String email ;
5
6 public void calculateGrade () { }
7 public void sendEmail () { }
8 public void saveToDatabase () { }
9 public void generateReport () { }
10 }

Refactored Code:
1 public class Student {
2 private String name ;
3 private int age ;
4 private String email ;
5 }
6
7 public class GradeCalculator {
8 public void calculateGrade ( Student student ) { }
9 }
10
11 public class StudentRepository {
12 public void save ( Student student ) { }
13 }
14
15 public class ReportGenerator {
16 public void generateReport ( Student student ) { }
17 }

Solution: Split the class into smaller classes, each with a clear and single responsibility.

1.5 Long Parameter List


A method has too many input parameters, making it difficult to use and maintain.
Code with Smell:

Code Smell Examples and Refactoring in Java


1 BLOATERS (BLOATED CODE) 5

1 public class UserService {


2 public void createUser ( String firstName , String lastName ,
3 String email , String phone , String address ) {
4 }
5 }

Refactored Code:
1 public class UserInfo {
2 private String firstName ;
3 private String lastName ;
4 private String email ;
5 private String phone ;
6 private String address ;
7 }
8
9 public class UserService {
10 public void createUser ( UserInfo userInfo ) {
11 }
12 }

Solution: Group related parameters into an object or class to reduce the number of param-
eters.

Code Smell Examples and Refactoring in Java


2 OBJECT-ORIENTATION ABUSERS 6

2 Object-Orientation Abusers
All smells in this group are incomplete or incorrect application of object-oriented programming
principles.

2.1 Alternative Classes with Different Interfaces


Classes have similar functionality but different interfaces, making them difficult to substitute
for each other.
Code with Smell:
1 public class Rectangle {
2 public int getArea () { return width * height ; }
3 }
4
5 public class Square {
6 public int calculateArea () { return side * side ; }
7 }

Refactored Code:
1 public interface Shape {
2 int getArea () ;
3 }
4
5 public class Rectangle implements Shape {
6 private int width ;
7 private int height ;
8
9 @Override
10 public int getArea () {
11 return width * height ;
12 }
13 }
14
15 public class Square implements Shape {
16 private int side ;
17
18 @Override
19 public int getArea () {
20 return side * side ;
21 }
22 }

Solution: Standardize interfaces using inheritance or composition to make classes inter-


changeable.

2.2 Refused Bequest


A subclass does not use or refuses methods/properties inherited from the parent class, violating
the Liskov Substitution Principle.
Code with Smell:
1 public class Bird {
2 public void fly () { }
3 public void eat () { }
4 }
5
6 public class Penguin extends Bird {
7 @Override
8 public void fly () {
9 throw new U n s u p p o r t e d O p e r a t i o n E x c e p t i o n ( " Can ’t fly ! " ) ;

Code Smell Examples and Refactoring in Java


2 OBJECT-ORIENTATION ABUSERS 7

10 }
11 }

Refactored Code:
1 public class Bird {
2 public void eat () { }
3 }
4
5 public interface Flyable {
6 void fly () ;
7 }
8
9 public class Sparrow extends Bird implements Flyable {
10 @Override
11 public void fly () { }
12 }
13
14 public class Penguin extends Bird {
15 }

Solution: Use composition instead of inheritance, or restructure the hierarchy to avoid


inappropriate inheritance.

2.3 Switch Statements


Excessive use of switch/case statements, especially switches based on type, violating the Open/-
Closed Principle.
Code with Smell:
1 public class PaymentProcessor {
2 public void process ( String type , double amount ) {
3 switch ( type ) {
4 case " CREDIT_CARD " :
5 break ;
6 case " PAYPAL " :
7 break ;
8 default :
9 throw new I l le g a lA r g um e n tE x c ep t i on () ;
10 }
11 }
12 }

Refactored Code:
1 public interface PaymentMethod {
2 void process ( double amount ) ;
3 }
4
5 public class CreditCardPayment implements PaymentMethod {
6 @Override
7 public void process ( double amount ) { }
8 }
9
10 public class PayPalPayment implements PaymentMethod {
11 @Override
12 public void process ( double amount ) { }
13 }
14
15 public class PaymentProcessor {
16 public void process ( PaymentMethod method , double amount ) {
17 method . process ( amount ) ;
18 }

Code Smell Examples and Refactoring in Java


2 OBJECT-ORIENTATION ABUSERS 8

19 }

Solution: Use polymorphism, strategy pattern, or state pattern to replace switch state-
ments.

2.4 Temporary Field


A field is only used in specific cases and is often null or has no value, making the code difficult
to understand.
Code with Smell:
1 public class Order {
2 private double total ;
3 private double discount ;
4
5 public void calculateTotal () {
6 total = 100;
7 if ( hasPromotion () ) {
8 discount = 10;
9 total -= discount ;
10 } else {
11 discount = 0;
12 }
13 }
14
15 private boolean hasPromotion () {
16 return false ;
17 }
18 }

Refactored Code:
1 public class Order {
2 private double total ;
3
4 public void calculateTotal () {
5 total = 100;
6 if ( hasPromotion () ) {
7 total = applyDiscount ( total ) ;
8 }
9 }
10
11 private double applyDiscount ( double amount ) {
12 return amount * 0.9;
13 }
14
15 private boolean hasPromotion () {
16 return false ;
17 }
18 }

Solution: Extract the logic that uses the field into a separate class, or use a parameter
object.

Code Smell Examples and Refactoring in Java


3 CHANGE PREVENTERS 9

3 Change Preventers
These smells mean that if you need to change something in one place in your code, you have to
make many changes in other places too. Program development becomes much more complicated
and expensive as a result.

3.1 Divergent Change


A class is changed for many different reasons, violating the Single Responsibility Principle.
Code with Smell:
1 public class Employee {
2 private String name ;
3 private double salary ;
4
5 public double calculateSalary () {
6 return salary * 1.1;
7 }
8
9 public void saveToDatabase () { }
10
11 public void generateReport () { }
12 }

Refactored Code:
1 public class Employee {
2 private String name ;
3 private double salary ;
4 }
5
6 public class SalaryCalculator {
7 public double calculateSalary ( Employee employee ) {
8 return employee . getSalary () * 1.1;
9 }
10 }
11
12 public class EmployeeRepository {
13 public void save ( Employee employee ) { }
14 }
15
16 public class ReportGenerator {
17 public void generateReport ( Employee employee ) { }
18 }

Solution: Split the class into smaller classes, each changing for only one reason.

3.2 Parallel Inheritance Hierarchies


When you create a subclass in one hierarchy, you must create a corresponding subclass in another
hierarchy.
Code with Smell:
1 public class Employee { }
2 public class Manager extends Employee { }
3
4 public class EmployeeDAO { }
5 public class ManagerDAO extends EmployeeDAO { }

Refactored Code:

Code Smell Examples and Refactoring in Java


3 CHANGE PREVENTERS 10

1 public class Employee { }


2 public class Manager extends Employee { }
3
4 public class EmployeeDAO < T extends Employee > {
5 public void save ( T employee ) { }
6 }

Solution: Use generics or composition to avoid parallel hierarchies.

3.3 Shotgun Surgery


When you change one thing, you have to change many classes in different places.
Code with Smell:
1 public class Order {
2 private String status ;
3 }
4
5 public class OrderValidator {
6 public boolean validate ( Order order ) {
7 return ! order . getStatus () . equals ( " CANCELLED " ) ;
8 }
9 }
10
11 public class OrderProcessor {
12 public void process ( Order order ) {
13 if ( order . getStatus () . equals ( " CANCELLED " ) ) {
14 return ;
15 }
16 }
17 }

Refactored Code:
1 public enum OrderStatus {
2 PENDING , CANCELLED ;
3
4 public boolean canProcess () {
5 return this != CANCELLED ;
6 }
7 }
8
9 public class Order {
10 private OrderStatus status ;
11
12 public boolean isCancelled () {
13 return status == OrderStatus . CANCELLED ;
14 }
15 }
16
17 public class OrderValidator {
18 public boolean validate ( Order order ) {
19 return ! order . isCancelled () ;
20 }
21 }
22
23 public class OrderProcessor {
24 public void process ( Order order ) {
25 if ( order . isCancelled () ) {
26 return ;
27 }
28 }
29 }

Code Smell Examples and Refactoring in Java


3 CHANGE PREVENTERS 11

Solution: Move related changes into a single class, use Move Method or Move Field refac-
toring techniques.

Code Smell Examples and Refactoring in Java


4 DISPENSABLES 12

4 Dispensables
A dispensable is something pointless and unneeded whose absence would make the code cleaner,
more efficient, and easier to understand.

4.1 Comments
Too many comments or comments explaining complex code instead of making the code self-
explanatory.
Code with Smell:
1 public class Calculator {
2 // This method adds two numbers
3 public int add ( int a , int b ) {
4 return a + b ; // Return the sum
5 }
6
7 // Check if number is even
8 public boolean isEven ( int number ) {
9 return number % 2 == 0; // If remainder is 0 , it ’s even
10 }
11 }

Refactored Code:
1 public class Calculator {
2 public int add ( int a , int b ) {
3 return a + b ;
4 }
5
6 public boolean isEven ( int number ) {
7 return number % 2 == 0;
8 }
9 }

Solution: Make code self-documenting, only comment when truly necessary (e.g., explaining
complex algorithms).

4.2 Duplicate Code


The same code appears in multiple places, requiring changes in many locations and making
maintenance difficult.
Code with Smell:
1 public class OrderService {
2 public void processOrder ( Order order ) {
3 if ( order == null ) {
4 throw new I ll e g al A r gu m e nt E x ce p t io n ( " Order cannot be null " ) ;
5 }
6 }
7
8 public void cancelOrder ( Order order ) {
9 if ( order == null ) {
10 throw new I ll e g al A r gu m e nt E x ce p t io n ( " Order cannot be null " ) ;
11 }
12 }
13 }

Refactored Code:
1 public class OrderService {
2 public void processOrder ( Order order ) {

Code Smell Examples and Refactoring in Java


4 DISPENSABLES 13

3 validateOrder ( order ) ;
4 }
5
6 public void cancelOrder ( Order order ) {
7 validateOrder ( order ) ;
8 }
9
10 private void validateOrder ( Order order ) {
11 if ( order == null ) {
12 throw new I ll e g al A r gu m e nt E x ce p t io n ( " Order cannot be null " ) ;
13 }
14 }
15 }

Solution: Extract Method, Extract Class, or use inheritance/composition to eliminate du-


plication.

4.3 Data Class


A class only has getters/setters and no behavior, lacking encapsulation with business logic
scattered elsewhere.
Code with Smell:
1 public class Order {
2 private double total ;
3
4 public double getTotal () {
5 return total ;
6 }
7
8 public void setTotal ( double total ) {
9 this . total = total ;
10 }
11 }
12
13 public class OrderCalculator {
14 public double calculateTotal ( Order order ) {
15 return 100.0;
16 }
17 }

Refactored Code:
1 public class Order {
2 private List < OrderItem > items ;
3
4 public double getTotal () {
5 return items . stream ()
6 . mapToDouble ( item -> item . getPrice () * item . getQuantity () )
7 . sum () ;
8 }
9 }

Solution: Move behavior into the class, or create methods with meaningful business logic.

4.4 Dead Code


Code that is never used or cannot be accessed, unnecessarily increasing complexity.
Code with Smell:
1 public class UserService {
2 public void createUser ( String name ) { }

Code Smell Examples and Refactoring in Java


4 DISPENSABLES 14

3
4 public void updateUser ( String name ) { }
5
6 public void deleteUser ( String name ) {
7 // Never called
8 }
9
10 private String unusedField = " test " ;
11 }

Refactored Code:
1 public class UserService {
2 public void createUser ( String name ) { }
3
4 public void updateUser ( String name ) { }
5 }

Solution: Remove unused code, use code analysis tools to identify dead code.

4.5 Lazy Class


A class doesn’t do much and doesn’t have enough responsibility to exist, unnecessarily increasing
complexity.
Code with Smell:
1 public class NameFormatter {
2 public String format ( String name ) {
3 return name . trim () ;
4 }
5 }

Refactored Code:
1 public class User {
2 private String name ;
3
4 public String getName () {
5 return name != null ? name . trim () : " " ;
6 }
7 }

Solution: Inline Class, merge into another class, or add behavior if needed.

4.6 Speculative Generality


Code is written too generally for current needs, "just in case" for the future, violating YAGNI
(You Aren’t Gonna Need It).
Code with Smell:
1 public interface PaymentProcessor < T extends Payment > {
2 void process ( T payment ) ;
3 }
4
5 public class CreditCardProcessor implements PaymentProcessor < CreditCard > {
6 @Override
7 public void process ( CreditCard payment ) { }
8 }

Refactored Code:
1 public class CreditCardProcessor {
2 public void process ( CreditCard payment ) { }
3 }

Code Smell Examples and Refactoring in Java


4 DISPENSABLES 15

Solution: Simplify code, only implement what is truly necessary. Refactor to create ab-
straction when needed.

Code Smell Examples and Refactoring in Java


5 COUPLERS 16

5 Couplers
All smells in this group contribute to excessive coupling between classes or show what happens
if coupling is replaced by excessive delegation.

5.1 Feature Envy


A method uses data from another class more than data from its own class, violating encapsula-
tion.
Code with Smell:
1 public class Order {
2 private Customer customer ;
3 private List < OrderItem > items ;
4 }
5
6 public class OrderPrinter {
7 public void print ( Order order ) {
8 String name = order . getCustomer () . getName () ;
9 int count = order . getItems () . size () ;
10 }
11 }

Refactored Code:
1 public class Order {
2 private Customer customer ;
3 private List < OrderItem > items ;
4
5 public String getSummary () {
6 return customer . getName () + " - " + items . size () + " items " ;
7 }
8 }
9
10 public class OrderPrinter {
11 public void print ( Order order ) {
12 System . out . println ( order . getSummary () ) ;
13 }
14 }

Solution: Move the method to the class that contains the data used most.

5.2 Inappropriate Intimacy


Two classes know too much about each other’s implementation details, creating tight coupling.
Code with Smell:
1 public class Order {
2 private List < OrderItem > items ;
3
4 public List < OrderItem > getItems () {
5 return items ;
6 }
7 }
8
9 public class OrderCalculator {
10 public void calculate ( Order order ) {
11 order . getItems () . clear () ;
12 }
13 }

Refactored Code:

Code Smell Examples and Refactoring in Java


5 COUPLERS 17

1 public class Order {


2 private List < OrderItem > items ;
3
4 public List < OrderItem > getItems () {
5 return new ArrayList < >( items ) ;
6 }
7
8 public void recalculate () {
9 // Calculation logic here
10 }
11 }
12
13 public class OrderCalculator {
14 public void calculate ( Order order ) {
15 order . recalculate () ;
16 }
17 }

Solution: Reduce coupling by using interfaces, dependency injection, or extracting shared


logic.

5.3 Incomplete Library Class


A class from an external library lacks some necessary features, requiring workarounds.
Code with Smell:
1 public class ExternalEmailService {
2 public void send ( String to , String subject , String body ) { }
3 }
4
5 public class EmailSender {
6 private ExternalEmailService service ;
7
8 public void sendWithAttachment ( String to , String subject ,
9 String body , String attachment ) {
10 String newBody = body + " \ nAttachment : " + attachment ;
11 service . send ( to , subject , newBody ) ;
12 }
13 }

Refactored Code:
1 public interface EmailService {
2 void send ( String to , String subject , String body ) ;
3 void sendWithAttachment ( String to , String subject ,
4 String body , String attachment ) ;
5 }
6
7 public class EmailServiceAdapter implements EmailService {
8 private ExternalEmailService externalService ;
9
10 @Override
11 public void send ( String to , String subject , String body ) {
12 externalService . send ( to , subject , body ) ;
13 }
14
15 @Override
16 public void sendWithAttachment ( String to , String subject ,
17 String body , String attachment ) {
18 // Implementation
19 }
20 }

Code Smell Examples and Refactoring in Java


5 COUPLERS 18

Solution: Use wrapper class, extension methods, or adapter pattern to extend library func-
tionality.

5.4 Middle Man


A class only delegates calls to another class without adding any value, unnecessarily increasing
complexity.
Code with Smell:
1 public class Person {
2 private Department department ;
3
4 public Department getDepartment () {
5 return department ;
6 }
7 }
8
9 public class PersonManager {
10 private Person person ;
11
12 public Department getDepartment () {
13 return person . getDepartment () ;
14 }
15 }

Refactored Code:
1 public class Person {
2 private Department department ;
3
4 public Department getDepartment () {
5 return department ;
6 }
7 }
8
9 // Remove PersonManager , use Person directly

Solution: Inline Class, remove the middle man and call directly.

5.5 Message Chains


Long chains of method calls like [Link]().getB().getC().doSomething(), creating tight
coupling.
Code with Smell:
1 public class Person {
2 private Department department ;
3 public Department getDepartment () { return department ; }
4 }
5
6 public class Department {
7 private Company company ;
8 public Company getCompany () { return company ; }
9 }
10
11 public class Company {
12 private String name ;
13 public String getName () { return name ; }
14 }
15
16 public class PersonService {
17 public String getCompanyName ( Person person ) {

Code Smell Examples and Refactoring in Java


5 COUPLERS 19

18 return person . getDepartment () . getCompany () . getName () ;


19 }
20 }

Refactored Code:
1 public class Person {
2 private Department department ;
3
4 public String getCompanyName () {
5 return department != null ? department . getCompanyName () : null ;
6 }
7 }
8
9 public class Department {
10 private Company company ;
11
12 public String getCompanyName () {
13 return company != null ? company . getName () : null ;
14 }
15 }
16
17 public class PersonService {
18 public String getCompanyName ( Person person ) {
19 return person . getCompanyName () ;
20 }
21 }

Solution: Hide Delegate, create method wrapper, or use Law of Demeter to reduce chain
length.

Code Smell Examples and Refactoring in Java

You might also like