Home > OS >  OOP avoid unnecessary repeated calls
OOP avoid unnecessary repeated calls

Time:10-20

so I have a question on OOP class design. I have read that we should "Tell, don't ask" and not use Exceptions for "Flow control". However in this particular case I see some redundant code being executed!

Lets assume Person have a list of events that he will be attending, and it must be enforced that he cannot attend an event that overlaps with his current schedule. So I have the following Java code

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?
    }
}

The issue I am facing in general with this way of doing things, is that "canAttendEvent()" is being called twice. However it is good practice according to OOP design patterns?

What would be a better way to do something like this? Thank you for reading this.

CodePudding user response:

try - catch in the main is the best way to achieve what you are trying to avoid: call twice the function canAttendEvent

  • Related