【发布时间】:2014-06-23 12:04:40
【问题描述】:
我有一个基于规则实现逻辑的类方法。结构如下:
sub process {
# declarations etc
# other code
# core logic:
if($conditions->{size} == $item_size) {
#do something here as it matches the rule based on size
return $result;
}
if($conditions->{area} == $item_area_dispatch) {
#do something that matches the area criteria
return $result;
}
if($conditions->{country} == $item_country) {
#do something that matches the country criteria
return $result;
}
}
基本上有一系列 if/else 语句来验证某些条件是否适用并执行相应的逻辑。
从上到下的 if/else 系列是适用的最通用的最具体的标准
如果没有适用的规则,则什么也不做。
这可行,但顺序取决于 if/else,每当我想添加新规则时,我都会在“正确”位置添加新的 if/else。
所以这不是理想的解决方案。我想知道为此重构我的代码的最佳方法是什么?
【问题讨论】:
-
这可能更适合Programmers
-
哎呀?显而易见的选择是将规则存储为对象。
标签: algorithm oop design-patterns data-structures