Should I always make my methods static where possible? - c#

I have often pondered this one... its probably an idiot question but here goes.
Say I have this class:
public class SomeClass
{
public int AProperty { get; set; }
public void SomeMethod()
{
DoStuff(AProperty);
}
}
Is there any advantage to doing this:
public class SomeClass
{
public int AProperty { get; set; }
public static void SomeMethod(int arg)
{
DoStuff(arg);
}
}
The only advantage that is obvious is that I can now access SomeMethod directly.
So is it good practice to make these kind of methods static where a little refactoring will allow or is it a waste of my time?
EDIT: I forgot to mention (and ShellShock's comment reminded me) that the reason I ask is that I use ReSharper and it always makes suggestions that 'Method X can be made static' and so on...

Static isn't evil. Static is evil if used incorrectly, like many parts of our programming toolkit.
Static can be very advantageous. As the accepted answer here points out, static can have a potential speed improvement.
As a general rule if the method isn't using any fields of the class then its a good time to evaluate its function, however ultimately utility methods that can be called without instantiating an object can often be useful. For instance the DirectoryInformation and FileInformation classes contain useful static methods.
Edit
Feel obligated to point out that it does make mocking a lot harder but it is still definitely testable.
It just means you need to think harder about where static methods go, so that you can always test them without needing to rely on a mock/stub. (ie: don't put them on your DTO that requires a persistent connection to the database).

I'll attempt to answer your specific question involving the code sample you provided.
If SomeMethod is only useful in the class it is declared in, I would avoid the static conversion and leave it as an instance method.
If SomeMethod is useful outside of the class it is in, then factor it out of the class. This may be as a static method in a static utility class somewhere. To make it testable, ensure that all its dependencies are passed in to it as arguments. If it has loads of dependencies, you might want to review the design and figure out exactly what it's supposed to be doing - it might be better as an instance method in one of the classes you're passing in to it.
Some people say that static is evil. This is generally because of the pitfalls that mutable static state provides, where variables hang around from the point a static constructor is called to the tear down of an app domain, changing in between. Code reliant on that state can behave unpredictably and testing can become horrendous. However, there is absolutely nothing wrong with a static method which does not reference mutable static state.
For a (very simple) example where a static is evil, but can be converted to a non-evil version, imagine a function that calculates someone's age:
static TimeSpan CalcAge(DateTime dob) { return DateTime.Now - dob; }
Is that testable? The answer is no. It relies on the massively volatile static state that is DateTime.Now. You're not guaranteed the same output for the same input every time. To make it more test friendly:
static TimeSpan CalcAge(DateTime dob, DateTime now) { return now - dob; }
Now all the values the function relies on are passed in, and it's fully testable. The same input will get you the same output.

Static methods make sense, if you should be able to call them without creating an object of the class before. In Java, for example, the Math-Class contains only static methods, because it wouldn't make much sense to instanciate a Math-Class only to do mathematical operations on other objects.
Most of the time it's better to avoid static methods. You should get familiar with object oriented programming - there are lots of good resources out there, explaining all the concepts like static methods, etc.

I think it will depend on the way you want to use the methods. Using a static method is okay if it is used as a common method over a few instances of the class.
For the sake of an example, say you have a string class and two strings A and B. To compare A and B, you can either have a A.CompareTo(B) method or String.Compare(A, B) method.
Please correct me if I am wrong.

No. Static is evil. It tightly couples the caller to the used class and makes it hard to test.

Related

OOP in General and C# in Particular - Should the constructor return quickly?

I'm currently refactoring some old code for my work. Some idiot (me, 2 years ago) wrote a few things that I think stink. I have this feeling in my gut (I've might read somewhere and forgotten the source) that a constructor in C# should return quickly, because of some technical detail, possibly to do with garbage collection. I.e. the following
class A
{
public object Result {get; private set;}
private object RunLongOperation(){/* ... */}
public A(){
Result = RunLongOperation();
}
}
is bad practise. So my question is twofold - Is it actually bad, and if so why? The above can be rewritten as
class A
{
public object Result {get; private set;}
private static object RunLongOperation(){/* ... */}
private A() { }
public static A Make(){
return new A { Result = RunLongOperation() };
}
}
through a kind of factory static method. This to me just seems more code than necessary, but the actual object is constructed quickly.
To shine a light, the constructor takes a few parameters and renders an image in RunLonOperation(), and does some other stuff based on the input parameters. The class then reduces to immutable result container. The operation takes about 10 to 20 seconds, based on parameters.
Yes doing real work in a constructor is a bad thing from a testability point of view.
It is very hard to write a test for a class that does heavy work in the constructor because you don't have any means left to change the dependencies needed for that object or to inject some custom behaviour by mocking the object.
See http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/ for a good explanation of this design flaw.
I don't think there should be a general rule for this, but in fact it's better to use factory pattern and do not handle too many things in constructor.
I don't think that there is a technical requirement (e.g. GC) that a constructor should not take more than a certain time. However from a programmers point of view, I certainly do not expect that new-ing an object will take a long time. The factory method seems better suited for that use to me.
You also might consider removing the long running operation and injecting the result into the constructor and have a RenderImageFactory instead. Would make the process more obvious and might help with unit testing (meaning: If you want to unit tets class A you might not want to have to render the image every time but instead be able to just mock it out to speed things up and reduce test setup overhead)
There is no hard rule about how long a constructor may take. It depends on what you could reasonably expect depending on what the object does.
If it's possible to use lazy loading, you should consider it that is good for your class. If you for example are loading different things in the constructor, and some of them are not always used, it could be better to load them when and if they are actually needed.
Other than that there isn't often a good reason to put work anywhere else than the constructor, if it needs to be done anyway.
There's no reason at all why a constructor should not take as long as it needs to do its job. The options proposed by you and others look to me like they will make your code more complex for no discernible benefit.
Be lazy:
class A
{
private A() { }
private static object _Result;
public static object Result
{
get
{
if (_Result == null)
_Result = RunLongOperation();
return _Result;
}
}
private static object RunLongOperation(){/* ... */}
}
Anytime we consider a long-running task call from the .ctor is a good sign of a bad design smell. I was always keeping this in my mind until I stuck on a similar issue, running a log code in a type .ctor. In my case I'm about to run a Task<T> asynchronously in the constructor and total the problem, I can't get rid of the task at all since it's all about reflections where your hands are off of any good design principle implementation.
The Thread.Suspend and Thread.Pause seemed to be the only dangerous candidates for running long tasks from constructors, but they're obsolete (after 1.1) and now it seems there's no any reason to limit the execution of the .ctor but the intuitive principle of any API design (that the .ctor is simply a way to quickly "prepare" the object for further usage. MSDN has a good guideline for that).
My suggestion would be using a Factory instead, since constructors are not the place to put business logic within, typically. If you can refactor then you should. If you can't
nobody will punish you for that ;)
If the long running operation is referentially transparent, then you could only run it once for each possible outcome of 'Result', and re-use those results for each object instance. This may provide a performance benefit. If there are multiple possible results then you'll need some way to look up which result is appropriate.
This is just a rough example, may need some tweaking:
class A
{
static Dictionary<String, Object> memoizationCache;
public static bool TryGetMemoizedResult(A instance, out object result)
{
// do the checking etc.
result = memoizationCache[instance.SomeMember];
}
public static void AddMemoizedResult(A instance, object result)
{
memoizationCache.Add(instance.SomeMember, result);
}
public object Result {get; private set;}
public string SomeMember { get; private set; }
private object RunLongOperation(){/* ... */}
public A()
{
object result;
if (TryGetMemoizedResult(this, out result))
{
Result = result;
}
else
{
Result = RunLongOperation();
AddMemoizedResult(this, this.Result);
}
}
}
The reason I bring that up is because it looks like in your case the operation may be referentially transparent, but if not, then I'd go with the lazy loading approach. As it stands I dont think there should be a huge performance difference between your two initialization techniques, though.

