class - OOP 避免不必要的重复调用
问题描述
所以我有一个关于 OOP 类设计的问题。我读过我们应该“告诉,不要问”,而不是使用“流控制”的例外。但是在这种特殊情况下,我看到正在执行一些冗余代码!
让我们假设 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 - 主要捕获是实现您试图避免的最佳方法:调用两次函数 canAttendEvent
推荐阅读
- ios - 如何修复 Xcode 中的“固定宽度约束可能导致剪辑”警告?
- hive - HIVE 中的空桶
- c# - 如何将标签页的上下文绑定到 Xamarin 的 CS 代码中的其他页面?
- r - R:在 plm 中过滤数据
- flutter - 如何将图像处理路由转换添加到 Flutter
- paypal - 捕获订阅智能按钮与 SDK 集成的错误 - Sandbox 和 Live
- flutter - Flutter - 显示和跟踪动态问题答案的最佳方式
- python - Google Cloud Speech to Text 准确性问题
- wpf - 如何在 XAML 中获取 DynamicResource 的属性?
- laravel - laravel 多条记录到一条记录....但是如何?