Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is return boolean for operation success / fail a good practice in Java?

Tags:

java

I have some function works with database. I have set a try/catch for error handling here, and display a message, It works fine.

Now the class calling this delete function need to know if there is a error or not. In my case : refresh the GUI if success, nothing to do if fail (as there already show up a message message dialog).

I come up a idea to return boolean in this function.

public static Boolean delete(int id){

    String id2 = Integer.toString(id);
    try {
        String sql = 
                "DELETE FROM toDoItem " +
                "WHERE id = ?;";
        String[] values = {id2};
        SQLiteConnection.start();
        SQLiteConnection.updateWithPara(sql, values);
    } catch (SQLException e) {
        Main.getGui().alert("Fail when doing delete in DataBase.");
        System.out.println("Exception : "+ e.getMessage());
        return false;
    }
    return true;
}

Don't know if this is good or bad, please tell.


EDIT :

Here is more detail for How do I use :

Let's say the code above is inside Class A, in Class B :

public boolean deleteItem(int id){
    int i = index.get(id);
    if(theList[i].delete()){  //<---- here is the function from Class A
        theList[i] = null;
        index.remove(id);
        retutn true;
    }
    retutn false; 
}

I need to pass the boolean in more than one class, I don't know if that can better through...

in Class C :

public void toDoList_deleteItem(){
    MyButton btn = (MyButton)source;
    int id = btn.getRefId();
    List toDoList = Main.getToDoList();
    if(toDoList.deleteItem(id)){  //<-------function in Class B
        Main.getGui().refresh();
    }
}

Edit 2 :

I have notice the question is somehow more likely asking "What should I handle a Exception at database Layer that affect to GUI Layer ?"... Something like that. Please correct me if the question title should be edit.

like image 854
user3662467 Avatar asked Feb 25 '15 14:02

user3662467


People also ask

Can we return boolean in Java?

Java Boolean equals() methodThe equals() method of Java Boolean class returns a Boolean value. It returns true if the argument is not null and is a Boolean object that represents the same Boolean value as this object, else it returns false.

Does boolean return true or false?

Writing a Boolean Method Writing a method that returns a boolean is just like writing any method with a return value, but ultimately we are just returning either true or false. For example, suppose we are writing code for a hybrid-electric car.

Can a function return a boolean result?

A Boolean function is like a built-in function except that it returns a value of true or false instead of number, string, or date. The result of a Boolean function cannot be printed; it can only be used as a condition. A Boolean function is composed of a function name followed by an operand in parentheses.


2 Answers

It looks like you are returning a boolean status to indicate that an exceptional condition had occurred. Generally, this is not a good practice, for two reasons:

  • It encourages an error-prone way of handling exceptions - it is very easy to miss a status check, leading to ignored errors
  • It limits your API's ability to report errors - a single pass/fail bit is not always sufficient, it may be desirable to pass more information about the error.

A better approach would be to define an application-specific exception, and use it in your API. This forces the users of your API to pay attention to exceptional situations that may happen, while letting you pass as much (or as little) additional information as you find necessary. At the same time, your code does not get polluted with if (!delete(id)) { /* handle error */ } code on each API call, shrinking your code base, and improving its readability.

Can you tell me more about "define an application-specific exception", or show some code example please?

Here is how I would do it:

public class DataAccessException extends Exception {
    ... // Define getters/setters for passing more info about the problem
}
...
public static void delete(int id) throws DataAccessException {
    try {
        ... // Do something that may lead to SQLException
    } catch (SQLException se) {
        // Do additional logging etc., then
        throw new DataAccessException("Error deleting "+id, se);
    }
}

Note: It is common to give custom exceptions four constructors mirroring the constructors of the Exception class to allow exception chaining. The constructors are described here.

like image 60
Sergey Kalinichenko Avatar answered Oct 17 '22 03:10

Sergey Kalinichenko


As long as you do not want the caller to know what happens, just that it fails (and that failing is part of its intended behavior) you should be fine.

That being said, I am noticing this: Main.getGui().alert("Fail when doing delete in DataBase.");.

It would seem that you are accessing the GUI layer from some other place. This might cause issues should you decide to multi-thread your application. Also, it is usually considered good practice to have your layers not intersect.

like image 4
npinti Avatar answered Oct 17 '22 03:10

npinti