I have classes with methods implemented as follow:
void methodOne() {
try {
getHelper().doActionOne();
} catch ( Exception ex ) {
throw new CustomException( ex );
}
}
void methodTwo() {
try {
getHelper().doActionTwo();
} catch ( Exception ex ) {
throw new CustomException( ex );
}
}
void methodThree() {
try {
getHelper().doActionThree();
} catch ( Exception ex ) {
throw new CustomException( ex );
}
}
void methodFour;
void methodFive;
...
Is there a better way to do this? These codes make me uncomfortable.
EDIT:
Sorry for unclear example. I’m implementing GenericDao class with Hibernate, the real code is something like this:
class GenericDaoImpl<T, PK> {
PK create( T object ) {
try {
getSession().save( object );
} catch( Exception ex ) {
throw new DataAccessLayerException( ex );// wrap any exception to my exception
}
}
T read( PK id ) {
try {
getSession().get( T.class, id );
} catch ( Exception ex ) {
throw new DataAccessLayerException( ex );
}
}
void update( T object );
void delete( T object );
}
Just a basic suggestion, but you could refactor this into something like a “Command Pattern.” This pattern allows you to encapsulate some functionality into a class that implements a single method. The class can be instantiated and passed into another class to be executed, and the executor class doesn’t have to know or care what it’s doing, it just needs to call execute(). If the actions require arguments, the classes that implement Command can include fields/properties that can be set in the constructor or by standard property setters.
Make an interface like this (my Java is rusty, so this may not be 100% valid syntax):
Then create the class that executes the action, and the calling code just needs to pass in the correct Command implementation class.