在阅读有关OOP缺点的严厉文章以支持其他一些范例的过程中,我遇到了一个例子,我发现它没有太多的缺点。
我想对作者的论点持开放态度,尽管我从理论上可以理解他们的观点,但尤其是一个例子,我很难想象如何用FP语言更好地实现它。
来自:http : //www.smashcompany.com/technology/object-oriented-programming-is-an-expensive-disaster-which-must-end
// Consider the case where “SimpleProductManager” is a child of
// “ProductManager”:
public class SimpleProductManager implements ProductManager {
private List products;
public List getProducts() {
return products;
}
public void increasePrice(int percentage) {
if (products != null) {
for (Product product : products) {
double newPrice = product.getPrice().doubleValue() *
(100 + percentage)/100;
product.setPrice(newPrice);
}
}
}
public void setProducts(List products) {
this.products = products;
}
}
// There are 3 behaviors here:
getProducts()
increasePrice()
setProducts()
// Is there any rational reason why these 3 behaviors should be linked to
// the fact that in my data hierarchy I want “SimpleProductManager” to be
// a child of “ProductManager”? I can not think of any. I do not want the
// behavior of my code linked together with my definition of my data-type
// hierarchy, and yet in OOP I have no choice: all methods must go inside
// of a class, and the class declaration is also where I declare my
// data-type hierarchy:
public class SimpleProductManager implements ProductManager
// This is a disaster.
请注意,我并不是要对作者的论点提出反驳,即“这3种行为应与数据层次结构链接的任何合理理由吗?”。
我要特别问的是,如何用FP语言对这个示例进行建模/编程(实际代码,而不是理论上的代码)?