0

フラグか何かを持つ関数があるとします:

void foo (Param p1, Param p2, bool setVariable)
{
    //if setVariable is true, set some bool var to true, else false
}

次のうち、どちらかを優先する傾向はありますか?

if (setVariable)
    _someClassVariable = true;
else
    _someClassVariable = false;

また

_someClassVariable = setVariable;

明らかに 2 番目の方がタイピングが少なくなりますが、1 番目の方が読みやすいと思います。どちらが好ましいでしょうか?

4

4 に答える 4

3

私は一般的に2番目を好みます。私にとって、最初は、コードを書いた人はせいぜい有能ではないという強い警告です。

そうは言っても、原則として bool をパラメーターとして渡さないことをお勧めする傾向があります。foo(true);vs.が実際に何を意味するのかがすぐにわかることはめったにありませfoo(false);ん。通常は、列挙型を使用してfoo(do_this);vs.foo(do_that);

于 2012-04-19T12:46:03.930 に答える
3

I would go for the second, it is just as readable. Readability is more on the names of the variables than on the choice of both options. If the variables and parameters have good names the assignment will be natural. This is similar to returning a boolean from a function you would not do:

bool conditionHolds() {
    if (condition)
       return true;
    else
       return false;
}

(And if you are considering doing it, please rethink it)

于 2012-04-19T12:44:55.507 に答える
2

I would prefer the second one. If less typing isn't enough of an argument for you, also consider your co-worker's opinions. I, personally, would laugh if I saw something like

if (condition)
   return true;
else
   return false;

in production code. (provided the variables are bool, and you're not using this to implement some casting mechanism).

于 2012-04-19T12:45:03.417 に答える
2

The latter is much better, the if else just looks useless an introduces extra complexity both in the code and the compiler produced code gen (although PROBABLY optimised away).

I would also avoid the leading underscore notation, some of those name are reserved fro the standard library and compiler.

于 2012-04-19T12:45:11.357 に答える