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,根据情况,“做两件事”?