加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 08:39:44 所属栏目:Java 来源:网络整理
导读:我的课程实现方法如下: void methodOne() { try { getHelper().doActionOne(); } catch ( Exception ex ) { throw new CustomException( ex ); }}void methodTwo() { try { getHelper().doActionTwo(); } catch ( Exception ex ) { throw new CustomExcepti
我的课程实现方法如下:

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

}

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读