jeudi 15 février 2018

Get rid of multiple (nested) if statements in python

So far, I've created a couple of programs, and the issue that comes up for me the most is how ugly and non-scalable they look.

For example, currently I'm working on a telegram bot. Before replying to a message I need to check that the message follows a couple of rules. In order to minimize the number of if/elif statements I've even created a couple of functions that return True or False if my condition is met, but the code still looks very ugly:

# only if messages are not empty and description has a hyphen
if channel and (description and description[0] == '-'):

    if is_channel(channel) and is_length(description):

        if channel_is_size(channel):
            bot.reply_to(message, replies.success_add.format(channel))
            write_results(' '.join(message_words[1:]))
        else:
            bot.reply_to(message, replies.small_chan.format(min_channel_size))

    else:
        bot.reply_to(message, replies.enter_chan)

elif not description and channel:
    bot.reply_to(message, replies.enter_desc_error)
else:
     bot.reply_to(message, replies.enter_addmessage_error) # if empty

As you can see, these are the conditions for which the user message will be accepted into the database (it's a text file), and this can be seen right under the triple nested if statements. I've tried to make this code look nicer many times over, but now it seems very messy and if I would want to add more conditions, which I am planning to do, these nested statements will grow out of proportion.

P.S. I'm fairly new to both Python and Stackoverflow.

Aucun commentaire:

Enregistrer un commentaire