Coding practice - using abstract or a private constructor - c#

I have a question about coding practice. I want to create a class which can't be initialized. I believe I have 3 options:
Abstract modifier
Static modifier
Private constructor
I don't want to create a static class simply because of having to name all of my properties and methods 'static' - it looks messy (and I can't use the 'this' keyword).
According to the MSDN:
Use the abstract modifier in a class declaration to indicate that a
class is intended only to be a base class of other classes.
Edit Nothing will inherit form this class.
However, it would be a solution (but it seems wrong to me to use it in this situation).
Or, I can make a private constructor so the class cannot be initialized.
If it helps the reason for why is this: The class is responsible for starting off a work flow process. It doesn't need to be initialized since nothing is returned - it just needs to be 'started'.
Demo code
class Program
{
static void Main(string[] args)
{
WorkFlow wf = new WorkFlow(); // this will error which is fine!
ComplexObject co = new ComplexObject();
WorkFlow.Begin(co);
Console.ReadKey();
}
}
public class WorkFlow
{
private WorkFlow()
{
//private to prevent initialization but this feels wrong!
}
public static void Begin(ComplexObject co)
{
//code to begin the workflow
}
}

I want to create a class which can't be initialized.
That leaves the possible usages: static or base-class only.
If your class is going to be derived from, use abstract. A private/protected constructor would be a hack in this situation.
Your sample code looks more like a static class. With Singleton as alternative.

What about doing just what you have done but using your Begin method as a factory to create your workflow.
var workflow = Workflow.Begin(complexObject);
public class WorkFlow
{
private WorkFlow()
{
//private to prevent initialization but this feels wrong!
}
public static WorkFlow Begin(ComplexObject co)
{
return new Workflow(co);
}
}

Good practice: Private constructor (at least is what the GOF book recommends when using the Factory pattern, for example). I'll suggest you to use abstract if it's a base class (that's what it's name suggest).

If the class is strictly being used as a base class, it would have to be abstract for me.
Based on your update I would go for a static class & method e.g.
WorkFlow.Begin(co);
However, since you don't want to do this I think it only leaves you with one option...private constructor.

Seems like you would need a singleton.
More reference here:
http://msdn.microsoft.com/en-us/library/ff650849.aspx
if you dont like the ideea, well an abstract class would be best suited because as you said you dont want to instantiate it, and lets not forget that the abstract class does just that, so why try and use a private constructor.

