这是一个糟糕的模式吗?(在 for/foreach 循环内切换) [英] Is this a bad pattern? (Switch inside for/foreach loop)

查看:29
本文介绍了这是一个糟糕的模式吗?(在 for/foreach 循环内切换)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己在编写代码,例如:

foreach($array as $key => $value) {开关($key){案例'东西':做某事($价值);休息;案例'别的东西':doSomethingElse($value);休息;}}

有没有更好的方法来解决这个问题?对我来说似乎很脏,但我可能只是想多了.

我能想到的唯一另一种选择是每个键的 if 语句,这似乎并没有更好.IE.:

if($array[0] == 'something') {doSomething($array[0]);}if($array[1] == '别的东西') {doSomethingElse($array[1]);}

(或类似的东西)

如果需要,我可以发布确切的代码,但这是发生的事情的大纲.请批评一下,但请记住,我在这里寻求帮助.因此,如果我做错了什么,请指出.

解决方案

将你的函数映射到字典/关联数组中的键是这种情况的常用方法(正如@jldupont 提到的)——不仅在 PHP 中,而且在许多具有关联数组的动态语言.例如,Python 和 Lua 甚至没有 switch 语句——这几乎是模拟 switch 的唯一方法.

考虑这种方法:

<代码>

输出:

<前>再见.你好.

当您只有两个不同的值时,这是一种矫枉过正的方法,但随着您必须涵盖的情况数量增加,这显然成为一种更有价值的方法.

I find myself writing code such as:

foreach($array as $key => $value) {
    switch($key) {
        case 'something':
            doSomething($value);
            break;
        case 'somethingelse':
            doSomethingElse($value);
            break;
    }
}

Is there a better way to go about this? Seems dirty to me, but I might just be over thinking it.

The only other alternative that I can think of is an if statement for each key, which doesn't seem any better. I.e. :

if($array[0] == 'something') {
    doSomething($array[0]);
}
if($array[1] == 'somethingelse') {
    doSomethingElse($array[1]);
}

(or something like that)

I can post exact code if needed, but this is the general outline of what happens. Please critique away, but remember that I'm looking for help here. So if I'm doing something egregiously wrong, then point it out.

解决方案

Mapping your functions to keys in a dictionary/associative array is a common approach for this situation (as @jldupont has mentioned) -- not just in PHP but in many dynamic languages with associative arrays. For example, Python and Lua don't even have a switch statement -- this is pretty much the only way to emulate a switch.

Consider this approach:

<?
$arr[] = "bye";
$arr[] = "hi";

function sayHi() { print("Hello.\n"); }
function sayBye() { print("Goodbye.\n"); }

$funcs["hi"] = sayHi;
$funcs["bye"] = sayBye;

foreach($arr as $k){
    $funcs[$k]();
}

?>

Output:

Goodbye.
Hello.

It's overkill when you only have two distinct values, but obviously it becomes a more worthwhile approach as the number of situations you have to cover increases.

这篇关于这是一个糟糕的模式吗?(在 for/foreach 循环内切换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