I have been reviewing some code of some old projects and I found a singleton there. It is a requirement to use a singleton and I was thinking of a way to make it look "simpler" when using.
I found, it would be easier to access the methods and properties like a static class. So I basically implemented a singleton using static methods to skip the requirement to use GetInstance(). This is how I implemented it:
public class ExampleSingleton
{
string someRequiredValue = "This is an example.";
/// <summary>
/// Private Constructor
/// </summary>
private ExampleSingleton() { }
private static volatile ExampleSingletoninstance;
/// <summary>
/// !!! PRIVATE !!!
/// Instance Property.
/// Returns the instance of this singleton.
/// (ThreadSafe)
/// </summary>
private static ExampleSingleton Instance
{
get
{
if (instance == null)
{
lock (_lock)
{
if (instance == null)
{
instance = new ExampleSingleton();
}
}
}
return instance;
}
}
/// <summary>
/// Example field contains a value that should be
/// accessible from outside.
/// </summary>
public static string SomeRequiredField
{
get
{
// Here you do the job you would have to do "outside"
// of the class normally.
return ExampleSingleton.Instance.someRequiredValue;
}
}
// Helper for a secure thread synchronisation.
private static object _lock = new object();
}
So when you want to access the singleton values you can just do it like this:
// Access the values like this
string requiredField = ExampleSingleton.SomeRequiredField;
// Instead of this
string requiredField = ExampleSingleton.Instance.SomeRequiredField;
// Or even this
string requiredField = ExampleSingleton.GetInstance().SomeRequiredField;
Am I violating the principles of the singleton pattern here? It basically is still a singleton pattern but the work of getting the instance is done internally. What could be the con's of this example? Are there other pro's?
Thanks
In terms of cons, there are two that have bitten me in the past:
It's hard to mock the singleton due to the fact that the getters are static
Changes to the singleton interface need 2 separate changes (one for the public static, one for the internals).
Namely, I think that this:
ExampleSingleton.Instance.SomeRequiredField
Is easier to mock simply because you would need to replace/revert the Instance field. Questions pop up from time to time around "how to mock static this or that" probably due to classes like the one you posted:
How to mock with static methods?
Mocking Static methods using Rhino.Mocks
In general, a singleton pattern in C# is probably not the best idea due to the fact that they are harder to mock in general, unless you make the constructor public or use a ioc container, but if you need one, having the instance getter is probably easier to test in general.
Second point is more around incremental maintenance cost of code. Basically to "add to the class" you have two points of code that must be changed:
class ExampleSingleton
{
... existing code ...
public static int ComputeComplicatedMethod()
{
return ComputeComplicatedMethodImplementation();
}
private int ComputeComplicatedMethodImplementation()
{
// really complex code.
}
}
So you've essentially added an extra layer of abstraction for every new field versus just once for a get instance field. Either that or you have a static method that uses the internal static singleton like so:
class ExampleSingleton
{
... existing code ...
public static int ComputeComplicatedMethod()
{
// use ExampleSingletonInstance here
}
}
Which is really no better than just having a static class with static methods. A better question is why isn't the Singleton pattern implemented with just a static class? That might be better explained here: http://www.dotnetperls.com/singleton-static
I think you have to choose the solution with the least code (but it looks like people likes to wrote a bunch of useless code, so you may have difficulty to explain what is your point).
Use a static access to a property like in your example save you a word:
string requiredField = ExampleSingleton.SomeRequiredStuff;
vs
string requiredField = ExampleSingleton.Instance.SomeRequiredStuff;
But you have to wrote the getter for this property.
Also if you have a lot of properties it became an issue: you have to wrote a lot of static getter.
And this is not standard and go against OOP spirit: you handle the property of an object, so get the object then the property.
Also if your value is invariable, it is not a property!, the habit is to put the field const and public. Like ulong.MaxValue.
Doing this for the methods look like a bad idea. (and again in OOP, method belong to objects). If you don't want to have anything static you will have to build static functions that call the non-static ones. It will be not pleasant to maintain.
Related
I have a (growing) list of Data-Generators. The generator that I need is created by a factory class. The generators all implement a common Interface, which includes among other things a static string name.
What I would like to do: Call the factory.Create method with a string parameter for the above mentioned name. The create method finds the generator with this name and returns a new instance of said generator.
Bonus in my opinion of this way to do it: I only have to add new generator classes without having to edit the factory.
Question:
Is this a good way to handle this problem?
How can I find all generators? Reflection over every implementation of the interface/every member of the namespace (unique for the generators + their interface)?
Is it correct to call this way of working a factory, or is this some different pattern?
In the end I would call the factory like this (simplified):
//Caller
public DataModel GetData2()
{
var generator = new DataFactory().Create("Gen.2");
return generator.GetData();
}
//Factory
public class DataFactory
{
public AbstractDataGenerator Create(string type)
{
//Here the magic happens to find all implementations of IDataGenerator
var allGenerators = GetImplementations();
var generator = allGenerators.FirstOrDefault(f => f.name == type);
if (generator != null)
return (AbstractDataGenerator)Activator.CreateInstance(generator);
else
return null;
}
}
//Interface
public abstract class AbstractDataGenerator
{
public static string name;
public abstract DataModel GetData();
}
//Data-Generators
public class DataGen1 : AbstractDataGenerator
{
public static string name = "Gen.1";
public DataModel GetData()
{
return new DataModel("1");
}
}
public class DataGen2 : AbstractDataGenerator
{
public static string name = "Gen.2";
public DataModel GetData()
{
return new DataModel("2");
}
}
Should the magic GetImplementations() in the factory be done via Reflection or somehow different? Should I use a completely different approach?
Since answers refer to IoC and DI: This project uses NInject already, so it would be available.
Switched from interface to abstract class.
Is this a good way to handle this problem?
Having a factory to get an instance of the logic class you need by some key - I believe it is a good way. It is a pattern that I use a lot myself. About the way you have your key - I'd prefer to not have it as a static member (regardless to the fact that interfaces can't have static members) but just as a property and to add a base class to the IDataGenerator. That base class will have a constructor that will get the name - That way each new DataGenerator you create will have to set it and you wont forget.
About having the name as a string - I personally prefer having it "strongly typed". What I mean is that if I pass Gen . 2 instead of Gen.2 with strings I will discover this problem only in runtime. Possible other ways (if you want, because a simple string is fine too - a matter of taste):
Replace strings with an enum
Have a static class with static readonly strings for all your values - then in your code use those values. You get the benifits of the intellisense and of not getting the string wrong but better than enum - you can just still pass strings that are not in the "list" so you can add new ones as add-ons.
Have a RequestGenerator object, with each Generator being IDataGenerator<TGeneratorRequest>. This might be an overkill but if you have also extra information you need for the creating of a DataGenerator which differs between them then consider it .
How can I find all generators? Reflection over every implementation of the interface/every member of the namespace (unique for the generators + their interface)?
Yes, reflection can be a good way to do so. However, I would suggest to read into Dependency Injection and IoC Containers like Castle Windsor for example. There are things out there that already implement it for you, so why to re-invent the wheel :)
DI is a life changer concept in my opinion
Is it correct to call this way of working a factory, or is this some different pattern?
Yap. It is a Factory
Should the magic GetImplementations() in the factory be done via Reflection or somehow different?
See answer for question 2
This is where constructor injection can REALLY shine. Look into dependency injection tools and employ one! It also checks your "Bonus" request.
Here's what your factory might look like with constructor injection:
public class DataFactory
{
private Dictionary<string, IDataGenerator> generators;
public DataFactory(IDataGenerator[] generatorReferences)
{
this.generators = generatorReferences
.ToDictionary(k => k.name, v => v);
}
public IDataGenerator Create(string type)
{
IDataGenerator generator = null;
this.generators.TryGetValue(type, out generator);
return generator;
}
}
Most DI software has the capability to automatically scan assemblies for implementations of a certain type (e.g. IDataGenerator) and register those with itself, when it constructs an instance of your DataFactory it'll automatically include them.
I have a math helper class where every single function is static, i.e., params fed in as arguments, value returned. Should I declare the entire class as static? Would adding the static modifier to the class make a difference in performance?
Also, I am not sure what this guideline means in: "do not treat static classes as a miscellaneous bucket." - I have a few classes that are just a bunch of miscellaneous static functions...
It's perfectly fine to make classes like that static, in fact if you look at System.Math you'll see it's static as well:
public static class Math
What the guideline is trying to say is you should not put every static method you have to one static class which would do everything and play a role of a bucket for static methods. Instead, if it's appropriate, create smaller util classes with methods related to the same functionality, like it's done with System.Math and couple more within BCL as well.
Should I declare the entire class as static?
Yes. Adding static to a class says that it contains only static members and that you can't ever instantiate it. Without it, users of your class might get confused and try to create an instance or variable of your class. With static, that's not possible.
It seems like this is exactly your case.
Would adding the static modifier to the class make a difference in performance?
No, call to a static method will always have the same performance characteristics, it doesn't matter whether the containing class is static or not. Actually, the whole concept of static classes doesn't exist at the CIL level, they're just sealed abstract classes (a combination that wouldn't compile in C#).
But even if there was a difference, it would be tiny. Don't optimize prematurely, especially when it comes to micro-optimizations.
Helper classes are normally static classes, so that you don't need to instantiate them. There is no great cost in instantiating a managed .NET object (especially helper classes), it is just a matter of convenience.
It is extremely tempting to just put together a static class with minimal helper methods and get the job done. They have their place in code, and can be used especially when there is deterministic input/output. e.g. ComputeHash of a string, Find Average of numbers etc.
But the one reason, Static classes are discouraged is because they normally interfere with unit testing and present all sorts of problems. (Fakes, Moles, Private Accessors etc.)
An interfaced based approach for even helper classes, helps with the unit testing of the overall code. This is especially true for big projects which involve workflows such that the static helper methods are only a part of the workflow.
e.g. Suppose you need to check if the current year is a leap year. It is tempting to write a quick static method.
public static class DateHelper
{
public static bool IsLeapYear()
{
var currentDate = DateTime.UtcNow;
// check if currentDate's year is a leap year using some unicorn logic
return true; // or false
}
}
and if this method is used in your code somewhere like:
public class Birthday
{
public int GetLeapYearDaysData()
{
// some self-logic..
// now call our static method
var isLeapYear = DateHelper.IsLeapYear();
// based on this value, you might return 100 or 200.
if (isLeapYear)
{
return 100;
}
return 200;
}
}
Now, if you go and try to unit test this method public int GetLeapYearDaysData(), you might end up in trouble since the return value is indeterminate.. i.e. depends on the current year and it is not recommended to have unit tests behaving unpredictably/deteriorate as time progresses.
// this unit test is flaky
[Test]
public void TestGetLeapYearDaysData()
{
var expected = 100;
// we don't know if this method will return 100 or 200.
var actual = new Birthday().GetLeapYearDaysData();
Assert.AreEqual(expected, actual);
}
The above problem happens because we cannot control/mock the method IsLeapYear() in the above code. so we're at its mercy.
Now imagine the following design:
public interface IDateHelper
{
bool IsLeapYear();
}
public class DateHelper : IDateHelper
{
public bool IsLeapYear()
{
var currentDate = DateTime.UtcNow;
// check if currentDate's year is a leap year using some unicorn logic
return true; // or false
}
}
Now our birthday class can be injected with a helper:
public class Birthday
{
private IDateHelper _dateHelper;
// any caller can inject their own version of dateHelper.
public Birthday(IDateHelper dateHelper)
{
this._dateHelper = dateHelper;
}
public int GetLeapYearDaysData()
{
// some self-logic..
// now call our injected helper's method.
var isLeapYear = this._dateHelper.IsLeapYear();
// based on this value, you might return 100 or 200.
if (isLeapYear)
{
return 100;
}
return 200;
}
}
// now see how are unit tests can be more robust and reliable
// this unit test is more robust
[Test]
public void TestGetLeapYearDaysData()
{
var expected = 100;
// use any mocking framework or stubbed class
// to reliably tell the unit test that 100 needs to be returned.
var mockDateHelper = new Mock<IDateHelper>();
// make the mock helper return true for leap year check.
// we're no longer at the mercy of current date time.
mockDateHelper.Setup(m=>m.IsLeapYear()).Returns(true);
// inject this mock DateHelper in our BirthDay class
// we know for sure the value that'll be returned.
var actual = new Birthday(mockDateHelper).GetLeapYearDaysData();
Assert.AreEqual(expected, actual);
}
As you can see, the moment the helper methods were Interface based, they were easily testable. Over the course of a big project, many such smaller static methods ultimately result in bottlenecks in testing key functional flows.
So it pays to be aware of this pitfall in advance and make the additional investment upfront. Basically identify what classes/methods need to be static and what shouldn't be.
It all starts from when should I have a static method, and that is when you don't have any dependency on instance variables.
Now that said if none of you methods are depending on instance variable, you can make your class static.
Static class serve several benefits, and many more.
I came across this answer by Marc Gravell on how to create an object without calling its constructor. Can someone confirm this will not circumvent even the complete and best implementation of singleton pattern(Reference implementations here. And why? I guess more specifically I am not clear on the inner workings of GetSafeUninitializedObject() in the context of a Class's constructors (static, private etc)
Within the singleton pattern you have a static variable on your type that will be initialized by the type constructor.
By calling GetSafeUninitializedObject you only avoid the instance constructor which will be called after the type constructor.
Example:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private static string _StaticMessage = "Type ctor;";
private string _Message = "init; ";
static Singleton()
{ }
private Singleton()
{
_Message += "ctor; ";
}
public static Singleton Instance
{
get { return instance; }
}
public string Message { get { return _StaticMessage + _Message; } }
}
internal class Program
{
private static void Main(string[] args)
{
var singleton = Singleton.Instance;
// writes "Type ctor;init; ctor;"
Console.WriteLine(singleton.Message);
var instance = (Singleton)System.Runtime.Serialization.FormatterServices
.GetSafeUninitializedObject(typeof(Singleton));
// writes "Type ctor;"
Console.WriteLine(instance.Message);
}
}
Update to clarify difference between type initializer and static ctor asked from IllidanS4
This doesn't really belong to the answer above, but to the question within the comments: And a answer simply doesn't fit into a simple comment.
#IllidanS4: The type initializer is just a shortcut for writing an implicit static constructor. If you create a class that contains both initialization methods and decompile the resulting assembly you can see only one static constructor (.cctor) that will initialize all the variables. The both assignments will be merged where the type initializer will be called first and the statements within the static constructor last.
Take this sample class:
internal static class C
{
public static readonly string ByTypeCtor;
public static readonly string ByTypeInitializer = "From type init; ";
public static string ByBoth = "From type init; ";
static C()
{
ByTypeCtor = "From static ctor; ";
ByBoth += "From static ctor";
}
}
If you compile it and afterwards decompile it (e.g. by using ILSpy) you'll get the following code back:
internal static class C
{
public static readonly string ByTypeCtor;
public static readonly string ByTypeInitializer;
public static string ByBoth;
static C()
{
C.ByTypeInitializer = "From type init; ";
C.ByBoth = "From type init; ";
C.ByTypeCtor = "From static ctor; ";
C.ByBoth += "From static ctor";
}
}
Due to this fact i normally never use to initialize a variable directly when it will be declared. Instead i always leave them uninitialized (like the ByTypeCtor variable) and make all initializations within the constructor. This simply avoids cluttering variable initialization to different positions within the class which improves maintainability.
As everyone has mentioned, it can circumvent and undermine your design pattern.
But take a look at the recommended usage for GetSafeUninitializedObject
According to MSDN:
GetSafeUninitializedObject should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.
The GetSafeUninitializedObject method works even on objects with private constructors, so it could potentially be used to circumvent the singleton pattern.
Yes, the default Singleton pattern is definitely better in most situations. The expected behaviour of your type, is that it's ctor has to be called.
Creating an object without calling ctor method on that type, is not something "normal", so I, personally, would always avoid using this solution till have really strong reasons to do so.
Side note: the singleton pattern is just a pattern and not framework behaviour. In my opinion, in this question, you mix 2 concepts that don't mix together.
The first case is a way to create an object, the second case, is a way to architect code.
General rule is: don't do "strange things" (GetSafeUninitializedObject is strange one), till you really need do so. Keep goinig on common shared across all developers patterns and keep things simple as much as it possible.
I am working with WF4 and need to use Types I created before, in a Workflow, but I'm not sure of my strategy.
I have a class:
class MyClass
{
public MyClass()
{
//Constructor Logic
}
public void Connect()
{
//Connect to a TCP/Device for example
}
public void Disconnect()
{
//Disconnect from a TCP/Device for example
}
}
and i want to use it in a WF4 Flowchart or StateMachine.
Then i have my main application:
class Program
{
private MyClass myObject;
WorkflowApplication WorkflowApplicationHoster;
static void Main(string[] args)
{
myObject = new MyClass;
IDictionary<string,object> input = new Dictionary<string,object>() {{"MyClassInstance",myObject} };
WorkflowApplicationHoster = new WorkflowApplication(new MyWorkflow,input);
WorkflowApplicationHoster.Run();
}
}
In my Workflow i have the "InArgument" -> "MyClassInstance" which is a MyClass Type and i use it for the whole workflow.
This doesn't feel correct. How to use own classe with the WF4?
OK -- so if I'm understanding this properly what you're trying to understand is how to get a new instance of your type into the workflow so it can be used. Generally speaking I've always been able to simply declare a variable and initialize it in some manner, but the question becomes what kind of initialization do you need?
If you just need to create a new instance of it, like shown above, then declare a variable of your type and in the Default Value issue the New {TypeName}() to create a new instance.
However, you're going to need to provide a lot more information if this doesn't help.
You want to use that MyClass instance in global scope; is how I read this.
One popular way is to create it as a Singleton. Generally this means you have a private/protected constructor and a public Instance method that ensures that one and only one instance is ever created.
Another way is to make the class, and thus all it's methods, static.
There are multiple threads in StackOverflow on the topic of these approaches. Additionally, it seems the real argument is whether to have something in global scope or not, not necessarily how that's implemented.
I have an application that gets some data from the user when the application loads and is needed throughout the application, what is the best way to keep hold of the object that holds this data throughout the entire lifetime of the application?
This data needs to be available to most other objects created during the lifetime of the application.
I learnt the other day that Singletons are not necessarily a good idea. Especially in multi threaded environments, which my application is.
I have been using Singletons to handle this problem, but I wondered if this is a good way to deal with this?
EDIT:
Let me elobarate: I'm asking for username and password when the application starts, now I know keeping a password in-memory is out security and bad practice, but throughout the logon process there is quite a few places I need this data to check various things, so this is where I used a Singleton.
I'd advise against using a class that defines its own singleton just because that usually means you'll have pains during unit testing.
If you use a generic singleton, you'll have the same functionality, but with added benefits later on when testing / moving away from the singleton pattern (going multi-users for example).
Note that the singleton is initialized with a delegate. The rationale here is that the delegate will only be called once, even if two threads are somehow registering the singleton at the same time...
Using an interface makes your life easier when writing unit tests as you can mock the part of the singleton you are interested in for your test (or your ultra quick - 2 minutes before demoing to the CEO patch/debugging session).
It might be overkill for storing a login/pass tuple, but this pattern saved my bacon more times than I care to count.
public static class Singleton<T>
{
private static T instance;
private static readonly object sync = new object();
static bool registered = false;
public static T Instance
{
get
{
return instance;
}
}
public static void Register(Func<T> constructor)
{
lock (sync)
{
if (!registered)
{
instance = constructor();
registered = true;
}
}
}
}
class Demo
{
class Data
{
public string Pass { get; set; }
public string Login { get; set; }
}
void SimpleUsage()
{
string login = "SEKRIT";
string pass = "PASSWORD";
// setup
Singleton<Data>.Register(() => new Data { Login = login, Pass = pass });
//
var ltCommander = Singleton<Data>.Instance;
}
/// <summary>
/// Using an interface will make the singleton mockable for tests!
/// That's invaluable when you'll want to fix something FAST without running the whole app!
/// </summary>
interface IData
{
string Login { get; }
string Password { get; }
}
class UnitTestFriendlyData : IData
{
public UnitTestFriendlyData(string login, string password)
{
Login = login;
Password = password;
}
public string Login { get; private set; }
public string Password { get; private set; }
}
void SmarterUsage()
{
// same setup, but through the interface.
Singleton<IData>.Register(() => new UnitTestFriendlyData("login", "pass"));
// and same for the retrieval
var data = Singleton<IData>.Instance;
}
void UnitTestSetupWithMoq()
{
// Register a mock.
var mock = new Mock<IData>();
mock.SetupProperty(x => x.Login, "Login");
mock.SetupProperty(x => x.Pass, "Pass");
Singleton<IData>.Register(() => mock.Object);
// and same for the retrieval
var data = Singleton<IData>.Instance;
}
}
See this for some explanations
Implementing Singleton in C# , looking at Multithreaded Singleton.
Also Ist way of implementing Singleton Pattern in C#: looking at IIIrd way of implementing Singleton Pattern in C#: Simple Multithreaded Singleton Pattern and IVth way of implementing Singleton Pattern in C#: Multithreaded Singleton Pattern
In this case, a singleton is the proper choice. You just don't want to start shoving in a lot of unrelated stuff in there -- you want the class to remain cohesive and not just a "bag of properties" that sits around. As far as multithreading goes, you can put the appropriate controls on your singleton class, no problem. What types of locks and protections you use, however, is specific to your implementation (there's not enough detail in your question to answer that, though).
My first reaction to this is that if you have a piece of data that is required by most other types in the application, you may want to encapsulate it better. It sounds like a violation of the Single Responsibility Principle. However, without knowing more about your scenario, it difficult to say what the remedy could be.
From the way you described your situation, it sounds like you just want to save off a string once at startup and then it would always just be read-only everywhere else. If this is the case, you can really just do something like:
internal static class LoginInfo
{
internal static string Username;
internal static string Password;
}
Then from anywhere in your app you can just say:
var usr = LoginInfo.Username;
var pwd = LoginInfo.Password;
Now i'm sure everyone will comment that is is a terrible design practice, but I'm prepared to live with that :)
Now if you plan on changing the value all the time, and if this wasn't just a string and was instead some more complex object, then thread-safety could certainly become an issue. You could always make a thread-safe getter on a property.
The reason people say that a Singleton isn't necessarily a good idea is because it encourages a scenario like yours. Needing a static object is the bad part - a Singleton is just seen as an enabler.
That said, I can't really comment on whether it's neccesary in your application, because you haven't detailed it. But if you REALLY need static data held in an object for the application's lifetime, go right ahead and use a singleton.
You can make them thread-safe as well.