A previous developer has a couple public classes that do not inherit from any other classes but are filled with static properties. Is this another way of creating a struct or enum? Is this an older or newer technique of housing static data to be referenced? I find it odd/different to see a class built in this way but am wondering what other fellow programmers thoughts or feelings are about what this coder was trying to accomplish.
This is a made up example of what I am seeing…
public class CashRegister
{
public static decimal OneDollarBill
{
get { return (decimal)1; }
}
public static decimal TenDollarBill
{
get { return (decimal)10; }
}
}
4
Funny, I can’t imagine why you’d use an enum if it’s just human-readable representations of a variety of numbers.
Enums are good for a bunch of text values that don’t have numeric representations.
public enum Days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
They’re also good for enumeration maths (State = State ++
). In C#, they’ve also been designed to handle flags easily.
But for what you’re doing there, I much prefer a static class. Ultimately, it’s no different, but it does express the fact that I’m not expecting it to be enumerable.
In your example, I’m more disturbed by the use of (decimal)1
, which creates a constant int and casts it to a decimal, rather than 1M
which would be a constant decimal.
4
As you said, this kind of a class can act like an enum, see the int enum pattern(seen at least in java before java introduced enums as their own class).
Another reason would be to group up all kinds of small utility methods, such as handling xml, constants and the like, especially if handling them in their languange of choice is verbose.
It could also just mean that the developer who wrote the code does not know how to/is not comfortable using enums.
1
I think the main reason in this case is to add semantics to the code. It’s about code readability.
Instead of code looking like:
CashRegister.Add(1 + 10)
It now looks like:
CashRegister.Add(OneDollarBill + TenDollarBill)
(not saying this has high value, just thinking this might have been the reasoning).
2
The only thing that occurs to me is reflection. If you have a function somewhere that gets values using reflection, maybe a serilization function, it might make sense to do this. While you can use reflection on a static class, you can’t get an instance of it to pass around.
Note that while I am tossing this out as an answer, chances are that it is not /the/ answer.
The class you posted could indeed be replaced by an enum. However, there are some situations a developer might want to use a class of static properties, for example if they needed to execute code in get{} (do some calculations based on other variables, etc.) and/or they wanted the value to be changeable via set{}.