这样的重构是否有必要呢?
在写数据查询的业务逻辑里,经常需要对查询条件进行合并;对于条件的构造是否有必要构造一个新的类把条件构造分离出来提供其条件的重用性呢?首先看下代码:
public IList<Balances> BalancesList(
[Bind(Convert = typeof(ToEnum<BalanceState>))]BalanceState? state, DateTime? from, DateTime? to)
{
Expression exp = new Expression();
if (state != null)
{
exp &= Balances.state == state;
}
else
{
exp &= Balances.state == new BalanceState[] { BalanceState.等待发工资, BalanceState.已发放工资, BalanceState.已发放虚拟货币 };
}
if (from != null)
exp &= Balances.timeCreated >= from;
else
exp &= Balances.timeCreated >= DateTime.Parse(DateTime.Now.ToShortDateString());
if (to != null)
exp &= Balances.timeCreated <= to;
return exp.List<Balances>(new Region(0, 1000), Balances.timeCreated.Desc);
}
这是一个非常典型的数据查询逻辑,根据参数来组件查询条件。在构造条件组合类前写一个接口好规范所有条件组合类。
public interface IExpressionBuilder
{
Expression Execute();
}
直下来对上面那个数据查询方法进行简单的重构,把条件分离出来:
public class TestBuiler : IExpressionBuilder
{
public BalanceState? State{get;set;}
public DateTime? From{get;set;}
public DateTime? To { get; set; }
public Expression Execute()
{
Expression exp = new Expression();
if (State != null)
{
exp &= Balances.state == State;
}
else
{
exp &= Balances.state == new BalanceState[] { BalanceState.等待发工资, BalanceState.已发放工资, BalanceState.已发放虚拟货币 };
}
if (From != null)
exp &= Balances.timeCreated >= From;
else
exp &= Balances.timeCreated >= DateTime.Parse(DateTime.Now.ToShortDateString());
if (To != null)
exp &= Balances.timeCreated <= To;
return exp;
}
}
分离之后的逻辑方法相对就简洁很多
public IList<Balances> BalancesList(
[Bind(Convert = typeof(ToEnum<BalanceState>))]BalanceState? state, DateTime? from, DateTime? to)
{
TestBuiler builder = new TestBuiler();
builder.State = state;
builder.From = from;
builder.To = to;
return builder.Execute().List<Balances>(new Region(0, 1000), Balances.timeCreated.Desc);
}
从代码简洁性来看似乎没有多大的改变,紧紧是提高了基于这条件复用性。在某些情况可以减少部分代码的编写:
public IList<Balances> BalancesList(
[Bind(Convert = typeof(ToEnum<BalanceState>))]BalanceState? state, DateTime? from, DateTime? to)
{
TestBuiler builder = new TestBuiler();
builder.State = state;
builder.From = from;
builder.To = to;
return (builder.Execute()& Balances.userid==loginer).List<Balances>(new Region(0, 1000), Balances.timeCreated.Desc);
}
对于重构的价值有时真的很难衡量,很多时候到了后期你会发现,原来的重构并没有带来什么得益。
如果重构能使代码变得更简洁和方便维护那重构是必须的,但从复用性上来对代码进行重构就要看情况来考虑一下,不是所有代码都有很高的复用价值。