Asp.net – Using Classes for cleaner, efficient code
What is efficient code? A huge mistake many beginner programmers do is to re-use the same code over and over on multiple pages. Not only is this inefficient, it makes your app unnecessarily fat. Asp.Net has a friendly little thing called a class that will allow you to save some code in a central location and refer to it from anywhere within in your.
Let’s take a look at an example.
Assuming I need to know the path of the current page, we can just use the below code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim sPath As String = System.Web.HttpContext.Current.Request.Url.ToString Label1.Text = "This page is named " & sPath.ToString End Sub
This works and is a handy little tool. Good, so where’s the problem? Well, let’s assume that your app has 10 webforms and in each form’s Page_Load, you’re running the above code, hmm, that’s a lot of repeating code. What happens the day you need to edit this code, to say set the returning text to all lowercase? You have to edit the same code on 10 pages, this is the polar opposite of Efficient Code.
That’s when we make mistakes. A Typo? Maybe missed 1 page, etc.?
Let’s see if we can clean that up a little.
Efficient Code – Adding a Class
Right click in your Solution Explorer at the root level, you’ll see a menu system appear. Find Add and active the sub-menu using the Expand Arrow. At this point, you’ll see a small list of things that you can add, categorised by type, in this exercise we’ll choose Class. A new window will appear with a long list of items that could be added to your application, Class should already be highlighted and named generically class1.vb.
For this exercise, we’ll rename the class to Common.vb. Go ahead and change Class1 to common and then hit Add.
Now, let’s add some code. Given that this code will reside in a central location, presumably with additional code eventually, let’s move it to a sub-routine or function. This keeps things cleaner and will make maintenance a lot simpler as well.
Ok, so in this case I am going to use a Function, why, well I only need to return one piece of data which will be the page name, so a Function is the way to go.
Writing your function
For this exercise, I’m going to assume you understand the basics of using a function.
Public Class common Protected Function GetCurrentPageName() As String Dim sPath As String = System.Web.HttpContext.Current.Request.Url.ToString Return sPath End Function End Class
Ok, the above code is how you would write a typical function, correct? We can clearly see that the first line in function GetCurrentPageName (misnomer since I’m actually returning the full path) is the exact same code we were using in the Page_Load of our 10 pages. The new, second line will simply return the path when we call our function.
Let’s try it.
If we go back to our Page_Load and REM out the 2 lines of code, we can try to return the information from our Common.vb Class. To do this, we merely type in the name of the Class and let the Intellisense do the rest of the work for us.
Type Common. and let’s take a look at what’s available. Hmmm, that’s weird, where’s our function? Ok, so what’s happening is that when we create a Function or sub-routine in a class, we need to declare it as a Public Shared Function, this makes it accessible from the entire application.
Public Class common Public Shared Function GetCurrentPageName() As String Dim sPath As String = System.Web.HttpContext.Current.Request.Url.ToString Return sPath End Function End Class
Let’s try it again. Go back to your Page_Load and start typing common.
You should now see your function appear (if it doesn’t, try a Build Ctrl+Shift+B).
Yay, Efficient code!
Efficient Code – Bring it all together
Using the code above, we can now efficiently call our function from a central location, the below would replace the Page_Loads for all your webforms.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'Dim sPath As String = System.Web.HttpContext.Current.Request.Url.ToString 'Label1.Text = "This page is named " & sPath.ToString Label1.Text = "This page is named " & common.GetCurrentPageName() End Sub
This was a particularly small example but you can certainly imagine how much tighter and more efficient code can help your application when pulling code centrally this way. Most of my web applications contain at least 2 class files, typically my Class for setting and reading Cookies and separately, my Class for all other Common Functions, such as trimming text, the above GetCurrentPageName and a few more.
This is a good habit to get into, it’ll help you maintain your code. Just note that in some instances, the same code that works directly in a page may not work from class, due simply to how the code references the page.
I hope this helps!
Visit my Sponsors
- [RESOLVED]leanModal - a JQuery modal plugin with asp.net controls | ASP Web Form Data Control on Using the Ajax Modal Popup as a Login Control – A Beginner`s Guide
- [RESOLVED]Localization of sitemap | ASP Web Form Data Control on asp.Net Easily make your web application multilingual – Part 1
- [RESOLVED]Multiple Page Load with Working Map Page Route | ASP Web Form Data Control on asp.Net 4.0 Routing, a simple Tutorial that works
- [RESOLVED]masterpage initializeculture no suitable method found to override error? | ASP Web Form Data Control on asp.Net Easily make your web application multilingual – Part 1
- repeater databing | ASP.NET MVC on Nested Repeaters, do it clean and simple – A Beginner’s Tutorial – Part 1