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 ...
随机推荐
- Android 学习笔记之AndBase框架学习(三) 使用封装好的函数完成Http请求..
PS:踏踏实实走好每一步... 学习内容: 1.使用AndBase框架实现无参Http Get请求... 2.使用AndBase框架实现有参Http Post请求... 3.使用AndBase框架实现 ...
- ASP.NET 让无码编程不在是梦 -.NET通用平台、通用权限、易扩展、多语言、多平台架构框架
先拿出我半前年前平台的设计初稿,经过半年的努力我已经完成了该设计稿的所有功能.并且理念已经远远超出该设计稿. 下面是一些博友对我贴子的评价: 1.楼主,想法很美好,现实很骨感,我们公司就有一套你说的这 ...
- IOS开发UI基础UIImagePickerController的属性
UIImagePickerController 1.+(BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType ...
- 以神经网络使用为例的Matlab和Android混合编程
由于需要在一个Android项目中使用神经网络,而经过测试发现几个Github上开源项目的训练效果就是不如Matlab的工具箱好,所以就想在Android上使用Matlab神经网络代码(可是...) ...
- [新手学Java]使用内省(Introspector)操作JavaBean属性
获取类bean中的所有属性: @Test //获取类bean中的所有属性 public void test1() throws Exception{ BeanInfo info = Introspec ...
- 转帖一篇sixxpack破解的文章!
星期天闲着没事玩游戏,玩游戏不能无外挂.于是百度了半天,找到了一个,看介绍貌似不错,就下载了下来.一看,竟然是用.net写的,下意识地Reflector了一下.发现竟是一个叫actmp的程序集.如图: ...
- 004_URL 路由 - URL 路由
在Web Form 情况下,每一个 ASPX页面既是一个文件,又是一个队请求自包含的响应.而在 MVC 情况下,请求是由控制器类中的动作方法处理的,而且与硬盘上的文件没有一对一的相互关系. ASP.N ...
- bootstrap学习笔记(6)
滚动监听 滚动监听有两种方式: (1)通过属性控制 向想要滚动监听的元素添加如下属性data-spy="scroll",然后添加data- ...
- 重新想象 Windows 8.1 Store Apps (72) - 新增控件: AppBar, CommandBar
[源码下载] 重新想象 Windows 8.1 Store Apps (72) - 新增控件: AppBar, CommandBar 作者:webabcd 介绍重新想象 Windows 8.1 Sto ...
- 《JAVA与模式》之组合模式
定义(GoF<设计模式>): 将对象组合成树形结构以表示“部分整体”的层次结构.组合模式使得用户对单个对象和使用具有一致性. 及角色: 1.Component 是组合中的对象声明接口,在适 ...