我的课程实现方法如下:
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;
...
有一个更好的方法吗?这些代码让我感到不舒服.
编辑:
抱歉,不清楚的例子.我正在用Hibernate实现GenericDao类,真正的代码是这样的:
class GenericDaoImpl {
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 );
}
解决方法:
只是一个基本的建议,但你可以将其重构成类似“命令模式”的东西.此模式允许您将某些功能封装到实现单个方法的类中.该类可以被实例化并传递到另一个要执行的类,而执行器类不必知道或关心它正在做什么,它只需要调用execute().如果操作需要参数,则实现Command的类可以包括可以在构造函数中设置的字段/属性,也可以包含标准属性设置器.
创建一个这样的界面(我的Java生锈了,所以这可能不是100%有效的语法):
public interface Command
{
public void execute();
}
public class ActionOne implements Command
{
public void execute()
{
// do actionOne...
}
}
public class ActionTwo implements Command
{
public void execute()
{
// do actionTwo...
}
}
// etc. for more actions
然后创建执行操作的类,调用代码只需要传入正确的Command实现类.
public class Executor
{
public void executeCommand(Command command)
{
try
{
// Put any boilerplate code here (logging, auditing, etc.)
command.execute();
}
catch (Exception ex)
{
// Put general error handling code here. If you're just catching and rethrowing, consider not catching the Exception at this level. If it's a checked exception, add a throws clause to the method.
throw new CustomException();
}
}
}
标签:java,methods,refactoring,coding-style
来源: https://codeday.me/bug/20190730/1578842.html