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的更多相关文章

  1. 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 ...

  2. 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 ...

  3. Core Java Volume I — 4.7. Packages

    4.7. PackagesJava allows you to group classes in a collection called a package. Packages are conveni ...

  4. 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 ...

  5. Core Java Volume I — 3.8. Control Flow

    3.8. Control FlowJava, like any programming language, supports both conditional statements and loops ...

  6. Core Java Volume I — 4.6. Object Construction

    4.6. Object ConstructionYou have seen how to write simple constructors that define the initial state ...

  7. 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 ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. hadoop工作流引擎之azkaban [转]

    介绍 Azkaban是twitter出的一个任务调度系统,操作比Oozie要简单很多而且非常直观,提供的功能比较简单.Azkaban以Flow为执行单元进行定时调度,Flow就是预定义好的由一个或多个 ...

  2. javascript密码强度验证!

    //CharMode函数 //测试某个字符是属于哪一类 function CharMode(iN) { if (iN>=48 && iN <=57) //数字 return ...

  3. bzoj 1818: [Cqoi2010]内部白点

    #include<cstdio> #include<iostream> #include<algorithm> using namespace std; struc ...

  4. treap 1296 营业额统计

    有一个点答案错误,求大神指教 #include<cstdio>#include<iostream>#include<cstdlib>#include<ctim ...

  5. Windows8 10设置程序为 系统默认浏览器

    从win8 开始,MS修改了文件和协议的关联方式,普通的注册表修改是无效的. 必须使用组策略(group policy )对象GP才行. http://blogs.technet.com/b/mrml ...

  6. Linux的三种特殊权限

    1.Suid Set位权限 ●对文件以文件的拥有者身份执行文件 ●对目录无影响 权限设置: ●suid=u+s 2.Sgid Set位权限 ●对文件以文件的组身份执行文件 ●对目录在目录中最新创建的文 ...

  7. 结构化视角看django

    分析一个软件的整体框架,我认为应该从静态和动态两方面入手.静态方面,看它有哪些用例,即有哪些功能模块:动态方面,看主流程如何连接上这些模块 静态方面:分View.Model.Template.Sess ...

  8. 常用控件产品官方文档/手册/API列表 c#控件文档API列表 asp.net控件产品技术文档中文版

    .netCHARTING报表图表控件 文档帮助手册Ab3d.PowerToys 文档帮助手册Ab3d.Reader3ds 文档帮助手册ABViewer 文档帮助手册 (工程图纸文档管理系统)Activ ...

  9. python遍历文件夹下的文件

    在读文件的时候往往需要遍历文件夹,python的os.path包含了很多文件.文件夹操作的方法.下面列出: os.path.abspath(path) #返回绝对路径 os.path.basename ...

  10. 迭代器(Iterator)模式

    转自:http://blog.csdn.net/lilu_leo/article/details/7609496 概述      迭代器(Iterator)模式,又叫做游标(Cursor)模式.GOF ...