Effective Java 英文 第二版 读书笔记 Item 14:In public classes,use accessor methods,not public fields...

本文探讨了在面向对象编程中,直接暴露类的内部字段与通过提供get和set方法来访问这些字段之间的区别。重点分析了这两种方法对代码灵活性及可维护性的影响。

本章主要分析 公开属性与私有属性提供公开get、set方法两种方式对比

 

// Degenerate classes like this should not be public!
class Point {
public double x;
public double y;
}

 

 

// Public class with exposed immutable fields - questionable
public final class Time {
private static final int HOURS_PER_DAY = 24;
private static final int MINUTES_PER_HOUR = 60;
public final int hour;
public final int minute;
public Time(int hour, int minute) {
if (hour < 0 || hour >= HOURS_PER_DAY)
throw new IllegalArgumentException("Hour: " + hour);
if (minute < 0 || minute >= MINUTES_PER_HOUR)
throw new IllegalArgumentException("Min: " + minute);
this.hour = hour;
this.minute = minute;
}
... // Remainder omitted
}

Certainly, the hard-liners are correct when it comes to public classes:

if a class is accessible outside its package, provide accessor methods, to preserve the

flexibility to change the class’s internal representation. If a public class exposes its
data fields, all hope of changing its representation is lost, as client code can be distributed
far and wide.

如果我们直接公开域,我们将无法对属性进行限制,这样会导致,在调用该处的代码都要添加上限制,而修改次数随着调用的次数而增加,

如果我们提供get,set方法,就能容易的在set方法内对传入参数进行限制。

转载于:https://www.cnblogs.com/linkarl/p/5663952.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值