Should every class that is only used once be static? - c#

I've seen various discussions about this and I suppose it may be a bit opinion based, but what I'm trying to find out is if I know I will only use a class once (one instance), should I just make it static for convenience? Is that bad practice or will it create a problem?
For example. If I make a single player game, there will only be one player at all times. So do I make public static class Player{} or do I stick with public class Player{} Player player = new Player();
The idea is that this would save time by not needing to pass around references.

Note that there is a difference between using a class only once and using only one instance of a class (more on that below).
Static classes are usually classes whose purpose is to expose a set of functionalities and/or constants which are independent of each other and do not need to maintain state information. If this is what your class does then you can declare it as a static.
In your example, I do not think that this is the way to go. A Player object might have different states and other properties, such as location, health etc. The moment you try to have 2 players in the game then your design breaks.
Using only one instance of a class is usually achieved through the Singleton design pattern. The aim of this pattern is to provide you with the same instance of a given object, regardless of how many times you actually make use of said object.

It is bad practice. You don't know how your game will scale, so in some time you will decide to make abstractions behind your class and it will turn refactoring of code into hellpit.
If you, for example, decided what your Player is inherited from class Human or from some abstract class VisibleObject you will be stuck with dilemma.
So, when to use static? Primarly on methods, Extensions classes, some very simple fields and that's all.

static class is basically same as other class but the difference is that you cannot instantiated.
In above example, it does not matter you use static class or not.

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

Static abstract objects with virtual methods

I'm working on a personal project and I've run into an issue.
I have object a couple of objects that have the same properties, methods, etc. The only things that differ are their names, values of properties, and the implementation of the methods. They also need common default implementation of methods. So right away, an interface is out of the question.
So I created a base class with the properties and "default" methods. But this base class needs to be abstract. The methods are virtual so they can be overridden.
The reason I need them to be static is that objects will be properties of other objects.
So, for example, the objects referenced above are (for sake of simplicity) objX, objY, objZ. They are derived from their base, objW.
objContainer is a completely unrelated object, but it has a property of type objW, which is an instance of either objX, objY, objZ.
objX, objY, and objZ will never change. Their properties will all be readonly. So multiple objects of instance objContainer will have objX, objY, or objZ.
public class objContainer1
{
objW processor = new objY;
}
public class objContainer2
{
objW processor = new objY;
}
How do I go about doing this? I wanted to keep them static so I don't have multiple instances of the same objects, when all of them are the exact same, really.
Do I use a singleton? Factory pattern?
I'm lost as to which direction to go with this (if any). Maybe I'm overthinking it and there's a very simple solution/
You want to use static classes sparingly. There are obvious downsides to static classes, such as the inability to take advantage of the polymorphic nature of class inheritance since you can't inherit from a static class. The only time you want to use a static class, really, is when you have something like a set of related tools that you want to make available across your application and for which you don't need to maintain any state. Think of the System.Math class, for example: a set of math functions that you can use anywhere in your application. Having an instance of that class doesn't really make any sense, and it would be rather cumbersome and unnecessary.
I would suggest sticking to non-static classes and creating instances of those classes. If you should only ever have one instance of your class, then you should use a singleton, as you suggested.

Should I use multiple static classes with maximum one public method

I'm writing a structural detailing (CAD) software for concrete buildings in C#. I have defined like hundreds of static classes each with one public method and if needed some private methods. Each one of these methods in these static classes does part of the job. They are called from one God static class named Building.cs.
For example one class looks like this:
public static partial class GetMainRebars
{
public static void GetMainRebars()
{
}
// other possible variables and private methods
}
The program is running very very fast compared to other similar programs. But deep in my heart, looking at the above code I feel that something still may be wrong with this design pattern. Maybe I will encounter problems in terms of maintenance, or ...? I've taught myself programming, so I may have missed many core principles during the fast self teaching process. Can you elaborate the cons and pros of the above pattern?
And one very rookie question relevant to the pattern. Let's say I define a static variable inside such a class, will it remain in memory during the life time of the program? No disposing and whatsoever? Is it OK?
Ok. First of all I want to say that this is a VERY bad pattern (if I can even call it that). You shouldn't have many static classes with single methods... not even gonna talk about the single god static class. You should read up on SOLID principles. For now though I am gonna give you a few pointers.
Instead of having 1000 small static classes, try to group some of them, so you reduce the number a bit(if they have similar function or something of course not otherwise). After that you can turn those static classes into service classes which should derive from interfaces. For example if you have a BuildingService class, you can make it derive from IBuildingService. That way if for some reason in the feature you decide to switch this class out for another one, you can do that without having to change it in a 1000 places but just in one.
Determining which implementation of each interface is going to be used is an IoC(Unity for example)'s job. Also the god class should be removed entirely. Having a class that does 1000 things violates the separation of concern pattern, it doesn't matter if it does them using methods implemented inside other classes or not. If you really need that functionality you can maybe create class that stores a collection of services which can later be invoked.
I hope this points you in the right direction.

