views:

42

answers:

2

I'm kinda getting mixed messages about this so I'm hoping someone can clear this up for me.

Should I be using Shared methods/functions in the following situation:

I have a generic class named "Person". This class represents a person in the database.

I have a manager class named "PersonManager". This class contains methods which adds, updates, deletes individual Person objects. A method also exists to lookup Persons from the database.

Should these methods in the manager class be declared as shared methods? Or is it more appropriate to create a new instance of the PersonManager class each time and call the appropriate method on it.

So, if shared:

PersonManager.AddPerson(NewPerson) 

versus non-shared:

Dim MyPersonManager as PersonManager
MyPersonManager.AddPerson(NewPerson)

When looking up Persons, the shared version would be:

Dim dt as New DataTable
dt = PersonManager.GetPersons

versus the non-shared version:

Dim dt as New DataTable
Dim MyPersonManager as New PersonManager
dt = MyPersonManager.GetPersons
+2  A: 

Use static methods (shared in Visual Basic) when they contain behaviour that isn't associated with a particular object. They don't require any state to perform their tasks.

See Static Classes and Static Class Members on the MSDN:

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine.

In your case, you probably don't want to use static methods if PersonManager contains some object state. Instead, you should be able to create multiple PersonManager objects and manipulate them separately.

Rich
So in this example, is PersonManager considered to be containing object state? At present, it seems to me that the PersonManager is just doing something and not holding anything. I'm just wondering about best practice.Another example could be handling errors. Where a method is used to send an email containing the exception error to someone. A shared/status method seems best for such a case, yes?
Michael
+1  A: 

Since shared methods and members are called static in c# there is already stuff on stackoverflow...

http://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c

Yves M.
Thanks for the link! I've been in VB mode for the past while and hadn't considered the C# side of things.
Michael