What Would Proudhon Do?
17 March 2009 Leave a comment
(stackoverflow rep: 3958, Project Euler 66/236 complete)
Dick Kusleika wrote about some of his personal code construction methods in Daily Dose of Excel recently. Something that caught my eye was this:
I generally end up with a lot of Property statements that do nothing but read and write to a module-level variable.
Probably fairly familiar, goodness knows I’ve written enough of those, and I never used MZ-Tools to automate the process, either. So I was nodding away as I read, muttering “amen brother” and whatnot, when I had a vicious attack of the Whys.
Why do we write a Property Set/Let/Get just to set, let or get a member variable? What’s a Property for, anyway?
I think a Property should probably only be used to assign a value when some processing needs to occur other than simply setting the member variable. Code such as:
Private mName As String Public Property Let Name(value As String) mName = value End Property

Serendipitously, I just completed Project Euler problem 84...
…just doesn’t seem to be adding any value. Rename the member variable, make it Public and move on, secure in the knowledge that you just saved some keystrokes and reduced your carbon footprint (well, maybe) by some infinitesimal fraction of a gram. The world thanks you.
Now if you need to validate the input in some way, a Property Let may be the ideal place to do so. It may not, as well, but that’s not important right now.
What else? What if you need something to happen, other than validation, when you set a property? Here’s where I’d suggest that you’re doing something wrong: I’m not a big fan of hidden side-effects (British understatement warning) – I have too many scars from self-inflicted wounds from doing that. If setting a property causes some activity or state-change, then the code should probably be refactored into a Sub with a suitably informative name.
I suppose write-only properties need a Let/Set (so that we can ensure no Get is written) but how often do we need that?
Otherwise, let’s just access the member variable directly without the indirection (think of the planet).
Getting.
Honestly, how different is a Property Get from a Function?
Given a class defined thus:
Public ws As Worksheet Public Property Get Wksh() As Worksheet Set Wksh = ws End Property Public Function WkshF() As Worksheet Set Wksh = ws End Function
… what are the differences between the three Sets here:
Public Sub GetWksh() Dim wsh As Worksheet With New Class1 Set wsh = .ws Set wsh = .Wksh Set wsh = .WkshF End With End Sub
I submit, Your Honours, that the only time a Property Get makes much sense over a Function is when there’s no pre- or (ugh) post-processing around the accessing of the member variable. In which case, why bother?
Anyway, Proudhon wouldn’t have liked Properties.