Member-only story

Effective Java! Prefer Class Hierarchies to Tagged Classes

Kyle Carter
3 min readJan 11, 2021

It seems like a lot of the previous chapters of Effective Java have shared some concerns with using all the capabilities that object-oriented programming offers us. There are indeed pitfalls with over using some of the functionality of these patterns so they should be used with prudence. Today, however, we look at a topic where object-oriented programming can come to the rescue.

Let’s start out by looking at the following class.

class Figure {
enum Shape {CIRCLE, RECTANGLE}
final Shape shape;
double length;
double width;
double radius; Figure(double radius) {
shape = Shape.CIRCLE;
this.radius = radius;
}
Figure(double length, double width) {
shape = Shape.RECTANGLE;
this.length = length;
this.width = width;
}
double area() {
switch(shape) {
case RECTANGLE:
return length * width;
break;
case CIRCLE:
return Math.PI * (radius * radius);
break;
default:
throw new AssertionError(shape);
}
}
}

As you can see in the class above this is a single class that has a enum in it that is being used a flag to indicate whether the class is a Circle or a Rectangle. Presumably the reasoning (albeit extremely thin) was that they both have a area function. Outside of saving that one line everything else is worse about this class. Let's list some of…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet