Main Content

Screw it or Glue it? Access to Object variables - a warning

Archive - Originally posted on "The Horse's Mouth" - 2007-09-12 08:44:55 - Graham Ellis

If you screw two pieces of material together, you have the opportunity, later on, to unscrew them ... resuse them differently, install a waterproof membrane between them, and so on. But if you glue them together, later modification will be much harder or perhaps impossible. And in a similar way, if you're connecting two pieced of software together it's better to screw them than to glue them. What am I getting at?

If you access a member variable within an object directly from your main calling code, then you don't leave yourself the opportunity to intersperse some extra check or twist later on, whereas if you access all member variables via methods - even if they are really just empty wrappers, you leave yourself the flexibility for later. Let's see an example.

Here is a (Python) class:

class pidgeon:
  def __init__(self, name, value):
    self.name=name
    self.value=value
  def getvalue(self):
    return self.value


which I can use like this:

george = pidgeon("John Smith",200)
gina = pidgeon("Jenny Smith",50)
print "Value of George is",george.getvalue();
print "Value of Gina is",gina.getvalue();


and it will print out 200 and 50. Here is an alternative class:

class woodpecker:
  def __init__(self, name, value):
    self.name=name
    self.value=value


and I can access the data, more simply, as follows:

print "Value of Gerry is",gerry.value;
print "Value of Graeme is",graeme.value;


I now want to set a mimimum value of 75 pounds on all birds - pidgeons and woodpeckers. With pidgeons, it's easy - I just modify the getvalue method as follows:

  def getvalue(self):
    if self.value < 75: return 75
    return self.value


but with my woodpecker class I'm stuck.

Pidgeons are like screws, and woodpeckers stick like glue!

Full Source code of example.