Main Content

Why populate object with values as you construct them?

Archive - Originally posted on "The Horse's Mouth" - 2016-02-18 14:22:41 - Graham Ellis

Objects are a great way to bundle up a whole lot of values (also known as properties or attributes) into a single container / collection, allowing the the programmer who makes use of the objects to be able to set them up just once and delegate the management of the values to the class / object code. So:

  trafalgar = square(110,"London, UK")
  more code here
  print ("circumference of {}m in {}".format(
    trafalgar.getEdge(), trafalgar.getCountry()))


sets up an object of class square early on, then referenced it twice without having to pass in values again (and indeed without having to manage those values) later on.

In contrast, if the user were to construct the objects without attributes and pass their values in later, there's likely to be significantly more code to be written in the application for attribute management, and that code will be much more prone to errors and require the application programmer to be much more knoweledgable about the objects as (s)he will need to know what method requires what parameters. So this is a poor approach!

  trafalgar = square()
  more code here
  print ("circumference of {}m in {}".format(
    trafalgar.getEdge(110), trafalgar.getCountry("London, England")))


There's a pedantic school of thought that says that each method should perform a single task, and that a constructor with parameters passed in is both creating and populating an object, and that the setup should be done in separate calls, so it might look like:

  trafalgar = square()
  trafalgar.setWidth(110)
  trafalgar.setLocation("London, Great Britain")
  more code here
  print ("circumference of {}m in {}".format(
    trafalgar.getEdge(), trafalgar.getCountry()))


There's nothing 'wrong' with this approach in that all the attributes are stored in the object like they were in my original code, but it does make for longer applications, and it does mean that object methods really need to check that the population has been done. So, personally for most uses, I would go for create-and-populate constructor, the only exception being if I needed the granularity at setup for some reason. Even then, I would probably use optional and perhaps named parameters, with other methods available to set attributes later on if need be.

Sample code - top example (best)
Sample code - middle example (POOR)
Sample code - lower example (pedantic)

Source code examples all in Python (Python 3).