Static vs. public C#

I know that it's been answered multiple times here on SO, but I still don't get the nuts of bolts of what exactly it means to instantiate a class. I read this and it did help my understanding.
I know that static classes like Console cannot be used with the new expression like Console c = new Console() because there aren't any instance variables in that class. I also know that static classes provide on 'generic' methods and are generally used for Math functions. I know that once you instantiate a class like Double d = new Double(); you are now given access to whatever methods are inside of the Double class.
I know these facts but I feel like I don't really understand what they actually MEAN. Could someone give an example of where a static class is absolutely necessary and one where creating an instance of a class is absolutely necessary?
Think of a class like a set of blueprints. Instantiating a class is like taking the blueprints and building the item. When an engineer designs a car, he comes up with the design. That would be the class. After the car is designed, the plans are handed off to the assembly line to be built. Each car that rolls off the line would be an instance of that design.
When the car is still just a design, you can't really do anything with it. You can't open its door if there's no car. Once you have the instance of a car, you can manipulate it. You can open the door, start the engine, etc. The same goes for a class like Double. Once you have the instance, you can manipulate it.
A static class, like Console, are classes that don't have instances. They're more like a way to group useful related functionality. In the case of Console, the functionality is used to interact with the command line. Math is used to group mathematics related code. Configuration is used to read/manipulate configuration files. None of these things require you to create anything unique for them to work.
A public class must be called in application by another class, for exampel this may be a class of data access (called by businnes layer).
A static class need not necessarily the creation of an instance for example tracing or logging class.
One (perhaps over) simplified example for thinking about static is the following:
If you have the class Dog; you could instantiate the class to create Dog Poodle = new Dog(); and Dog Labrador = new Dog();
If the Dog class has a variable hairColor, then for Poodle and Labrador, hairColor could be different. The two different instances are seperate.
If however, you added a static variable to Dog called numberOfDogs, and incremented the variable every time a new Dog was instantiated (you could do this is the constructor for example), then the variable would count the total number of Dogs, and would be the same number regardless of which instance of Dog you checked.
This is useful (and dangerous) depending on how you use it.

Making Methods All Static in Class

