Writing VB.NET Code That Lasts
Consistent naming makes VB.NET code self-documenting. Use PascalCase for types, methods, properties, and public fields (CustomerOrder, CalculateTotal, IsActive), and camelCase for local variables and parameters (orderCount, customerName). Prefix interfaces with I (IRepository, IValidator) to match the .NET-wide convention shared with C#. Avoid Hungarian notation like strName or intCount, VB.NET's type inference and IntelliSense make the type visible without cluttering the identifier. Because VB.NET is case-insensitive, never rely on casing alone to distinguish two identifiers, for example total and Total, the compiler will flag it as a conflict, and even if it didn't, it would be unreadable.
Cricket analogy: It's like every IPL team using the same jersey-numbering convention so commentators can call out 'eighteen, Kohli' and everyone instantly knows who's batting, consistent identifiers work the same way for the next developer reading your code.
Error Handling and Resource Management
Modern VB.NET should use structured exception handling with Try...Catch...Finally, not the legacy On Error Goto or On Error Resume Next statements that still compile for backward compatibility. Catch specific exception types (IOException, SqlException) rather than a bare Catch ex As Exception, so bugs aren't silently masked by handling errors you didn't anticipate. Any type implementing IDisposable, a SqlConnection, a StreamReader, a FileStream, should be wrapped in a Using block so its Dispose method runs deterministically even if an exception is thrown, rather than relying on the garbage collector's finalizer to eventually reclaim the underlying OS handle.
Cricket analogy: It's like a fielding captain having a specific plan for a yorker versus a plan for a bouncer, rather than one generic 'defend everything' instruction, catching the exact exception type lets you respond precisely instead of blanket-handling every failure the same way.
Performance and Memory Practices
String concatenation inside a loop using the & or + operator creates a new String object on every iteration because strings in .NET are immutable; for anything beyond a handful of iterations, use System.Text.StringBuilder and call .Append, then .ToString once at the end. Avoid late binding, calling methods on an Object-typed variable resolved at runtime, in performance-sensitive code, it bypasses compile-time checks and is markedly slower than early-bound calls resolved at compile time. Prefer structures (Structure) only for small, immutable value types to avoid unnecessary boxing when they're stored in generic collections like List(Of T), and reserve classes for anything with reference semantics or larger data.
Cricket analogy: It's like rebuilding your entire batting lineup card from scratch after every single run scored instead of just updating the scoreboard, StringBuilder is the equivalent of keeping a running tally rather than rewriting the whole card each time Rohit Sharma taps a single.
Structuring Larger Codebases
As a VB.NET application grows, resist the temptation to pile logic into a single Module or a bloated Sub Main. Organize code by responsibility using namespaces and separate class libraries, a data-access layer, a business-logic layer, and a presentation layer, at minimum, so a change to database access doesn't ripple through UI code. Favor dependency injection and interfaces (IOrderRepository rather than a hard reference to a concrete SqlOrderRepository) so components can be swapped and, critically, unit tested in isolation using a framework like MSTest, NUnit, or xUnit. Shared mutable state in Module-level fields is a common source of hard-to-reproduce bugs in multi-threaded VB.NET applications, prefer passing state explicitly through method parameters or constructor injection instead.
Cricket analogy: It's like a franchise separating its scouting department, coaching staff, and commercial operations into distinct units rather than having one person try to do all three, a layered VB.NET architecture separates data access, business logic, and UI the same way for the same reason: focused responsibility.
Public Class OrderProcessor
Private ReadOnly _repository As IOrderRepository
Public Sub New(repository As IOrderRepository)
_repository = repository
End Sub
Public Function BuildSummary(orderIds As IEnumerable(Of Integer)) As String
Dim sb As New System.Text.StringBuilder()
For Each id In orderIds
Try
Dim order = _repository.GetById(id)
sb.Append($"Order #{order.Id}: {order.Total:C}").AppendLine()
Catch ex As Data.SqlClient.SqlException
sb.Append($"Order #{id}: failed to load ({ex.Number})").AppendLine()
End Try
Next
Return sb.ToString()
End Function
End ClassVB.NET still compiles legacy On Error Goto / On Error Resume Next syntax for backward compatibility with VB6-era code, but it should not appear in new code. Structured Try...Catch...Finally gives you typed exceptions, nested exception handling, and Finally blocks that behave predictably under refactoring.
On Error Resume Next silently swallows every runtime error after it, including ones you never intended to ignore, a NullReferenceException three lines later can go completely unnoticed until it corrupts data further downstream. Never use it in new VB.NET code.
- Use PascalCase for types/methods/properties and camelCase for locals and parameters; never rely on VB.NET's case-insensitivity to distinguish identifiers.
- Prefer structured Try...Catch...Finally over legacy On Error Goto / On Error Resume Next.
- Wrap every IDisposable resource (SqlConnection, StreamReader, FileStream) in a Using block.
- Use StringBuilder instead of & / + concatenation inside loops to avoid repeated string allocation.
- Avoid late binding in performance-critical code; keep Option Strict On to catch type errors at compile time.
- Layer applications into data-access, business-logic, and presentation concerns, and inject dependencies via interfaces for testability.
- Avoid Module-level mutable shared state in multi-threaded applications; pass state explicitly instead.
Practice what you learned
1. Why should StringBuilder be preferred over & concatenation inside a loop?
2. What is the main risk of On Error Resume Next?
3. What does wrapping a SqlConnection in a Using block guarantee?
4. Why prefer catching SqlException over a bare Catch ex As Exception?
5. What is a benefit of injecting IOrderRepository instead of referencing SqlOrderRepository directly?
Was this page helpful?
You May Also Like
VB.NET vs C#
A practical comparison of Visual Basic .NET and C# covering syntax, features, and when to choose each language on the .NET platform.
Building a Simple CRUD App in VB.NET
A step-by-step walkthrough of building a Create-Read-Update-Delete application in VB.NET using ADO.NET and a repository pattern.
VB.NET Quick Reference
A condensed reference for VB.NET syntax covering data types, control flow, collections, LINQ, and object-oriented constructs.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics