Violations of fundamental design principles that negatively impact code quality
Bad Smells in Code by Kent Beck and Martin Fowler
If it stinks, change it.
One thing we won’t try to do here is give you precise criteria for when a refactoring is overdue. In our experience no set of metrics rivals informed human intuition. What we will do is give you indications that there is trouble that can be solved by a refactoring. You will have to develop your own sense of how many instance variables are too many instance variables and how many lines of code in a method are too many lines.
– Kent Beck and Martin Fowler
The same expression in two:
See two implementations (one in each subclass) of the getArea()
abstract method. How can we eliminate the duplicate code?
The object programs that live best and longest are those with short methods.
A block of code with a comment that tells you what it is doing can be replaced by a method whose name is based on the comment. Even a single line is worth extracting if it needs explanation.
The object-oriented notion of polymorphism gives you an elegant way to deal with this problem
public double getArea(String shape) {
switch (shape) {
case "triangle":
// area = (side² × √3)/ 4
double areaTriangle = Math.pow(measure, 2) * Math.sqrt(3) / 4;
double roundedAreaTriangle = Math.round(areaTriangle * 100.0) / 100.0;
return roundedAreaTriangle;
case "circle":
// area = pi * radius²
double areaCircle = Math.PI * Math.pow(measure, 2);
double roundedCircleArea = Math.round(areaCircle * 100.0) / 100.0;
return roundedCircleArea;
case "square":
// area = side * side
double areaSquare = measure * measure;
double roundedSquareArea = Math.round(areaSquare * 100.0) / 100.0;
return roundedSquareArea;
default:
System.out.println("Shape string not recognized");
return 0;
}
}
Replace Conditional with Polymorphism
getArea()
abstract methodgetArea()
A telephone number may be represented as a string for a while, but later you realize that the telephone needs special behavior for formatting, extracting the area code, and the like
Brush.java
class with private instance variables for size, color, and shape.square.setFill(brush.getColor())
Go back to your own code that you have written this semester, and try to find examples of bad smells.