I was told by my colleague based on one of my classes (it is an instance class) that if you have no fields in your class (backing fields), just make all methods static in the class or make the class a singleton so that you don't have to use the keyword new for calling methods in this BL class.
I assume this is common and good practice? Basic OOP? I just want to see people's opinion on that.
I think basically he's saying since there's no state, no need for the methods to be instance methods.
I'm not sure about making it a singleton every time as an option in this case...is that some sort of pattern or good advice he's giving me?
Here's the class I'm talking about (please do not repost any of this code in this thread, this is private): http://www.elbalazo.net/post/class.txt
There is very little downside to calling new and constructing a class reference, especially if the class has no state. Allocations are fast in .NET, so I wouldn't use this alone as a justification for a class to be static.
Typically, I feel a class should be made static if the class has no specific context - if you're using the class just as a placeholder for "utility" methods or non-context specific operations, then it makes sense to be a static class.
If that class has a specific need for context, and a meaning in a concrete sense, then it probably does not justify being static, even if it has no state (although this is rare). There are times where the class purpose is defined by its reference itself, which provides "state" of a sort (the reference itself) without any local variables.
That being said, there is a big difference between a static class and a singleton. A singleton is a different animal - you want to use it when you need an instance, but only one instance, of the class to be created. There is state in a singleton, but you are using this pattern to enforce that there is only a single copy of the state. This has a very different meaning, and I would highly recommend avoiding using a singleton just to prevent needing to "call new".
There's no absolute rule for when a class should be static. It may have no state, but you may need it for reference equality or locking. Classes should be static when their purpose fits it being implemented as a static class. You shouldn't follow hard-and-fast rules in these situations; use what you 'feel' is right.
Having no state makes it a candidate for static-ness, but look at what it's being used for before arbitarily refactoring it.
A lack of state alone is no reason to make methods static. There are plenty of cases where a stateless class should still have instance methods. For example, any time you need to pass specific implementations of some logic between routines, it's much easier to do it with classes that have instance methods, as it allows us to use interfaces:
interface IConnectionProvider
{
object GetConnectedObject();
}
We could have a dozen implementations of the above, and pass them into routines that require an IConnectionProvider. In that case, static is a very clumsy alternative.
There's nothing wrong with having to use new to use a method in a stateless class.
As long as you don't need to create any abstraction from your class then static methods are fine. If your class needs to be mocked or implement any sort of interface then you're better off making the class a singleton, since you cannot mock static methods on classes. You can have a singleton implement an interface and can inherit instance methods from a singleton whereas you cannot inherit static methods.
We generally use singletons instead of static methods to allow our classes to be abstracted easily. This has helped in unit testing many times since we've run into scenarios where we wanted to mock something and could easily do so since the behavior was implemented as instance methods on a singleton.
Utility classes are often composed of independant methods that don't need state. In that case it is good practice to make those method static. You can as well make the class static, so it can't be instantiated.
With C# 3, you can also take advantage of extension methods, that will extend other classes with those methods. Note that in that case, making the class static is required.
public static class MathUtil
{
public static float Clamp(this float value, float min, float max)
{
return Math.Min(max, Math.Max(min, value));
}
}
Usage:
float f = ...;
f.Clamp(0,1);
I can think of lots of reasons for a non-static class with no members. For one, it may implement an interface and provide/augment behavior of another. For two, it may have virtual or abstract methods that allow customization. Basically using 'static' methods is procedural programming at it's worst and is contrary to object-oriented design.
Having said that, often small utilities routines are best done with a procedural implementation so don't shy away if it make sense. Consider String.IsNullOrEmpty() a great example of a procedural static routine that provides benefit in not being a method. (the benefit is that it can also check to see if the string is null)
Another example on the other side of the fence would be a serialization routine. It doesn't need any members per-say. Suppose it has two methods Write(Stream,Object) and object Read(Stream). It's not required that this be an object and static methods could suffice; however, it make sense to be an object or interface. As an object I could override it's behavior, or later change it's implementation so that it cached information about the object types it serialized. By making it an object to begin with you do not limit yourself.
Most of the time it's OK to make the class static. But a better question is why do you have a class without state?
There are very rare instances where a stateless class is good design. But stateless classes break object oriented design. They are usually a throwback to functional decomposition (all the rage before object oriented techniques became popular). Before you make a class static, ask yourself whether the data that it is working on should be included int he class or whether all of the functionality in the utility class shouldn't be broken up between other classes that may or may not already exist.
Make sure that you have a good reason to make class static.
According to Framework Design Guidelines:
Static classes should be used only as
supporting classes for the
object-oriented core of the framework.
DO NOT treat static classes as a miscellaneous bucket.
There should be a clear charter for
the class.
Static Class, Static Methods and Singleton class are three different concepts. Static classes and static methods are usually used to implement strictly utility classes or making them stateless and hence thread-safe and conncurrently usable.
Static classes need not be Singletons. Singleton means there is only one instance of a class, which is otherwise instantiable. It is most often used to encapsulate the physical world representation of a truly single instance of a resource, such as a single database pool or a single printer.
Coming back to your colleague's suggestion -- I tend to agree it is a sound advice. There is no need to instantiate a class if the methods are made static, when they can be static. It makes the caller code more readable and the called methods more easily usable.
It sounds like you're talking about a strictly Utility class, in which case there's really no reason to have seperate instances.
Make those utility methods static. You can keep the class as a regular object if you'd like (to allow for the future addition of instance methods/state information).

Categories

Resources