Whether to use static class or not [duplicate] - c#

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.

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 Class inside Normal class for ASP.Net

I know that making a class static in a ASP.Net project will cause that class's runtime properties to be available to all sessions on the web server.
My question is this: If I declare nested classes static, but the container not, does the sharing of the classes across sessions still apply?
Example:
public class FooContainer
{
public static class Bar
{
}
public static class dog
{
}
}
Yes; a static nested class has the same behaviour as any other static class. The only time nested classes behave differently is when the outer class is generic type (the nested type is then implicitly generic via the parent, so FooContainer<X>.Bar would be independent of FooContainer<Y>.Bar).
And just be careful: static for sharing data between sessions is fraught with danger. Synchronize like a paranoid thing. Personally I would need a very good reason to do this... and it needs careful implementation. I only use that approach for things like configuration caching, and even then I'm insanely careful about it.
Ultimately, yes.
The nested static classes are compiled just the same as root-level static classes (Marc wisely notes subtle differences where generics are involved) - the only difference is the qualifying of the path of the type, but this is only natural in any environment and not a side-effect at all.
When I see someone say "static data" and "ASP.NET" in the same sentence all sorts of alerts go off.
Yes, as Marc said, static classes will be static even if they are nested, you just need to call them via the containing class
MyStaticClass.StaticField = 3; ///wont work
MyInstanceClass.MyStaticClass.StaticField = 3; // works
Any instantiable class can have static methods/properties/constructors, making a class explicitly static just has the added benefit that you can't make something non-static my mistake, clarifying the purpose and intent of the class.
But beware, static classes in ASP.net are trully static on an application level, so if you have multiple users, they will all see the same static data, regardless of authorizations, and a change of that data will affect all users who use it.
So a static variable might be the right place to put something that is read once from the db, and then just displayed, i.e. the current version of the application, or the application's start time, but it's a very wrong place to put user-specific data like language preferences, usernames, etc, etc...

What are reasons why one would want to use nested classes? [duplicate]