I don't want to create a static class simply because of having to name
all of my properties and methods 'static' - it looks messy (and I
can't use the 'this' keyword).
Well, either you make ctor private or make a class static, the only way caller can access methods and properties of your class (if the caller is not derived one) is via public static members.
Having private ctor give you more flexibility in inheritance chain, but doesn't help much in "avoid static members" scenario.

I will prefer private constructor ie its identical to Singleton pattern
Info
Coding
Private constructors seems to be good approach for your requirement. Abstracts are good too but private constructor is handy than abstract. But if you would like to extend its information then its probably good idea to use abstract.

If the class needs to be "started" it needs to be initialized (unless all you're going to use are static methods).
Abstract classes are used to leave some (or all) of the implementation to subclasses, and by your description - not suitable for you.
"Static classes" - no special gain here I guess (in your case).
Private constructors - used to limit who can instantiate the class.
Not sure that any of these matches your design, but I guess you really want a singleton - look it up, this is the most common and basic design pattern.
BTW - I use singletons only as a last resort, usually when the class controls some kind of non shared resource.

Related

Moving singleton definition into mixins in C#

I have to change around 10 classes into singletons and I thought that instead of copy-pasting the code it makes sense to use mixins, like it is described here: http://msdn.microsoft.com/en-us/vstudio/bb625996.aspx
However, I need not that much of additional methods, but more additional changes to the class itself, I have problems applying those instructions.
I tried to create an empty interface ISingleton and then to add the singleton part as extension to the new class public static class Singleton
This is singleton part which I would like to use:
public static SomeClass Instance
{
get { return _instance ?? (_instance = new SomeClass ()); }
}
private static SomeClass _instance;
But when adding it as extension I had a problem - how to define the Instance property, so it will be reusable by many classes?
And the second issue - I still need to change the constructors to private manually.
Does this approach makes any sense?
I haven't used mixins before, maybe this is just not the right scenario for it?
The mixins link you gave shows extension methods being used to add functionality to all objects supporting an interface. You still need to create the objects first. As singleton patterns handle the creation of objects it's basicly too soon to apply these techiniques.
Singleton needn't be so complicated, you're reading Jon Skeets article, a simple:
public sealed MyClass
{
private MyClass(){}
public static MyClass Instance = new MyClass();
}
Is often all you need. I'd happily repeat that code 10 times if needed. Or one can use a service locator or IoC container to manage the lifetime of objects.

Best way to prevent a class from being Instantiated?

I need to know how to prevent a class from being Instantiated in .net?
I know few methods like making the class Abstract and Static.
Is there any more way to achieve this?
Making the class static is the best approach, if you absolutely don't want any instances. This stops anyone from creating instances. The class will be both sealed and abstract, and won't have any constructors.
Additionally, the language will notice that it's a static class and stop you from using it in various places which imply instances, e.g. type arguments and variables. This indicates the intention more clearly than just having a private constructor - which could mean that there are instances, created within that class (e.g. for a singleton implementation).
Oh, and making the class static will stop you from introducing any pointless instance members in the class, too :)
See MSDN for more information about static classes.
Mark the constructor(s) private, protected or if in used from another assembly, internal
Marking the constructor private. Of course, this doesn't prevent the class from instantiating itself through a static method, for example...
More practically, what's the purpose of disallowing class instantiation. If it's to have a singleton, then a private constructor is appropriate. If it's to force subclassing, making the class abstract is better; if it's to have a class with utility methods, making it static is one way (then you can only have static methods).
I need to know how to prevent a class from being Instantiated in .net?
Your question is not clear.
Do you mean instantiated at runtime? Make the class abstract or static.
Do you mean that the constructor is not accessible in code? Make the constructor private. But note that someone could still use reflection to grab a handle on a constructor and instantiate an instance at runtime.
So, which do you mean?
If the question is:
How can you make your class not be instanced without having your class
be static or abstract?
Then the answer to this is to implement the singleton pattern, which in .NET 4+ this is done easily with:
public sealed class myClass
{
private static readonly Lazy<myClass> lazyInstance =
new Lazy<myClass>(() => new myClass());
public static Instance
{
get
{
return lazyInstance.Value;
}
}
private myClass()
{
// constructor logic here
}
}
The singleton pattern allows you to pass your class around as a reference to methods, while still ensuring that you have only a single instance of your class. It also makes testing much easier as you can have a ImyClass instance which myClass implements, this is very helpful when making mock objects.
Without .NET4 you can still implement the singleton pattern, for example:
private static readonly myClass instance = new myClass();
public static Instance
{
get
{
return instance;
}
}
// rest of code remains the same
Which doesn't have deferred loading until it's called, there's lots of other ways as well (I think about 6 different ways), but the above two are the most common ones.
In summary the question is likely asking if you know the singleton pattern and if you recognise it's importance over static classes for unit tests and mock objects.
As others have already pointed out, static fields, even those marked readonly can be set with reflection, in addition the private constructor can be called using reflection. If you need to prevent these, either you need to make the calling code run in a less trusted app-domain space, or you will need to implement your class as static.
Generally though, people don't bother with such levels of reflection to get around your constraints unless they 'really need to' for example, writing obscure / extreme fringe case unit tests.

When would I want to model a class with a private ctor? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the need of private constructor in C#?
Hi,
I've seen plenty of classes in .NET which have private constructor (Stream is one of them I think). When would I want to model a class like this?
I keep thinking that if my class has no internal state/fields, then I can make it have a private constructor.
Am I on the right track with this idea? I can understand the use of a factory (I've run into the tipping point a few times), but not with a private constructor class.
Thanks
Private constructors are normally used for:
Constructor-Chaining - As targets for other constructors in the same class.
Controlling construction - Occasionally, all the constructors of a class are made private to:
Enforce the singleton pattern.
Only allow construction through static factory-methods.
Only allow nested classes (if any) to inherit from it.
I've seen plenty of classes in .NET
which have private constructor (Stream
is one of them I think)
System.IO.Stream is not an example of any of these - it has a single, protected constructor (at least as of .NET 4.0) . Since it is an abstract class, it does not make sense for it to have public constructors.
I keep thinking that if my class has
no internal state/fields, then I can
make it have a private constructor.
In this case, consider creating a static class instead, providing no instance constructors at all (a static class can't have instance constructors since instances of it cannot be created). Of course, there are cases when this may not be appropriate despite the lack of any state, such as when the class must implement an interface.
Make the constructor private if you don't want to allow external code to create an instance of your class. This is often used when implementing the Singleton pattern.
Actually, a private constructor is relatively rare. The constructor of the Stream class is protected, not private. That way only derived classes can call it.
The main reason for a private constructor is when implementing the Singleton design pattern. However there are other instances where limited the visibility of the ctor is useful. Sometimes I want to implement dependency injection (constructor injection) but only allow my own test classes to inject a dependency. In this case I'll make the constructor with the injection parameter internal (not private) and allow my unit test project access through the AssemblyInfo.cs file (see here).
Additionally, sometimes you want to use a private constructor on an abstract base class so that you can implement a factory method to return particular concrete implementations that are not publicly exposed. Think something like this
public abstract class Base {
private Base() { }
public static Base CreateClass() {
if (someCondition()) return new Concrete1();
else return new Concrete2();
}
private class Concrete1 : Base { }
private class Concrete2 : Base { }
}
The enumerators in .NET are good examples of this pattern.
I think you can make the constructor private to hide it. That way you cannot call the constructor and you cannot instantiate the class. This can be useful for classes that don't need to be instantiated (helpers with only static methods) or base classes that need to be inherited from, although you would preferably make those abstract.

C# class design - what can I use instead of "static abstract"?

I want to do the following
public abstract class MyAbstractClass
{
public static abstract int MagicId
{
get;
}
public static void DoSomeMagic()
{
// Need to get the MagicId value defined in the concrete implementation
}
}
public class MyConcreteClass : MyAbstractClass
{
public static override int MagicId
{
get { return 123; }
}
}
However I can't because you can't have static abstract members.
I understand why I can't do this - any recommendations for a design that will achieve much the same result?
(For clarity - I am trying to provide a library with an abstract base class but the concrete versions MUST implement a few properties/methods themselves and yes, there are good reasons for keeping it static.)
You fundamentally can't make DoSomeMagic() work with the current design. A call to MyConcreteClass.DoSomeMagic in source code will be translated into MyAbstractClasss.DoSomeMagic in the IL. The fact that it was originally called using MyConcreteClass is lost.
You might consider having a parallel class hierarchy which has the same methods but virtual - then associate each instance of the original class with an instance of the class containing the previously-static members... and there should probably only be one instance of each of those.
Would the Singleton pattern work perhaps? A link to the MSDN article describing how to implement a singleton in C#:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
In your particular example, the Singelton instance could extend an abstract base class with your MagicId in it.
Just a thought :)
I would question that there are "good reasons" for making the abstract members static.
If your thinking is that these members might reflect some property of the derived class itself rather than a given instance, this does not necessarily mean the members should be static.
Consider the IList.IsFixedSize property. This is really a property of the kind of IList, not any particular instance (i.e., any T[] is going to be fixed size; it will not vary from one T[] to another). But still it should be an instance member. Why? Because since multiple types may implement IList, it will vary from one IList to another.
Consider some code that takes any MyAbstractClass (from your example). If this code is designed properly, in most cases, it should not care which derived class it is actually dealing with. What matters is whatever MyAbstractClass exposes. If you make some abstract members static, basically the only way to access them would be like this:
int magicId;
if (concreteObject is MyConcreteClass) {
magicId = MyConcreteClass.MagicId;
} else if (concreteObject is MyOtherConcreteClass) {
magicId = MyOtherConcreteClass.MagicId;
}
Why such a mess? This is much better, right?
int magicId = concreteObject.MagicId;
But perhaps you have other good reasons that haven't occurred to me.
Your best option is to use an interface with MagicId only using a setter
public interface IMagic
{
int MagicId { get; }
}
By the nature of Static meaning there can only be one (yes like Highlander) you can't override them.
Using an interface assumes your client will implement the contract. If they want to have an instance for each or return the value of a Static variable it is up to them.
The good reason for keeping things static would also mean you do NOT need to have it overridden in the child class.
Not a huge fan of this option but...
You could declare the property static, not abstract, virtual and throw a NotImplementedException which returns an error message that the method has to be overridden in a derived class.
You move the error from compile time to run time though which is kinda ugly.
Languages that implement inheritance of static members do it through metaclasses (that is, classes are also objects, and these objects have a metaclass, and static inheritance exists through it). You can vaguely transpose that to the factory pattern: one class has the magic member and can create objects of the second class.
That, or use reflection. But you can't ensure at compile-time that a derived class implements statically a certain property.
Why not just make it a non-static member?
Sounds like a Monostate, perhaps? http://c2.com/cgi/wiki?MonostatePattern
The provider pattern, used by the ASP.NET membership provider, for example, might be what you're looking for.
You cannot have polymorphic behavior on static members, so you'll have a static class whose members delegate to an interface (or abstract class) field that will encapsulate the polymorphic behaviors.

How can I make a class global to the entire application?

I would like to access a class everywhere in my application, how can I do this?
To make it more clear, I have a class somewhere that use some code. I have an other class that use the same code. I do not want to duplicate so I would like to call the same code in both place by using something. In php I would just include("abc.php") in both... I do not want to create the object everytime I want to use the code.
Do you want to access the class or access an instance of the class from everywhere?
You can either make it a static class - public static class MyClass { } - or you can use the Singleton Pattern.
For the singleton pattern in its simplest form you can simply add a static property to the class (or some other class) that returns the same instance of the class like this:
public class MyClass
{
private static MyClass myClass;
public static MyClass MyClass
{
get { return myClass ?? (myClass = new MyClass()); }
}
private MyClass()
{
//private constructor makes it where this class can only be created by itself
}
}
The concept of global classes in C# is really just a simple matter of referencing the appropriate assembly containing the class. Once you have reference the needed assembly, you can refer to the class of choice either by it's fully qualified Type name, or by importing the namespace that contains the class. (Concrete instance or Static access to that class)
Or
You can have a Singleton class to use it everywhere but some people won't recommend you this way to proceed.
The other answers that you've been given about using a static class or a singleton pattern are correct.
Please consider, however, the fact that doing so does compromise your ability to test. In general, if you can, prefer dependency injection over globally accessed classes. I know this isn't always possible (or practical).
Just on that, you should also look up the abstract factory pattern. It allows you to have a well known factory class that produces the actual instance of a class that you're using. To have a globally accessed logging class, for example, don't directly create a logging class. Instead, use a logging factory to create it for you and return an interface to a logging class. That way it's easier to swap in and out different logging classes.
Since you do not want to create the object every time and it sounds like you are talking about some sort of utility methods...
I suggest you use static methods in an assembly which you can reference where needed

Categories

Resources