Understanding Access Modifiers in VB 2005
Access modifiers in Visual Basic .NET are represented by the four words—public, protected, friend, and private—that support a cornerstone of object-oriented programming (OOP): encapsulation. Encapsulation supports information hiding, and the general purpose of an access modifier is to determine who has access to what (or from whom certain information in your code is hidden). The reason you want to limit access is because all access, all the time is a very bad thing. Just ask anyone who's used procedural programming.
Blah! Blah! Blah! You've probably heard all of that before already, but it doesn't explain when or how you would use access modifiers. As far as I can tell, there are two reasons you need to know about access modifiers:
- You just need some simple rules to figure out which keyword to use.
- You need all of the theory mumbo jumbo to pass an OOP IQ test.
Simple Rules, Simple Tools
Almost everyone has heard the acronym KISS, or Keep It Simple Stupid. To keep it simple, consult the following three simple rules (listed in order of simplicity) to figure out which modifier to use:
- You can always use the Public modifier to allow everyone to have access to everything.
- Make everything Protected except what absolutely must be Public. I mean everything, and try to make as little as possible Public.
- You can always change access modifiers up until the point the software is shrink-wrapped. (Don't worry if you get it wrong in version 1; you have version 2 to get it right. Plus, even the experts make mistakes here.)
Now, if the simplicity of the above rules seems fishy, consider the policy I use:
- Fields are always Private and wrapped in Public properties.
- Only the subroutines and functions that define the class's primary behavior are made public; everything else is private.
- If I know a child class will be created—and I usually do because I design the classes beforehand—I will make some behaviors protected, but just the behaviors I think that I will change.
- Occasionally, I use the Friend modifier to reduce the signal-to-noise ratio between assemblies.
These rules will satisfy a huge percentage of the programming you do. I have simple, general rules because simple rules facilitate speed. Listing 1 is an example of the application of these rules.
Listing 1: Elements of a .vb File Containing Access Modifiers as I Would Apply Them
'Access modifier not needed here Namespace AllAccess Friend Class OnlyInThisAssembly Public Function AddTwo(ByVal lhs As Integer, _ ByVal rhs As Integer) As Integer Return lhs + rhs End Function End Class Public Class CustomerEveryOneCanUse Private nameField As String Friend key As String Public Sub New(ByVal nameField As String) End Sub Public Property NameProperty() As String Get Return nameField End Get Set(ByVal value As String) nameField = value End Set End Property Protected Overridable Sub ChildClassCanExtend() ' do something End Sub End Class End Namespace
Don't beat yourself up if it's not perfect the first time. No one gets it perfect the first time.
Encapsulation: OOP Cornerstone
Encapsulation enables you to hide information, but no one ever tells you what to hide and from whom. The answer is that you are hiding information from yourself mostly and other programmers sometimes. You hide the information because consumers—you and other programmers—don't need to know it to use the code element (like class). You are hiding it to make using the element easier.
A consumer is anyone who uses the element, which more often than not is you at a later date. When one consumes code, only the public members need to be considered directly and the general behaviors need to be considered indirectly. That is, a consumer needs to learn only how to use what is public and whether or not the code as a whole will complete the work needed.
Public members are members that anyone can use. Private members are like underwear; only you should see them. Protected members come into play only when you want members to appear private to external consumers, but accessible to child classes. By making members protected, you are conveying that these members can be changed by generalizers—those that will inherit from and extend the members. (Protected members are like underwear from Victoria's Secret: they are meant to be seen by a trusted few.) Finally, the Friend modifier means that an element is accessible only in the same assembly, like helper classes and members.
Most of the time, you will be creating private fields, private helper methods, public classes, public properties, and public methods and events that represent consumable behaviors. Most of your classes will be public.
For more information about using access modifiers, refer to How to: Control the Availability of a Variable on MSDN.
Practice Makes Perfect
Remember, no one gets all access modifiers correct all the time. If you are still a little unsure, try making everything private and then change one item at a time to public until the code you write satisfies the very minimal set of elements needed to make the code usable. If that prospect frightens you intellectually, make everything public and change one element at a time to private. If the private modifier makes your code stop working, change the item back to public and try the next item.
Finally, to do the best job you can; you will need to have to have an intimate understanding of encapsulation. Continue reading articles like this one, buy books on the subject, and get lots of practice.
About the Author
Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his new book UML DeMystified from McGraw-Hill/Osborne and his upcoming book C# Express for the Professional Programmer from Addison Wesley (Spring 2006). Paul is an architect for Tri-State Hospital Supply Corporation. You may contact him for technology questions at email@example.com.
If you are interested in joining or sponsoring a .NET Users Group, check out www.glugnet.org.
Copyright © 2006 by Paul T. Kimmel. All Rights Reserved.