Effective Java 英文 第二版 读书笔记 Item 14:In public classes,use accessor methods,not public fields...
本章主要分析 公開屬性與私有屬性提供公開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.
如果我們直接公開域,我們將無法對屬性進(jìn)行限制,這樣會(huì)導(dǎo)致,在調(diào)用該處的代碼都要添加上限制,而修改次數(shù)隨著調(diào)用的次數(shù)而增加,
如果我們提供get,set方法,就能容易的在set方法內(nèi)對傳入?yún)?shù)進(jìn)行限制。
轉(zhuǎn)載于:https://www.cnblogs.com/linkarl/p/5663952.html
總結(jié)
以上是生活随笔為你收集整理的Effective Java 英文 第二版 读书笔记 Item 14:In public classes,use accessor methods,not public fields...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 招行魔漫相机联名卡怎么样?独一无二的专属
- 下一篇: 交行优逸白金卡一直在审核中怎么回事?审核