Common functions and inheritance
I received some interesting comments on one of my recent posts.
What do you think about these ideas ?
This is a question which I've puzzled over as well, the general advice about static methods is 'don't use them to group a bunch on unrelated function together for convenience' umm...yes...well I've yet to come across a project which doesn't do just that. Most of my prjects has a 'Common' class somewhere about which has a whole bunch of 'Is' type functions and formatters etc..(IsGuid being a favourite in a current project). Other stuff is broken up into more appropriate classes like Security, encryption, compression etc...but I do think these types of classes are necessary.
One way to get around the problem of these messy source files is through the use of Partial classes like we'll have when Whidbey arrives, these will give a very useful method of breaking the sprwaling source files which can occur when you use this approach into better subdivisions (especially useful when using source control and multiple coders own parts of the same class...not ideal but it does happen!)There realy is nothing to develop...it is literally a catch-all for methods which don't belong anywhere else. These are usually implemented as static methods...with compiled static regular expressions (very useful when validation farily compelx data) implemented within as well.
It really is better practice not to do this at all - it can lead to some very sloppy practices and you have to keep a tight rein on when something drifts into this class - a rule which I tend to use, is ' is it used by more than 3 unrelated classes' - if they're releated (i.e., can inherit from the same parent class) then the parent class should really implement the method and not the 'Common'.
If you've got a fair number of methods which are similar (like format validators such as IsGuid / IsLong...etc..) - then by all means set up other classes - oh, and don't be afraid to refactor as you go! Word has it that Whidbey has some pretty neat refactoring stuff!
All my pages inherit from a
Page class, which in turn derives from System.Web.Ui.Page. Pages with more specialized function derive from a subclass of this main page (eg. all the edit pages might derive from EditPage). All the convenience methods/objects I need which aren't in the framework are added to the base page(s). I've found creating a base page class to be very powerful (example: I changed all the validators on all of my pages to display a little exclamation mark image beside the control they were validating when there was an error, and show the validation message as a popup when you clicked on the image, all in 4 lines in the base class). I'm fairly happy with it, but would be interested in hearing how others do things.