How to create instance of inherited in static base method? - c#

From an instance, I might do this.
var obj= Activator.CreateInstance(GetType());
Not sure how to get typeof of the inherited class in a static base method though.
Is this the best way forward?
public static Method<T>() where T : SomeBase, new()

You could make the base class generic and close the generic in the derived class.
public abstract class CreatorOf<T> where T : CreatorOf<T>
{
public static T Create()
{
return (T)Activator.CreateInstance(typeof(T));
}
}
public class Inheritor : CreatorOf<Inheritor>
{
public Inheritor()
{
}
}
public class Client
{
public Client()
{
var obj = Inheritor.Create();
}
}
There are some who consider this to be an "anti-pattern", but I believe there are circumstances where it is an acceptable approach.

Maybe you should better tryto use abstract factory pattern?
http://en.wikipedia.org/wiki/Abstract_factory_pattern

There is no such thing as a derived static method. So there is no way to create a static factory method that returns a different type depending on which derived class you call it on.
As Lonli-Lokli suggested, you should use the Abstract Factory design pattern.
public interface ISomething
{
void DoSomething();
}
public class SomeClass : ISomething
{
public virtual void DoSomething() { Console.WriteLine("SomeClass"); }
}
public class SomeDerivedClass : SomeClass
{
private int parameter;
public SomeDerivedClass(int parameter)
{
this.parameter = parameter;
}
public virtual void DoSomething()
{
Console.WriteLine("SomeDerivedClass - {0}", parameter);
base.DoSomething();
}
}
public interface IFactory
{
public ISomething Create();
}
public class SomeClassFactory : IFactory
{
public ISomething Create() { return new SomeClass(); }
}
public class SomeDerivedClassFactory : IFactory
{
public ISomething Create() { return new SomeDerivedClass(SomeParam); }
public int SomeParam { get; set; }
}
Pros of Abstract Factory vs static Factory methods:
It is much more flexible, allowing a new implementation of your factory logic (which can be as complicated as you want) for every implementor of the abstract factory. You could have more than one factory per class, if you wanted.
Since you aren't calling a static method, it is much easier to replace at runtime. This is quite useful for injecting mocks in unit tests.
The pros are huge. Abstract Factories are superior to static factory methods in every way, even if you could get static methods to work the way you want them to.
Cons of Abstract Factory vs static Factory methods:
Users of the abstract factory must have a factory instance to create your derived types.
You have to write a new abstract factory implementation for each derived class.
The cons are very marginal.
It is extremely easy for a user to instantiate a factory to create a single object:
MyClass myClass = new MyClassFactory().Create();
As for code duplication in the factory implementation: Saving the implementer a tiny bit of typing is pointless. It is a goal in programming to write code that can be read, understood, and easily modified. There is no programming goal to save paper or keystrokes :)

Related

How to require an implementation of an abstract class in C#?

I want to build a class that would have a property, in which there is an instance of a class, which implements an abstract class. Here's and example.
public class MyClass {
public MyDerivedClassA derived;
public void mainClassUtility () {
derived.foo();
}
}
public abstract class MyAbstractBaseClass {
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass {
public override void foo(){
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
return;
}
}
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use. There will be many implementations of the abstract class and depending on the current state of the program, MyClass might be using different implementations of the ABC. I want to write the program in a way, that no matter what implementation of the ABC is currently being used, there is a way to call it's methods by MyClass. What would be the best solution to this problem?
Unless I'm misunderstanding the question, you're pretty much there. Have MyClass expect a property of the abstract base class and you should be all set.
using System;
public class Program
{
public static void Main()
{
var myClassOne = new MyClass(new MyDerivedClassA());
var myClassTwo = new MyClass(new MyDerivedClassB());
myClassOne.mainClassUtility();
myClassTwo.mainClassUtility();
}
public class MyClass
{
public MyAbstractBaseClass Derived;
public MyClass(MyAbstractBaseClass derived)
{
Derived = derived;
}
public void mainClassUtility ()
{
Derived.foo();
}
}
public abstract class MyAbstractBaseClass
{
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassA");
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassB");
return;
}
}
}
How to require an implementation of an abstract class in C#?
You can not instantiate a abstract class - and thus can not use it for most cases. Except as variable/argument/generic type argument. You need to make a concrete (non-abstract) class that inherits from it. You can only use the abstract class as a variable/argument type. To guarantee that only stuff that inherits from it can be used there.
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use.
Then use the abstract class as type argument. It means only instaces of the abstract class (of wich there can be no instance) or instances of classes that inherit from it (that somebody else writes) can be used at that place.
Note that Abstract classes and Interfaces overlap in nearly all uses. There is a miriad small differences, but I do not think they mater. The only big difference I can see, is one of exclusivity:
a class can implement as many Interfaces as it wants.
You can only inherit from one abstract class. that means it is for a primary, exclusive purpose. That way you prevent some dumb ideas, like someone trying to make a Windows Form that is also a DBConnection.

