tags:

views:

73

answers:

4

Often we have to use some of the methods which don't return anything useful. If I invoke saveOrUpdate() in hibernate , I don't know whether it has been performed successfully . I use a implementation like this (which I think is a bit awkward) :

public int saveOrUpdateA(A a) {
        int resultFlag = 0 ;
    try {
        // obtaining session is omitted
        session.saveOrUpdate(a);
        resultFlag = 1 ;    
    } catch (Exception e) {
        e.printStackTrace();
    } 
    return resultFlag ;
}

How do you do this ? Any good idea ?

Exception should be caught in DAO layer or Service Layer ?

+2  A: 

Why you need to return anything here? If it happens to be unsuccessful, exception is there to tell you about that.

In case your calling method need something, you can just do it like this.

public void saveOrUpdateA(A a) throws Exception{
    // obtaining session is omitted
    session.saveOrUpdate(a);
}
Adeel Ansari
Because sometimes , this method is called via RPC. I can catch exception in java , but can't in actionscript or javascript , I need a indicator to show this method has completed successfully to the front end.
ZZcat
If you know what you are doing, then your version is fine. Go with that.
Adeel Ansari
A: 

The issue with the code is that you do not bubble up the exception. The rule we tend to follow is: If there is an exception, throw that up. If there is no exception, then it has completed successfully.

Kapil Viren Ahuja
A: 

The lack of an exception is a success indicator.

If you truly want the indicator, I'd go for a boolean return.

public boolean saveOrUpdateA(A a) {
  boolean success = false;   
  try {
    // obtaining session is omitted
    session.saveOrUpdate(a);
    success = true;

  } catch (Exception e) {
    // log it and swallow exception
    // calling code has to be sure to check on success flag; 
    // otherwise it has no idea something went terribly wrong
  } 
  return success ;
}

Your application will still have to check the return status and handle it appropriately, which is not a whole lot different than handling the potential exception thrown by session.saveOrUpdate().

public void saveOrUpdateA(A a) throws Exception {

  try {
    // obtaining session is omitted
    session.saveOrUpdate(a);
  } catch (Exception e) {
    // log it and rethrow; let calling code figure how to handle
    throw e;
  } 
}
marklai
A: 

I dont think you should wrap this method at all. Just use it keeping in mind that you will have an exception in case of error.

Artic