Using generalization
Generalization is one of the most powerful features of OOP, and it must be used wisely (with great power comes great responsibility). I’ll report here just some of the most interesting refactorings in this area, going fast with the most basic and delving a little bit deeper with the others.
Pull up field
This technique consists of moving a field (or variable) from a subclass to a superclass. This is typically done when multiple subclasses share the same field or when you want to establish a common interface or behavior in the superclass. Here’s an example:
public class Triangle { private Integer sidesNumber; } public class Square { private Integer sidesNumber; }
Triangle
and Square
have a field in common; just extract an interface or an abstract
class to do the trick:
public abstract class Polygon { private Integer sidesNumber; } public class Square extends Polygon...