Alex Rivera | Logout

How to decide between C# static and non-static methods?

Asked 2009-04-28T13:48:58.820
14

[Edit]

My original-question was "Why to decide between static and non-static? Both do the same..."

Unfortunately it was edited to a C#-specific question what I really wanted to avoid.

So, let me do some additions:

When I say interface, I don't mean the C#-keyword-interface but what I understand something like a C++-interface: A set of well defined functions to operate with my object. When saying weaken my interface, I mean I have different functions (static/non-static) that do the same thing. My interface is not well defined anymore when there are different functions to do the same thing.

So, as Bob the Janitor posted, I can implement a Validate()-function

Document.Validate(myDocumentObject);    

but also

myConcreteDocumentObject.Validate();

To get back to my Copy()-example one could implement Copy() like

myConcreteDocument.Copy(toPath);

but also

Document.Copy(myConcreteDocumentObject, toPath)

or

Document.Copy(fromPath, toPath)

when I think of a folder that contains all the files belonging to my Document (in this case I'm not dependent of a concrete instance - but I'm dependent from other things :)).

In general I'm talking about static methods not static classes (sorry, if I forgot to mension).

But as Anton Gogolev said I think my Document class is not a good example and not well designed so I think I will have to have a look at the Single Responsibility Principle.

I could also implement some kind of ManagerClass that operates with my DocumentClass:

For example:

myDocumentManagerObject.Copy(myConcreteDocumentObject, toPath);

or

myDocumentManagerObject.Copy(myConcreteDocumentObject, toPath);

but if I refer to approach 1) I would tend to create objects that per

Edit
Report

2 Answers

6

My "rule" is:

  • If I don't need to use properties from my class, make it static. (in other words, if the method is not really attached to the class, just there for logic association, use static )
answered 2009-04-28T13:54:10.053
0

Same as altCongnito, and i will add that fileObject.Copy everybody will use, more than the object fileObject. Static for a function that have ideal relationship with the class and not functional dependency of it.

answered 2009-04-28T13:56:46.053

Your Answer