Too Many if Statements?

bruno at modulix onurb at xiludom.gro
Tue Feb 7 13:04:03 EST 2006


slogging_away wrote:
> I don't consider myself to be a seasoned programmer

nor do I.

> so if you mean
> redesigning the script to make the checks and therefore reduce the
> number of 'if' statements, I'm not sure if that can be done. 

I strongly doubt it could *not* be done !-)

> The
> script needs to make numerous checks for the existence of particular
> strings within the configuration file.  It also uses 'if' statements to
> determine what type of file is being examined, etc.. If an error is
> encounterd it writes warning messages to a master file.  

Yeps, that's pretty common with this kind of scripts. I recently had a
script doing thousands of regexp substitutions, image resizing, file
moves, database inserts etc, and of course a fair amount of logging. And
I can tell you that there many few "if" in this code.

> I guess what I
> am trying to say is that in order to make the many checks on the
> configuration files I do not know of any other way than to check for
> the existance of particular statements, (strings), and then report on
> those if they are incorrect or missing - hence at least one 'if'
> statement for every check. 

Suppose you have to match a line against a list of regexp and log if it
doesn't match. You could of course repeat the whole code for each
regexp, ie:

if not re.match(r'a/regexp/here', line):
  log('a first message')

if not re.match(r'another/regexp/here', line):
  log('another message')

(... 150 regexps later ...)

if not re.match(r'150/regexps/later', line):
  log('pfww, getting tired of copy/pasting')

etc...

But you could also factor much of it:

def checkMatch(line, regexp, msg):
  if not re.match(regexp, line):
    log(msg)

then have a list of regexps/messages pairs and:
  for exp, msg in regexps:
    checkMatch(line, exp, msg)

And now, you can add as many thousands regexps you want, you still have
one (and only one) if in the code (well, in this snippet at least...).

> I appreciate the feedback though!

You're welcome !-)



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list