Effective Java 20 Prefer class hierarchies to tagged classes
Disadvantage of tagged classes
1. Verbose (each instance has unnecessary irrelevant fields).
2. Error-prone (Program will fail by initializing wrong fields).
3. Inefficient (Memory footprint is increased for not used field).
/**
* Tagged class - vastly inferior to a class hierarchy!
* @author Kaibo
*/
class Figure {
enum Shape {
RECTANGLE, CIRCLE
};
// Tag field - the shape of this figure
final Shape shape;
// These fields are used only if shape is RECTANGLE
double length;
double width;
// This field is used only if shape is CIRCLE
double radius;
// Constructor for circle
Figure(double radius) {
shape = Shape.CIRCLE;
this.radius = radius;
}
// Constructor for rectangle
Figure(double length, double width) {
shape = Shape.RECTANGLE;
this.length = length;
this.width = width;
}
double area() {
switch (shape) {
case RECTANGLE:
return length * width;
case CIRCLE:
return Math.PI * (radius * radius);
default:
throw new AssertionError();
}
}
}
/*
* Refined with Hierarchies
*/
/**
* Class hierarchy replacement for a tagged class
* @author Kaibo
*/
abstract class Figure {
abstract double area();
}
public class Rectangle extends Figure {
// specific fields
final double length;
final double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
/*
* Common methods
* @see com.effectivejava.classinterface.Figure#area()
*/
@Override
double area() {
return length * width;
}
}
public class Circle extends Figure {
/**
* specific fields.
*/
final double radius;
Circle(double radius) {
this.radius = radius;
}
/*
* common method
* @see com.effectivejava.classinterface.Figure#area()
*/
@Override
double area() {
return Math.PI * (radius * radius);
}
}
Summary
If you're tempted to write a class with an explicit tag field, think about whether the tag could be eliminated and the class replaced by a hierarchy. When you encounter an existing class with a tag field, consider refactoring it into a hierarchy.
Effective Java 20 Prefer class hierarchies to tagged classes的更多相关文章
- Effective Java 69 Prefer concurrency utilities to wait and notify
Principle Use the higher-level concurrency utilities instead of wait and notify for easiness. Use Co ...
- Effective Java 35 Prefer annotations to naming patterns
Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...
- Effective Java 53 Prefer interfaces to reflection
Disadvantage of reflection You lose all the benefits of compile-time type checking, including except ...
- Effective Java 68 Prefer executors and tasks to threads
Principle The general mechanism for executing tasks is the executor service. If you think in terms o ...
- Effective Java 18 Prefer interfaces to abstract classes
Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...
- Effective Java 25 Prefer lists to arrays
Difference Arrays Lists 1 Covariant Invariant 2 Reified at runtime Erased at run time 3 Runtime type ...
- Effective Java 46 Prefer for-each loops to traditional for loops
Prior to release 1.5, this was the preferred idiom for iterating over a collection: // No longer the ...
- Effective Java 49 Prefer primitive types to boxed primitives
No. Primitives Boxed Primitives 1 Have their own values Have identities distinct from their values 2 ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
随机推荐
- (翻译)为你的MVC应用程序创建自定义视图引擎
Creating your own MVC View Engine For MVC Application 原文链接:http://www.codeproject.com/Articles/29429 ...
- 第一个sprint总结和读后感
总结:通过第一个sprint的冲刺,了解了sprint的整个流程,学会了在一个团队里该如何开展一个项目和分配任务.我们的队团在第一个sprint中没有达到我们预期的效果,我们也做出了反省,原因一是我们 ...
- JS代码的位置与事件响应代码块的封装问题
JS代码的位置 我们可以将JavaScript代码放在html文件中任何位置,但是我们一般放在网页的head或者body部分. 放在<head>部分最常用的方式是在页面中h ...
- .net接口学习笔记
1.接口的声明 接口的声明不能包含:数据成员,静态变量:只能包含如下类型的静态成员函数的声明:方法,属性,事件,索引器.声明中不能包含任何实现的代码,而在每个成员成名的主体后,必须使用分号. 接口声明 ...
- JS获取屏幕高度
主要使用了document对象关于窗口的一些属性,这些属性的主要功能和用法如下. 要 得到窗口的尺寸,对于不同的浏览器,需要使用不同的属性和方法:若要检测窗口的真实尺寸,在netscape下需要使用w ...
- HTML5 Wijmo:控制 Wijmo Grid 插件的编辑模式
Wijmo jQuery 插件经常应用于在财务类网站中创建平滑和良好用户体验的交互表格.WijGrid 插件用于显示.排序.分组和编辑数据.今天我们来分享下如何控件WijGrid插件的编辑模式. 在本 ...
- sso demo ( cas )
1. generate keystore command : keytool -genkey -alias testtomcat -keyalg RSA -keystore "C:\User ...
- MySQL Plugin 'InnoDB' init function returned error一例
早上上班后,测试说演示环境挂了,维护上去看了下,启动报错了: XXXXXX08:30:47 mysqld_safe Starting mysqld daemon with databases from ...
- FAQ_1_陌生的VERSION.SDK_INT
看到VERSION.SDK_INT不禁诧异,这是何物?! 看API的定义,如下: 原来是一个常量值.但是这个常量值可以根据系统的不同而不同哟!为了揭开其神秘的面纱,将源码ctrl如下: 可以看出,获取 ...
- java分派
变量被声明时的类型叫做变量的静态类型(Static Type) 又叫明显类型(Apparent Type).变量所引用的对象的真实类型又叫做变量的实际类型(Actual Type). 根据对象的类型而 ...