Core Java Volume I — 4.10. Class Design Hints
4.10. Class Design Hints
Without trying to be comprehensive or tedious, we want to end this chapter with some hints that will make your classes more acceptable in well-mannered OOP circles.
1. Always keep data private.
This is first and foremost; doing anything else violates encapsulation. You may need to write an accessor or mutator method occasionally, but you are still better off keeping the instance fields private. Bitter experience shows that the data representation may change, but how this data are used will change much less frequently. When data are kept private, changes in their representation will not affect the user of the class, and bugs are easier to detect.
2. Always initialize data.
Java won't initialize local variables for you, but it will initialize instance fields of objects. Don't rely on the defaults, but initialize all variables explicitly, either by supplying a default or by setting defaults in all constructors.
3. Don't use too many basic types in a class.
The idea is to replace multiple related uses of basic types with other classes. This keeps your classes easier to understand and to change. For example, replace the following instance fields in a Customer class:
private String street;
private String city;
private String state;
private int zip;
with a new class called Address. This way, you can easily cope with changes to addresses, such as the need to deal with international addresses.
4. Not all fields need individual field accessors and mutators.
You may need to get and set an employee's salary. You certainly won't need to change the hiring date once the object is constructed. And, quite often, objects have instance fields that you don't want others to get or set, such as an array of state abbreviations in an Address class.
6. Break up classes that have too many responsibilities.
This hint is, of course, vague: "too many" is obviously in the eye of the beholder. However, if there is an obvious way to break one complicated class into two classes that are conceptually simpler, seize the opportunity. (On the other hand, don't go overboard; ten classes, each with only one method, are usually an overkill.)
Here is an example of a bad design:
public class CardDeck // bad design
{
private int[] value;
private int[] suit;
public CardDeck() { . . . }
public void shuffle() { . . . }
public int getTopValue() { . . . }
public int getTopSuit() { . . . }
public void draw() { . . . }
}
This class really implements two separate concepts: a deck of cards, with its shuffle and draw methods, and a card, with the methods to inspect its value and suit. It makes sense to introduce a Card class that represents an individual card.
Now you have two classes, each with its own responsibilities:
public class CardDeck
{
private Card[] cards;
public CardDeck() { . . . }
public void shuffle() { . . . }
public Card getTop() { . . . }
public void draw() { . . . }
}
public class Card
{
private int value;
private int suit;
public Card(int aValue, int aSuit) { . . . }
public int getValue() { . . . }
public int getSuit() { . . . }
}
7. Make the names of your classes and methods reflect their responsibilities.
Just as variables should have meaningful names that reflect what they represent, so should classes. (The standard library certainly contains some dubious examples, such as the Date class that describes time.)
A good convention is that a class name should be a noun (Order), or a noun preceded by an adjective (RushOrder) or a gerund (an "-ing" word, like BillingAddress). As for methods, follow the standard convention that accessor
methods begin with a lowercase get (getSalary) and mutator methods use a lowercase set (setSalary).
In this chapter, we covered the fundamentals of objects and classes that make Java an "object-based" language. In order to be truly object-oriented, a programming language must also support inheritance and polymorphism. The Java support for these features is the topic of the next chapter.
Core Java Volume I — 4.10. Class Design Hints的更多相关文章
- Core Java Volume I — 3.10. Arrays
3.10. ArraysAn array is a data structure that stores a collection of values of the same type. You ac ...
- Core Java Volume I — 1.2. The Java "White Paper" Buzzwords
1.2. The Java "White Paper" BuzzwordsThe authors of Java have written an influential White ...
- Core Java Volume I — 4.7. Packages
4.7. PackagesJava allows you to group classes in a collection called a package. Packages are conveni ...
- Core Java Volume I — 5.1. Classes, Superclasses, and Subclasses
5.1. Classes, Superclasses, and SubclassesLet's return to the Employee class that we discussed in th ...
- Core Java Volume I — 3.8. Control Flow
3.8. Control FlowJava, like any programming language, supports both conditional statements and loops ...
- Core Java Volume I — 4.6. Object Construction
4.6. Object ConstructionYou have seen how to write simple constructors that define the initial state ...
- Core Java Volume I — 4.5. Method Parameters
4.5. Method ParametersLet us review the computer science terms that describe how parameters can be p ...
- Core Java Volume I — 4.4. Static Fields and Methods
4.4. Static Fields and MethodsIn all sample programs that you have seen, the main method is tagged w ...
- Core Java Volume I — 4.1. Introduction to Object-Oriented Programming
4.1. Introduction to Object-Oriented ProgrammingObject-oriented programming, or OOP for short, is th ...
随机推荐
- cisco LAN
由于实验需要,需要搞个内部局域网(以前我们实验室是直接从学校拖了根线过来,然后直接用switch连).因此得先配个router,做个小局域网.由于从没接触过路由器,所以先去网上找了些资料,接着就打开c ...
- 如何使用JCONSOLE 监控eclipse的tomcat
在默认情况下,使用jconsole 监控本地tomcat 是不需要任何配置的,直接连接就可以监控tomcat. 但是在eclipse 下启动是监控不了. 解决方法: 设置jvm参数: ...
- FZU 2092 收集水晶 bfs+记忆化搜索 or 暴力
题目链接:收集水晶 一眼看过去,觉得是普通的bfs,初始位置有两个.仔细想了想...好像如果这样的话..........[不知道怎么说...T_T] dp[12][12][12][12][210] 中 ...
- 客户端访问AIDLService(远程绑定Service)
import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android. ...
- 使用rosed编辑ROS文件
1.1使用rosed. rosed是rosbash套件的一部分.它可以使你通过package的名字直接编辑一个package中的文件而不用输入package的整个路径. 用法: $ rosed [pa ...
- dx wpf的各种坑
这篇随笔总结dx wpf使用中的各种坑,持续更新~ LookUpEdit里内嵌的DXGrid的名字必须是"PART_GridControl",不能不写.也不能写错.我对比了2个小时 ...
- Java中的深拷贝和浅拷贝
1.浅拷贝与深拷贝概念 (1)浅拷贝(浅克隆) 浅拷贝又叫浅复制,将对象中的所有字段复制到新的对象(副本)中.其中,值类型字段(java中8中原始类型)的值被复制到副本中后,在副本中的修改不会影响到源 ...
- HDU 2594 扩展kmp模板题
题目大意: 给定两个字符串,在第一个字符串中找到一个最大前缀作为第二个字符串的后缀 #include <iostream> #include <cstdio> #include ...
- Rhel6-heartbeat+lvs配置文档
系统环境: rhel6 x86_64 iptables and selinux disabled 主机: 192.168.122.119 server19.example.com 192.168.12 ...
- iframe中的jquery ui modal dialog 覆盖父窗口
在iframe中 使用jquery ui dialog,弹出后可以覆盖父窗体 ///iframe中的jquery ui modal dialog 覆盖父窗口 function openDialog() ...