简体   繁体   English

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

[英]Can we refactor these methods?

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: 我正在用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 );

}

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(). 该类可以被实例化并传递到另一个要执行的类,而执行器类不必知道或关心它正在做什么,它只需要调用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. 如果操作需要参数,则实现Command的类可以包括可以在构造函数中设置的字段/属性,也可以包含标准属性设置器。

Make an interface like this (my Java is rusty, so this may not be 100% valid syntax): 创建一个这样的界面(我的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

Then create the class that executes the action, and the calling code just needs to pass in the correct Command implementation class. 然后创建执行操作的类,调用代码只需要传入正确的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();
        }
    }
}

Yes, you can always refactor code. 是的,你总是可以重构代码。 The only issue is whether you're going to refactor to make it better or worse. 唯一的问题是你是否要重构以使其变得更好或更糟。 The hints that this code is odd, is a good hint that it can be made much better. 这段代码奇怪的提示是一个很好的提示,它可以做得更好。

This looks like a good candidate for polymorphisim. 这似乎是多态性的良好候选者。 Instead of five different methods, try five different classes with one shared method. 使用一个共享方法尝试五个不同的类,而不是五种不同的方法。 The interface will tie it all together. 界面将它们连接在一起。

public interface DoIt {
  public void doIt();
}

public class One implements DoIt {
  public void doIt() {
    // code which was previously in getHelper.doActionOne();
  }
}

public class Two implements DoIt {
  public void doIt() {
    // code which was previously in getHelper.doActionTwo();
  }
}

...

public class Five implements DoIt {
  public void doIt() {
    // code which was previously in getHelper.doActionFive();
  }
}

Now the only thing is to create the right class for the situation, and call its doIt() method. 现在唯一的事情是为情境创建正确的类,并调用其doIt()方法。

This facility is provided by the Spring Framework along with many others. 此工具由Spring Framework以及许多其他工具提供。 First, it has a specific HibernateTemplate which maps each Hibernate-specific exception to an unchecked, related Spring exception. 首先,它有一个特定的HibernateTemplate ,它将每个特定于Hibernate的异常映射到未经检查的相关Spring异常。 Second, it provides an AOP service to translate exceptions at the method level so you can specify the mappings once and apply them uniformly across multiple services. 其次,它提供了一个AOP服务来在方法级别转换异常,因此您可以指定一次映射并在多个服务之间统一应用它们。

While I wouldn't use Spring for just this one feature, it has huge benefits for building applications and I have continued using it for many years. 虽然我不会将Spring用于这一功能,但它对构建应用程序有很大的好处,而且我已经使用它多年了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM