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 ...
随机推荐
- Java:一个简单的Java应用程序
/** * 这是文档注释 * @version * @author */ /* 这之间的内容也是注释 */ //这是行注释 public class FirstSample { public st ...
- php圖片中寫入字符串然後生成圖片下載到本地
<?php /** * 生成卡片得類 * Enter description here ... * @author perry * @time 2014-03-03 10:02:20 */ cl ...
- 使用Join代替In
我们知道,在sql中使用IN让我们的where子句可以规定多个值.当需要从一个集合中查询包含某几个值的记录的时候,通常我们会选择使用IN来实现,其实,使用JOIN也可以实现这样的功能,而且性能要比IN ...
- C#中三种定时器对象的比较
·关于C#中timer类 在C#里关于定时器类就有3个1.定义在System.Windows.Forms里2.定义在System.Threading.Timer类里3.定义在System.Timers ...
- bzoj 1911: [Apio2010]特别行动队
#include<cstdio> #include<iostream> #define M 1000009 #define ll long long using namespa ...
- C语言中 scanf 和 printf 的小要点
1 scanf_s需指定%c 个数 h short l long关键字 * 不赋给任何值 W 指定读入宽度 转换字符 a 读浮点值(c99) A 读浮点值(c99) c 读单字符 d 读十进制数 i ...
- Fence9
题目大意: 求点(0,0),(n,m),(p,0)三点构成的三角形内部(不包括边界)整点的个数. 解题过程:1.直接枚举纵坐标,然后算出两条直线上纵坐标为y的点的横坐标,然后他们中间的点就是符合要求的 ...
- NOIP 2001解题报告
第一题: 有形如:ax3+bx2+cx+d=0 这样的一个一元三次方程.给出该方程中各项的系数(a,b,c,d 均为实数),并约定该方程存在三个不同实根(根的范围在-100至100之间),且根与 ...
- SelectedRows.CurrentRowSelected 和 DeleteItem
procedure TBMListEh.SetCurrentRowSelected(Value: Boolean); var Index: Integer; Current: TUniBookmark ...
- MyEclipse的 at com.genuitec.eclipse.ast.deploy.core.Deployment.<init>错误解决办法
我们使用myeclipse自动部署web项目时会设置服务器的位置,而部署的相关配置会存储在myeclipse工作目录下的“/.metadata/.plugins/org.eclipse.core.ru ...