11

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

PositiveGuy
  • 46,620
  • 110
  • 305
  • 471
  • can u be more specific on the exact class - its a broad subject, and while that might apply in a specific scenario its just not a golden rule - and because of that is far from being called good practice. – eglasius Sep 29 '09 at 17:18
  • The class basically has a lot of CRUD methods in it. It's a BL class. – PositiveGuy Sep 29 '09 at 18:22
  • I just wonder about the ability to Unit test these now that this class will be static. – PositiveGuy Sep 29 '09 at 18:24
  • I've updated the original post to show the class. Please do not repost any of its code in here. – PositiveGuy Sep 29 '09 at 18:37
  • So actually I changed the methods to be static, class is not. – PositiveGuy Sep 29 '09 at 18:42
  • Any other suggestions are welcomed. The reason this class is like a free for all BL class that really has other sh** in it is because we don't really have a true BL separation for each domain entity. So right now, this is how I have to do it (boss will bitch if I don't as we're not refactoring our BL at this point yet) – PositiveGuy Sep 29 '09 at 18:44

10 Answers10

13

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".

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • (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) Well no, but my boss would. He loves shortcuts. In this case he may be right, why have to create an instance for a class that basically has no state and really are just calling CRUD methods. On the other hand, non-static classes can't be unit tested I think as a downside? – PositiveGuy Sep 29 '09 at 18:23
  • It all depends on the context of the code. It's very easy to write code where the bottleneck is the allocation, although you'd have to write some really bad code. But in the general case, it's unlikely allocation + constructor is something expensive (at least with respect to the rest of the code). – Vitali Sep 29 '09 at 18:34
  • The can be unit tested, but it's odd. For me, it's not a shortcut to prevent construction, though (often, it's longer - since you have to type the class name for every method call!). There are things you can do with stateless classes, though, like use them as arguments to other classes - which would allow you to easily change data operations, etc (it can act like a collection of delegates, since you can pass an interface). For example, many DAL architectures end up with concrete class instances that have no state, for good reason. – Reed Copsey Sep 29 '09 at 18:37
  • @unknown: This is very, very true in C++ - in C# (.NET), memory allocation itself is very, very fast, so it's rarely a bottleneck. Construction can be a bottleneck if your constructor is doing work (which should be avoided anyways), but that's a separate issue. – Reed Copsey Sep 29 '09 at 18:38
  • I've updated the original post to show the class to give a little more perspective. (note: Please do not re-post any of its code in here) – PositiveGuy Sep 29 '09 at 18:43
  • @coffeeaddict: For me - this is borderline. EVerything's static, so it'd be fine to make the class static and use it how you have it written. However, if you ever wanted to support a different backend, other than "Database", having a non-static instance would make that much easier. You could use DI to grab the appropriate SilverpopBL instance for your specific backend, etc. Non-static, in this case, is allowing for extra flexibility in the future - but it's totally up to you. – Reed Copsey Sep 29 '09 at 19:02
  • I totally agree that nonstatic is the way to go, just that I can't get my boss to change his mind on things like this. It's somewhat a "keep my job" sort of thing unfortunately. Yes, he doesn't think about unit testing, nor do we do it. We don't use a lot of interfaces...we should. He thinks doing stuff like that is over complicated for our .com, I disagree. – PositiveGuy Sep 29 '09 at 20:58
7

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.

thecoop
  • 45,220
  • 19
  • 132
  • 189
  • I've updated the original post to show the class to give a little more perspective. (note: Please do not re-post any of its code in here) – PositiveGuy Sep 29 '09 at 18:42
5

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.

Rex M
  • 142,167
  • 33
  • 283
  • 313
  • I've updated the original post to show the class to give a little more perspective. (note: Please do not re-post any of its code in here) – PositiveGuy Sep 29 '09 at 18:46
2

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.

Binz
  • 580
  • 4
  • 9
  • I've updated the original post to show the class to give a little more perspective. (note: Please do not re-post any of its code in here) – PositiveGuy Sep 29 '09 at 18:45
1

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);
Coincoin
  • 27,880
  • 7
  • 55
  • 76
  • I've updated the original post to show the class to give a little more perspective. (note: Please do not re-post any of its code in here) – PositiveGuy Sep 29 '09 at 18:46
  • I see that you can make a class non-static and still have static methods. So per your statement above about making the class static too, in my case why would it be bad to have a non-static class with all static methods? – PositiveGuy Sep 29 '09 at 18:47
  • Sorry for the confusion, making the class static is optional. However, if you chose to use extension methods, they will require the class to be static. Also, if there is no point in instantiating a class because it only contains static methods, making the class static explicitly tells your intentions. – Coincoin Oct 01 '09 at 14:17
0

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.

csharptest.net
  • 62,602
  • 11
  • 71
  • 89
  • I've updated the original post to show the class to give a little more perspective. (note: Please do not re-post any of its code in here) – PositiveGuy Sep 29 '09 at 18:50
0

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.

Jeff Hornby
  • 12,948
  • 4
  • 40
  • 61
0

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.

Vadim
  • 21,044
  • 18
  • 65
  • 101
  • I've updated the original post to show the class to give a little more perspective. (note: Please do not re-post any of its code in here) – PositiveGuy Sep 29 '09 at 18:50
0

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.

srini.venigalla
  • 5,137
  • 1
  • 18
  • 29
  • I've updated the original post to show the class to give a little more perspective. (note: Please do not re-post any of its code in here) – PositiveGuy Sep 29 '09 at 18:48
-1

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).

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536