0

And more to the point, how do I avoid it?

See the link below for further reference; specifically the reply by paxdiablo. How do I check if a variable exists?

As you probably guessed, I have a scenario where I've programmed a web page that has a variable whose existence is unknown at run time.
What is happening is, a user uploads information that can be in several different formats. To be more concrete, an address. For example, the street may have a directional (southwest, north), and the address may have a condo qualifier (unit#2F). These (or things/scenarios like them) will be assigned to and represented by different variables. As the data is manipulated in my code, I have conditionals

if street_dir_var:
    #do something

Hence my question(s): why is this bad form, and whats a proper substitute?

PS - if it matters, I'm coding in Python

Community
  • 1
  • 1

1 Answers1

3

Conditionals are fine. The issue is if street_dir_var is not even defined, that line will throw a NameError. You can technically catch NameError, but that makes for messy unmaintainable code. It also suggests that you are putting data into your variable names, which is a bad code smell.

In general, a variable should be defined in any logical branch that tries to access it. If it "doesn't apply" for whatever reason, it should at very least be None. This serves as a fine default value for your variables, and often serves as a default for keyword arguments which need one.

To get more specific here:

These (or things/scenarios like them) will be assigned to and represented by different variables.

Really bad code smell. All those variables represent data for a single address - you need to aggregate all those variables into a single variable, be it a class, a list, a dict, or a namedtuple.

class Address:
    def __init__(self, **kwargs):
       self.street = kwargs.get('street')
       self.directional = kwargs.get('directional')
       self.condo = kwargs.get('condo')

user_data = parse_data(some_data_source) # user_data looks like a dict

address = Address(**user_data)

One address, one container. address.condo might be None, but at least it's defined when I ask for it.

roippi
  • 25,533
  • 4
  • 48
  • 73
  • Thanks for your response. I'm a beginning programmer so coding with a paradigm in mind is difficult. Usually, I just want the code to work. Can you explain briefly why different parts of an address being represented by different variables has a "really bad code odor"?? Specifically, what problems does it cause? – user3398838 Apr 21 '14 at 04:02
  • The point is that you need to collect all those variables together into one object. Doing this makes your code easier to read and FAR easier to maintain/refactor. Hard to explain more without writing an essay, I'm afraid. Do more research on Object-Oriented Programming and maybe come back to this problem in a few weeks, see if it makes any more sense to you then. – roippi Apr 21 '14 at 04:55