HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Checking if there are no numbers from cellular services

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fromarecellularnumberscheckingservicesthere

Problem

I have this piece of code, which raises an exception if there are no numbers from 3 services. I really don't like how it looks at the moment.

no_numbers = False
if use_verizon_sms:
  if not Api.check_avalible_credits():
    no_numbers = True
elif use_verizon:
  if not buy_verizon_number():
    no_numbers = True
else:
  if not check_count_numbers():
    no_numbers = True

if no_numbers:
  raise Exception("THERE IS NO AVAILABLE NUMBERS")


A shorter version looks even more ugly to me and less clear:

if (use_verizon_sms and not Api.check_avalible_credits()) or \
  (use_verizon and not buy_verizon_number()) or \
  not check_count_numbers():
  raise Exception("THERE IS NO AVAILABLE NUMBERS")


Do you have any ideas how to rewrite it?

Solution

Have a look whether you can extract the code into a function. It then may look like this.

def has_no_numbers():
  if use_verizon_sms:
    return Api.check_avalible_credits()

  if use_verizon:
    return buy_verizon_number()

  if check_count_numbers()
    return True

  raise Exception("THERE IS NO AVAILABLE NUMBERS")

Code Snippets

def has_no_numbers():
  if use_verizon_sms:
    return Api.check_avalible_credits()

  if use_verizon:
    return buy_verizon_number()

  if check_count_numbers()
    return True

  raise Exception("THERE IS NO AVAILABLE NUMBERS")

Context

StackExchange Code Review Q#144142, answer score: 6

Revisions (0)

No revisions yet.