.NET Dynamic Decision to Call Similar Classes? - dynamic

C# on .NET 4.5:
public Interface IMyInterface
{
public string DoSomething( string input1 )
}
public MyClass1 : IMyInterface
{
public string DoSomething( string input1 )
{
return "1";
}
}
public MyClass2 : IMyInterface
{
public string DoSomething( string input1 )
{
return "2";
}
}
At runtime, I want to detect the hosting environment, set some kind of "global", and then based on the global always instance and use MyClass1 or MyClass2. I do not want to have a single "MyClass" and then do lots of case logic inside it to detect the environment.
What is a good pattern or practice to do that? Is this actually a good place for Dynamics?
Thanks.

Seems like you need to use Factory. Create a method in Factory class to return MyClass object. Keep the return type of the method as IMyInterface. Within the method, you can execute your hosting logic and depending upon the output of hosting logic, instantiate proper class and return the reference to the object.

Related

Strategy pattern to consume REST API

I have to consume two different REST API providers about VoIP. Both API do the same with different endpoints and parameters. I'm modeling classes as strategy pattern and the problem that i have encountered is the parameters of each method strategy because are different.
public interface VoIPRequests
{
string ApiKey { get; set; }
string GetExtensionsList();
string TriggerCall();
string DropCall();
string RedirectCall();
}
How can i change parameters for each of this methods depend on the implementation?.
It's good idea use strategy pattern for this case?
There is another pattern that suits better?
Thank you.
Per comment thread:
TriggerCall(), one api only needs one parameter "To" , and other api has two mandatory parameters "extension" and "destination"
I'll focus on TriggerCall, then, and let you extrapolate from there.
Implementation 1
public class VoIPRequests1 : VoIPRequests
{
private readonly object to; // Give this a more appropriate type
public VoIPRequests1(object to)
{
this.to = to;
}
public string TriggerCall()
{
// Use this.to here and return string;
}
// Other interface members go here...
}
Implementation 2
public class VoIPRequests2 : VoIPRequests
{
private readonly object extension; // Give this a more appropriate type
private readonly object destination; // Give this a more appropriate type
public VoIPRequests2(object extension, object destination)
{
this.extension = extension;
this.destination = destination;
}
public string TriggerCall()
{
// Use this.extension and this.destination here and return string;
}
// Other interface members go here...
}

Is there a better alternative to check for collections with members with optional interfaces?

I have a configuration registry class which holds a collection of configuration classes with a certain interface. These classes can also have an optional interface. So these classes may look like this in pseudocode:
class ConfigurationRegistry {
private ModuleConfiguration[];
public function ConfigurationRegistry(ModuleConfiguration[] collection) {
this.collection = collection;
}
public function getCollection() {
return this.collection;
}
}
class ConfigurationClass1 implements ModuleConfiguration, SpecificConfiguration {
public function moduleMethod() {
// do something
}
public function specificMethod() {
// do specific thing
}
}
class ConfigurationClass2 implements ModuleConfiguration {
public function moduleMethod() {
// do something
}
}
public interface ModuleConfiguration {
public function moduleMethod();
}
public interface SpecificConfiguration {
public function specificMethod();
}
In my client code I would like to use these configuration classes. Sometimes I need the whole collection of configuration classes and sometimes I only need to collection of configuration classes which implement the SpecificConfiguration interface.
I could filter the collection method by using instanceof or I could loop through the collection and check whether the class implements the interface. But I've read quite a few articles stating online that using instanceof in this case is not considered a good practice.
My question is: is my implementation a good design? If not, do you have any suggestions how I could redesign or improve this?

Replace Conditional with Polymorphism — how it works?

Often i heard that "try to avoid if/switch constructions. If you have them then refactor them to subclasses"
I don't realize how this thing works.
Ok, you have a if/switch in your code. And you create several new classes. But to decide which class you will use you need to implement switch if in fabric class (where you generate these objects). Am i wrong?
P.S. Sorry for my English. I'm reader, not writer.
But to decide which class you will use you need to implement switch if
in fabric class (where you generate these objects). Am i wrong?
No, you are not wrong. While the Polymorphism over switches is a good thing, there are exceptions. One such exception is when you have parameterized factory, and that's absolutely acceptable. So instead of your client code creating specialized classes based on conditions, you will ask such factory to create them for you. Advantage is Factory will solely be responsible for creating those class instances, and if new class is introduced only factory will be modified not client code.
So instead of this:
public class Client {
public string Serialize<T>(string contentType, T instance) where T : class {
switch(contentType) {
case "XML":
return new XMLSerializer().Serialize(instance);
case "JSON":
return new JSONSerializer().Serialize(instance);
}
}
}
You will have this:
public interface ISerializer {
string Serialize(object instance);
object Deserialize(string content);
}
public class XMLSerializer : ISerializer { }
public class JSONSerializer : ISerializer { }
public class SerializerFactory() {
public static ISerializer CreateSerializer(string type) {
switch(type) {
case "XML":
return new XMLSerializer();
case "JSON":
return new JSONSerializer();
}
}
}
public class Client {
public string ParseAPIResponse(string contentType, string responseData) {
ISerializer serializer = SerializerFactory.CreateSerializer(contentType);
var responseObj = serializer.Deserialize(responseData);
}
}
Note there can be only one reason for Factory to change and that is introduction of new Serializer, so we are good on SRP here. Going even further there are ways by which you can avoid modifying factory too, using config files to store identifier-type mappings or simply exposing another method on factory to allow it's users to register new types etc. That's on you.

