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

我的课程实现方法如下:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值