Monday, March 26, 2012

Newbie ? about Classes

I'm not entirely clear on when to create a class and when to just code subs and funcs. I'm getting pretty comfortable with the latter and am beging to wonder if I should be learning to write classes. Any thoughts would be apreaciated.
Thanks
Raif
This depends entirely on a combination of your goals and your preferences.

Classes are an excellent way to get some reusability out of your code that might apply to more than one web page, or even multiple applications. They can increase development time initially, but you may recover this time on future projects from reuse.

Using classes can also make your code more readable, and therefor more maintainable.

The biggest advantage to writing classes is that it gets you going with Object Oriented Programming. OOP is extremely important in .NET because as you create classes and such, you will begin to build a giant library that you and your team can re-use for future projects. If you do not practice OOP in .NET, you will be spending way to much time in writing the same code over and over again for different projects. For instance, creating Table controls, TableRow controls, TableCell controls can be tedious at times. This would call for a WebControlHelper class that you can reuse for all of your projects. Not only that, as you come up with better techniques for clean up and speed, you can make changes to that class and as long as the method signature and its return type doesn't change, all applications you used this helper for would benefit from it.

i.e.


public class WebControlHelper
{
public WebControlHelper
{

}

public Table CreateTable ()
{
return new Table();
}

public Table CreateTable (int numRows)
{
Table thisTable = null ;

try
{
thisTable = CreateTable();
for (int i=0;i<numRows;i++)
thisTable.Rows.Add(new TableRow());
}
catch (Exception e)
{ throw new Exception (e.ToString(), e); }
finally
{
thisTable.Dispose();
thisTable = null ;
}
}
}

This can go on and on to create quite a large helper class and it will save you time later. Let me know if I can be of further help. I'll be glad too!
AND - if you have subs or functions that you use over and over, you'd want to centralize them in a .vb or .cs file (depending on the language you're using)
That way, they're accessible to any aspx document in your application.
how do i include the cs/vb file containing my reusable functions and procedures?

i read that you can compile it to a dll and have it as part of your Imports. is there a way to do it without compiling?

thanks.

0 comments:

Post a Comment