Appropriate use of Static Method

Conceptually, is it appropriate to use a static method (C#) when the method will only take inputs and reformat the input as the output? For example:
public static string FormatString(string inputString){
return "some formatting" + inputString + "Some other formatting";
}
If I were to have a few of these types of methods, would a static "utility" class be a good idea?
I'd agree with the other answers so far that it certainly makes sense a lot of the time.
Sometimes, you may want to actually give yourself a little more flexibility by defining an interface and implementing that with instance methods. This gives you the option of using different methods in your code down the road.
Here's an example of what I mean. Say you are using this formatString method of yours in some code somewhere that looks like this:
public void DumpToConsole()
{
foreach (DataField field in m_fields)
{
Console.WriteLine(StringUtils.formatString(field.ToString()));
}
}
OK, this is great. (Actually, it's stupid, but whatever—for illustration only!) But you could make such a method more flexible by having it accept an interface, of which you might have various implementations which provide completely different sorts of formatting:
public void DumpToConsole(IFormatter<DataField> formatter = null)
{
// Perhaps you could specify a default. Up to you.
formatter = formatter ?? Formatter<DataField>.Default;
foreach (DataField field in m_fields)
{
Console.WriteLine(formatter.Format(field));
}
}
Then instead of StringUtils being a static utility class, it would be merely one implementation of a class that offers a way to format a certain type of object (in your case, string objects; in my example, these imaginary DataField objects).
So this is all a very long-winded way of saying, it depends. If you're aiming for super flexibility down the road, maybe you should consider implementing an interface instead of going with a static helper class.
Do note that in my example above, another completely acceptable way of approaching the problem could've been to accept a Func<T, string> delegate instead of this hypothetical IFormatter<T> interface. This is mostly a stylistic choice, in my opinion. But often interfaces become more realistic when there are multiple behaviors that you want to customize; i.e., defining methods that accept 3, 4, or more delegates can quickly become cumbersome compared to accepting a single interface.
Yes, if you have several static methods that are generally related, putting them together in a static utility class is a good idea.
If you're talking about convention, it's also worth noting that naming conventions in most .NET code call for Pascal-cased public members (so FormatString instead of formatString) and camel-cased parameters and fields (so inputString instead of InputString).
If you're making these public, then yes, it might potentially be better to make a utility class of some sort.
That being said, I would try to make it as "general purpose" as possible, since otherwise, they tend to get unmaintainable quickly.
Yes, the static methods in the way you are using them in C# is very similar to C++'s idea of "free functions". It just so happens C# doesn't have free functions. Eric Lippert has an interesting post around here somewhere of why that is the case. A static class is used to group functions of similar utility and would be appropriate if you had several of these that were similar.
Yes that's fine, your class will then act as a 'library' of related functions. Your other choices for this would be to either pollute the global namespace with various functions or to create a Singleton which would be unneeded since there's no 'state' to account for...
Yes, you could do that. Or you could create a string extension method.
msdn extension methods
For your example above, I would use the string formatter instead of inline concatenation.
string.Format("some formatting {0} some other formatting", inputString )
It is if that particular formatting would be useful in more than one place in your code.
If it would make sense only within one specific class, then I'd rather use a private method (static or instance, it wouldn't make a difference).
Utility classes are a useful thing. The only thing you should be careful about is not to use them too often. If most of your code is in utility classes, then you're doing something wrong. But factoring out some common code in helper methods is a perfectly justified use.
You could use an extension method for this to extend the String class. It would make the calling code a little neater, but it's just a matter of personal taste in the end.
public static string MyWeirdFormat(this string str)
{
return string.Format("{0} is weird",str);
}
public static void Test()
{
string myString = "ABCD";
string weirdString = myString.MyWeirdFormat();
}
In my opinion the answer is yes you would put these methods in a Utility (Util) class. On a Java web-based application that I am currently working on we actually have 3 such Util classes each of which comprises of only static methods similar to the one you have shown. The reason why we have 3 is one for the client only Util methods, one for server only and a third one for shared Util methods.
Depending on what your app is you may end up with something similar.
As an aside, if you want to learn more about when to use static classes in C#, have a look here.
I hope that answered your question sufficiently.
Personally I'd lean more towards the use of an extension method, still static though ;)
public static class StringExtensions
{
public static string MyFormat(this string input)
{
return string.Format("some formatting {0} Some other formatting", input);
}
}

Is there anything wrong with a class with all static methods?

I'm doing code review and came across a class that uses all static methods. The entrance method takes several arguments and then starts calling the other static methods passing along all or some of the arguments the entrance method received.
It isn't like a Math class with largely unrelated utility functions. In my own normal programming, I rarely write methods where Resharper pops and says "this could be a static method", when I do, they tend to be mindless utility methods.
Is there anything wrong with this pattern? Is this just a matter of personal choice if the state of a class is held in fields and properties or passed around amongst static methods using arguments?
UPDATE: the particular state that is being passed around is the result set from the database. The class's responsibility is to populate an excel spreadsheet template from a result set from the DB. I don't know if this makes any difference.
Is there anything wrong with this
pattern? Is this just a matter of
personal choice if the state of a
class is held in fields and properties
or passed around amongst static
methods using arguments?
Speaking from my own personal experience, I've worked on 100 KLOC applications which have very very deep object hiearchies, everything inherits and overrides everything else, everything implements half a dozen interfaces, even the interfaces inherit half a dozen interfaces, the system implements every design pattern in the book, etc.
End result: a truly OOP-tastic architecture with so many levels of indirection that it takes hours to debug anything. I recently started a job with a system like this, where the learning curve was described to me as "a brick wall, followed by a mountain".
Sometimes overzealous OOP results in classes so granular that it actually a net harm.
By contrast, many functional programming languages, even the OO ones like F# and OCaml (and C#!), encourage flat and shallow hiearchy. Libraries in these languages tend to have the following properties:
Most objects are POCOs, or have at most one or two levels of inheritance, where the objects aren't much more than containers for logically related data.
Instead of classes calling into each other, you have modules (equivalent to static classes) controlling the interactions between objects.
Modules tend to act on a very limited number of data types, and so have a narrow scope. For example, the OCaml List module represents operations on lists, a Customer modules facilitates operations on customers. While modules have more or less the same functionality as instance methods on a class, the key difference with module-based libraries is that modules are much more self-contained, much less granular, and tend to have few if any dependencies on other modules.
There's usually no need to subclass objects override methods since you can pass around functions as first-class objects for specialization.
Although C# doesn't support this functionality, functors provide a means to subclass an specialize modules.
Most big libraries tend to be more wide than deep, for example the Win32 API, PHP libraries, Erlang BIFs, OCaml and Haskell libraries, stored procedures in a database, etc. So this style of programming is battle testing and seems to work well in the real world.
In my opinion, the best designed module-based APIs tend to be easier to work with than the best designed OOP APIs. However, coding style is just as important in API design, so if everyone else on your team is using OOP and someone goes off and implements something in a completely different style, then you should probably ask for a rewrite to more closely match your teams coding standards.
What you describe is simply structured programming, as could be done in C, Pascal or Algol. There is nothing intrinsically wrong with that. There are situations were OOP is more appropriate, but OOP is not the ultimate answer and if the problem at hand is best served by structured programming then a class full of static methods is the way to go.
Does it help to rephrase the question:
Can you describe the data that the static methods operates on as an entity having:
a clear meaning
responsibility for keeping it's internal state consistent.
In that case it should be an instantiated object, otherwise it may just be a bunch of related functions, much like a math library.
Here's a refactor workflow that I frequently encounter that involves static methods. It may lend some insight into your problem.
I'll start with a class that has reasonably good encapsulation. As I start to add features I run into a piece of functionality that doesn't really need access to the private fields in my class but seems to contain related functionality. After this happens a few times (sometimes just once) I start to see the outlines of a new class in the static methods I've implemented and how that new class relates to the old class in which I first implemented the static methods.
The benefit that I see of turning these static methods into one or more classes is, when you do this, it frequently becomes easier to understand and maintain your software.
I feel that if the class is required to maintain some form of state (e.g. properties) then it should be instantiated (i.e. a "normal" class.)
If there should only be one instance of this class (hence all the static methods) then there should be a singleton property/method or a factory method that creates an instance of the class the first time it's called, and then just provides that instance when anyone else asks for it.
Having said that, this is just my personal opinion and the way I'd implement it. I'm sure others would disagree with me. Without knowing anything more it's hard to give reasons for/against each method, to be honest.
The biggest problem IMO is that if you want to unit test classes that are calling the class you mention, there is no way to replace that dependency. So you are forced to test both the client class, and the staticly called class at once.
If we are talking about a class with utility methods like Math.floor() this is not really a problem. But if the class is a real dependency, for instance a data access object, then it ties all its clients in to its implementation.
EDIT: I don't agree with the people saying there is 'nothing wrong' with this type of 'structured programming'. I would say a class like this is at least a code smell when encountered within a normal Java project, and probably indicates misunderstanding of object-oriented design on the part of the creator.
There is nothing wrong with this pattern. C# in fact has a construct called static classes which is used to support this notion by enforcing the requirement that all methods be static. Additionally there are many classes in the framework which have this feature: Enumerable, Math, etc ...
Nothing is wrong with it. It is a more "functional" way to code. It can be easier to test (because no internal state) and better performance at runtime (because no overhead to instance an otherwise useless object).
But you immediately lose some OO capabilities
Static methods don't respond well (at all) to inheritance.
A static class cannot participate in many design patterns such as factory/ service locator.
No, many people tend to create completely static classes for utility functions that they wish to group under a related namespace. There are many valid reasons for having completely static classes.
One thing to consider in C# is that many classes previously written completely static are now eligible to be considered as .net extension classes which are also at their heart still static classes. A lot of the Linq extensions are based on this.
An example:
namespace Utils {
public static class IntUtils {
public static bool IsLessThanZero(this int source)
{
return (source < 0);
}
}
}
Which then allows you to simply do the following:
var intTest = 0;
var blNegative = intTest.IsLessThanZero();
One of the disadvantages of using a static class is that its clients cannot replace it by a test double in order to be unit tested.
In the same way, it's harder to unit test a static class because its collaborators cannot be replaced by test doubles (actually,this happens with all the classes that are not dependency-injected).
It depends on whether the passed arguments can really be classified as state.
Having static methods calling each other is OK in case it's all utility functionality split up in multiple methods to avoid duplication. For example:
public static File loadConfiguration(String name, Enum type) {
String fileName = (form file name based on name and type);
return loadFile(fileName); // static method in the same class
}
Well, personnally, I tend to think that a method modifying the state of an object should be an instance method of that object's class. In fact, i consider it a rule a thumb : a method modifying an object is an instance method of that object's class.
There however are a few exceptions :
methods that process strings (like uppercasing their first letters, or that kind of feature)
method that are stateless and simply assemble some things to produce a new one, without any internal state. They obviously are rare, but it is generally useful to make them static.
In fact, I consider the static keyword as what it is : an option that should be used with care since it breaks some of OOP principles.
Passing all state as method parameters can be a useful design pattern. It ensures that there is no shared mutable state, and so the class is intrinsicly thread-safe. Services are commonly implemented using this pattern.
However, passing all state via method parameters doesn't mean the methods have to be static - you can still use the same pattern with non-static methods. The advantages of making the methods static is that calling code can just use the class by referencing it by name. There's no need for injection, or lookup or any other middleman. The disadvantage is maintanability - static methods are not dynamic dispatch, and cannot be easily subclassed, nor refactored to an interface. I recommend using static methods when there is intrinsicly only one possible implementation of the class, and when there is a strong reason not to use non-static methods.
"state of a class is ...passed around amongst static methods using arguments?"
This is how procedual programming works.
A class with all static methods, and no instance variables (except static final constants) is normally a utility class, eg Math.
There is nothing wrong with making a unility class, (not in an of itself)
BTW: If making a utility class, you chould prevent the class aver being used to crteate an object. in java you would do this by explictily defining the constructor, but making the constructor private.
While as i said there is nothing wrong with creating a utility class,
If the bulk of the work is being done by a utiulity class (wich esc. isn't a class in the usual sense - it's more of a collection of functions)
then this is prob as sign the problem hasn't been solved using the object orientated paradim.
this may or maynot be a good thing
The entrance method takes several arguments and then starts calling the other static methods passing along all or some of the arguments the entrance method received.
from the sound of this, the whole class is just effectivly one method (this would definatly be the case is al lthe other static methods are private (and are just helper functions), and there are no instance variables (baring constants))
This may be and Ok thing,
It's esc. structured/procedual progamming, rather neat having them (the function and it's helper)all bundled in one class. (in C you'ld just put them all in one file, and declare the helper's static (meaning can't be accesses from out side this file))
if there's no need of creating an object of a class, then there's no issue in creating all method as static of that class, but i wanna know what you are doing with a class fullof static methods.
I'm not quite sure what you meant by entrance method but if you're talking about something like this:
MyMethod myMethod = new MyMethod();
myMethod.doSomething(1);
public class MyMethod {
public String doSomething(int a) {
String p1 = MyMethod.functionA(a);
String p2 = MyMethod.functionB(p1);
return p1 + P2;
}
public static String functionA(...) {...}
public static String functionB(...) {...}
}
That's not advisable.
I think using all static methods/singletons a good way to code your business logic when you don't have to persist anything in the class. I tend to use it over singletons but that's simply a preference.
MyClass.myStaticMethod(....);
as opposed to:
MyClass.getInstance().mySingletonMethod(...);
All static methods/singletons tend to use less memory as well but depending on how many users you have you may not even notice it.

Should a c# class generate instances of itself?

I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file.
I added a static method to my class CallRate that returns a List<CallRate>. Is it ok for a class to generate new instances of itself by calling one of its own constructors? It works, I just wonder if it's the proper thing to do.
List<CallRates> cr = CallRates.ProcessCallsFile(file);
It is perfectly fine to get object(s) of its own from the static method.
e.g.
One of the dot net libraries does the same thing as you did,
XmlReadrer reader = XmlReader.Create(filepathString);
Sure that's fine, even encouraged in some instances. There are several design patterns that deal with object creation, and a few of them do just what you're describing.
I often use this pattern when I need to check the validity of parameters. It is strongly discouraged to throw an exception from a constructor. It's not so bad from a factory method, or you can choose to return null.
Seems fine to me. In other languages you would probably write a function, but in a language like C#, static methods take up that role.
It is ok. What you just created is something like a simple factory method. You have a static method that creates a valid instance of a type. Actually your method doesn't even have to be static and you still have a valid code. There is a design pattern (Prototype) that creates a new valid object from an existing object. See details at http://www.dofactory.com/Patterns/PatternPrototype.aspx.
Sure, for simple parsing (or similar) scenarios - I actually prefer the factory method be part of the class. Yes - it does break SRP, but it fulfills KISS - so I call it a net win. For larger apps, or more complicated parsing routines - it makes more sense to have it be an external factory class.
For your particular case, I'd probably prefer a method that took in an IEnumerable<string> instead of a filename - that'd still give you the parsing logic, but allow easy unit tests and "reuse". The caller can wrap the file into an IEnumerable easily enough.
Factory methods are often a good design. When I write them in C#, I call them 'New', so that:
new MyClass()
becomes
MyClass.New()
Trivially it's implemented like this:
class MyClass
{
public static MyClass New()
{
return new MyClass();
}
}
Mostly I do this when there are additional conditions about whether to actually create the class or just return null, or whether to return MyClass or something derived from it.
I sometimes use public static methods as an alternative to constructor overloading.
Especially in situations where it is not nice to rely on parameter types alone to indicate what kind of object construction is intended.
I'm a fan of having static methods return instances, as suggested plenty of times, above.
#Paul: don't forget to tick the comment above, which you find is the best answer.
Just like to point out
"generate new instances of itself by calling one of its own constructors"
It is not from the constructor, it is from the static method.
I generally use this when I need instant implementations of a class. For example
public class Car
{
public static Car RedExpensiveCar = new Car("Red", 250000);
public Car()
{
}
public Car(string color, int price)
{
Color = color;
Price = price;
}
public string Color { get; set; }
public int Price { get; set; }
}
And with this, I don't need to remember or write constructor parameters in my code.
Car car = Car.RedExpensiveCar;
It's perfectly acceptable to do this. When I do, I typically make the real constructors for the class private so that it's clear that the only way to construct instances is through the static method.
This is very useful in cases where "construction" may not always return a new instance. For example, you may want to return a previously cached object instead.

Static methods vs instance methods in C#

For an application I am writing, I want to have extreme extensibility and extension methods seem to give me what I want, plus the ability to call them without an instance, which I need too.
I remember reading that static methods are faster than instance methods but don't get the advantages of GC. Is this correct?
It's highly unlikely I will change my design unless I find a superior alternative by design not speed. But still for extra information I wanna know the differences in speed, GC, etc.
EDIT: Thanks. More info: Let's say we have a Person class:
class Person
which can have an instance Distance method so like:
this.Distance (Person p)
This is great, but this doesn't give me the ability to calculate the distance between 2 points (say Point3), without creating instances of the Person class.
What I want to do is this:
class Person (no Distance methods)
but extension methods of Distance:
Distance (this Person, Person)
Distance (this Point3, Point3)
This way I can both do:
myPerson.Distance (yourPerson)
and
Extensions.Distance (pointA, pointB)
EDIT2: #Jon, yeah I think that was what was meant by (don't get the advantages of GC), but I somehow thought that the static methods create this burden/overhead.
Choosing between static and instance methods is a matter of object-oriented design. If the method you are writing is a behavior of a an object, then it should be an instance method. If it doesn't depend on an instance of an object, it should be static.
Basically, static methods belong to a type while instance methods belong to instances of a type.
What do you mean by "don't get the advantages of GC"? Methods aren't garbage collected - instances are.
Virtual methods are slightly slower than non-virtual ones, and I guess there's that pesky null check before any instance method, but it's not significant. Go with the most appropriate design.
Static methods are a pain for testing though - for instance, if you authenticate in method Foo() by calling some static method, then when you're testing Foo() you can't make it just call a mock authenticator (unless the static method itself lets you do that). If you give the original instance of whatever you're testing a mock implementation of some interface containing an Authenticate() method, however, you can make it behave however you want.
EDIT: In this case, it sounds like what you really need is an instance method on your Point type to calculate the distance between two points ("this" one and another) - or potentially a static factory method on the Distance type.
If by being faster you mean the code inside the method is executed faster, then no. A code in a static method is just as fast as code in a non static method.
If your are talking about the overhead of performing the call to the method it becomes a little more complex. It is common for languages as Java that instance calls have more overhead. In C# this is not the case however because instance methods are not virtual by default.
So a virtual method has slightly more overhead than a non virtual method. Static methods cannot be virtual, but instance methods can be declared virtual.
As for Garbage collection, this is mainly relevant for fields, not methods. Static fields can be accessed from everywhere in the code so the garbage collector can't determine if the reference will be used again, so it is never collected.
Based on your example, I would write a static utility function to find the distance between two points:
public static class Geometry
{
public static double GetDistanceBetween(Point a, Point b) { ... }
}
And then I would give Person a property called Position that returned a point. So I could write:
double distance = Geometry.GetDistanceBetween(personA.Position, personB.Position);
It's practically in English already - why make it more obscure? If you make Distance a method, then you can write:
personA.Distance(personB)
or:
personB.Distance(personA)
There's no difference between those two orderings, and yet the use of method-call syntax suggests that there might be a difference.

Categories

Resources