Returning status messages

Vengeancos :

There are methods in classes like "addSomething()". This can be successful or not successful. The status of the success can therefore be displayed with a boolean return value. But sometimes a method invocation can fail because of several reasons. "false" displays that, but only in a general manner. Sometimes the programmer wants to know the reason, why something failed. Is it, for this purpose, useful to provide an own report class that offers functionality like that?

public class Report {
    private final boolean success;
    private final String message;

    public Report(boolean success) {
        this.success = success;
        this.message = "empty message";

    }

    public Report(boolean success, String message) {
        this(success);
        this.message = message;
    }

    public boolean wasSuccessful() {
        return success;
    }

    public String getMessage() {
        return message;
    }
}

Then you can decide if you want to get a general success report with "wasSuccessful()" or if you also want to log the exact reason with "getMessage()".

GhostCat salutes Monica C. :

Is it, for this purpose, useful to provide an own report class that offers functionality like that?

"Usefulness" is subjective. If the above is what nicely solves your specific problem, then of course it is useful, and might be a good approach.

But in general, failure in Java is typically modelled by using exceptions of some wort.

Therefore, in many situations you simply go with void methods. As: the method just returning means: "all fine". Otherwise, if there was some problem, the method throws an exception at you.

Now, if on the other hand, you have situations where a method might pass or fail, and both outcomes are fully okay (for example if some method checks whether an optional parameter is present), then sure: your approach can be useful. You simply allow to add new Report objects for each method invocation that matters to you. And then whoever calls the method can create Report objects and add them to some context-specific ReportCollector.

But note: the real issue in my eyes: when you think about programmatically collecting (and using) such "progress" information, then message strings quickly turn into a problem. There is a good reason why people sometimes use numerical error ids: to enable programmatic handling of such situations. Strings only carry meaning for humans who read them.

Your code can't do much with strings. Remember: doing a contains("this") or contains("that") to determine how to react to error (messages) later on, that is a real anti pattern!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=155369&siteId=1