Simon Bergot
Simon Bergot

Reputation: 10592

refactoring a field into a property

I am currently learning vb.net for my new job and I have mixed feelings over public fields. I see many arguments about them hurting the encapsulation. In python, the common practice is to keep things simple and use fields when they are enough. If we want to add logic later, we just refactor them into a property without breaking anything for the client code.

In the codebase I am working with I see huge classes containing dozen of properties like:

Private __GetDescriptionMode As Boolean
<DefaultValue(False)> _
 Public Property GetDescriptionMode() As Boolean
    Get
        GetDescriptionMode = __GetDescriptionMode
    End Get
    Set(ByVal Value As Boolean)
        __GetDescriptionMode = Value
    End Set
End Property

That's 10 lines of code with little value inside. I can barely see 3 of them in my visual studio window. So I have 2 questions:

EDIT To clarify my first question: Do I have a chance of breaking client code if I change a field into a trivial property?

Upvotes: 0

Views: 1457

Answers (2)

MarkJ
MarkJ

Reputation: 30408

It is a good idea to create properties rather than fields.

  • You can break client code if you change a public field into a public property.
  • You can only use data-binding with properties.
  • Fields can't be used in interfaces
  • You will break binary serialization code if you change a public field into a public property.
  • If you are using reflection, changing a field to a property later could break your reflection code.

Read more from this blog post by the Vb.Net team, or this from Jon Skeet about the same issue in C#

In Visual Basic 2010 and later, use auto-properties

Public Property GetDescriptionMode As Boolean

Upvotes: 3

Jon Egerton
Jon Egerton

Reputation: 41559

IMHO its always worth setting up the properties in the first place:

  • You may well be making someone else's life harder when they need the properties.
  • May also mean unnecessary amendments to projects with many dependencies.
  • If you don't like space taken up by the properties, wrap then in a Region
  • Various things such as reflection/data binding etc may have issues with fields.

Worth saying that, as of VS2010, this problem largely goes away with the advent of auto-properties. The above would condense to:

Public Property GetDescriptionMode As Boolean

Upvotes: 2

Related Questions