Download problems and solutions for code smells and more Assignments Software Engineering in PDF only on Docsity!
Made by Adel Abd Elstar
Code smells
A code smell : is any characteristic in the source code of a program
that possibly indicates a deeper problem determining what is and is not
a code smell is subjective, and varies by language, developer, and
. development methodology
Life-cycle of a smell:
: Bloaters
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 (and especially when nobody
. makes an effort to eradicate them)
: Its types
:Long Method. 1
:Signs and Symptoms
A method contains too many lines of code.
Generally, any method longer than ten lines
. should make you start asking questions
Reasons for the Problem:
Like the Hotel California, something is always being added
to a method but nothing is ever taken out. Since it is
easier to write code than to read it, this “smell” remains
unnoticed until the method turns into an ugly, oversized
beast.
Mentally, it is often harder to create a new method than to
add to an existing one: “But it’s just two lines, there’s no
use in creating a whole method just for that...” Which
means that another line is added and then yet another,
giving birth to a tangle of spaghetti code.
Treatment:
As a rule of thumb, if you feel the need to comment on
something inside a method, you should take this code and
put it in a new method. Even a single line can and should
be split off into a separate method, if it requires
explanations. And if the method has a descriptive name,
nobody will need to look at the code to see what it does.
To reduce the length of a method body, use Extract Method.
Problem
You have a code fragment that can be grouped together.
void printOwing () { printBanner();
// Print details. System.out.println("name: " + name); System.out.println("amount: " + getOutstanding()); }
Solution
Move this code to a separate new method (or function) and replace
the old code with a call to the method.
void printOwing () { printBanner();
Solution
Replace these parameters with an object.
Preserve Whole Object
Problem
You get several values from an object and then pass them as
parameters to a method.
int low = daysTempRange.getLow(); int high = daysTempRange.getHigh(); boolean withinPlan = plan.withinRange(low, high);
Solution
Instead, try passing the whole object.
boolean withinPlan = plan.withinRange(daysTempRange);
If none of the previous recipes help, try moving the entire
method to a separate object via Replace Method with
Method Object.
Replace Method with Method Object
Problem
You have a long method in which the local variables are so
intertwined that you cannot apply Extract Method.
class Order { // ... public double price() { double primaryBasePrice; double secondaryBasePrice; double tertiaryBasePrice; // Perform long computation. } }
Solution
Transform the method into a separate class so that the local
variables become fields of the class. Then you can split the method
into several methods within the same class.
class Order { // ... public double price() { return new PriceCalculator( this ).compute(); } } class PriceCalculator { private double primaryBasePrice; private double secondaryBasePrice; private double tertiaryBasePrice;
public PriceCalculator(Order order) { // Copy relevant information from the // order object. } public double compute() { // Perform long computation. } }
Conditional operators and loops are a good clue that code can
be moved to a separate method. For conditionals,
use Decompose Conditional. If loops are in the way, try
Extract Method.
Decompose Conditional
Problem
You have a complex conditional (if-then/else or switch).
if (date.before(SUMMER_START) || date.after(SUMMER_END)) { charge = quantity * winterRate + winterServiceCharge; } else { charge = quantity * summerRate; }
Solution
Decompose the complicated parts of the conditional into separate
methods: the condition, then and else.
if (isSummer(date)) { charge = summerCharge(quantity); } else { charge = winterCharge(quantity); } Payoff:
Among all types of object oriented code, classes with
short methods live longest. The longer a method or
function is, the harder it becomes to understand and
maintain it.
In addition, long methods offer the perfect hiding
place for unwanted duplicate code.
Payoff
Refactoring of these classes spares developers from
needing to remember a large number of attributes
for a class.
In many cases, splitting large classes into parts
avoids duplication of code and functionality.
3.Primitive Obsession Signs and Symptoms
Use of primitives instead of small objects for simple
tasks (such as currency, ranges, special strings for
phone numbers, etc.)
Use of constants for coding information (such as a
constant USER_ADMIN_ROLE = 1 for referring to users
with administrator rights.)
Use of string constants as field names for use in data
arrays.
Reasons for the Problem
Like most other smells, primitive obsessions are born in
moments of weakness. “Just a field for storing some data!”
the programmer said. Creating a primitive field is so much
easier than making a whole new class, right? And so it was
done. Then another field was needed and added in the
same way. Lo and behold, the class became huge and
unwieldy.
Primitives are often used to “simulate” types. So instead
of a separate data type, you have a set of numbers or
strings that form the list of allowable values for some
entity. Easy-to-understand names are then given to these
specific numbers and strings via constants, which is why
they are spread wide and far.
Another example of poor primitive use is field simulation.
The class contains a large array of diverse data and string
constants (which are specified in the class) are used as
array indices for getting this data.
Treatment
If you have a large variety of primitive fields, it may
be possible to logically group some of them into their
own class. Even better, move the behavior
associated with this data into the class too. For this
task, try Replace Data Value with Object.
Replace Data Value with Object
Problem
A class (or group of classes) contains a data field. The field
has its own behavior and associated data.
Solution
Create a new class, place the old field and its behavior in
the class, and store the object of the class in the original
class.
If the values of primitive fields are used in method parameters,
go with Introduce Parameter Object or Preserve Whole Object.
Introduce Parameter Object
Problem
Your methods contain a repeating group of parameters.
Solution
Create a new class and use its objects instead of the type
code values.
person
BoldGroup
O: BoldGroup
A: BoldGroup
B: BoldGroup
AB: BoldGroup
Replace Type Code with Subclasses
What is type code? Type code occurs when, instead of a separate
data type, you have a set of numbers or strings that form a list of
allowable values for some entity. Often these specific numbers and
strings are given understandable names via constants, which is the
reason for why such type code is encountered so much.
Problem
You have a coded type that directly affects program behavior
(values of this field trigger various code in conditionals).
Solution
Create subclasses for each value of the coded type. Then extract
the relevant behaviors from the original class to these subclasses.
Replace the control flow code with polymorphism.
Replace Type Code with State/Strategy
What is type code? Type code occurs when, instead of a
separate data type, you have a set of numbers or strings that form a
list of allowable values for some entity. Often these specific
numbers and strings are given understandable names via constants,
which is the reason for why such type code is encountered so much.
Problem
You have a coded type that affects behavior but you cannot use
subclasses to get rid of it.
Solution
Replace type code with a state object. If it is necessary to replace a
field value with type code, another state object is “plugged in”.
If there are arrays among the variables, use Replace Array with
Object.
method to the code for calling the method, but the created objects
are passed to the method as parameters. Thus the original class no
longer knows about the relationships between objects, and
dependency has decreased. But if several of these objects are
created, each of them will require its own parameter, which means
a longer parameter list.
It is hard to understand such lists, which become contradictory and
hard to use as they grow longer. Instead of a long list of parameters,
a method can use the data of its own object. If the current object
does not contain all necessary data, another object (which will get
the necessary data) can be passed as a method parameter.
Treatment
Check what values are passed to parameters. If some of the
arguments are just results of method calls of another object,
use Replace Parameter with Method Call. This object can be
placed in the field of its own class or passed as a method
parameter.
Replace Parameter with Method Call Problem
Before a method call, a second method is run and its result is sent
back to the first method as an argument. But the parameter value
could have been obtained inside the method being called.
int basePrice = quantity * itemPrice; double seasonDiscount = this .getSeasonalDiscount(); double fees = this .getFees(); double finalPrice = discountedPrice(basePrice, seasonDiscount, fees); Solution
Instead of passing the value through a parameter, place the value-
getting code inside the method.
int basePrice = quantity * itemPrice; double finalPrice = discountedPrice(basePrice);
Instead of passing a group of data received from another object
as parameters, pass the object itself to the method, by
using Preserve Whole Object.
Preserve Whole Object
Problem
You get several values from an object and then pass them as
parameters to a method
int low = daysTempRange.getLow(); int high = daysTempRange.getHigh(); boolean withinPlan = plan.withinRange(low, high);
Solution
Instead, try passing the whole object.
boolean withinPlan = plan.withinRange(daysTempRange);
If there are several unrelated data elements, sometimes you can
merge them into a single parameter object via Introduce Parameter
Object.
Introduce Parameter Object
Problem
Your methods contain a repeating group of parameters.
Solution
Replace these parameters with an object.
Payoff
More readable, shorter code.
Refactoring may reveal previously unnoticed duplicate code.
5.Data Clumps Signs and Symptoms
Sometimes different parts of the code contain identical groups of
variables (such as parameters for connecting to a database). These
clumps should be turned into their own classes.
1.Switch Statements
Signs and Symptoms
You have a complex switch operator or sequence of if statements.
Reasons for the Problem
Relatively rare use of switch and case operators is one of the
hallmarks of object-oriented code. Often code for a single switch can
be scattered in different places in the program. When a new
condition is added, you have to find all the switch code and modify
it.
As a rule of thumb, when you see switch you should think of
polymorphism.
Treatment
To isolate switch and put it in the right class, you may need Extract
Method and then Move Method.
If a switch is based on type code, such as when the program’s
runtime mode is switched, use Replace Type Code with Subclasses
or Replace Type Code with State/Strategy.
After specifying the inheritance structure, use Replace Conditional
with Polymorphism.
Replace Conditional with Polymorphism
Problem
You have a conditional that performs various actions depending on
object type or properties
class Bird { // ... double getSpeed() { switch (type) { case EUROPEAN: return getBaseSpeed(); case AFRICAN: return getBaseSpeed() - getLoadFactor() * numberOfCoconuts; case NORWEGIAN_BLUE: return (isNailed)? 0 : getBaseSpeed(voltage); } throw new RuntimeException("Should be unreachable"); } }
Solution
Create subclasses matching the branches of the conditional. In
them, create a shared method and move code from the
corresponding branch of the conditional to it. Then replace the
conditional with the relevant method call. The result is that the
proper implementation will be attained via polymorphism depending
on the object class.
abstract class Bird { // ... abstract double getSpeed(); } class European extends Bird { double getSpeed() { return getBaseSpeed(); } } class African extends Bird { double getSpeed() { return getBaseSpeed() - getLoadFactor() * numberOfCoconuts; } } class NorwegianBlue extends Bird { double getSpeed() { return (isNailed)? 0 : getBaseSpeed(voltage); } } // Somewhere in client code speed = bird.getSpeed();
If there are not too many conditions in the operator and they all call
same method with different parameters, polymorphism will be
superfluous. If this case, you can break that method into multiple
smaller methods with Replace Parameter with Explicit
Methods and change the switch accordingly.
Replace Parameter with Explicit Methods
Problem
A method is split into parts, each of which is run depending on the
value of a parameter.
void setValue ( String name, int value) { if (name.equals("height")) { height = value; return ; } if (name.equals("width")) { width = value; return ; } Assert.shouldNeverReachHere(); }
Solution
Extract the individual parts of the method into their own methods
and call them instead of the original method.
Signs and Symptoms
Temporary fields get their values (and thus are needed by objects)
only under certain circumstances. Outside of these circumstances,
they are empty.
Reasons for the Problem
Oftentimes, temporary fields are created for use in an algorithm
that requires a large amount of inputs. So instead of creating a large
number of parameters in the method, the programmer decides to
create fields for this data in the class. These fields are used only in
the algorithm and go unused the rest of the time.
This kind of code is tough to understand. You expect to see data in
object fields but for some reason they are almost always empty.
Treatment
Temporary fields and all code operating on them can be put in a
separate class via Extract Method. In other words, you are
creating a method object, achieving the same result as if you would
perform Replace Method with Method Object.
Introduce Null Object and integrate it in place of the conditional code
which was used to check the temporary field values for existence.
Payoff
Better code clarity and organization.
3.Refused Bequest
Signs and Symptoms
If a subclass uses only some of the methods and properties
inherited from its parents, the hierarchy is off-kilter. The unneeded
methods may simply go unused or be redefined and give off
exceptions.
Reasons for the Problem
Someone was motivated to create inheritance between classes only
by the desire to reuse the code in a superclass. But the superclass
and subclass are completely different.
Treatment
If inheritance makes no sense and the subclass really does have
nothing in common with the superclass, eliminate inheritance in
favor of Replace Inheritance with Delegation.
Replace Inheritance with Delegation
Problem
You have a subclass that uses only a portion of the methods of its
superclass (or it’s not possible to inherit superclass data).
Solution
Create a field and put a superclass object in it, delegate methods to
the superclass object, and get rid of inheritance.
If inheritance is appropriate, get rid of unneeded fields and methods in
the subclass. Extract all fields and methods needed by the subclass
from the parent class, put them in a new subclass, and set both
classes to inherit from it ( Extract Superclass ).
Payoff
Improves code clarity and organization. You will no longer have to
wonder why the Dog class is inherited from the Chair class (even
though they both have 4 legs).
4.Alternative Classes with Different Interfaces
Signs and Symptoms
Two classes perform identical functions but have different method
names.