dongshiqin1352 2013-08-15 14:33
浏览 19
已采纳

如何最好地使用OOP原则来处理具有10-15 +匹配标准的情况,这些标准都需要通过?

I have a class that takes in lines of text and uses about 15 different "criteria" (individual preg_match statements) to check if the line should qualify to be saved in an array.

How does one best handle such a situation with clean, maintainable code?

Initially I had a crazy long if statement which had all the criteria, for example:

if (
    preg_match($criteria1,$line) &&
    preg_match($criteria2, $line) &&
    ...
    ...
    ...
    preg_match($criteriaN,$line)
) {
    //do something, e.g. save the line to an array.
}

I've since put each preg_match statement into a different function within a separate class and call each function in a row, checking if it's true... But now I have 15 separate functions that are only subtly different from each other and it still doesn't feel like I'm writing good code. How is it best to handle this situation?

  • 写回答

3条回答 默认 最新

  • doujuncuo9339 2013-08-15 14:56
    关注

    Well, if you want to keep things object oriented, you could use a class like this...

    class Validator{
    
        /* Any criteria needing to be met must exist in this array */
        public static $criterias = array($criteria1,
                                          $criteria2,
                                          ... ,
                                          $criteriaN);
    
    
    
        public static function validate($line){
    
            /* Make sure this line meets each criteria */
            foreach(Validator::$criterias as $criteria){
    
                  if(!preg_match($criteria, $line))
                       return false;
            }
    
            return true;
        }
    

    It makes sense to have the methods and properties static because they are unique to no instance. Then you can simply check to see if a line meets the criteria by calling

    Validator::validate($line)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog