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.
Related
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.
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.
Some months ago I created a C# Project of a game called Vexed. Now I'm creating a Tetris, but in C++. Basically I want to use the same logic I used in the other project, it was a little bit like this:
I created a Class called "Game" where there was all the information about the game. It had it's methods, variables and everything. Then, I created a static class called "PublicInstances" or something like that, and in that class I declared something like this:
static class PublicInstances
{
public static Game vexedGame = new Game(); //This is C# and works.
}
It made it so simple to use then, because any change I made on the game was saved in that static instance of my class and I could access it anywhere on the project. I want to know how to do exactly that with C++, to create a public or global instance of my class Game so I can access it and change it everywhere and have everything updated in any Form or class of my project. I would really appreciate your help.
// Sorry if my English isn't the best ^^
Revisited and summarised
Option 1
You may simply declare and define a global instance of Game object.
In a header file, e.g. game.h:
extern Game globalGameObj;
When you include game.h in a source file globalGameObj name becomes visible.
You also need to create an actual object. In a source file, e.g. game.cc (outside of any class):
Game globalGameObj;
Access it by the variable name:
globalGameObj.do_some_work();
Option 2
Use a pattern often called singleton. Add the following to your Game class (game.h):
class Game
{
public:
static Game &shared_instance() {static Game game; return game;}
private:
// Make constructor private. Only shared_instance() method will create an instance.
Game() {/*whatever initialisation you need*/}
};
You access Game instance with shared_instance() method:
Game::shared_instance().do_some_work();
You do not use anything like your static class PublicInstances in the above. C++ allows you to introduce a namespace (e.g. PublicInstances) to provide name isolation and keep your global objects in one place but it'll probably to be an overkill. In any case if you have few global objects then it is likely to be a bad design.
What option is better? Some people would argue that singleton pattern should be used. It guarantees that only a single instance is created. However both option 1 and option 2 have the same problem: they introduce a global object in your code with all disadvantages attributed to global variables. I'd say that singleton is a global object in disguise. I do not see deciding technical reasons in favour of either option so I'd say that it is a matter of personal taste.
Historical note :)
My first suggestion for Option 2 was to use a dynamically allocated Game object rather than a function local static object.
static Game *instance() {if (!_inst) _inst = new Game(); return _inst;}
Few people suggested that it was not the best way anymore, thank you Kal, argiopeweb and Simple. C++03 has issues initialising static objects in presence of threads. C++11 guarantees safe initialisation of statics.
C++11 draft, secion 6.7
such a variable is initialized the first time control passes through its declaration;
such a variable is considered initialized upon the completion of its initialization. [...]
If control enters the declaration concurrently while the variable is being initialized,
the concurrent execution shall wait for completion of the initialization.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I will write code in which I need class which holds methods only. I thought it is good idea to make class static. Some senior programmer argue that do not use static class. I do not find any good reason why not to use static class. Can someone knows in C# language there is any harm in using static class. Can static class usage required more memory than creating object of class? I will clear that my class do not have single field and hence property too.
For further information I will explain code also.
We have product in which we need to done XML handling for chart settings. We read object from XML file in class Library which holds chart related properties. Now I have two Layers first is product second class Library and XML related operations. Actually senior programmers want independent class to read and write XML. I make this class static.
In another situation I have class of chartData. In that class I want methods like whether Line of Axis,series of chart is valid or not. Also whether color of chart stores in ARGB format or plain color name. They do not want those methods in same project. Now can I make class static or create object.
If your class does not have to manage state then there is absolutely no reason to not declare it static.
In C# some classes even have to be static like the ones that have extension methods.
Now if there's a chance that it requires state in the future, it's better to not declare it as static as if you change it afterwards, the consumers will need to change their code too.
One concern is that statics can be harder (not impossible) to test in some situations
The danger of static classes is that they often become God Objects. They know too much, they do too much, and they're usually called "Utilities.cs".
Also, just because your class holds methods only doesn't mean that you can't use a regular class, but it depends on what your class does. Does it have any state? Does it persist any data that's being modified in your methods?
Having static classes is not bad, but could make you think why you have those methods there. Some things to keep in mind about that:
if the methods manage behavior for classes you have in your project, you could just add the methods to those classes directly:
//doing this:
if(product.IsValid()) { ... }
//instead of:
if(ProductHelper.IsValid(product)) { ... }
if the methods manage behavior for classes you can't modify, you could use extension methods (that by the end of the day are static! but it adds syntactic sugar)
public static bool IsValid( this Product product ) { ... }
//so you can do:
if(product.IsValid()) { ... }
if the methods are coupled to external services you may want to mock, using a non-static class with virtual methods or implementing an interface will let you replace the instance with a mock one whenever you need to use it:
//instead of:
StaticService.Save(product);
//you can do:
public IService Service {get;set;}
...
Service.Save(product);
//and in your tests:
yourObject.Service = new MockService(); //MockService inherits from your actual class or implements the same IService interface
by the other hand, having the logic in non-static classes will let you make use of polymorphism and replace the instance with another one that extends the behavior.
finally, having the logic in non-static classes will let you use IoC (inversion of control) and proxy-based AOP. If you don't know about that, you could take a look at frameworks like Spring.net, Unity, Castle, Ninject, etc. Just for giving you an example of what you could do with this: you can make all the classes implementing IService log their methods, or check some security constraints, or open a database connection and close it when the method ends; everything without adding the actual code to the class.
Hope it helps.
It depends on the situation when to use static classes or not. In the general case you create static classes when you do not need to manage state. So for example, Math.cs, or Utility.cs - where you have basic utility functions - eg string formatting, etc.
Another scenario where you want to use static is when you expect the class to not be modified alot. When the system grows and you find that you have to modify this static class alot then its best to remove the static keyword. If not then you will miss out on some benefits of OOD - eg polymorphism, interfaces - For example you could find that I need to change a specific method in a static class, but since you can't override a static method, then you might have to 'copy and paste' with minor changes.
Some senior programmer argue that do not use static class.
Tell him he is a traineee, not even a junior. Simple. The static keyword is there for a reason. if your class only has methods without keeping state - and those cases exist - then putting them into a static class is valid. Point.
Can someone knows in C# language there is any harm in using static class.
No. The only valid argument is that your design isbroken (i.e. the class should not be static and keep state). But if you really have methods that do not keep state - and those cases exist, like the "Math" class - then sorry, this is a totally valid approach. There are no negatives.
I am using C#, but I think this is a pretty generic OO question. Suppose I have a class called Animal, and it has properties like LegCount, EyeCount, HasFur, EatsMeat, etc.
Let's say I have an instance a of Animal. Suppose a has LegCount set to 4 and EyeCount set to 2.
Now, I'd like to create an instance d of type Dog, which inherits from Animal. I'd like to initialize d with all the values of a. I realize I could create a constructor or otherwise some other method that would take an Animal and spit out a new Dog with all the values copied in, but I was hoping there was some Object Oriented principle / trick that had me covered.
What I want to do, in plain English, is:
Create new Instance d of Dog, with all starting values from a. The key is "all", as opposed to specifying each property individually.
When you design a class that inherits from some other class, you don't need to list all the members it inherits. It just inherits all of them. So I am wondering if I can "inherit the values" on actual instances.
The feature you want is called "prototype inheritance" or "prototype-oriented programming". C# does not support this feature, so you're out of luck there.
You might consider using a language that supports prototype inheritance if your architecture fundamentally needs this feature. JavaScript is the most commonly used prototype inheritance language.
Prototype inheritance can be quite tricky to get correct if you're not careful. If this subject interests you, see my article on some of the bizarre situations you can run into with prototype inheritance in JScript:
http://blogs.msdn.com/b/ericlippert/archive/2003/11/06/53352.aspx
You can't do what you're asking for with some C# language construct, you have to manually write mapping or delegating code. Or, take a look at AutoMapper for that.
You could try a different approach with using the decorator pattern? An alternative to subclassing for extending functionality. Then all your values in the Animal class instance is preserved
http://www.dofactory.com/Patterns/PatternDecorator.aspx
public class Animal
{
public Animal(Animal otherAnimal)
{
if (otherAnimal == null)
throw new ArgumentNullException("otherAnimal");
foreach (System.Reflection.PropertyInfo property
in typeof(Animal).GetProperties())
{
property.SetValue(this, property.GetValue(otherAnimal, null), null);
}
}
}
and then just call this Animal constructor from your Dog(Animal otherAnimal) constructor
But still you should to think over one more time about design of your classes and make Animal an abstract class. Because what do you imagine as instance of class Animal..