OOP 避免不必要的重复调用
OOP avoid unnecessary repeated calls
所以我对 OOP class 设计有疑问。我读到我们应该“告诉,不要问”而不是使用“流量控制”的例外。但是在这种特殊情况下,我看到一些冗余代码正在执行!
假设 Person 有一个他将要参加的活动列表,并且必须强制他不能参加与他当前日程重叠的活动。所以我有以下 Java 代码
public class Person {
// this arraylist of events must not have overlapping events!
ArrayList<Events> eventsToAttend;
// checks if a person is free to attend a new event by viewing all events he is attending
public boolean canAttendEvent(Event newEvent) {
for(int i = 0; i < eventsToAttend.size(); i++) {
if (newEvent.isSameDayAndTime(eventsToAttend.get(i))) {
return false;
}
}
return true;
}
public void attendEvent(Event newEvent) {
// enforce the validity of the newEvent
if (!canAttendEvent(newEvent)) {
// throw exception and return
}
eventsToAttend.add(newEvent);
}
public static main(String[] args) {
// just an example usage!
Person person = somePersonWithEventsAlready;
Event event = new Event();
if (person.canAttendEvent(event)) {
// !!!
// Notice that canAttendEvent() is called twice!! how do you prevent this?
// !!!
person.attendEvent(event);
}
// Alternatively I could just try - catch around person.attendEvent(), but is that bad practise?
}
}
我用这种做事方式通常面临的问题是“canAttendEvent()”被调用了两次。然而,根据 OOP 设计模式,这是一种很好的做法吗?
做这样的事情有什么更好的方法吗?感谢您阅读本文。
try - catch in the main 是实现你试图避免的最好方法:调用函数 canAttendEvent
两次
所以我对 OOP class 设计有疑问。我读到我们应该“告诉,不要问”而不是使用“流量控制”的例外。但是在这种特殊情况下,我看到一些冗余代码正在执行!
假设 Person 有一个他将要参加的活动列表,并且必须强制他不能参加与他当前日程重叠的活动。所以我有以下 Java 代码
public class Person {
// this arraylist of events must not have overlapping events!
ArrayList<Events> eventsToAttend;
// checks if a person is free to attend a new event by viewing all events he is attending
public boolean canAttendEvent(Event newEvent) {
for(int i = 0; i < eventsToAttend.size(); i++) {
if (newEvent.isSameDayAndTime(eventsToAttend.get(i))) {
return false;
}
}
return true;
}
public void attendEvent(Event newEvent) {
// enforce the validity of the newEvent
if (!canAttendEvent(newEvent)) {
// throw exception and return
}
eventsToAttend.add(newEvent);
}
public static main(String[] args) {
// just an example usage!
Person person = somePersonWithEventsAlready;
Event event = new Event();
if (person.canAttendEvent(event)) {
// !!!
// Notice that canAttendEvent() is called twice!! how do you prevent this?
// !!!
person.attendEvent(event);
}
// Alternatively I could just try - catch around person.attendEvent(), but is that bad practise?
}
}
我用这种做事方式通常面临的问题是“canAttendEvent()”被调用了两次。然而,根据 OOP 设计模式,这是一种很好的做法吗?
做这样的事情有什么更好的方法吗?感谢您阅读本文。
try - catch in the main 是实现你试图避免的最好方法:调用函数 canAttendEvent
两次