-4
\$\begingroup\$

Which of these variations do you think is the best way to write a function that returns True based on multiple conditions?

Variation 1:

def is_trial_plan(order):
    return (
        "shipping" not in order
        and order["amount"] == 0
        and order["description"] == "Affiliate"
    )

Variation 2:

def is_trial_plan(order):
    if (
        "shipping" not in order
        and order["amount"] == 0
        and order["description"] == "Affiliate"
    ):
        return True

Variation 3:

def is_trial_plan(order):
    if (
        "shipping" not in order
        and order["amount"] == 0
        and order["description"] == "Affiliate"
    ):
        return True
    return False
\$\endgroup\$
2
  • 3
    \$\begingroup\$ I hope you're aware that the second version is not equivalent to the others... In case the condition doesn't hold it returns None... \$\endgroup\$
    – Tomerikoo
    Nov 10 '20 at 18:16
  • 3
    \$\begingroup\$ Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. This question is off-topic \$\endgroup\$
    – Parekh
    Nov 10 '20 at 20:22
1
\$\begingroup\$

I personnaly prefer var1 as the function name is in "isSomething...." form i'll assume all conditions to be true.

I may prefer other versions if other cases of multiples conditions arise in the function.

If there is multiples more conditions and if theirs reading cost is high (for example reading from file/parsing,db.., you may prefer return multiple false to avoid evaluation even if this augment code size.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Please dont answer questions that are off-topic \$\endgroup\$
    – Parekh
    Nov 10 '20 at 20:22
  • \$\begingroup\$ sorry, i just joined codereview and didn't though that question was off-topic, i'll care more in future \$\endgroup\$
    – jolrael
    Nov 10 '20 at 20:44
  • \$\begingroup\$ Not a problem, you can find a lot of information in the help center. If you feel a question is off-topic it's best to not answer, and instead flag it for closure. :) \$\endgroup\$
    – Parekh
    Nov 10 '20 at 21:27

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