首页 > 解决方案 > 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 设计模式,这是一种很好的做法吗?

做这样的事情有什么更好的方法?谢谢您阅读此篇。

标签: classoop

解决方案


try - 主要捕获是实现您试图避免的最佳方法:调用两次函数 canAttendEvent


推荐阅读