C# Multiple Stub implementation for method with T

Currently I have a factory class where I have method to instantiate different classes using reflection and return a base interface which all classes implement. The code works fine in general. But when I turned to write unit test (ms-test) on the class I'm running into issues when I try to instantiate multiple classes
Factory class:
public class BusinessFactory : IBusinessFactory
{
public BusinessFactory()
{
}
public IBaseBusiness Create<T>() where T : class
{
return (IBaseBusiness) Activator.CreateInstance(typeof(T));
}
}
Unit test:
I tried to stub the IBusinessFactory and inject into my class under test so I can fake the implementations that the class uses.
Example: failing to complete TestInit method, and it's failing when instantiating stub of class2.
interface IClass1 : IBaseBusiness{}
public Class1 : IClass1{}
interface IClass2 : IBaseBusiness{}
public Class2 : IClass2{}
public TestFactory{
[TestInitialize]
public void TestInit()
{
var fkBusFac = new StubIBusinessFactory();
fkBusFac.CreateOf1<Class1>(() => new StubIClass1() { });
fkBusFac.CreateOf1<Class2>(() => new StubIClass2() { });
}
Can anyone please help?
Not an answer to your question, but...
What happens if I do the following?:
var business = Create<string>();
You have absolutely no type safety at all here. If the created object implements IBaseBusiness, ensure it does and simply call new() (oh, and if its a factory method, shouldn't you be making it static?):
public static IBaseBusiness Create<T>() where T : IBaseBunsiness, new()
{
return new T();
}

NUnit - Static Vs. Public methods

My project has been growing in size and in functionality so I decided to test some features using NUnit however the problem I'm facing is that most of the methods are Static, so the first thing that ocurred to me was create public methods and I am calling them from the Unit Test class however those public methods are beginning to be many, so I wonder if rather than create new Public methods inside the main class, I should create an interface or if the Static ones should be Public and be instantiated using an class intermediate.
This is an example of how my program is structured,
namespace Mynamespace
{
public class Foo
{
InsertUser();
SortUser();
}
static void InsertUser()
{
}
static void SortUser()
{
}
//Here start the public methods to be called from the unit test class
public DoSort()
{
InsertUser();
SortUser();
}
}
What's the best approach to keep separated the main logic of my program and the testing classes?
Thanks,
Instead of keeping static methods and adding non-static methods, it's better to convert all your methods from static to instance methods and extract abstraction which clients of Foo class will depend on:
public interface IFoo
{
void InsertUser();
void SortUser();
}
public class Foo : IFoo
{
void InsertUser() { ... }
void SortUser() { ... }
}
Static members introduce coupling into your application. And it's a real headache to mock static members. You should program to abstraction, instead of programing to implementation in order to make your code testable and loosely coupled. When your code depend on interface instead of static class, you can easily mock this dependency:
Mock<IFoo> fooMock = new Mock<IFoo>();
fooMock.Setup(f => f.InsertUser()).Throws<InvalidOperationException>();
var sut = new ClassUnderTest(fooMock.Object);
fooMock.VerifyAll();
And if you really need to access these methods in global scope (which is not very good idea - it's a procedural style of programming), then implement your class as Singleton:
public class Foo : IFoo
{
public static Foo Instance = new Foo(); // simple singleton implementation
private Foo() { }
void InsertUser() { ... }
void SortUser() { ... }
}
You will be able to get class instance anywhere in your application
IFoo foo = Foo.Instance;
foo.SortUser();
In my opinion, you should have your real classes and your unit classes both implementing a common interface, like this:
interface IFoo
{
void InsertUser();
void SortUser();
}
For your actual implementation, use this:
public class RealFoo : IFoo
{
public void InsertUser()
{
throw new NotImplementedException();
}
public void SortUser()
{
throw new NotImplementedException();
}
}
For your testing classes, use this:
public class FakeFoo : IFoo
{
public void InsertUser()
{
throw new NotImplementedException();
}
public void SortUser()
{
throw new NotImplementedException();
}
}
Note: Your FakeFoo class would not need to exist in the same location as your RealFoo class, but rather your IFoo interface definition should be referenced by each of the projects (one for real implementation and the other in your test project).
If your IFoo interface becomes too large (read: too many methods), then you can use the Repository Pattern, which would segment your methods into interfaces more along the lines of functionallity.

Java Inheritance Constraints

I am trying to port some code I wrote in C# to Java, but do not know all of the Java syntax yet. I also have no idea what this type of thing is called, so it is harder to search..I am calling it "inheritance constraints."
Basically, is there a java equivalent to this C# code:
public abstract class MyObj<T> where T : MyObj<T>, new()
{
}
Thanks.
Edit:
Is there any way to do this:
public abstract class MyObj<T extends MyObj<T>> {
public abstract String GetName();
public virtual void Test() {
T t = new T(); // Somehow instantiate T to call GetName()?
String name = t.GetName();
}
}
Not quite. There's this:
public abstract class MyObj<T extends MyObj<T>>
but there's no equivalent to the new() constraint.
EDIT: To create an instance of T, you'll need the appropriate Class<T> - otherwise type erasure will byte you.
Typically you'd add this as a constructor parameter:
public MyObj(Class<T> clazz) {
// This can throw all kinds of things, which you need to catch here or
// propagate.
T t = clazz.newInstance();
}
Judging by your comment above, you're looking for the following construct:
An interface with which you will interact with MyObj objects in code... you will be calling the test() method (standard style in Java is camelcase methods, capitalized classes/interfaces)
public interface IMyObj {
public void test();
}
You will want the abstract superclass... for the example that you've chosen, you don't NEED to specify any genericism, although you absolutely can if the actual implementation is more reliant on type safety... this class should implement the IMyObj interface:
public abstract class MyObj implements IMyObj {
String name;
public abstract String getName();
public void test() {
name = getName();
}
}
From here you would write your subclasses to MyObj...
public class MySubObj1 extends MyObj {
public String getName() { return "MySubObj1"; }
}
public class MySubObj2 extends MyObj {
public String getName() { return "MySubObj2"; }
}
Then you safely and correctly use the following snippet in another class:
IMyObj obj = new MySubObj1();
obj.test();
The key is that you use interfaces to hide the implementation, and use abstract classes to hold common code that subclasses will utilize in their implementations.
Hope this helps!

Is it a good idea to have a factory class using generics to instantiate objects?

Is it a good idea to have a factory class using generics to instantiate objects?
Let's say I have a class Animal and some subclasses (Cat, Dog, etc):
abstract class Animal
{
public abstract void MakeSound();
}
class Cat : Animal
{
public override void MakeSound()
{
Console.Write("Mew mew");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.Write("Woof woof");
}
}
static class AnimalFactory
{
public static T Create<T>() where T : Animal, new()
{
return new T();
}
}
Then in my code I would use AnimalFactory like this:
class Program
{
static void Main(string[] args)
{
Dog d = AnimalFactory.Create<Dog>();
d.MakeSound();
}
}
Depends on what you want to do with it. The example you gave is not that helpful, as all it does is simply call new() which is something you can do in your code as well. A factory is more useful if you want to place logic which has to be ran during the object creation process somewhere outside the object to create but also away from the code which instantiates the objects.
In that light, it depends on what logic you want to run in your factory and if that logic is also writable using the same generic constraints as the factory. If not, you'll likely need a pattern called Abstract factory, which uses a general factory to instantiate the right specific factory behind the scenes for the type to create the object at hand.
Yes, factory methods in non-generic classes can often be useful. In particular, generic methods can have type inference applied to them, whereas generic types can't.
I sometimes have two layers of factories, too - for a generic type with 2 type parameters, I might have:
class Foo
{
static Foo<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value)
{...}
}
class Foo<TKey>
{
static Foo<TKey, TValue> Create<TValue>(TValue value)
{...}
}
class Foo<TKey, TValue>
{
}
This allows:
Foo.Create(x, y);
Foo<string>.Create(y);
new Foo<string, int>(x, y);
I have a blog entry with more examples and reasoning.
One of the more annoying things that come from this, and there might be a way around this, is that you are stuck with using a parameterless constructor. Far as I know, you can't do this:
public class Factory
{
public static T Create<T>() where T : ParentClass, new(String)
{
}
}
Or this
public class Factory
{
public static T Create<T>() where T : ParentClass
{
T child = new T("hi")
}
}
Or even more fun like:
public class Factory
{
public static T Create<T>() where T : ParentClass, new()
{
T child;
child = new T();
if (child is ChildClass)
{
child = new ChildClass("hi");
}
return child;
}
}
Which can limit you to certain class design. This may be a problem if you don't want just the default constructor called.
That is unless someone has found a way to get around this.
I know I've run into this problem with Activator.CreateInstance() also since in reality all that does is call the parameterless constructor.
I would recommend separating the factory concern from the constructor concern. This allows varying instantiation strategies:
public interface IFactory<T>
{
T Create();
}
public class DefaultConstructorFactory<T> : IFactory<T> where T : new()
{
public T Create()
{
return new T();
}
}
public class ActivatorFactory<T> : IFactory<T>
{
public T Create()
{
return Activator.CreateInstance<T>();
}
}
public class AnimalTamer<TAnimal> where TAnimal : Animal
{
IFactory<TAnimal> _animalFactory;
public AnimalTamer(IFactory<TAnimal> animalFactory)
{
if(animalFactory == null)
{
throw new ArgumentNullException("animalFactory");
}
_animalFactory= animalFactory;
}
public void PutOnShow()
{
var animal = _animalFactory.Create();
animal.MakeSound();
}
}
class Program
{
static void Main(string[] args)
{
var tamer = new AnimalTamer<Tiger>(new DefaultConstructorFactory<Tiger>());
tamer.PutOnShow();
}
}
You could make it even more dynamic by using open/close generics and funcs when nothing or very little is known until runtime. Seems like you have a good grasp on generics so keep it up.
using generics for your constructor is called the abstract factory pattern.
Its good but only if you're using it, in this example you've got some of the defaults in the factory at least.
static class AnimalFactory
{
public static Animal Create<T>() where T : Animal
{
return Create<T>("blue");
}
public static Animal Create<T>(string colour) where T : Animal, new()
{
return new T() {Colour = colour};
}
}
Is it a good idea to have a factory
class using generics to instantiate
objects?
For the case you described, no it isn't. You'd just be using a pattern for the sake of using a pattern and from the example, is only going to unnecessarily compicate things.
Now if your app has several objects implementing some interface and you load one of those objects based on a config file, then yes, it makes sense to use a factory to create that object.
The generics portion of this problem would actually come in the factory implementation itself. I have no supporting code, but this is how I would envision the calling code to look:
Factory<IAwesome> awesomeFactory = new Factory<IAwesome>();
IAwesome awesomeObject = awesomeFactory.Load(configValue);
yes. the creational design patterns (http://en.wikipedia.org) work well with generics. and generics can be a bit complicated (http://www.artima.com/intv/genericsP.html), so it's fine to hide any construction complexity in some kind of factory to make it easier for the client.

Categories

Resources