Why can't I use Get<ClassNameOfConcreteInstance> as a method name in Ninject Extension Factory?

Look at this very simple example: Calling CreateCar it works, calling GetCar it fails, saying "Error activating ICar: No matching bindings are available, and the type is not self-bindable".
public interface ICar { }
public class Car : ICar
{
public Car(string carType) { }
}
public interface ICarFactory
{
ICar CreateCar(string carType); // this is fine
ICar GetCar(string carType); // this is bad
}
public class CarModule : NinjectModule
{
public override void Load()
{
Bind<ICarFactory>().ToFactory();
Bind<ICar>().To<Car>();
}
}
public class Program
{
public static void Main()
{
using (var kernel = new StandardKernel(new FuncModule(), new CarModule()))
{
var factory = kernel.Get<ICarFactory>();
var car1 = factory.CreateCar("a type");
var car2 = factory.GetCar("another type");
}
}
}
Is assume it must be related to some kind of convention with Get*ClassName* (something like the NamedLikeFactoryMethod stuff). Is there any way to avoid this convention to be applied? I don't need it and I don't want it (I already wasted too much time trying to figure out why the binding was failing, it was just luck that I made a typo in 1 of my 10 factories and I noticed it to work just because the factory method name was "Ger" instead of "Get").
Thanks!
Yes, there is a convention, where the Get is used to obtain instances using a named binding. The factory extension generates code for you so you don't have to create boilerplate code for factories. You don't need to use it, if you don't want to.
But if you do, you are bound to its conventions. Use Create to build instances and Get to retrieve instances via a named binding.
All this is documented in the wiki.

Adapter Pattern: Class Adapter vs Object Adapter

I have a few questions about the Adapter pattern. I understand that the class adapter inherits from the adaptee while the object adapter has the adaptee as an object rather than inheriting from it.
When would you use a class adapter over an object adapter and vice versa? Also, what are the trade-offs of using the class adapter and the trade-offs of the object adapter?
I can see one advantage for the object adapter, depending on your programming language: if the latter does not support multiple inheritance (such as Java, for instance), and you want to adapt several adaptees in one shot, you'll be obliged to use an object adapter.
Another point for object adapter is that you can have the wrapped adaptee live his life as wanted (instantiation notably, as long as you instantiate your adapter AFTER your adaptee), without having to specify all parameters (the part for your adapter AND the part for your adaptee because of the inheritance) when you instantiate your adapter. This approach appears more flexible to me.
Prefer to use composition, over inheritance
First say we have a user;
public interface IUser
{
public String Name { get; }
public String Surname { get; }
}
public class User : IUser
{
public User(String name, String surname)
{
this.Name = name;
this.Surname = surname;
}
public String Name { get; private set; }
public String Surname { get; private set; }
}
Now, imagine that for any reason, youre required to have an adapter for the user class, we have then two aproaches, by inheritance, or by composite;
//Inheritance
public class UserAdapter1 : User
{
public String CompleteName { get { return base.Name + " " + base.Surname } }
}
//Composition
public class UserAdapter2
{
private IUser user;
public UserAdapter2(IUser user)
{
this.user = user;
}
public String CompleteName { get { return this.user.Name + " " + this.user.Surname; } }
}
You are totally ok, but just if the system don't grow... Imagine youre required to implement a SuperUser class, in order to deal with a new requirement;
public class SuperUser : IUser
{
public SuperUser(String name, String surname)
{
this.Name = name;
this.Surname = surname;
}
public String Name { get; private set; }
public String Surname { get; private set; }
public Int32 SupernessLevel { get { return this.Name.Length * 100; } }
}
By using inheritance you would not be able to re-use your adapter class, messing up your code (as your would have to implement another adapter, inheriting from SuperUser that would do ECXATLY the same thing of the other class!!!)... Interface usage is all about uncopling, thats the main reason that I'm 99% likely to use them, of course, if the choice is up to me.
Class Adapter is plain old Inheritance, available in every object-oriented language, while Object Adapter is a classic form of an Adapter Design Pattern.
The biggest benefit of Object Adapter compared to Class Adapter ( and thus Inheritance ) is loose coupling of client and adaptee.
A class adapter uses multiple inheritance to adapt one interface to another: (depending on your programming language: Java & C# does not support multiple inheritance)
An object adapter depends on object composition:
Images Source: Design Pattern (Elements of Reusable Object-Oriented Software) book
class adapters adapts Adaptee to Target by committing to a specific Adapter class will not work when we want to adapt a class and its subclasses.
object adapters lets a single Adapter work with many Adaptees (the Adaptee and all adaptees hierarchy)
In addition to what renatoargh has mentioned in his answer I would like to add an advantage of class adapter.
In class adapter you can easily override the behavior of the adaptee if you need to because you are just subclassing it. And it is harder in Object adapter.
However advantages of object adapter usually outweighs this tiny advantage of class adapter.