Home > Mobile >  How to return object A or object B from a method
How to return object A or object B from a method

Time:09-22

I have a method that consumes a REST API and can receive either an OK response object (which I'll call MyObject) or an error object (MyError) as a response. My method at this point will have to return either MyObject or MyError, how should I handle it?

My idea is to create a HandleResponse object that contains both MyObject and MyError and return this object. Then in the calling class I check to see which of the two is null and therefore work on the other object. Is it correct or is there a more correct management?

CodePudding user response:

The way that you propose is ok, in fact, something similar is the way that functional programming uses to handle this kind of situation. In vavr library (https://www.vavr.io/) a library to add functional programming features to java, there is a monad called Either that does exactly de same.

It is an object with two generic types Either<E, T> where E is the type of the error object and T is the type for a successful answer. And you can apply different transformations to these objects on both parts (the error or the success) to apply the logic needed in either case. If you are interested in how to apply this you can visit https://www.baeldung.com/vavr-either.

Another option if the error in the API call means also an error in your own application, is to throw an exception when the API returns an error and handle it properly so the method only return the success case

  • Related