Encapsulation in Visual Basic
Encapsulation is one of the fundamental principles of object‑oriented programming. It allows a class to hide its internal state and require all interaction to be performed through well‑defined interfaces.
Why Use Encapsulation?
- Data Protection: Prevents external code from putting the object into an invalid state.
- Maintainability: Implementation details can change without affecting consuming code.
- Abstraction: Exposes only what is necessary for the object's usage.
Access Modifiers
Visual Basic provides several access modifiers to control visibility:
Public
– Accessible from any code.Private
– Accessible only within the containing class.Protected
– Accessible within the class and its derived classes.Friend
– Accessible within the same assembly.Protected Friend
– Combination ofProtected
andFriend
.
Example: Encapsulating a Bank Account
Public Class BankAccount
Private _balance As Decimal
' Read‑only property – external code can get the balance but not set it
Public ReadOnly Property Balance As Decimal
Get
Return _balance
End Get
End Property
' Deposit method – validates the amount before updating the balance
Public Sub Deposit(amount As Decimal)
If amount <= 0 Then
Throw New ArgumentException("Deposit amount must be positive.")
End If
_balance += amount
End Sub
' Withdraw method – ensures sufficient funds
Public Sub Withdraw(amount As Decimal)
If amount <= 0 Then
Throw New ArgumentException("Withdrawal amount must be positive.")
End If
If amount > _balance Then
Throw New InvalidOperationException("Insufficient funds.")
End If
_balance -= amount
End Sub
End Class
Best Practices
- Keep fields
Private
and expose them through properties or methods. - Validate input in property setters or public methods.
- Prefer
ReadOnly
properties for data that should not be modified directly. - Document the public API clearly; internal implementation can change.
For a deeper dive, see the related topics: