Singletons and constants - c#

I am making a program which makes use of a couple of constants. At first, each time I needed to use a constant, I'd define it as
//C#
private static readonly int MyConstant = xxx;
//Java
private static final int MyConstant = xxx;
in the class where I'd need it. After some time, I started to realise that some constants would be needed in more than one class.
At this time, I had 3 choises:
To define them in the different classes that needed it. This leads to repetition. If by some reason later I need to change one of them, I'd have to check in all classes to replace them everywhere.
To define a static class/singleton with all the constants as public.
If I needed a constant X in ClassA, ClassB and ClassC, I could just define it in ClassA as public, and then have ClassB and ClassC refer to them. This solution doesn't seem that good to me as it introduces even more dependencies as the classes already have between them.
I ended up implementing my code with the second option.
Is that the best alternative? I feel I am probably missing some other better alternative.
What worries me about using the singleton here is that it is nowhere clear to a user of the class that this class is using the singleton. Maybe I could create a ConstantsClass that held all the constants needed and then I'd pass it in the constructor to the classes that'd need it?
Thanks
edit: I'm using this mostly for complex types, not ints and strings. At least in the C# case that makes a difference as it means I can't use the const keyword.

No wording about C#, but in Java there are several ways to solve this problem.
Change the access modifier to default (package-only) or public. The most straightforward solution.
Group them in a package-private or public enum. Most straightforward if those values are related to each other. E.g. Role.ADMIN, Role.USER, Role.GUEST, etc.
Declare them in a package-private or public interface and let the classes implement it. Only do this if those constants belong to some contract the classes have to adhere as well.
Put them in properties files and load as private static final Properties and add a public static String getProperty(String key). Wrap this in some package-private or public Configuration class. More useful if those constants might be sensitive to changes which you could then control externally.
Constants doesn't require to be accessed by an instance, so the whole singleton idea makes no sense.

Use a properties file and put the constants in there.

ConfigurationManager.AppSettings Property in .Net exists for just this reason. You put the settings into config files assuming that these are elements that you want to be set in one place,e.g. for a website using ASP.Net the web.config is one location where settings can be placed so that development, test and production environments can each have different settings in how they run.

As far as int is concerned I usually use an enum in C#
public enum MyMagicNumbers
{
TheFirst = 1,
TheSecond = 2,
TheLast = 10,
}
For other types - like BalusC already mentioned - a sealed class is all you need
public sealed class MyMagicStuff
{
private MyMagicStuff() {}
public const string TheFirst = "One";
public const string TheSceond = "Two";
public const string TheLast = "Ten";
}

I'd define it in one place, in one of the classes that needed it. I'd make it static and final and public so it was true constant, accessible by any other client that needed it.

One approach to this would be to use Spring, available in both Java and .NET.
www.springsource.org
www.springframework.net - .net
Otherwise I'd use a config file.

Related

C# in Unity 3D/2D: Am I required to use Classes for every script?

A little background: I'm new to C# and Unity, but catching on very quickly. I'm also hoping this thread will not spark a debate about the merits of classes and abstract coding, as that debate is unrelated and well-worn (and unnecessarily heated); so please keep that in mind.
I'm simply wondering if every C# script in Unity is required to have a main class in any way or for any reason.
Or instead, can methods, and variables can be written outside of a class in a blank file (with namespaces) to be used in a video game?
I'm asking because, when I create a new C# script, it seems to force a class into my file and I'm afraid of breaking things.
I hope to keep code abstraction to a minimum, and the current project
I'm working on has several situations where a class is not needed, or
only one instance of the class will be used. I'd like to simply avoid
using classes in those cases.
In terms of declaring/defining variables and methods outside of any class, you can't really do that in C#. It just isn't how the language was designed (the answers to the question I linked to expand on that idea, so I won't duplicate them here).
You're not without options, though; if you have a number of variables or methods that need to be accessible from different places and don't need an object reference, you can make them static, so you won't need to instantiate the class to make use of them:
public class UtilityClass
{
public static float GravityConstant = 3.51f;
public static string GameName = "MyFirstGame";
public static float CalculateProduct(float a, float b)
{
return a * b;
}
}
Then, you can reference the class's methods/members by accessing it through its name:
float product = UtilityClass.CalculateProduct(6, 1.5f);
An example of where you might use this pattern is when defining mathematical formulae which aren't included in Unity's Mathf methods, and using them in multiple classes.
Additional note: Creating a new C# script through Unity's editor UI will default to declaring a class of the same name that inherits from Monobehaviour. You can alter it to remove the inheritance from Monobehaviour if you don't need any of the methods/attributes of the class, which avoids unnecessary overhead. One example for this would be with a static class that you never need to instantiate.
Yes, you are.
In C#, things like global variables and functions just do not exist. Everything must be contained in a class.
"But what should I do in order to declare some stuff that can be accessed everywhere, without creating an object?" you asked. There is something called the static modifier. You can access the methods or variables or fields or properties marked with this modifier without creating an object of that class.
You just add the word static in a method and it becomes a static method! How simple!
Let's see an example.
I have this non-static method:
public class MyClass {
public void DoStuff () {
}
}
I can call it like this:
var obj = new MyClass();
obj.DoStuff();
But if I modify it with static,
public class MyClass {
public static void DoStuff () {
}
}
I can call it like this:
MyClass.DoStuff();
How convenient!
Note:
Please do not misuse the static modifier! Only use it when it makes sense! When? When the method is a utility method or when the method does not belong to individual objects but the class itself.
First of All you need to check where Methods define as offical
docs stated
"Methods are declared in a class or struct by specifying the access
level such as public or private...."
So, Method should be declare in a Class or struct and A given class
should be, ideally, responsible for just one task.(see also)
Your this question "Or instead, can methods, and variables can be
written outside of a class in a blank file (with namespaces) to be
used in a video game?" answer is hidden in the below question.
Can there be stand alone functions in C# without a Class?
No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.
You have to make a class in order to use methods or its variable
either instance class or static class.
Am I required to use Classes for every script? Every script means you required a class. Unity Support Component Based
Architectural Design and if you require any script related
work then you definitely require a script component which means a
class require.
Finally for singleton, thanks to Unity3dWiki great detail
available. I think you will be feel comfortable to code and writing
class if you keep in mind component based architecture of Unity3d.
Singleton vs Static: I will also recommend to check this: Why do you use a Singleton class
if a Static class serves the purpose
Hope it will help.
[Note: If this helpful Any one can update this answer for future reference and use].

How to structure classes in a C# program

I have a VSTO (Excel) project written in C#. Three questions:
I have a lot of variables that are populated once and then referenced extensively throughout the project. So I created a public static class which I called "Omni" - since that is both descriptive and short. Is something like this the recommended approach?
I put common functions in a public static class that I named "Utilities". I then used the "this" keyword as the first parameter, making them extension methods. They can then be accessed from anywhere - without using a "Utilities." prefix (although I'm not exactly sure why). Same question: is this the preferred way of doing this?
Finally, I have some common 'subroutines', i.e., public void methods. So parameters are passed in and processed, but nothing is returned. Should such common code just go in its own appropriately named public static class and then get called with the class name as a prefix? If so, is there any convention as to what the name of the class would be?
I realize these are newbie type questions (and I have been searching for a while!). Thanks.
Regarding your points
I have a lot of variables that are populated once and then referenced
extensively throughout the project. So I created a public static class
which I called "Omni" - since that is both descriptive and short. Is
something like this the recommended approach?
Yes, it is common practise to centralize for example string constants that
are often used.
If you have more of those, I would start to structure those to different
classes.
If you want that to be flexible and e.g. have cases where there are
mappings between constants, like Green = 1, I would move to some
enumeration value technology.
More on that idea can be found in this article
If the value does not change between different starts of your application,
check if you can use resources for that, which is often a good choice
for string constants to.
I put common functions in a public static class that I named
"Utilities". I then used the "this" keyword as the first parameter,
making them extension methods. They can then be accessed from
anywhere - without using a "Utilities." prefix (although I'm not
exactly sure why). Same question: is this the preferred way of doing
this?
Extension methods are a handy way of getting things like conversions done.
Just do not everything as an extension, just conversions as a rule of thumb.
Finally, I have some common 'subroutines', i.e., public void methods.
So parameters are passed in and processed, but nothing is returned.
Should such common code just go in its own appropriately named public
static class and then get called with the class name as a prefix? If
so, is there any convention as to what the name of the class would be?
This, in opposite of the others, looks like a design flaw.
Perhaps you can provide more information on what those subroutines do.
In object oriented code, code is distributed near the objects it is working
with. If you depend heavily on code that is in static classes, probably there
is something wrong. Do your static classes have members? Do they share some
knowledge between different calls to your static classes?

What's the best way to implement a global constant in C#?

I have a Common project inside which I've added my public constants for QueryStringNames.
I know generally constants should be as internal or private but I'd need public constants here as I'd like to allow a global access to the query string names, session keys, etc.
There are 3 solutions that I know of but all of them have an important issue. The caller assembly would contain the copy of my constant which means if I have to change a constant value, I'll have to compile both my Common assembly and the caller assembly!
1) public const string ConstName = "a value";
2) public readonly string ConstName = "a value";
3) To be stored in a public resource file.
What would be the best approach to define public constants in C# apart from storing them in the web.config file (which doesn't have intellisense)?
It depends. If it is truly a constant that won't change, even in future versions of your code, then const is fine. Else go with a static readonly field.
A const will get embedded into the calling assembly, whereas with static readonly the calling assembly only contains a reference to the field. This means const requires recompilation of all dependent code whenever you change the value, whereas public readonly uses the new value even without recompiling the calling assembly.
If you want to store the "constant" in a config file, but like Intellisense, you can use a property with no public setter. And then fill it from the config file at runtime. But I'd argue that configuration values should not be static in the first place. For configuration values I'd use a singleton of some sort, preferably the IoC variation and not the Class.Instance variation. So I'd just define an interface like the following:
interface IMyConfig
{
string Key{get;}
}
And have classes that need this config take it as a constructor parameter:
public MyClass(IMyConfig config)
{
...
}
If you think you'd be changing it and you're worried about having to compile it, then why not use appSettings in the web config file? That's what it's for. If you really need intellisense then you could just put a class in one of the assemblies that reads the config value and exposes it as a property for easier referencing. If it's sensitive data then I wouldn't put it in a config file, I would just compile it anyways since you don't want to compromise your application.
<appSettings>
<add key="myconstant" value="here's the value!" />
</appSettings>
Here's the class to reference that value, which gives you intellisense, ability to change it easily in the future, and without having to recompile anything
public class MyAppConfigSettings
{
public string MyConstant { get; private set; }
public MyAppConfigSettings()
{
MyConstant = ConfigurationManager.AppSettings["myconst"];
}
}
It may not be the answer to your solution but it may give you some other ideas.
If you are activating fxCop (code analysis tool included in Visual studio distribution), you may get sugestion to change constant to become:
public static readonly string ConstName = "a value";
I'm not sure if I understand the problem completely... you're asking for a solution to storing some global variables that won't cause recompiles to assemblies that reference those global variables if you change them? If so then why not try thinking about redesigning your architecture as per the Inversion of Control principle? Think "don't call us, we'll call you" the hollywood principle. If all the assemblies that require some const just call an interface (that they own) that exposes a property with the value they require, and then you have a project of constants that implement those interface (by referencing those projects and then implementing those interfaces) then those projects will never need recompilling when you change the value of the constants.
I'm sure you know them anyway but have a read up on the SOLID principles, "D" being the Dependency Inversion principle (Inversion of Control). I think given your concerns (assuming I've understood you right) they could really help you out.
An example of Inversion of Control could be as simple as:
MyService.dll :
public class MyService
{
// injected dependency
public IMyConstants MyConstants { get; set; }
public MyMethod(){
// get your query...
var query = IMyConstants.Query;
}
}
MyConstants.dll :
public MyConstants : IMyConstants {
// implementation of query property from the myservices.dll interface
public string Query { ... }
}
So the myconstants.dll references the myservice.dll rather than the other way around (meaning myservices won't need recompiling). Then the bootstrapping code (to set it all up and inject dependencies) lives elsewhere.
Sorry if I misunderstood you, hope that helps though!
I prefer the 2nd option in most case since it won't cause problem (by copy value to other assemblies). The speed may have a slower than constants but this kind of nano-second speed is pretty immature.
You could use the Cache object and define them in Global.asax
As said before, it's not the same scenario:
const: is contant and cannot be modified except by recompiling.
readonly: the value is initialized in the declaration or in the constructor and stay readonly after.
When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class

Using Static method and variables - Good vs Bad

I am developing C# and asp.net web application.
I have general class called utilities, I have lot of public and static variables in this public utilities class.
Since this number is gradually increasing, I want to know is it good practice to store utilities methods and variable as public static.
Example of my code
public class utilities
{
public static string utilVariable1 = "Myvalue";
public static string utilVariable2 = "Myvalue";
public static string utilVariable3 = "Myvalue";
:
public static string utilVariableN = "Myvalue";
public static string UtilMethod1()
{
//do something
}
public static string UtilMethod2()
{
//do something
}
public static string UtilMethodN()
{
//do something
}
}
There's nothing inherently wrong with static classes, although they should typically not have state (fields). Your use of public static fields indicates that this is not the case, so it seems like you are using abusing the static keyword slightly. If your class needs to have state, then it should be a normal, non-static class, and you should create instances of it. Otherwise, the only public fields visible on the class should be const (consider the Math class, with constants such as Math.PI - a good use of static methods and fields).
Another consideration is cohesion. Methods typically exist grouped in one class because they are closely related in one way or another. Again, the Math class is a good example; everything in there has to do with maths. At some point, you would want to split your global utility class into multiple smaller, more focussed ones. See Wikipedia for some examples on cohesion, it sounds like your usage falls under "Coincidental cohesion (worst)".
There's nothing wrong with this approach for methods, but variables should really be const if they're going to be static and public. If they are subject to change then you should look at a different structure for variables that are being manipulated by more than one component.
Personally, I'm a fan of the Singleton pattern.
static is not a bad thing per se. Methods that don't need to access any member variables or methods should always be declared static. That way the reader of the code sees immediately that a method won't change member variables or methods.
For variables the situation is different, you should avoid static variables unless you make them const. Public static variables are globally accessible and can easily raise issues if multiple threads access the same variable without proper synchronization.
It is hard to tell for your case if it's a good or a bad idea to use statics, because you didn't provide any context information.
Creating one class to do it all is not a good practice, and it's recommended to structure your project, and keep stuff that belongs to each other separated from the randomness.
A great example of this was a project I took over from a co-worker. There was 1 class, called Methods. It contained over 10K lines of methods.
I then categorized them into approx. 20 files, and the structure was restored.
Most of the methods from that project were validating user input, which can easily be moved into a static class Validation.
One awful thing I notice is the mutable public and static variables. This is bad for several reasons:
Incorrect behavior, because if some method changes this, while it isn't supposed to do that, it causes other methods to behave improperly, and it's really hard to track down/debug.
Concurrency, how are we going to ensure thread safety? Do we let it over to all methods that work with that? Say if it's a value type, what will we let them lock on? What if some method forgets to make it thread safe?
Expand-ability (I hope you understand what I mean with that), if you have for example a static class data that stores all these public static variables, that you shouldn't have. It can store that once, if for example you might change your application structure a bit, and say want to make it possible to load two projects in the same screen, then it's very difficult to make that possible, because you can't create two instances of a static class. There is only one class, and it'll remain like that.
For number 3 a cleaner solution would be to store either a list of instances of a data class, or to store a reference to the default and/or active data class.
Static member, and private static members (or protected) are a good practice, as long as you don't make huge classes, and the methods are related.
Public and static variables are okay if they're not really variable.
The two ways to do this is by marking them constant (const modifier) or readonly (readonly modifier).
Example:
public class UtilitiesClass
{
internal UtilitiesClass() { }
public void UtilityMethod1()
{
// Do something
}
}
// Method 1 (readonly):
public static readonly UtilitiesClass Utilities = new UtilitiesClass();
// Method 2 (property):
private static UtilitiesClass _utilities = new UtilitiesClass();
public static UtilitiesClass Utilities
{
get { return _utilities; }
private set { _utilities = value; }
}
The advantage of method 1 is that you don't have to worry about thread-safety at all, the value can't change.
Method 2 is not thread-safe (though it's not difficult to make it that), but it has the advantage of allowing the static class itself to change the reference to the utilities class.
No, it is not a good practice for large applications, especially not if your static variables are mutable, as they are then effectively global variables, a code smell which Object Oriented Programming was supposed to "solve".
At the very least start by grouping your methods into smaller classes with associated functionality - the Util name indicates nothing about the purpose of your methods and smells of an incoherent class in itself.
Second, you should always consider if a method is better implemented as a (non-static) method on the same object where the data that is passed as argument(s) to the method lives.
Finally, if your application is quite large and/or complex, you can consider solutions such as an Inversion of Control container, which can reduce the dependency on global state. However, ASP.Net webforms is notoriously hard to integrate into such an environment, as the framework is very tightly coupled in itself.

Lookup class use enum, struct, public const, something else?

I'm creating a lookup class so a constant value will be used throughout all the projects.
The thing is, there are several solutions to create such a thing. I could create a single class with enums, structs or constants in it or create a single class for every 'object'. I'm wondering what would be the best solution.
First I thought doing something like this:
public static class Defines
{
public enum PAGELAYOUT_NAMES
{
STANDARD = "Standard"
}
}
But personally I don't like using strings in enums that much.
Another option would be to use a struct, which is even more ugly if you see the code:
public static class Defines
{
public struct PAGELAYOUT_NAMES
{
public static string STANDAARD = "Standaard";
}
}
This looks a bit better, but could be confusing when having a lot of options:
public static class Defines
{
public const string PAGELAYOUT_NAMES_STANDARD = "Standard";
}
While typing this post, I think this will be the best/clean option:
public static class PageLayout
{
public const string STANDARD = "Standard";
}
Any other suggestions?
Filling up the project with several classes which only define some constants seem to me like a lot of overhead and clutter.
Edit
It wasn't very clear in the original context, but the lookup values aren't limited to only strings. Some very good suggestions below are only possible when you use only strings, but Int's, DateTime and other types need to be supported also. Got some nice ideas from the answers here, I'll try out which one will work best in my current project.
Final implemented solution
Thanks to the suggestions below, I've implemented the lookup classes like this:
internal class Base<T>
{
internal T Value{ get; private set;}
internal Base(T value)
{
Value = value;
}
}
public class PageLayout
{
public static string Standard { get { return new Base<string>("Standard").Value; } }
}
This is based on an answer given below.
Reason is because now I can use this for non-strings & integers also, which isn't really possible with an enum with a description and a resource file, even though that would feel cleaner to me.
Depending on what exactly it is you're doing, you probably want to look at Resources.
You define an xml file (or use the designer to help you), and it gets compiled into an assembly (either embedded, or a "satellite assembly").
Right-click the properties node under your class library in the solution explorer, click "Open" and go to the resources tab. It's pretty simple to get started from there.
Once it's set up, it's easy to get at the values from code e.g:-
String s = Resources.PageLayoutNames.Standard;
There are a few complications, but without knowing more about your app I can't advise more. The one that comes to mind is if you're unit testing ASP.NET applications you need to make sure that the resource gets embedded rather than deployed as a satellite otherwise the unit tests don't work.
They're also used for globalisation, so it's good to be familiar with them.
Edit:
Alternately after reading your question again, I'm inclined to ask "What do you need the string for at all?".
What are you doing that you can't do with just an enum?
enum PageLayouts
{
Standard,
ExtraAwesome
}
If you're trying to map text for display to an enum type, there are a bunch of ways to do that e.g. by using the DescriptionAttribute
enum PageLayouts
{
[Description("Standard")]
Standard,
[Description("Extra Awesome")]
ExtraAwesome
}
You can't give the DescriptionAttribute a resource key out of the box, though. You have to subclass it if you want to support globalisation...
I prefer this way using a factory style static properties. But it depends on the exact scenario. You can use string or enum as the field.
public class PageLayout
{
private readonly string LayoutType;
private PageLayout(string layoutType)
{
LayoutType = layoutType;
}
public static Standard {get {return new PageLayout("Standard");}}
}
Then in calling code use PageLayout.Standard
People advise against public nested classes, so in your earlier examples Defines should be a namespace rather than an outer class.
I always use the
public static class PageLayout
{
public const string STANDARD = "Standard";
}
approach.
I do however create more classes than one: When i use a lot of sessionvariables, i create a (public static)
class SessionNames
And i do make a difference between soultion wide constants and project wide constants.
sometimes the constants for one project (for example 20 placeholders in a PDF you have to create) have nothing to do with the other projects so i make that a project class, but when i have solution wide constants i create a class at the same place as i put my string extensions etc.

Categories