Why hardcoding is bad, especially in .NET

So, I had a habit of doing inline navigation by doing the following “Lazy Loading” method (code from administration navigation that handles look up tables):

Private Sub ChangeNavigation(ByVal pLinkButton As LinkButton)
	lnkUsers.CssClass = ""
	pLinkButton.CssClass = "selected"
	Select Case pLinkButton.ID
		Case "lnkUsers"
			mvData.SetActiveView(vwUsers)
			BindUsers()

		Case "lnkDivisions"
			mvData.SetActiveView(vwDivisions)
			BindDivisions()

		Case "lnkWithdrawalTypes"
			mvData.SetActiveView(vwWithdrawalType)
			BindWithdrawalTypes()

		Case "lnkMemoTypes"
			mvData.SetActiveView(vwMemoType)
			BindMemoTypes()

		Case "lnkWithdrawalTypePrefix"
			mvData.SetActiveView(vwWithdrawalTypePrefix)
			BindWithdrawalTypePrefix()

	End Select
End Sub

Somewhere down the line, a new request was made to make a certain item “plural”. This then caused some unintended consequences of having run-time issues because the string didn’t compare. And let’s not get started on the fact that it’s case sensitive. It’s actually one of the main reasons why I try to utilize enumerations whenever possible… They’re short, simple, and will break if you type it wrong.

Well, due to the issue, I realized I should utilize .NET’s compiler and properties to my advantage. With that, I turned

Case "lnkDivisions"

to

Case lnkDivisions.ID

VOILA. It slices! It dices! It compiles! Make an update to the text and it will still work. Rename the control without updating the case statement, and it will not compile. You are forced to fix it without stumbling across it during User Acceptance Testing.

Happy Coding!

Profile photo of superadmin

RJ writes custom Windows and Web applications using the Microsoft .NET framework, and enjoys solving problems with code, often while listening to a techno soundcloud stream. He hopes to one day write an application that many businesses will use.

Twitter 

Comments are closed.