如何在代码分支变得过于混乱之前处理它



所以我的实际问题是,如果我有多个if elseif案例在寻找一个正确的匹配,但所有案例都有很多相同的代码,但有些案例有点不同,哪种方式最有效?

按角色排序和重复代码?

$user_role = 2;
if ($user_role === 1) {
  codeMethod1();
  codeMethod2();
} elseif ($user_role === 2) {
  codeMethod1();
  codeMethod2();
  codeMethod3();
} elseif ($user_role === 3) {
  codeMethod2();
  codeMethod3();
}

或者,按代码/进程排序并生成大量if语句?

$user_role = 2;
if ($user_role === 1 || 2) {
  codeMethod1();
} 
codeMethod2();
if ($user_role === 2 || 3) {
  codeMethod3();
}

我意识到,对一些人来说,这是一个愚蠢的问题,因为他们已经想清楚了。我是编程新手,我只想从一开始就做好它。我不想破坏我的程序,也不想为那些可能需要修复我的代码的人破坏它。

更新

问题澄清场景:

当用户进入我的网站时,我会将它们识别为5个类别中的1个。一些用户会得到相同的待遇,但有一些变化,而另一些用户则会得到截然不同的待遇。大约有20种不同的方法,有些用户会全部使用,有些用户则很少使用。

因此,列出每个类别需要的方法是更好和/或更有效的,即使很多代码看起来都是一样的。

示例:

$user_role = getCurrentUserRole();
switch ($user_role) {
  case 1:
    (uses method1() to method10())
    break;
  case 2:
    (uses method5() to method15())
    break;
  case 3:
    (uses method10() to method20())
    break
  case 4:
    (uses method1() to method20())
    break
  case 5:
    method1();
    method4();
    method8();
    method15();
    method20();
}

或者,列出每个方法并使用if语句来查看$user_role是否需要它更好吗?

示例:

$user_role = getCurrentUserRole();
switch ($user_role) {
  // Check for method1
  case (1 || 4) {
    method1();
  }
  // Check for method2
  case (1 || 4) {
    method2();
  }
  ... skip ...
  // Check for method5
  case (1 || 2 || 4) {
    method5();
  }
  .. Continue checking role permission for each method ..
}

请忽略我糟糕的英语,如果你不明白我的问题,请告诉我详细说明。

将函数分组到您的用户角色函数下,并简单地为特定的用户角色调用这些函数。

$user_role = 2;
switch($user_role){
    case 1:
        userRole1(); 
        break;
    case 2:
       userRole2();
       break;
    case 3:
      userRole3();
      break;
}
function userRole1(){
        codeMethod1();
        codeMethod2();
}
function userRole2(){
       codeMethod1();
       codeMethod2();
       codeMethod3();
}
function userRole3(){
      codeMethod2();
      codeMethod3(); 
}

我会使用角色→特征关联。

但在您的情况下,通过一个简单的映射将角色编号与可能的功能关联起来可能更合适:

$role_funcs = [
    "method1" => [ 1, 2,        ],
    "method2" => [ 1, 2, 3,    5],
    "method3" => [       3,    5],
    "method4" => [ 1,    3, 4,  ],
    // …
    "method9" => [    2, 3,    5],
];

它提供了一个紧凑的概述,说明哪些功能块将为哪个用户类运行。而且它的使用非常琐碎:

foreach ($role_funcs as $callback=>$for_roles) {
    if (in_array($user_role, $for_roles)) {
        $callback();
    }
}

现在,只有当你真的把它们都作为函数可用时,这才是有效的。(否则,您甚至可能想要更高的目标,将用户和角色封装到对象中,以隐式地利用其中一种调度器模式。(

最新更新