semi-concatenated strings
Peter Hansen
peter at engcorp.com
Thu May 30 23:46:10 EDT 2002
"Delaney, Timothy" wrote:
>
> > From: Peter Hansen [mailto:peter at engcorp.com]
> >
> > And which has both embedded "\n" newlines and many more leading
> > spaces before each line...
>
> That's why I would bind it to a name first - that allows me to preprocess
> the query before passing it in.
> I would much rather write it so it is readable, then process it for the
> database, than the other way around.
>
> sql = """
> select cities.city, state, country
> from cities, venues, events, addresses
> where cities.city like %s
> and events.active = 1
> and venues.address = addresses.id
> and addresses.city = cities.id
> and events.venue = venues.id
> """
>
> sql = string.split(sql)
> sql = string.join(sql, ' ')
> sql = string.strip(sql)
>
> rows = self.executesql(sql, (city,))
What a lot of extra work to make something "readable"!
I don't think that this is more readable than the simple, straightforward
approach Skip presented. It uses many more lines and a bunch of
superfluous operations (without even a comment explaining why
you are splitting and joining things this way instead of just using
simple string concatenation).
If I saw code like this in my team I'd ask that a comment be
added to explain it, and if the comment said "# doing this so the
code is more readable" I'd ask that it be refactored so it didn't
need the comment at all, after I got back up off the floor.
I expect the refactoring would take the form of the original
example which needs no extra operations or commenting.
> Skip also asked why I would bind the statement to a name. For a query of
> this size, I find it easier to read - the sql query is separate and (to my
> eye) cleaner than having the literal as a function parameter. Plus it uses
> much less horizontal white space.
Nothing wrong with separating things out like that if you think it
looks more readable, but this is one case where I agree with Skip's
approach even though it looks a lot like "hardcoded strings" which
is generally a Code Smell. Simpler is much better here.
(I might agree with you more if I thought that maintaining the
string-concatenated version would actually be harder. Given the
likely nature of the maintenance -- adding fields to the line with
"from cities, ..." for example, or adding a new line to the
"where" intersection -- I don't believe it would be *any* harder.)
-Peter
More information about the Python-list
mailing list