When to use shared functions?

minboost

Newcomer
Joined
Apr 25, 2006
Messages
2
This may be a basic question, but I'm still a little confused about this one.

If I have a class is made up of ONLY functions (no properties), does that mean that I should automatically just make all of the functions shared?

What is the point of instantiating such an object?

Thanks...
 
It is not a matter of functions and properties. It is a matter of whether or not you need an object oriented approach. A function can be static ("shared") if it does not need to access any fields (variables) within an object of the type the function belongs to. If the class exists only to house helper functions then you are using an un-object-oriented approach and chances are there are no fields to access and the functions should all be declared as Shared.

If, though, you were to inherit from that class, you could benefit from having instance methods (not shared) in terms of polymorphic behavior, but on a utility class that most likely won't be of much use.

In VB you can make the object uninstantiable by declaring a private default constructor. In C# this can be done by declaring the class as static.
 
Thanks.

Actually the specific situation I was asking about DOES have other classes it is inheriting from, along with properties in those base classes that need to be accessed....so I guess that answered my question right there.

Out of curiousity, what if I had a collection of helper functions that could/should be shared, but instead I put them in a class and did not make them shared. What is the difference (other than being more difficult to code)? Is there any performance difference or is this simply a best practices thing?
 
If you don't make the functions shared then you have to instantiate the object. Although the object would have no data, it still takes time and memory to instantiate the object.

In reality it is only a few bytes and a small handful of CPU cycles for each pointless instantiation, but what it really does is make a mess of your code.
[Vb]
Public Class IsShared
Public Shared Sub DoThings()
End Sub
End Class

Public Class NotShared
Public Sub DoThings()
End Sub
End Class

Public Class Example
Public Sub Demonstrate
'With the shared class we can directly call the sub
IsShared.DoThings()

'With the not shared class, we have to write pointless code
'to instantiate an object. It takes twelve pointless bytes of RAM
'(I believe) and time to allocate memory for these pointless bytes,
'and adds extra data to the stack for each function call, but the
'biggest problem is the extra code:
Dim thing As New NotShared '<-- Right there
thing.DoThings()
End Sub
End Class
[/CODE]
Either way, it isn't a big deal, but using instance functions where they really have nothing to do with an instance of an object just doesn't make sense.
 
Back
Top