Why aren't methods in static classes implicitly static [duplicate] - c#

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.

Related

Static methods/class vs non static [duplicate]

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

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.

What are the gains of converting normal method to static?

As it is clear from question, if I convert a normal method to static what gains will I made?
You will gain clarity, because static makes it clear that the method doesn’t depend on an object state. You will also facilitate reusability because static methods may be used in more contexts (i.e. when you don’t have an instance of the class).
In general, it’s not really a question of gain, it’s a question of semantics: does your method depend on the object state? If so, make it non-static. In all other cases, make it static.
Apart from the semantic reasons mentioned above, static methods are generally faster (due to not having to create an object to call the method). They are subject to compile-time optimisations and as far as I recall, the CLR also performs some special optimisations on them.
Static function normally used for utility stuffs like ConverThisTypeToThatType(), and you can call them without having object of its class.
Ex: MessageBox.Show("Something");
here MessageBox is a Class and Show is static method in it, so we dont need to create object of MessageBox to call Show.

Should C# methods that *can* be static be static? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Should C# methods that can be static be static?
We were discussing this today and I'm kind of on the fence. Imagine you have a long method that you refactor a few lines out of. The new method probably takes a few local variables from the parent method and returns a value. This means it could be static.
The question is: should it be static? It's not static by design or choice, simply by its nature in that it doesn't reference any instance values.
It depends.
There are really 2 types of static methods:
Methods that are static because they CAN be
Methods that are static because they HAVE to be
In a small to medium size code base you can really treat the two methods interchangeably.
If you have a method that is in the first category (can-be-static), and you need to change it to access class state, it's relatively straight forward to figure out if it's possible to turn the static method into a instance method.
In a large code base, however, the sheer number of call sites might make searching to see if it's possible to convert a static method to a non static one too costly. Many times people will see the number of calls, and say "ok... I better not change this method, but instead create a new one that does what I need".
That can result in either:
A lot of code duplication
An explosion in the number of method arguments
Both of those things are bad.
So, my advice would be that if you have a code base over 200K LOC, that I would only make methods static if they are must-be-static methods.
The refactoring from non-static to static is relatively easy (just add a keyword), so if you want to make a can-be-static into an actual static later (when you need it's functionality outside of an instance) then you can. However, the inverse refactoring, turning a can-be-static into a instance method is MUCH more expensive.
With large code bases it's better to error on the side of ease of extension, rather than on the side of idealogical purity.
So, for big projects don't make things static unless you need them to be. For small projects, just do what ever you like best.
I would not make it a public static member of that class. The reason is that making it public static is saying something about the class' type: not only that "this type knows how to do this behavior", but also "it is the responsibility of this type to perform this behavior." And odds are the behavior no longer has any real relationship with the larger type.
That doesn't mean I wouldn't make it static at all, though. Ask yourself this: could the new method logically belong elsewhere? If you can answer "yes" to that, you probably do want to make it static (and move it as well). Even if that's not true, you could still make it static. Just don't mark it public.
As a matter of convenience, you could at least mark it internal. This typically avoids needing to move the method if you don't have easy access to a more appropriate type, but still leaves it accessible where needed in a way that it won't show up as part of the public interface to users of your class.
Not necessarily.
Moving public methods from static to non-static is a breaking change, and would require changes to all of your callers or consumers. If a method seems like an instance method, but happens to not use any instance members, I would suggest making it an instance method as a measure of future-proofing.
Yes. The reason "it can be static" is that it does not operate on the state of the object upon which it is called. Therefore it is not an instance method, but a class method. If it can do what it needs to do without ever accessing the data for the instance, then it should be static.
Yes, it should. There are various metrics of coupling that measure how your class depends on other things, like other classes, methods, etc. Making methods static is a way to keep the degree of coupling down, since you can be sure a static method does not reference any members.
I think it would make it a bit more readable if you marked it as static...Then someone who comes along would know that it doesn't reference any instance variables without having to read the entire function...
Personally, I'm a great fan of statelessness. Does your method need access to the state of the class? If the answer is no (and it is probably no, otherwise you wouldn't consider making it a static method), then yeah, go for it.
No access to state is less headache. Just as it is a good idea to hide private members that are not needed by other classes, it is a good idea to hide the state from members that don't need it. Reduced access can mean less bugs. Also, it makes threading easier as it is much easier to keep static members thread-safe. There is also a performance consideration as the runtime does not need to pass a reference to this as a parameter for static methods.
Of course the downside is that if you ever find that your previously static method will have to access the state for some reason, then you have to change it. Now I understand that this can be a problem for public APIs so if this is a public method in a public class, then perhaps you should think about the implications of this a bit. Still, I've never faced a situtation in the real world where this actually caused a problem, but maybe I'm just lucky.
So yeah, go for it, by all means.
Static methods are faster than the non-static ones so yes, they should be static if they can and there is no special reason for leaving them nonstatic.
I am surprised that so few are mentioning encapsulation here in fact. An instance method will automatically have access to all private (instance) fields, properties and methods. In addition to all protected ones inherited from base classes.
When you write code you should write it so that you expose as little as possible and also so that you have access to as little as possible.
So yes, it might be important to make your code fast which would happen if you're making your methods static, but usually more important then that is to make your code as incapable of creating bugs as possible too. One way to achieve that is to have your code have access to as little as possible of "private stuff".
This might seem irrelevant at first glance since the OP is obviously talking about refactoring which can not go wrong in this scenario and create any new bugs, however this refactored code must be maintained in the future and modified which makes your code have a bigger "attack surface" in regards to new bugs if it has access to private instance members. So in general I think the conclusion here is that "yes mostly your methods should be static" unless there are any other reasons for not having them static. And this simply because it's "better use of encapsulation and data hiding and creates 'safer' code"...
Making something static just because you can is not a good idea. Static methods should be static due to their design, not due to happenstance.
Like Michael said, changing this later will break code that's using it.
With that said, it sounds like you are creating a private utility function for the class that is, in fact, static by design.
If you were able to refactor a few lines out and the resulting method could be static, it is probably an indication that the lines you pulled out of that method don't belong in the containing class at all, and you should consider moving them into their own class.
It depends but generally I do not make those methods static. Code is always changing and perhaps someday I will want to make that function virtual and override it in a subclass. Or perhaps some day it will need to reference instance variables. It will be harder to make those changes if every call site has to be changed.
Personally I would have no choice but to make it static. Resharper issues a warning in this case and our PM has a rule "No warnings from the Resharper".
Inherently static methods that are for some reason made non-static are simply annoying. To wit:
I call my bank and ask for my balance.
They ask for my account number. Fair enough. Instance method.
I call my bank and ask for their mailing address.
They ask for my account number. WTF? Fail—should have been static method.
I suggest that the best way to think about it is this: If you need a class method that needs to be called when no instances of the class are instantioated, or maintains some kind of global state, then static is a good idea. But in general, I suggest you should prefer making members non-static.
You should think about your methods and classes:
How are you going to use them?
Do you need a lot of acces to them from different levels of your code?
Is this a method/class I can use in almost every thinkable project.
If the last two are 'yes', then your method/class should probably be static.
The most used example is probably the Math class. Every major OO language has it and all the methods are static. Because you need to be able to use them anywhere, anytime, without making an instance.
Another good example is the Reverse() method in C#.This is a static method in the Array class. It reverses the order of your array.
Code:
public static void Reverse(Array array)
It doesn't even return anything, your array is reversed, because all arrays are instances of the Array class.
As long as you make the new method private static it is not a breaking change. In fact, FxCop includes this guidance as one of its rules (http://msdn.microsoft.com/en-us/library/ms245046(VS.80).aspx), with the following information:
After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
That being said, the first comment from David Kean more succinctly summarizes the concerns by saying this is actually more about being correct than about the performance gain:
Although this rule is classified as a performance issue, the performance improvement of making a method static is only around 1%.
Rather, it is more a correctness issue that could indicate an either an incomplete or a bug in the member by its failure to use other instance members. Marking a method static (Shared in Visual Basic) makes it clear on its intention not to touch instance state.
I would definitely turn anything I can into static for a different reason:
Static functions, when JIT'd, are called without a "this" parameter.
That means, for example, that a 3 parameter non-static function (member method)
gets pushed with 4 params on the stack.
The same function compiled as a static function would get called with 3 parameters.
This can free up registers for the JIT and conserve stack space...
I'm in the "only make private methods static" camp. Making a public method can introduce coupling that you don't want and may decrease testability: You can't stub a public static method.
If you want to unit test a method that uses a public static method, you end up testing the static method as well, which might not be what you want.
I look at it generally from a functional perspective of pure functions. Does it need to be an instance method? If not, you may benefit from forcing the user to pass in the variables and not mangling the current instance's state. (Well, you could still mangle state, but the point is to, by design, not do so.) I generally design instance methods as public members and do my best to make private members static. If necessary (you can then more easily extract them into other classes later.
In those cases, i tend to move the method to a static or utils library, so i don't be mixing the concept of the "object" with the concept of "class"

When to use static variables?

I'm currently doing a project in C# with a lot of rendering, and throughout almost all the classes there's a constant value of the type integer being used for scaling of the rendering. I know I could define this constant in one place as a normal variable and then pass it around, but this seemes really cumbersome. When is it acceptable to use static variables in C#? The easiest solution to my problem would be to create a class containing the static variable that all the other classes could reference - would that be bad design?
How constant is the value? static is fine for things that are readonly, but you can quickly get into a mess if it isn't readonly - especially if you have multiple threads. The scaling factor doesn't sound like a hard constant to me - i.e. it isn't:
public const double ScaleFactor = 1;
I wouldn't hesitate to use a static variable for something I load once and leave alone. Other than that, I'd probably encapsulate (in your case) some kind of RenderContext with this value and any other utility methods - and pass the RenderContext between methods; this can also help you abstract away from the underlying implementation if you need to unit test, etc.
As you find you need more properties (and you inevitably will), you just extend the RenderContext class - nothing else changes.
(edit)
Also - consider the future: will you ever be doing more than one render at once? Since we all have lots of cores now, etc... static is good if all the threads share a value. There is [ThreadStatic], but that is a bit messy by comparison.
Not bad design at all. In fact, having a Common or Utility namespace and class that exposes static methods and static values centralizes these values in one place so you can ensure that every module in you application is using the appropriate values. It's low cohesion, but acceptable for the benefit. I see no problem with it.
No, that would actually be a perfect candidate for static variables. You can even go one step further and make the class static, so that it can't be instantiated. You can then add all your constants to that class as well as some helper methods if necessary.
The answer is that if the program works and is maintainable, do it.
Static variables aren't a sin, it is just good to know when to use them. :)
If all your classes have to understand this value + do something else, then (unless it's something like pi) you probably should check that your classes have a single concern. Perhaps that 'value' needs to become an object that can do the operations that are currently being done all over your codebase?

Categories

Resources