This question already has answers here:
Why/when should you use nested classes in .net? Or shouldn't you?
(14 answers)
Closed 10 years ago.
In this stackoverflow answer a commenter mentioned that "private nested classes" can be quite useful so I was reading about them in articles such as this one which tend to explain how nested classes function technically, but not why you would use them.
I suppose I would use private nested classes for little helper classes that belong to a larger class, but often I will need a helper class from another class and so I would just have to take the extra effort to (1) make the nested class non-nested or (2) make it public and then access it with the outer-class prefix on it, which both seems to be extra work without any added-value for having the nested class in the first place. Hence in general I really don't see a use case for nested classes, other than perhaps to keep classes a bit more organized into groups, but I that also goes against the one-class-per-file clarity that I have come to enjoy.
In what ways do you use nested classes to make your code more manageable, readable, efficient?
You've answered your own question. Use nested classes when you need a helper class that is meaningless outside the class; particularly when the nested class can make use of private implementation details of the outer class.
Your argument that nested classes are useless is also an argument that private methods are useless: a private method might be useful outside of the class, and therefore you'd have to make it internal. An internal method might be useful outside of the assembly, and therefore you'd make it public. Therefore all methods should be public. If you think that's a bad argument, then what is different about you making the same argument for classes instead of methods?
I make nested classes all the time because I am frequently in the position of needed to encapsulate functionality in a helper that makes no sense outside of the class, and can use private implementation details of the outer class. For example, I write compilers. I recently wrote a class SemanticAnalyzer that does semantic analysis of parse trees. One of its nested classes is LocalScopeBuilder. Under what circumstances would I need to build a local scope when I am not analyzing the semantics of a parse tree? Never. That class is entirely an implementation detail of the semantic analyzer. I plan to add more nested classes with names like NullableArithmeticAnalyzer and OverloadResolutionAnalyzer that are also not useful outside of the class, but I want to encapsulate rules of the language in those specific classes.
People also use nested classes to build things like iterators, or comparators - things that make no sense outside of the class and are exposed via a well-known interface.
A pattern I use quite frequently is to have private nested classes that extend their outer class:
abstract public class BankAccount
{
private BankAccount() { }
// Now no one else can extend BankAccount because a derived class
// must be able to call a constructor, but all the constructors are
// private!
private sealed class ChequingAccount : BankAccount { ... }
public static BankAccount MakeChequingAccount() { return new ChequingAccount(); }
private sealed class SavingsAccount : BankAccount { ... }
and so on. Nested classes work very well with the factory pattern. Here BankAccount is a factory for various types of bank account, all of which can use the private implementation details of BankAccount. But no third party can make their own type EvilBankAccount that extends BankAccount.
Returning an interface to the caller whose implementation you want to hide.
public class Outer
{
private class Inner : IEnumerable<Foo>
{
/* Presumably this class contains some functionality which Outer needs
* to access, but which shouldn't be visible to callers
*/
}
public IEnumerable<Foo> GetFoos()
{
return new Inner();
}
}
Private helper classes is a good example.
For instance, state objects for background threads. There is no compelling reason to expose those types. Defining them as private nested types seems a quite clean way to handle the case.
I use them when two bound values (like in a hash table) are not enough internally, but are enough externally. Then i create a nested class with the properties i need to store, and expose only a few of them through methods.
I think this makes sense, because if no one else is going to use it, why create an external class for it? It just doesn't make sense to.
As for one class per file, you can create partial classes with the partial keyword, which is what I usually do.
One compelling example I've run into recently is the Node class of many data structures. A Quadtree, for example, needs to know how it stores the data in its nodes, but no other part of your code should care.
I've found a few cases where they've been quite handy:
Management of complex private state, such as an InterpolationTriangle used by an Interpolator class. The user of the Interpolator doesn't need to know that it's implemented using Delauney triangulation and certainly doesn't need to know about the triangles, so the data structure is a private nested class.
As others have mentioned, you can expose data used by the class with an interface without revealing the full implementation of a class. Nested classes can also access private state of the outer class, which allows you to write tightly coupled code without exposing that tight coupling publicly (or even internally to the rest of the assembly).
I've run into a few cases where a framework expects a class to derive from some base class (such as DependencyObject in WPF), but you want your class to inherit from a different base. It's possible to inter-operate with the framework by using a private nested class that descends from the framework base class. Because the nested class can access private state (you just pass it the parent's 'this' when you create it), you can basically use this to implement a poor man's multiple inheritance via composition.
I think others have covered the use cases for public and private nested classes well.
One point I haven't seen made was an answer your concern about one-class-per-file. You can solve this by making the outer class partial, and move the inner class definition to a separate file.
OuterClass.cs:
namespace MyNameSpace
{
public partial class OuterClass
{
// main class members here
// can use inner class
}
}
OuterClass.Inner.cs:
namespace MyNameSpace
{
public partial class OuterClass
{
private class Inner
{
// inner class members here
}
}
}
You could even make use of Visual Studio's item nesting to make OuterClass.Inner.cs a 'child' of OuterClass.cs, to avoid cluttering your solution explorer.
One very common pattern where this technique is used is in scenarios where a class returns an interface or base class type from one of its properties or methods, but the concrete type is a private nested class. Consider the following example.
public class MyCollection : IEnumerable
{
public IEnumerator GetEnumerator()
{
return new MyEnumerator();
}
private class MyEnumerator
{
}
}
I usually do it when I need a combination of SRP (Single Responsibility Principal) in certain situations.
"Well, if SRP is your goal, why not split them into different classes?" You will do this 80% of the time, but what about situations where the classes you create are useless to the outside world? You don't want classes that only you will use to clutter your assembly's API.
"Well, isn't that what internal is for?" Sure. For about 80% of these cases. But what about internal classes who must access or modify the state of public classes? For example, that class which was broken up into one or more internal classes to satisfy your SRP streak? You would have to mark all the methods and properties for use by these internal classes as internal as well.
"What's wrong with that?" Nothing. For about 80% of these cases. Of course, now you're cluttering the internal interface of your classes with methods/properties that are only of use to those classes which you created earlier. And now you have to worry about other people on your team writing internal code won't mess up your state by using those methods in ways that you hadn't expected.
Internal classes get to modify the state of any instance of the type in which they are defined. So, without adding members to the definition of your type, your internal classes can work on them as needed. Which, in about 14 cases in 100, will be your best bet to keep your types clean, your code reliable/maintainable, and your responsibilities singular.
They are really nice for, as an example, an implementation of the singleton pattern.
I have a couple of places where I am using them to "add" value, as well. I have a multi-select combobox where my internal class stores the state of the checkbox and the data item as well. no need for the world to know about/use this internal class.
Private anonymous nested classes are essential for event handlers in the GUI.
If some class is not part of the API another class exports, it must be made private. Otherwise you are exposing more than you intend. The "million dollar bug" was an example of this. Most programmers are too slack about this.
Peter
The question is tagged C# so I'm not sure this is of interest, but in COM you can use inner classes to implement interfaces when a class C++ implements multiple COM interfaces... essentially you use it for composition rather than multiple-inheritance.
Additionally in MFC and perhaps other technologies you might need your control/dialog to have a drop-target class, which makes little sense other than as a nested class.
If it is necessary for an object to return some abstract information about its state, a private nested class may be suitable. For example, if an Fnord supports "save context" and "restore context" methods, it may be useful to have the "save context" function return an object of type Fnord.SavedContext. Type access rules aren't always the most helpful; for example, it seems difficult to allow Fnord to access properties and methods of a Fnord.SavedContext without making such properties and methods visible to outsiders. On the other hand, one could have Fnord.CreateSaveContext simply create a New Fnord.SaveContext with the Fnord as a parameter (since Fnord.SaveContext can access the internals of Fnord), and Fnord.LoadContextFrom() can call Fnord.SaveContext.RestoreContextTo().

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.

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