【发布时间】:2014-04-06 21:34:00
【问题描述】:
public class FooList {
public boolean add(Foo item) {
int index = indexOf(item.getKey());
if (index == -1) {
list.add(item);
}
return index == -1;
}
}
由于这增加了一个项目并且返回一个成功值,是否违反了单一职责原则?如果有,有关系吗?
另一种方法是抛出异常:
public class FooList {
public boolean add(Foo item) throws FooAlreadyExistsException {
int index = indexOf(item.getKey());
if (index == -1) {
list.add(item);
} else {
throw new FooAlreadyExistsException();
}
}
}
但这是否也违反了单一职责原则?该方法似乎有两个任务:如果该项目不存在,则添加它;否则,抛出异常。
额外问题:可以返回 null 的方法是否违反了单一职责原则?这是一个例子:
public class FooList {
public Foo getFoo(String key) {
int index = indexOf(key);
return (index == -1) ? null : list.get(index);
}
}
是返回 Foo 还是 null,取决于具体情况,“做两件事”?
【问题讨论】:
标签: oop single-responsibility-principle