Related
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.
Let me be more precise. In my winforms project im creating classes to manage/create every part of the program. I did it to have more control over my code. E.g. I have a class that manages my DataGridView control. I named it gridManager and in it i set all properties, colors and so on and also i have methods to change those settings (e.g. changeBackgroundColor() etc).
I also have this type of class for each Panel in splitContainer. In those classes i initialize every Control that is a child of panel i add them to that panel set all properties and so on.
I wrote it all to give you better view at the purpose of those classes.
Now my question is: is it good practice to make this classes static? With all controls and methods inside being static?
At first i had them non-static but when i wanted to call methods for (e.g.) changing color from options Form i had to either pass MainForm as a parameter or do it like this:
(Application.OpenForm[0] as MainForm).gridManager.changeColor();
Static version of it makes it a lot easier. But it makes me wonder if its a good thing to do.
Uh a lot of explaining i hope my not perfect English wont make it even more difficult to understand. :)
Global mutable state is usually a bad idea.
Static methods/classes are good for simple sideeffect free functions. Math and Enumerable are good examples.
You on the other hand want controls inside static fields. These are mutable state and thus should be avoided. For example if you tomorrow want to have two instances of your form, you need two instances of your manager class. But it's static and you now need to rewrite all the code using it.
Like anything, static classes have tradeoffs. The two "negative" ones that come to mind are
You can't inherit from static classes
You can't (easily) mock static classes for testing
But it sounds like in your cases you wouldn't be doing any inheritance of these classes anyway, so perhaps in this case it would be okay.
Edit This is assuming you're doing something like a control factory.
For example:
var grid = GridManager.CreateGrid(options);
If you're doing something like
var data = GridManager.GetDataFromGrid(myGrid)
I'd probably reconsider.
Static classes have their place, but this probably is not one of them unless it is a quick and dirty application. If you want to have automated tests around your code, it can be nearly impossible if the code under test uses static classes for preferences.
It might be better to use the singleton pattern. This way you can replace the implementation during the automated test.
You better do it with normal classes that is linked to that grid object. If you need another grid object you may need to instantiate another instance. Controllers are not the best candidate for static classes.
Its neither good nor bad practice, its just a common pattern for certain tasks.
Generally speaking you would use static methods for functionality that is related to a class type but does not rely upon any instance data to work, a classic use would be something like a factory type method that returns an initialized instance of the class its attached to.
public SomeClass = SomeClass.CreateWithSomeInit(parms);
Static classes certainly have their place, but I think that using them whenever you can is a bad advice.
The whole concept of OOP is built around instances and so you should use non-static classes most of the time. The reason? Primarily flexibility. You can have two instances that do the same thing is a slightly different way based on their internal state. You can have more implementations of the same concept and you can easily switch them. You can use things like Inversion of Control containers. And so on.
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.
I need to explain myself why I do not use static methods/propertis. For example,
String s=String.Empty;
is this property (belongs to .Net framework) wrong? is should be like?
String s= new EmptySting();
or
IEmptyStringFactory factory=new EmptyStringFactory();
String s= factory.Create();
Why would you want to create a new object every time you want to use the empty string? Basically the empty string is a singleton object.
As Will says, statics can certainly be problematic when it comes to testing, but that doesn't mean you should use statics everywhere.
(Personally I prefer to use "" instead of string.Empty, but that's a discussion which has been done to death elsewhere.)
I think the worst thing about using statics is that you can end up with tight coupling between classes. See the ASP.NET before System.Web.Abstractions came out. This makes your classes harder to test and, possibly, more prone to bugs causing system-wide issues.
Well, in the case of String.Empty it is more of a constant (kind of like Math.PI or Math.E) and is defined for that type. Creating a sub-class for one specific value is typically bad.
On to your other (main) question as to how they are "inconvenient:"
I've only found static properties and methods to be inconvenient when they are abused to create a more functional solution instead of the object-oriented approach that is meant with C#.
Most of my static members are either constants like above or factory-like methods (like Int.TryParse).
If the class has a lot of static properties or methods that are used to define the "object" that is represented by the class, I would say that is typically bad design.
One major thing that does bother me with the static methods/properties is that you sometimes they are too tied to one way of doing something without providing an easy way to create an instance the provides with easy overrides to the behavior. For example, imagine that you want to do your mathematical computations in degrees instead of radians. Since Math is all static, you can't do that and instead have to convert each time. If Math were instance-based, you could create a new Math object that defaulted to radians or degrees as you wished and could still have a static property for the typical behaviors.
For example, I wish I could say this:
Math mD = new Math(AngleMode.Degrees); // ooooh, use one with degrees instead
double x = mD.Sin(angleInDegrees);
but instead I have to write this:
double x = Math.Sin(angleInDegrees * Math.PI / 180);
(of course, you can write extension methods and constants for the conversions, but you get my point).
This may not be the best example, but I hope it conveys the problem of not being able to use the methods with variations on the default. It creates a functional construct and breaks with the usual object-oriented approach.
(As a side note, in this example, I would have a static property for each mode. That in my eyes would be a decent use of the static properties).
The semantics of your three different examples are very different. I'll try to break it down as I do it in practice.
String s=String.Empty;
This is a singleton. You would use this when you want to ensure that there's only ever one of something. In this case, since a string is immutable, there only ever needs to be one "empty" string. Don't overuse singletons, because they're hard to test. When they make sense, though, they're very powerful.
String s= new EmptySting();
This is your standard constructor. You should use this whenever possible. Refactor to the singleton pattern only when the case for a singleton is overwhelming. In the case of string.Empty, it very much makes sense to use singleton because the string's state cannot be changed by referring classes.
IEmptyStringFactory factory=new EmptyStringFactory();
String s= factory.Create();
Instance factories and static factories, like singletons, should be used sparingly. Mostly, they should be used when the construction of a class is complex and relies on multiple steps, and possibly state.
If the construction of an object relies on state that might not be known by the caller, then you should use instance factories (like in your example). When the construction is complex, but the caller knows the conditions that would affect construction, then you should use a static factory (such as StringFactory.CreateEmpty() or StringFactory.Create("foo"). In the case of a string, however, the construction is simple enough that using a factory would smell of a solution looking for a problem.
Generally, it is a bad idea to create a new empty string - this creates extra objects on the heap, so extra work for the garbage collector. You should always use String.Empty or "" when you want the empty string as those are references to existing objects.
In general, the purpose of a static is to make sure that there is ever only one instance of the static "thing" in your program.
Static fields maintain the same value throughout all instances of a type
Static methods and properties do not need an instance in order to be invoked
Static types may only contain static methods/properties/fields
Statics are useful when you know that the "thing" you are creating will never change through the lifetime of the program. In your example, System.String defines a private static field to store the empty string, which is allocated only once, and exposed through a static property.
As mentioned, there are testability issues with statics. For example, it is hard to mock static types since they can't be instantiated or derived from. It is also hard to introduce mocks into some static methods since the fields they use must also be static. (You can use a static setter property to get around this issue, but I personally try to avoid this as it usually breaks encapsulation).
For the most part, use of statics is o.k. You need to decide when to make the trade-off of using static and instance entities based on the complexity of your program.
In a purist OO approach, static methods break the OO paradigm because you're attaching actual data to the definition of data. A class is a definition of a set of objects that conform to semantics. Just like there are mathematical sets that contain one or zero elements, there can be classes that contain only one or zero possible states.
The way of sharing a common object and allowing multiple actors on its state is to pass a reference.
The main problem with static methods comes from, what if in the future you want two of them? We're writing computer programs, one would assume that if we can make one of something, we should be able to make two very simply, with statics this isn't the case. To change something from a static state to a normal instance state is a complete rewrite of the class in question.
I might assume I want to only ever use one SqlConnection pool, but now what if I want a high priority pool and a low priority pool. If the connection pool was instanced instead of static the solution would be simple, instead I have to couple pooling with connection instantiation. I better hope the library writer had forsight or else I have to reimplement the pooling.
Edit:
Static methods in single inheritance languages are a hack to provide reuse of code. Normally if there are methods one wanted to share common code between classes you could pull it in through multiple inheritance or a mixin. Single inheritance languages force you to call static methods; there's no way to use multiple abstract classes with state.
There are draw backs to using statics such as:
Statics dont allow extension methods.
Static constructor is called automatically to initialize the class before the first instance is created (depending on the static class being called of course)
Static class data lives throughout the lifespan of the execution scope, this wastes memory.
Reasons to use static methods
Statics are good for helper methods, as you dont want to create a local copy of a non-static class, just to calla single helper method.
Eeerm, static classes make the singleton pattern possible.
From a scenario-driven design, the criteria for choosing statics vs. instance methods should be: if a method can be called without an instance of a class to be created, make it static. Else, make it an instance method. First option makes the call a once line process, and avoid .ctor calls.
Another useful criteria here is whether responsabilities are in the right place. For ex. you got an Account class. Say you need functionality for currency conversion e.g. from dollars to euros. Do you make that a member of the Account class? account.ConvertTo(Currency.Euro)? Or do you create a different class that encapsulates that responsibility? CurrencyConverter.Convert(account, Currency.Euro)? To me, the latter is better in the sense that encapsulates responsibilities on a different class, while in the former I would be spreading currency conversion knowledge across different accounts.
Greetings,
I have a particular object which can be constructed from a file, as such:
public class ConfigObj
{
public ConfigObj(string loadPath)
{
//load object using .Net's supplied Serialization library
//resulting in a ConfigObj object
ConfigObj deserializedObj = VoodooLoadFunction(loadpath);
//the line below won't compile
this = thisIsMyObj;
}
}
I want to, in essense, say "ok, and now this object we've just deserialized, this is the object that we in fact are." There are a few ways of doing this, and I'm wondering which is considered a best-practice. My ideas are:
Build a copy-into-me function which copies the object field by field. This is the current implementation and I'm pretty sure its a horrible idea since whenever a new member is added to the object I need to also remember to add it to the 'copy-into-me' function, and there's no way that's maintainable.
Build a static method for the ConfigObj class which acts as a de-facto constructor for loading the object. This sounds much better but not very best-practice-y.
I'm not entirely happy with either of the two, though. What is the acknowledged best practice here?
Your second option is what is called a factory method and is a common design technique. If you do use this technique, you may find that you need to know the type of class you will load before you actually load the class. If you run into this situation, you can use a higher level type of factory that looks at the stream and calls the factory method for the appropriate type of class.
There's nothing wrong with having a static method instead of a constructor. In fact, it has a number of advantages.
I always go with the static method. Usually it's kind of a hierarchy which is loaded, and therefore only the root object needs the method. And it's not really an unusual approach in the .NET framework (e.g. Graphics.FromImage), so it should be fine with users of your class.