我们可以重构这些方法吗?

Gen*_*zer 3 java methods refactoring coding-style

我的课程实现方法如下:

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;
...
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?这些代码让我感到不舒服.

编辑: 抱歉不清楚的例子.我正在用Hibernate实现GenericDao类,真正的代码是这样的:

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 );

}
Run Code Online (Sandbox Code Playgroud)

And*_*ite 6

只是一个基本的建议,但你可以将其重构成类似"命令模式"的东西.此模式允许您将某些功能封装到实现单个方法的类中.该类可以被实例化并传递到另一个要执行的类,而执行器类不必知道或关心它正在做什么,它只需要调用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
Run Code Online (Sandbox Code Playgroud)

然后创建执行操作的类,调用代码只需要传入正确的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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你为什么要关心增加课程数量?10个小型,专注的课程比1个大课程更好,必须做10件不同的事情.除非你绝对必须走那条路,否则我也会避开反思.使用一些基本的接口和类可以更简洁地表达您的代码. (2认同)