1

OK let's say I have something like this:

public class MyObject {

    public static int DefaultValue = 9

    private int _value = DefaultValue;
    public int Value { get { return _value; } set { _value = value; } }

}

That way, changing the DefaultValue will change Value for all future instances - so having a constant default value is not the same thing.

Is this a known programming practice or pattern?

Matthew Flynn
  • 13,345
  • 2
  • 38
  • 57
  • This isn't much different from a `const`. Why not use that instead? Or if you prefer, what about a `Enum`? – Adam Zuckerman Apr 30 '16 at 02:09
  • 1
    Constants can't be changed at runtime. With a public static it can be changed to affect all future created objects. –  Apr 30 '16 at 03:03
  • 1
    BTW, with C# 6.0, you can simplify that to `public int Value { get; set; } = DefaultValue;`. – svick Apr 30 '16 at 10:42
  • 1
    I have trouble imagining worse disruption. Global state is bad enough by itself, but hidden global state? – Basilevs Apr 30 '16 at 15:31
  • Only if your class is immutable (or the internal mutability is unobservable). – CodesInChaos Apr 30 '16 at 16:38

2 Answers2

5

I'm sure there are situations where this would make sense to do, particularly if you're writing a small application, but in general I think it would be a bad idea.

You could apply any argument that you could make about global variables to static variables - they're still changeable anywhere in the application.

If your application (and dev team) is sufficiently large then you could easily have another developer accidentally update the default value without knowing the consequences.

If you were needing to create the objects using different default values - maybe you could take inspiration from the Factory Pattern, and have the code for specifying the defaults within the factory class so that different defaults could be used per instance. You could then go the distance and make your factory instances immutable so that you'd have to intentionally reassign references to it everywhere you wanted to use the new default value.

Though I think I may be suggesting over-engineering here.

Brett
  • 247
  • 1
  • 6
3

This is not a good idea because you can introduce a race condition.

In one thread you change the value to one you want but before you manage to create an instance of the class another thread changes the value, and you get an instance created with the wrong default value.

Your hair will grow whiter than mine, trying to figure out why things aren't working as it is supposed to.

In my opinion this is not an anti-pattern nor a smell. It is just simply wrong.

Bent
  • 2,566
  • 1
  • 14
  • 18