3

I have a ConstraintsResolver class which resolves a queue of Constraints. This is done when a ConstraintsResolver object calls meetConstraint() on a Constraint one.

Most of meetConstraint() implementations will return immediately, so I could just return a boolean, but there is at least one that will block, which means I need to implement the callback pattern.

Do I have an option to combine both solutions or I have to implement only the callback pattern?

6
  • Welcome: this question is about design so you're on the right place !
    – Christophe
    Nov 19, 2018 at 20:50
  • Just to be sure that I understood well: your constraint resolver check to see if constraints are met, but for some constraints, it's too long, so a callback calls the constraint resolver if the constraint is met. So you have two kind of constraints: immediate and asynchronous, is it ?
    – Christophe
    Nov 19, 2018 at 21:03
  • Exactly! @Christophe
    – Themelis
    Nov 19, 2018 at 21:04
  • 4
    Why can't you always callback and have the immediately returning ones simply immediately trigger the callback?
    – Telastyn
    Nov 20, 2018 at 2:00
  • @Telastyn that is my plan, but if, for example, there are 100 cases that the method returns immediately and just one case when it blocks I thought if there was another solution to that.
    – Themelis
    Nov 20, 2018 at 9:21

2 Answers 2

4

It looks like you have a code with both synchronous and asynchronous nature. If you need to combine it in a clean/organized way, you can use reactive programming paradigm. Check out the Observable pattern.

You might also achieve your goals with simpler tools like promises. (In Java standard library, they are called Future and there’s also a related CompletableFuture framework).

1
  • I upvoted this answer though I am not sure if it's a solution whether a suggestion.
    – Themelis
    Nov 20, 2018 at 9:49
1

It seems to me you don't need the callback pattern here. You just need threads.

Sync answers seem mandatory, since you will continue the process after receiving the response.

But I fail to see what would an async answer would improve. Anyway, you will be waiting for a response. Anyway, you are blocked. If such blocking stops other tasks, just use threads.

Callbacks are not used to unblock processes (for that, synchronous answers are just enough). They are just used when an interactor could send data by surprise. For example, I give a task to an employee and I give him my phone number, so he can "call me back" if something bad happens. If not, I don't need to know it.

If I am waiting for his call to continue my process, that's not a "back call", but just the synchronous answer I was waiting for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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