CodeSOD: Protect Your Property

Given the common need to have getter/setter methods on properties, many languages have adopted conventions which try and make it easier to implement/invoke them. For example, if you name a method foo= in Ruby, you can invoke it by doing: = 5.

In the .NET family of languages, there’s a concept of a property, which bundles the getter and setter methods together through some syntactical sugar. So, something like this, in VB.Net.

    Public Property Foo() as Boolean
            return _foo
        End Get
        Set(val as Boolean)
            _foo = val
        end Set
    End Property

Now, you can do obj.Foo = FILE_NOT_FOUND, which actually invokes the Set method.

You can have more fun- the Property declaration can be marked as ReadOnly, and then you can skip the Set portion, or you can mark it as WriteOnly and skip the Get portion.

Dave S was given some time to pay down existing technical debt, and went hunting for bad code. He found this unusual way of making a property read only:

    hfRequiredDocsPresent = CBool(hfAllDocumentsUploaded.Value)
    Public Property hfRequiredDocsPresent() As Boolean
            Return CBool(hfAllDocumentsUploaded.Value)
        End Get
        Set(ByVal value As Boolean)
            value = CBool(hfAllDocumentsUploaded.Value)
        End Set
    End Property

[Advertisement] Manage IT infrastructure as code across all environments with


. Puppet Enterprise now offers more control and insight, with role-based access control, activity logging and all-new Puppet Apps. Start your

free trial



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: