I found that there are two type of methods called static methods and instance methods and their differences.
But still I couldnt understand the advantages of one over another.
Sometimes i feel that static methods are not 100% object oriented.
Are there any performance differences between this two.
Can someone help?
In a perfect OO world there probably wouldn't be any need for static methods (I think Eiffel doesn't have them, either). But at the end of the day what matters is not OO-pureness of your code (C# has enough concepts that aren't strictly pure OO, like extension methods, for example) but rather what you're getting done.
You can use static methods for general helper methods (that don't need a general helper class or state on their own) or things like Color.FromARGB() which behave slightly contructor-like for value types.
In general, any method that doesn't touch an objects state (and therefore is more class-specific than object-specific) can be made static. Performance differences shouldn't really arise. Not very measurable, in any case. Jan Gray's great article Writing faster managed code: Know what things cost has some hard data on this, albeit to be taken with care.
The usefulness of a static method primarily comes when you need to call the method without ever instantiating the object. For example, maybe the static method is there to actually look up an existing instance and return it (an example being a singleton instance).
As others have stated, you can make any method static if it doesn't access state, and you'll get a tiny performance improvement.
If you actually want to be able to call the method on a specific instance though, and get the benefits of polymorphism (i.e. a derived class can override the behaviour of the method), then you should make the it an instance method.
If your classes implement interfaces, then the methods belonging to those interfaces must also be declared as instance methods.
Instance methods are tight to an instance. So you could see one advantage of static methods is not being tight to an instance. Static methods can (if visible) used by other objects to solve their problems. Sometimes this good and needed. Then you have to think about keeping your static methods in the same class or if you start building utility classes for broader use.
I wouldn't see the use of static methods of being "less OO". Static methods is one way to circumvent the shortcomings of OO (especially in single inheritance languages). You can call it a more functional approach (I know it isn't really).
Taking all this is just a bunch of questions that you should ask your code and that should determine if it is better an instance method, a static method of the same class or a static method of another class.
I wouldn't even think about performance issues. It will weaken your design and the difference isn't really that big. Performance is important if you have performance problems.
Instance methods require passing an implicit parameter (the this reference) which make them slightly slower than static methods. But that really should not be the reason to prefer them.
For a related discussion, look at:
Should C# methods that *can* be static be static?
If your method uses non-static data members, don't make it static (you "can't").
If your method does not use any non-static data members, you can make it static, but that mostly depends on your design rather than on whether it uses or not uses non-static members (there's not much difference in performance anyway as Mehrdad said).
If you have NO non-static data members in your class, sometimes it's a best practice to make all the methods static (like in the case of grouping helper functions under one class for the sake of good order).
I'm partially guessing based on the heritage of C# but I suspect it's the same as the other OO languages.
Static methods do not require an object to work on. A good example is something like:
Double pi = Math.PI.
Instance methods do require an object. An example is along the lines of:
Integer x = 9;
Integer y = x.sqrt();
Not all information belonging to a class should need an object instantiated for that class to get access to it. All those constants which can be used for creation of objects (Math.PI, Window.OVERLAPPED, etc) are prime examples of this.
No one is better than the other. It really depends on your requirement. Class methods are called when you want to apply a change to class as a whole. Whereas Instance methods are called when you are not applying change to the class but to a unique instance (object) of that class.
So I dont see a reason why one should be better than the other.
Related
Straight up question: If I run code analysis, it tells me to make methods static even in nonstatic classes.
As far as I know, static methods are JITed and run on the Type-Object in the Heap. So wouldn't make a method static in a non static class mean, that the instance has to search the type object in the Heap and run the method there?
Wouldn't that mean a performance issue? Sure it would not be that big of a deal, but I'd still be interested on this.
No, it doesn't work like that.
A static method is actually (imperceptibly) more efficient than a non-static one because (a) it does not have a hidden "this" pointer passed to it and (b) because it's static, the framework doesn't have to do anything about it being virtual (although that last point also applies to non-virtual member methods too, of course).
Here is an in-depth article about CLR runtime type handling. In particular, look at the information there about the MethodTable and the Method Slot Table.
Here's another good article from Joe Duffy. It doesn't explicitly talk about static methods, but it does explain how method calls are made at the lowest (assembler) level, so you would be able to see why a static method call is efficient.
Good post about performance comparsion of static methods vs instance methods: Performance of static methods vs instance methods
TLDR:
Mostly the performance costs of instance vs static are below
negligible.
What costs there are will generally come where you abuse
static for instance or vice-versa. If you don't make it part of your
decision between static and instance, you are more likely to get the
correct result.
There are rare cases where static generic methods in another type
result in fewer types being created, than instance generic methods,
that can make it sometimes have a small benefit to turn rarely used
(and "rarely" refers to which types it's used with in the lifetime of
the application, not how often it's called). Once you get what he's
talking about in that article you'll see that it's 100% irrelevant to
most static-vs-instance decisions anyway.
I think the point is that you're not calling a static method upon an instance, but on the class itself. Any method that does not directly rely on instance information could (and based upon code analysis also should) be marked static and then be called like this:
NonstaticClass.TheStaticMethod();
instead if this
NonstaticClass inst = new NonstaticClass();
inst.TheStaticMethod();
This is because less overhead is required to look up and run a static method than a non-static method on a class instance.
I'm new to c sharp and programming generally. I have a quick question - what is best practise with regards to static/non static variables.
I have a variable,private int x, which belongs to class y. To access this variable, i need to reference y. If x was static however, i can access this variable with no references to y.
Which is the best way to go, in a situation whereby several methods within the class y will be referencing this value ?
Hope this makes sense, and my question isn't too basic !
Many thanks
You need to think about static variables as belonging to the class, not to instances of the class.
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
In general having public static variables is bad practice - it is a shared global resource and if you change it you need to synchronize access to it. Having global state is something you want to avoid as much as possible.
Best practice is to avoid public static. In OOP, class is meant to hide its members. Static is actually not a member of the instance but of the type.
Static comes handy if you are implementing singleton pattern. But then again they need to be made private and accessible through a public property.
You need to read Static Classes and Static Class Members (C# Programming Guide).
Well I can't conclusively say that one is better, because they serve different purposes.
Are you familiar with OOP? In OOP, static objects or members of a class that can be accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.
C# follows a similar principle for the methods. The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore impractical (see below).
In OOP, static variables are used for values which cannot be stored by an instance variable. Example: supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?
The methods use a similar principle. They should be used for procedures for which it is impractical to do within an instance of a class. I tend to use them for broad procedures (not a technical term), meaning those that do not require me to instantiate an object. Example, adding two parameters. (This usage may or may not be correct, but I believe it is)
However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon realize, static methods cannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class the get these from unless it were told, since it is not part of an instance itself)
For the sake of no further complicating things, I'll stop here. Let me know if you misunderstood anything.
Your choice depends on your architecture.
Static makes part of a Type, others make part of an instance of that type. If you want have some shared state (say) between different instances of the same type, use static. If you want that every instance have it's own value, independent from others, use instance fields.
In both cases, by the way, avoid to expose like a public fields, but use properties.
I completely agree with Mr Oded:
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
Yes, adding static to a class member basically means you can access it without an instance, and only outside any instance. And yes, it becomes a global resource, or even a global variable if you will.
But I think there's at least another (heavily edited) good point to be made here...
Using static members as global vars go against OOP
This means once you set a static member you can't pass it around as an object. The more you use static as global var, the more difficult it is for unit testing / mocking classes.
There is a solution for that, Singletons. But they should never come without warnings!
At other hand, if you're sure you really need global vars, take a look at the Toolbox pattern. It's a not well known extension of Singleton pattern. It's so unknown in fact, if you google for it you won't find it with those keywords (toolbox pattern).
So plan ahead. Read more. Get to know about every option so you can decide better. Even get a book. Object Oriented Programming is more about applying concepts that will help in the long run than just making things work now.
In general if you want to have a variable public, either static or instance, you must wrap it in a property and expose it like that. This is for sure a principle that you will love to follow.
But despite some of the other answers I cannot say don't use static. Static is not the devil that you should avoid in any case. What you have to do will decide if you are going to use static or not, as long as you keep your program clean and easy to maintain.
Easily speaking, and not in the language of the elders, static stands for something that don't belong to any instance of this class but has an effect on them. An example of a static property in a class that generates instances is for example a factor, which should be global for all instances of the class, to take part in a calculation that is done inside instances. To this case, and to my opinion, it is better to have this factor declared as static rather that have it in every single instance. Especially if this factor changes in the lifetime of your program to affect the next calculation.
You need to ask a question to youself: why I need x to be static?
If you make x static it means that x is a part of all objects of class A, but when x is not static it means, than x is a part only of one object.
In geleral using of static fields is painfull for bug tracking, but in some cases this is very helpfull.
I suggest you to look in using of singelton http://en.wikipedia.org/wiki/Singleton
Obviously there can't be an instance member on a static class, since that class could never be instantiated. Why do we need to declare members as static?
I get asked questions like this all the time. Basically the question boils down to "when a fact about a declared member can be deduced by the compiler should the explicit declaration of that fact be (1) required, (2) optional, or (3) forbidden?"
There's no one easy answer. Each one has to be taken on a case-by-case basis. Putting "static" on a member of a static class is required. Putting "new" on a hiding, non-overriding method of a derived class is optional. Putting "static" on a const is forbidden.
Briefly considering your scenario, it seems bizarre to make it forbidden. You have a whole class full of methods marked "static". You decide to make the class static and that means you have to remove all the static modifiers? That's weird.
It seems bizarre to make it optional; suppose you have a static class and two methods, one marked static, one not. Since static is not normally the default, it seems natural to think that there is intended to be a difference between them. Making it optional seems to be potentially confusing.
That leaves making it required, as the least bad of the three options.
See http://blogs.msdn.com/b/ericlippert/archive/2010/06/10/don-t-repeat-yourself-consts-are-already-static.aspx for more thoughts on these sorts of problems.
Because by definition, all of their members must be static. They decided not to give some confusing syntactic sugar.
I would go one step further and ask: Why does C# have static classes at all? It seems like a weird concept, a class that's not really a class. It's just a container, you can't use it to type any variables, parameters or fields. You also can't use it as a type parameter. And of course, you can never have an instance of such a class.
I'd rather have modules, like in VB.NET and F#. And then, the static modifier would not be necessary to avoid confusion.
It could be implicit, but also it would complicate code reading and lead to confusions.
Richard,
Hmmmm... I'd guess that the language designers decided that it would be better to be very, very explicit... to avert any possible confusion when a maintainer, who doesn't know the code, jumps into the middle of a static class, and presumes that they are in a "normal" instance context.
But of course, that's just a guess. Most IDE's help you out there anyway, by adding the static modifier "automagically"... or at least highlighting your mistake at "write time", as apposed to "compile time".
It's a good question... unfortunately not one with a "correct" answer... unless someone can turn up a link from a C#-language-designers blog (or similar) discussing this decision. What I can tell you is: "I'd bet $1,000 that it's no accident."
Cheers. Keith.
Explicit coding makes things maintainable
If I want to copy a method from one class to another, so that code is better organized, then I would have to keep cheking a lot of things all the time, just in case the destination class is or is not static.
By declaring the member as static, you also have a visual indication of what the code is, when you see it.
It is also less confusing. Imagine a class that is static, and inside it has got members marked as static, and others not marked.
I can see lots of reasons, and many other reasons exist.
One reason I would think it is important to explicitly state it is a static is because in a multi-threaded programming model, these static variables are shared by multiple threads. When doing code review or code analysis, it is much easier to pick up this importance from reading the variable, instead of looking up the class declaration, and determine if the variables are static or non-static. It can get pretty confusing when reading variable during code review if you don't know if the class is static or non-static.
This is because copy-paste would be more complicated.
If you copy a method from a static class to a non-static class then you would have to add the static keyword.
If you copy a method from a non-static class to a static class you would have to remove the static keyword.
Moving methods around is the primary thing developers do ('I need to refactor this code, it will take a week at least'), and by making it easier Eric and his team allowed us to save hours of work.
I recall reading an article about constructors being evil (but can't place it). The author mentioned that constructors are a special case of methods; but have restrictions (such as that they cannot have a return value).
Are constructors evil? Is it better to have no constructors and instead rely on a method like Initialize, along with default values for member variables?
(Your answer can be specific to C# or Java, if you must pin down a language.)
That sounds like Allen Holub. One might argue that constructors are evil solely to drive web traffic :) They are no more evil than any other language construct. They have good and bad effects. Of course you can't eliminate them -- no way to construct objects without them!
What you can do, though, and this is the case that Allen was making, is you can limit your actual invocation of them, and instead favor, when sensible, factory methods like your Initialize. The reason for this is simple: it reduces coupling between classes, and makes it easier to substitute one class for another during testing or when an application evolves.
Imagine if your application does something like
DatabaseConnection dc = new OracleDatabaseConnection(connectionString);
dc.query("...");
and imagine that this happens in a hundred places in your application. Now, how do you unit test any class that does this? And what happens when you switch to Mysql to save money?
But if you did this:
DatabaseConnection dc = DatabaseConnectionFactory.get(connectionString);
dc.query("...");
Then to update your app, you just have to change what DatabaseConnectionFactory.get() returns, and that could be controlled by a configuration file. Avoiding the explicit use of constructors makes your code more flexible.
Edit: I can't find a "constructors" article, but here's his extends is evil one, and here's his getters and setters are evil one.
They aren't. In fact, there is a specific pattern known as Inversion of Control that makes ingenious use of Constructors to nicely decouple code and make maintenance easier. In addition, certain problems are only solvable by using non default constructors.
Evil? No.
Calling a constructor does require that you call "new", which does tie you to a particular implementation. Factories and dependency injection allow you to be more dynamic about runtime types, but they require programming to interfaces.
I think the latter are more flexible, but constructors evil? That's going too far, just like having an iterface for everything goes too far.
Constructors aren't evil, but (at least in Java) often it's better to use static Factory methods instead (which of course use constructors internally).
Here are a few quotes From Effective Java, Item 1: Consider static factory methods instead of constructors:
One advantage of static factory
methods is that, unlike constructors,
they have names. If the parameters to
a constructor do not, in and of
themselves, describe the object being
returned, a static factory with a
well-chosen name is easier to use and
the resulting client code easier to
read.
...
A second advantage of static factory
methods is that, unlike constructors,
they are not required to create a new
object each time they’re invoked. This
allows immutable classes (Item 15) to
use preconstructed instances, or to
cache instances as they’re
constructed, and dispense them
repeatedly to avoid creating
unnecessary duplicate objects.
...
A third advantage of static factory
methods is that, unlike constructors,
they can return an object of any
subtype of their return type.
...
A fourth advantage of static factory
methods is that they reduce the
verbosity of creating parameterized
type instances. Unfortunately, you
must specify the type parameters when
you invoke the constructor of a
parameterized class even if they’re
obvious from context. This typically
requires you to provide the type
parameters twice in quick succession:
Map<String, List<String>> m =
new HashMap<String, List<String>>();
...
The main disadvantage of providing
only static factory methods is that
classes without public or protected
constructors cannot be subclassed.
...
A second disadvantage of static
factory methods is that they are not
readily distinguishable from other
static methods.
Constructors allow initialization lists and other useful things. There's no way to dynamically initialize an object in an array (that doesn't use pointers to objects) without a copy constructor.
No they aren't evil.
They are special cases.
Constructors are not evil. They exist so that code can be run when an instance of a class is initialized. Just as with any other programming concept, if they aren't used right they can be a disaster to work with. But, if used correctly, they can be a great (and essential) tool.
http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)
I wouldn't say constructors are evil.
Constructors return a reference to the Object you are instantianting and should be used to set an object up to a default state. I can see benefits of using an Initialize method but there isn't much point. UNLESS you need to initialize some logic AFTER the object has been allocated stack space and initial values.
Constructors are not evil. Whatever article you read is wrong and you're better off having forgotten the link.
Constructors are not evil nor are they good. Constructors are a tool that can be very helpful if used properly and in the correct context. In fact at least in .NET languages such as C# if you do not explicitly declare a constructor in your code a constructor will be created for you by the compiler with no functionality.
Constructors are good when following normal OO programming paradigms. There are situations where you might need to place extra constraints on how objects are created, so in some cases a Factory pattern with private ctors might be a better fit. There is also a philosophy/best practice that says object instantiation should be the same as initialization, in which case constructors are the only real option outside factories that you have.
(factories still use constructors internally of course)
The question may not be about constructors in Java or C#, but constructors in javascript. In Javascript constructors can be a source of subtle errors. A lot of Javascript books recommend that beginners steer clear of constructors.
For a more detailed discussion of the evilness of constructors, and the new keyword, in javascript look : Is JavaScript's "new" keyword considered harmful?
I picked up this sort of vibe, to a degree, from Miško Hevery's talk "Don't look for things" which is available on YouTube. Part of the outlining discussion he gives, I interpret as a criticism of 'fat constructors', if not constructors in general.
The point of this argument, at least as I understood it, was that constructors that take in everything the object wants encourage you to enforce correctness using the constructor, instead of enforcing correctness with tests. Constructors do tend to bloat to do exactly that, so if this bothers you, you could consider it an evil streak in the concept of the constructor. In the talk he says he prefers to only require an object to 'have' another object when it's needed to do something, rather than requiring it on construction.
Here's one article that considers whether constructors are harmful, not "evil". It's mostly in the context of JavaScript/Es6 but the arguments may hold for any language which has constructors.
The argument is really about user-defined constructors, you still need to call the system provided default constructors, else you could not create any instances at all.
The simplest argument is that if you can do the same thing with static methods as with custom constructors, isn't it better to choose one of the approaches and always stick to that, except if there is a specific reason not to.
That makes your program simpler in total and thus less error-prone. Note that Smalltalk never had "constructors".
https://medium.com/#panuviljamaa/constructors-considered-harmful-c3af0d72c2b1
Is there a best practice for making private methods in classes static? I have a class with a few methods. Some of these can easily be made static, since they simply process data.
Should I make them static or just leave them as is? Is this more of a style issue? Are there performance considerations?
Edit:
Method can be made static, but should it?
If the methods don't access any of the type's state then they should be static.
Static method calls provide a performance gain over instance methods and the presence of a static method tells future readers of your code that calling this method will create no side effects in the the state of the current instance of the type.
The performance gain of a static method comes from the fact that the compiler does not have to emit callvirt instructions to call a static method. The callvirt instruction is handy for instance calls in that it does a null check prior to calling the method. However, when you call a static methods there is no need to check for null so the compiler is free to emit the faster call instruction which doesn't check for null.
As Dan Diplo says, if they can be made static, they should be made static. This is only true for private static methods (which is what you asked about). For public methods, however, they will just confuse users of your class. Public methods should be made static only if they will be used without an instance of the class by callers, the performance loss of not making them static be damned.
I always think if they can be made static (and the compiler will soon let you know if they can't) then they should be made so. See this duplicate question on SO for further discussion.
I only make methods static when i am sure that they don't have any side effects.
If a method doesn't use any instance data in the class, it should be static. That way it's clear that it's independent of the instances, and that you don't have to create an instance to call it.
Any performance differences should not be a concern. There is of course a difference in how a static method and an instance method are called, but you will most likely not be able to measure any consistent performance difference. The difference is so small that sometimes calling an instance method might actually be faster just because the instructions happens to line up better in the execution.
I agree that all private methods that can be static should be static. Just remember the performance variation between the 2 are insignificant so don't do this in an attempt to increase performance since early optimization is likely to cause more failures than successes until you know for sure you have a performance issue and profile your application.
Think about the static methods and multi-threading. You must be very careful.
This discusion is like pattern definition: "a solution for a problem in some context.".
You must not say "This should be done like this." It depends of the context.
If you have a private method that is static, that smells like it could be a method that shouldn't be in the class at all, but should rather be in a library of static methods that can be reused by other classes.