-1
\$\begingroup\$

I have an event handling code, something like

void handleEventType1(EventType1 event1) {
    if (someCheck()){
        function1(event);
        postCheckTrue();
    } else {
        function2(event);
        postCheckFalse();
    }
}

void handleEventType2(EventType2 event2) {
    if (someCheck()){
        function3(event);
        postCheckTrue();
    } else {
        function4(event);
        postCheckFalse();
    }
}

I was hoping, I can do something like

handleEvent(event1, Handler::function1, Handler::function2);
handleEvent(event2, Handler::function3, Handler::function4);

that will somehow call functions (1 or 2) or (3 or 4), but I'm somehow not able to solve it to my satisfaction.

\$\endgroup\$
3

1 Answer 1

1
\$\begingroup\$

First, lets use inheritance. We will inherit the specific event types from the event interface.

interface Event {}

class EventType1 implements Event{}

class EventType2 implements Event{}

Secondly, lets define the type of functions that we will call in the handleEvent() method. In this case it is Consumer<Event>

Now our handleEvent() function will look like this

void handleEvent(Event event, 
                 Consumer<Event> option1, 
                 Consumer<Event> option2) {
   if (someCheck()) {
      option1.accept(event);
   } else {
       option2.accept(event);
   }
}

Now we can call this function and pass instance of event interface and two lambdas or method references

Handler.handleEvent(new EventType1(),
    event -> {
       //do something
    }, 
    event -> {
       //do something else;
    });
}
\$\endgroup\$
4
  • \$\begingroup\$ Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer. \$\endgroup\$ Commented Feb 11, 2021 at 13:08
  • 1
    \$\begingroup\$ @TobySpeight I may have misunderstood something, but the author asked a question that I answered. He asked how to do what he wants, I showed how it can be done. If the question itself or my answer is irrelevant for this site, then you need to close it and forget about it. Sorry, maybe I should read the rules carefully. However, I provided assistance to the author. \$\endgroup\$
    – chptr-one
    Commented Feb 11, 2021 at 13:28
  • \$\begingroup\$ The question is off-topic (psuedo/hypothetical/example), so you would have been better leaving this one unanswered. \$\endgroup\$ Commented Feb 11, 2021 at 15:54
  • \$\begingroup\$ Thank you, I understood \$\endgroup\$
    – chptr-one
    Commented Feb 11, 2021 at 16:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.