mardi 2 mai 2017

Closing connection in Customer exception class ? What do you think?

try (PreparedStatement ps = connection.ps ("some prepared query" )) {
        ps .setInt(1, var1);
        ps .setInt(2, var2); // let say I failed here 
        ...
        ....
    } catch (SQLException e) {
        try {
            throw new DaoException(e);
        } finally {
            tryCloseConnection(enableConnectionClose);
        }
    }

The piece of code above provides a conventianal approach of closing connection during exception, where enableConnectionClose some boolean flag which regulated necessaty of connection closing, and where "connection" is a private data member of a some Class that uses jdbc.

try (PreparedStatement ps = connection.ps ("some prepared query" )) {
        ps .setInt(1, var1);
        ps .setInt(2, var2); // let say I failed here 
        ...
        ....
    } catch (SQLException e) {
            throw new DaoException(connection, enableConnectionClose, e)
                                    .setMessage("method failed").build();
    }


But there're two problems: 1) readability - finally block inside -catch block difficult to comprehend ; 2) It is easy to forget about to implement finally block ( by analogy with try with resources block ) ; - solution -> What do you think about putting closing private data member connection into DaoException which is design through Builder design pattern so it gives compile error if we will forget about connection instance ? Moreover, I believe it will be a good idea to make a interface and declare all methods of a Dao class add extention to methods signiture with DaoException.

Aucun commentaire:

Enregistrer un commentaire