Reduce usage of if-statements?

Asked by Calle Rundgren

I got two versions of the program I am automating. In the different versions of the programs the set of icons is not the same. I want to make a script who is universal and could be used in order to automate both versions.

An example on how a script could look like:

imgver1=(image1)
imgver2=(image2)

if exists(imgver1):
    click(imgver1)
if exists(imgver2):
    click(imgver2)

Is this the best way in order to perform the task? If my scripts getting longer there will be many if-statements.
Can I in some way reduce the usage of if-statements?

TYIA

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
RaiMan
Solved:
Last query:
Last reply:
Revision history for this message
Best RaiMan (raimund-hocke) said :
#1

It is a normal situation for every kind of programming since Turing invented his machine:
The more different cases should be handled in one program, the more decisions you will have to make and its increase mostly is more exponential than linear.
And the decision tool in Sikuli/Python is if/elif/else.

So be happy, that there is if/elif/else, to help you with your workflow and use it.

So the right question is: How to make decisions in a readable, elegant, efficient and robust way.

--- Taking your example:
Can both imagever's be there the same time? Since I guess no:

if exists(imgver1):
    click(imgver1)
elif exists(imgver2):
    click(imgver2)
else:
    print "None of them"
    exit(1)

this only tests until the first match is found (a case/switch in other languages).

--- One more thing
for efficiency use:

if exists(imgver1):
    click(getLastMatch())

you save one search.

--- One last thing:
When I am right with my guessing, in the moment you do your case study, one imagever must be there.
Then it is even more efficient to use:

if exists(imgver1, 0):
    click(imgver1)
elif exists(imgver2, 0):
    click(imgver2)
else:
    print "None of them"
    exit(1)

In the case without the second parameter as 0, a not successful search would last 3 seconds (standard waiting time). with the 0 it comes back in the average with 0.5 seconds or less.
So with 4 cases and the 4th case matches, it would take 10 seconds against maximum 2 seconds with the 0.
The magic is, that exists(img,0) only makes one search and comes back with the result.

Revision history for this message
Calle Rundgren (c-rundgren) said :
#2

Thanks RaiMan, that solved my question.