views:

104

answers:

7

Just a simple question:

I have read that a class should be made static when it does not modify its instance. So if I have a class which is called Account and it has properties such as Id, Duration, etc and these do not get modified by the class, then this can be made static otherwise it should remain static.

How does this (whether the instance itself, via its properties, mutates) effect the static/instance decision?

Furthermore, if a class takes loads of parameters (say this Account class, sticking to our analogy), but does not modify the instance (so no Account variable changes - nothing like Account.x = y // where y is from another class), I assume this can be still made static? So it's not the parameters which are an issue or where they come from, it's what they do?

If it is a property, the same principles apply as when deciding to make a field static or not (such as if the data the field holds will be expensive to get, then have one field holding it - static - correct me if I am wrong).

I've noticed there are over 100 threads on static methods (this falls into a static method as it is dealing with parameters) on C# and I will read all of these as there are good questions and good answers.

Thanks

A: 

I am no expert, but my understanding that if a Property doesnt change, it should be a constant, not static.

In my experience, static is used to denote that only 1 instance of the value exists in the application and is not encouraged within OOP design although its a necessary feature.

If you have an class Account which has Properties which never change, what you are looking at is a singleton instance of an immutable class. You can develop this using the static keyword to enforce that only 1 instance of the Account class can be instantiated, or alternatively, declare the Properties as constant.

If you have alot of methods which need to be static, then you essentially are designing the program to be non object oriented. At that point, it might be good to decide on using a non-OO programming language.

I especially despise static because its a major problem if you have a multithreaded application.

Andrew Keith
Despise is a strong word. static has it's place, especially when you are looking to implement singletons
Abhijeet Patel
I would not use a static class to implement singleton, you cannot control when the static class is instantiated.
Cade Roux
@Cade: How would you implement a Singleton?
Abhijeet Patel
My implementation (generic, lazy) is in my answer to this question: http://stackoverflow.com/questions/100081/whats-a-good-threadsafe-singleton-generic-template-pattern-in-c/1010662#1010662
Cade Roux
Note that this is not a static class (which cannot be inherited from) - it just has static methods.
Cade Roux
-1 for the 2nd paragraph. There's a number of reasons why a class would be static beyond implementing a singleton: utilities, factories, extensions, mutators etc.
SnOrfus
@Cade: Your solution in the link uses a static AND it's heavy to use since it uses reflection.The recommended approach by Jeff Richter in CLR Via C# is to use something similar to the answer I posted
Abhijeet Patel
+1  A: 

If the properties are not modified by the class, or by anything else, then make them static read only, or const fields, with only getter propperties. This would have nothing to do whether any specific method is static or not.

EDIT: A non-static class is a "template" for an object, which you "use" by creating (new) instances based on that template. A static class is just an organizational 'bucket' for methods (functions) that are self contained snippets of code that generally operate only on their passed in parameters. (as well as any other globally scoped variables)

Charles Bretana
+4  A: 

It sounds like you're looking to make the class immutable, rather than static?

Here's the definition of a Static Class from C# 3 in a Nutshell: "A class can be marked static, indicating that it must be comprised solely of static members and cannot be subclassed. The System.Console and System.Math classes are good examples of static classes."

In the case of an Account, I assume you want an individual Account instance for each account in your system. So that I don't think you want it to be static.

Abby Fichtner
+2  A: 

Looks like you are asking about methods AND classes so you have 2 questions.

Methods are easy. If I'm implementing a factory pattern; I use a static method. If I want to be able to use the method without an instance of the class for readability (think utility methods like LogIt(); I use a static method.

I use a static class (that I wrote myself) about as often as I win the lottery. So if you win a lot, then go ahead and use one a lot. Seriously, in a server environment, the threading/concurrency issues will kill you in all sorts of horribly slow and painful ways.

DancesWithBamboo
+1 I use static classes more often than that though :) simply because I find extension methods quite useful for certain problems, especially when you need a clean, intuitive way to work with sealed or tightly coupled classes in the BCL.
Si
A: 

I'm not sure I fully understand what it is you're trying to do but here are some thoughts:

1) You can't(at least directly) instantiate a static class, so you can't create objects of a static class. In your example you will never be able to create an instance of an Account. Is this what you want?

2)A static class can't have instance variables, it can only contain static variables, so in your example all the properties you have such as ID,Duration will have to be static (not advisable for an Account)

3) Expense: If you need to share resources which are expensive,creating a static variable enables you to implement the Singleton pattern since a static is shared between all instances of that type, typically this this is read only and instantiated once. Something like this:

public class Singleton
{
    private static Singleton _instance = new Singleton();

    private Singleton() {}

    public static Singleton Instance {
        get {
                return _instance;
        }
    }
}

4)It seems that you are looking for immutability which you can implement for lightweight objects using structs instead.

Hope this provides some guidance

Abhijeet Patel
+2  A: 

A static class contains only static member methods and static member variables/data. The static data can be public or private, but there is only one copy of the data and it is effectively global (although there can be restrictions in access scope). The static methods can access private static data - often in the form of buffers or initializers or control blocks for singleton-resources.

Typically a static class with only static methods (and no data) is used for libraries of methods/functions which maintain no internal state. Also extension methods. These are generally accepted as necessary when necessary, but there are not OO in any particularly special way.

If (static, of course, there is no non-static data in a static class) data is added to a static class, the functions are typically not automatically re-entrant or threadsafe - i.e. two calls to the same function on separate threads could step on each other or if a function takes a callback/delegate or similar and ends up calling into the same function while a prior call to the same function is under way.

With only static classes and static methods, most OO languages effectively collapse to something closer to traditional procedural languages like C or Pascal without making any structs and function pointers.

Cade Roux
+1 for not conflating "static class" with "global variable"
Nader Shirazie
+1  A: 

Immutable classes are often a good thing, as Abby Fichtner pointed out.

Static classes are often not good things. Aside from the threading issues DancesWithBamboo pointed out, you're dealing with global data if the class is not immutable. Ever try to debug a program that has lots of global variables?

Another issue is testability. You are likely to end up with many classes coupled to your static class. It's difficult to break that coupling for the purpose of unit testing. The static methods will always get called.

Singletons are nothing more than global data in sheep's clothing. They suffer from the same issues as static classes and global variables.

There are valid use cases for static classes (extension methods come to mind). Even Singletons have their place. But think carefully before implementing either.

TrueWill