Skip to content

Unreachable else best practice #18

@lukpueh

Description

@lukpueh

I was wondering how others feel about mutually exclusive conditionals, in a case like this:

Let's say we raise an exception if two conditions are not mutually exclusive and subsequently do different things depending on the conditions, which of the following alternatives do you find most readable? Note that the pragmas are necessary to prevent unittest code coverage decrease (if in place).

(1)

if not xor(condition1, condition2): 
  raise

if condition1:
  do1()
elif condition2:
  do2()
else: # pragma: no cover
  raise

(2)

if not xor(condition1, condition2): 
  raise

if condition1:
  do1()
elif condition2: # pragma: no branch
  do2()

(3)

if not xor(condition1, condition2):
  raise

if condition1:
  do1()
else: # condition2
 do2()

(4)

if not xor(condition1, condition2):
  raise

if condition1:
  do1()
if condition2:
  do2()

The code style guidelines currently recommend to use (1) and to not use (3), however the example in the guidelines does not consider an initial check for mutual exclusiveness.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions