Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good practise of executing some operation and returning boolean value indicating successfulness of that in Java?

Tags:

java

methods

What I mean is, I read that a good way to write a method is by being guided with a rule: one method should do only one task. And if I have different sequential operations, then I need to split the method into several ones. It should make code cleaner and simple, self-explaining method names. But if I want to implement method which should do something and then return boolean value – true is success, false if failed. For example, assume we have setter called setObjectValue(). [again, it is just an example].

Question: Would it be good to use this name and return boolean values, or should it be something as: isSuccessfullsetObjectValue(), setObjectValueAndCheckIsOk(), or should there be two methods or what? Because name "setObjectValue()" doesn't tell you that the method is doing something besides setting value.

like image 472
LaRRy Avatar asked Dec 11 '22 17:12

LaRRy


1 Answers

Unless there's a good reason, I would normally use Exceptions to indicate this. This has two benefits:

  1. You follow the convention of 1 method - 1 idea
  2. You force yourself (if the Exception is checked) to handle the failure case. If you return a boolean, then the code could easily ignore this case.

If you do something like this:

try{

  setObjectValue("foo")
} catch(SomeKindOfException e){
  //handle
} 

Then you get the further benefit of it reading like English: "try to set the object value, but if you can't then handle it by ... "

like image 156
James Kingsbery Avatar answered May 20 '23 23:05

James Kingsbery