-6
\$\begingroup\$

Lets say I have simple IsSomething() method which checks, if object meets few requirements. Which approach is better?

public bool IsSomething()
{
    if (!MeetRequirementX()) return false;
    if (!MeetRequirementY()) return false;
    if (!MeetRequirementZ()) return false;

    return true;
}

Or

public bool IsSomething()
{
    if (MeetRequirementX() &&
       MeetRequirementY() &&
       MeetRequirementZ())
        return true;

    return false;
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Which approach is more redable? btw, without context your question is off-topic on Code-Review. We require real and working code here. \$\endgroup\$
    – t3chb0t
    Commented Jul 1, 2019 at 12:41
  • 3
    \$\begingroup\$ I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see Why is hypothetical example code off-topic for CR? \$\endgroup\$
    – Heslacher
    Commented Jul 1, 2019 at 12:52

1 Answer 1

1
\$\begingroup\$

Your second example doesn't compile; you're using too much ifs.

If you would be looking what the compiler would make of it, there wouldn't be too much of a difference; the && operator short-circuits. Therefore, you can concentrate on what's more readable for the maintainers of the code (which could be a future you).

The shortest version would be

public bool IsSomething()
{
    return MeetRequirementX() && MeetRequirementY() && MeetRequirementZ();
}

which is fine if it's kind of obvious how these requirements combine into the desired result for IsSomething(). If that's not obvious, you'd better explain why each requirement is necessary with a comment, and then I'd prefer the following:

public bool IsSomething()
{
    // comment explaining why requirement X is necessary
    if (!MeetRequirementX()) return false;

    // comment explaining why requirement Y is necessary
    if (!MeetRequirementY()) return false;

    // comment explaining why requirement Z is necessary
    return MeetRequirementZ();
}

Or replace the last line with

    if (!MeetRequirementZ()) return false;

    return true;

if you prefer the symmetry of that.

\$\endgroup\$
1
  • 6
    \$\begingroup\$ You should avoid answering clearly off-topic questions. \$\endgroup\$
    – t3chb0t
    Commented Jul 1, 2019 at 12:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.