我被要求维护一些不像我想要的那样遗留的代码,并且它充满了编译器指令,使其几乎不可读并且几乎可以维护。一个例子:
#if CONDITION_1
protected override void BeforeAdd(LogEntity entity)
#else
protected override void BeforeAdd(AbstractBusinessEntity entity)
#endif
{
#if CONDITON_1
entity.DateTimeInsert = DateTime.Now;
#else
((LogEntity) entity).DateTimeInsert = DateTime.Now;
#endif
base.BeforeAdd(entity);
}
using
指令更漂亮:
#if CONDITION_1
using CompanyName.Configuration;
#endif
#if CONDITION_2||CONDITION_1
using CompanyName.Data;
using CompanyName.Data.SqlBuilders;
#else
using CompanyName.Legacy.Database;
using CompanyName.Legacy.Database.SQLBuilders;
using CompanyName.Legacy.Database.SQLBuilders.parameterTypes;
#endif
我以为我会试一试,ConditionalAttribute
但在这种情况下那行不通
有什么办法可以摆脱这个编译器指令的噩梦吗?
代码是针对.NET 3.5
.
更新:
Oded 回答建议删除该BeforeAdd
方法周围的编译器指令,从而使其重载。不幸的是,这不起作用,因为这两种方法都应该覆盖一个AbstractBusiness
类,该类根据最终包含的程序集提供两种不同的实现:
protected virtual void BeforeAdd(TEntity entity) {}
或者
protected virtual void BeforeAdd(AbstractBusinessEntity entity) {}
该代码从公司过去一段时间创建的一组库中获取其依赖关系,并且从那时起一直在“升级”。他们现在拥有这组库的 4 个不同版本,具有冲突的命名空间和不同的实现。全部以使用(非常)旧版本的应用程序的“向后兼容性”的名义。
结论
我最终选择了@Oded 的答案,因为它作为一种通用方法(KISS等等)最有意义。不过在这种情况下我不能使用它;你在这里看到的只是冰山一角。如果它付钱给我,我不想亲吻这个代码。