常识# 统一访问原则 (uniform acces principle)
The Uniform Access Principle was put forth by Bertrand Meyer. It states "All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation." This principle applies generally to object-oriented programming languages. In simpler form, it states that there should be no difference between working with an attribute, precomputed property, or method/query.
上文是wiki里对统一访问原则的描述,用《scala编程》一书中的说法就是“客户代码不应由属性是通过字段实现还是方法实现而受到影响”。这句话到底什么意思呢?代码说话
elem.width
上面这种表达方式有两种实现形式,当改成任意的另外一种时,都不会改变当前代码的用法。(当然对某些语言是行不通的)
class Elem{ val width = 1 }
class Elem{ def width:Int = 1 }
另附wiki上用python语言写的例子
egg = Egg( 4, "White") egg.color = "Green" print egg.weight, egg.color, egg.quack() # prints: 4 Green quack
字段实现
class Egg(object): def __init__(self, weight, color): self.weight = weight self.color = color def quack(self): return "quack"
方法实现
class Egg(object): def __init__(self, weight, color): self.__weight = toGrams(weight) self.__color = toRGB(color) def setColor(self, colorname): self.__color = toRGB(colorname) def getColor(self): return toColorName(self.__color) color = property(getColor, setColor, doc="Color of the Egg") def setWeight(self, weightOz); self.__weight = 29.3*weightOz def getWeight(self): return self.__weight/29.3; weight = property(setWeight, getWeight, doc="Weight in Ounces") def quack(self): return "quack"