Asier's thoughts

Blogging about software development

Command returns true/false for success/error

2 Comments

I’ve seen this kind of pattern usually when working with web services.

Imaging the following piece of code:

public bool RunCommand()
{

    // .. Some logic ..

    return true; // success

}

Basically we have a method in a class that executes some logic, if this is successful it returns a true, if not a false. At first you would say this make sense, right?

It kind of reminds me the days when I was learning C 🙂

But this is just over-complicating things. Any client of this method will have to add a check.


if(RunCommand()) {
  // everything good

  // Show user success message

} else {

  // error!

  // show user something went wrong

}

Why not just assume that the method is going to be execute successfully? If not just throw and exception! Then just handle that exception. Simple!

Just adding the true/false return for success/error is basically re-implementing exceptions. Well, it’s even worse. Exceptions are explicit, they mean that something went wrong, they even have a custom error message. A boolean just means that.. a boolean: true or false, it’s open to interpretations. When we get a false it could mean anything, no error message, no custom exception.

Also returning values from command methods is a bad practice. You should have two kind of methods: querys that return values but don’t change anything in your system and commands that change something but return nothing! This is known as CQS or Command and Query Separation.

2 thoughts on “Command returns true/false for success/error

  1. I agree that just returning true/false from an endpoint is not great, it doesn’t tell you much. But I’d only rely on exceptions if an error is really exceptional, otherwise my preference would be for a response object to be returned that includes all the relevant information about the results of the endpoint method.

    I hope you’re not advocating wrapping endpoint calls in try / catch blocks? I think that is one of the biggest anti-patterns I commonly come across 😉

  2. Yes, exceptions should be just for exceptional situations. Totally agree! Like if something errors unexpectedly in your application.

    I am not saying that you should throw exceptions to avoid returning true/false. I am just saying that you shouldn’t return anything if you method is a command. The client will just assume that everything is going to work as expected, no need to check for anything extra. Not need of an if-else (like in the example) or try-catches.

Leave a comment