Determine what implementationt to use in C# during run time - c#

My code talks to 4 different machines (money machines from different companies). Each one of them does:
1. Dispense
2. Deposit
let's call the machines(A,B,C,D).
In my code if I want to call Deposit from a machine I would end up with something like:
MyProject.A.Deposit()
I ended up with switch statements that are basically something like this:
Switch(machine){
case A:
MyProject.A.Deposit();
break;
case B:
MyProject.B.Deposit();
break;
}
The bigger the code gets,the problem of very long namespaces and switch statements becomes annoying.
My question is:
Is there a way I can tell the compiler to use the specific namespace during the run-time? Or Maybe by using a config variable or a string that has namespace path.
I wanted something where I can do:
Deposit();
Since i have the information of which machine I am connected to, the problem is just how to change dynamically the namespace.

Yes, assuming all four machines' Dispense and Deposit methods share the same contract, all you need is to create an interface that they all implement:
public interface IMachine
{
void Dispense();
void Deposit();
}
Then make sure you implement this same interface on all your machine concrete implementations:
public class MachineA : IMachine
{
public void Dispense()
{
// do something here
}
public void Deposit()
{
// do something here
}
}
public class MachineB : IMachine
{
public void Dispense()
{
// do something here
}
public void Deposit()
{
// do something here
}
}
public class MachineC : IMachine
{
public void Dispense()
{
// do something here
}
public void Deposit()
{
// do something here
}
}
public class MachineD : IMachine
{
public void Dispense()
{
// do something here
}
public void Deposit()
{
// do something here
}
}
I'm assuming you don't use Dependency Injection or have an IoC container currently in your system, so to keep things simple you can have a Factory to always create the IMachine instances for you:
public static class MachineFactory
{
// this is assuming you are reading the machine name from AppConfig
private static Lazy<string> _machineName = new Lazy<string>(() => ConfigurationManager.AppSettings["TargetMachine"]);
public IMachine GetMachine()
{
switch(_machineName.Value)
{
case "MachineA":
return new MachineA();
case "MachineB":
return new MachineB();
case "MachineC":
return new MachineC();
case "MachineD":
return new MachineD();
}
}
}
Now, in the rest of your application, whenever you need an instance of a machine, all you need to do is use the factory without having to worry about the different machine implementations:
var machine = MachineFactory.GetMachine();

You could go through a switch-case for the value that will decide the namespace, where you have "using NamespaceX;" inside the cases.

Related

Why can a class implement its own private nested interface in C#?

The following code is a valid C# construct that compile juste fine.
public class Weird : Weird.IWeird
{
private interface IWeird
{
}
}
What would be the possible uses of this?
Edit: This question is more specific that this one: "What is a private interface?". It shows that it's possible to implement a private interface from the parent type itself, which seems to be rather pointless. The only use I can think of would be a weird case of interface segregation where you would want to pass an instance of the parent class to a nested class instance as IWeird.
This is probably one of these situations in compiler development when prohibiting something has a higher cost than allowing it. Prohibiting this use would require writing and maintaining code to detect this situation, and report an error; if the feature works as-is, this is an additional work for the team, and it could be avoided. After all, perhaps someone with good imagination could figure out a way to use the feature.
As far as a useful example goes, one potential use is to make another implementation in the class, and use it as an alternative without exposing it to the users of the API:
public class Demo : Demo.Impl {
// Private interface
private interface Impl {
public bool IsValidState {get;}
void DoIt();
}
// Implementation for the error state
private class Error : Impl {
public bool IsValidState { get { return false; } }
public void DoIt() {
Console.WriteLine("Invalid state.");
}
}
private readonly string name;
// Implementation for the non-error state
public bool IsValidState { get { return true; } }
public void DoIt() {
Console.WriteLine("Hello, {0}", name);
}
// Constructor assigns impl depending on the parameter passed to it
private readonly Impl impl;
// Users are expected to use this method and property:
public bool IsValid {
get {
return impl.IsValidState;
}
}
public void SayHello() {
impl.DoIt();
}
// Constructor decides which impl to use
public Demo(string s) {
if (s == null) {
impl = new Error();
} else {
impl = this;
name = s;
}
}
}
As far as best practices go, this design is questionable at best. In particular, I would create a second nested class for the non-error implementation, rather than reusing the main class for that purpose. However, there is nothing terribly wrong with this design (apart from the fact that both IsValidState and DoIt are visible) so it was OK of the C# team to allow this use.

Modifying type hierarchies at runtime

I've been having trouble even defining what I am looking for.
I am writing an app to determine winners in a tournament. I would like my base class to be able to change it's inheritance based on how many people are playing, given that multiple inheritance is not an option, and probably wouldn't be a very good one the more i think on it.
I see something along the lines of
class Base
{
//Constructor receiving the quantity of players
public Base (int quantityOfPlayers)
{
//Changes Base inheritance dynamically based on QuantityOfPlayers
switch (quantityOfPlayers)
{
case 4: (Base : FourPlayers);
case 5: (Base : FivePlayers);
}
}
}
But of course i can't seem to find a means (if there is one) of dynamically changing the inheritance like that. Otherwise I'm stuck using more complicated means though each of the getter and setter functions are going to be essentially the same.
Very good solutions. let me add that I'm using a GUI not the console.
I have to think on this, the factory class is good, but it has convinced me I'm over thinking my approach.
There is a software design pattern called strategy pattern for this kind of situation.
Define an interface for the game strategy
public interface IGameStrategy
{
// Things that depend on the number of players, go here...
}
The right strategy gets injected into the game through constructor injection
public class Game
{
private IGameStrategy _strategy;
// Constructor injection
public Game(IGameStrategy strategy)
{
_strategy = strategy;
}
// Things common to all types of games go here...
}
Define a factory method like this:
private IGameStrategy CreateGameStrategy(int numberOfPlayers)
switch (numberOfPlayers)
{
case 4:
return FourPlayersStrategy();
case 5:
return FivePlayersStrategy();
default:
throw new ArgumentException("Invalid number of players");
}
}
Then create a game like this:
var game = new Game(CreateGameStrategy(numberOfPlayers));
Of course the strategy classes implement the interface. They can do so directly or they can inherit a common abstract base class implementing the interface.
The game logic is split into things common to all types of games implemented in the Game class and things specific to the number of players implemented in the strategy classes.
You could create a factory class that generates the proper class based on the number of players:
public class PlayerQtyFactory
{
//You can add any other args you might need as well
public BaseClass CreatePlayerQty(int numPlayers)
{
switch (numPlayers)
{
Case 2:
return new TwoPlayers();
Case 3:
return new ThreePlayers();
{
}
}
Without knowing more about what you are trying to do, it is hard to say if this is the best approach, but it is certainly A aproach.
For this particular situation I would use a factoryesque (or just plan factory) solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tester
{
//declare common functionality
public interface ISharedFunctionality
{
//put all shared functionality here
void SomeMethod();
void SomeOtherMethod();
void DifferentMethod();
string Name {get;set;}
}
public interface ISinglePlayerFunctionality : ISharedFunctionality
{
//put single player functionality here
void SomeOtherMethod();
void SomeMethod();
}
public interface IMultiplePlayerFunctionality : ISharedFunctionality
{
//put multiplayer functionality here
void DifferentMethod();
void SomeMethod();
}
public class ImplementationBase : ISharedFunctionality
{
//shared implementation here
public void SomeMethod()
{
//do stuff
Console.WriteLine("In Base");
}
public void SomeOtherMethod()
{
//one you don't want to inherit in multiplayer
Console.WriteLine("In Base");
}
public void DifferentMethod()
{
Console.WriteLine("In Base");
}
public string Name
{
get;
set;
}
}
public class MultiPlayerImplementation : ImplementationBase, IMultiplePlayerFunctionality
{
//multiplay impl
// you inherit some method but don't want to inherit
//SomeOtherMethod when cast to ISharedFunctionality
void ISharedFunctionality.SomeMethod()
{
//when cast to ISharedFunctionality this method will execute not inherited
Console.WriteLine("In MutilPlayImplementation");
}
}
public class SinglePlayerImplementation : ImplementationBase , ISinglePlayerFunctionality
{
//singleplay impl
void ISharedFunctionality.SomeOtherMethod()
{
Console.WriteLine("In SinglePlayerImplementation" );
}
}
public class Factory
{
//logic to decide impl here
public ISharedFunctionality Create(int numberOfPlayer)
{
if (numberOfPlayer == 1)
{
return new SinglePlayerImplementation();
}
else if(numberOfPlayer > 1)
{
return new MultiPlayerImplementation();
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
var factory = new Factory();
var results = new[]{factory.Create(1) , factory.Create(2) };
int j=0;
foreach (var i in results)
{
///for single player will be base
///multiplaryer will be mutliplayer
i.SomeMethod();
//for single player will be single player
// for multiplayer will be base
i.SomeOtherMethod();
i.DifferentMethod();
i.Name = "Item-Number-" + j;
Console.WriteLine();
}
}
}
}
The benefit to this is two fold, you now no longer have ambiguity in terms of what method is being called, and you have a unified place to construct future implementations based off of similair contracts (i.e. three player behavior, different menu behavior, and it might be even less code if you want the exact same methods to just behave differently

How to initialize class before it is needed in the Main method using C#

Given this code:
using System;
using System.Collections.Generic;
using FactoryCallback = System.Func<System.Object>;
interface IMessageProvider
{
string Message { get; }
}
class MessageProvider : IMessageProvider
{
private Random generator = new Random();
public static void Register()
{
InstanceFactory.Register(typeof(IMessageProvider), () => new MessageProvider());
}
public string Message
{
get
{
switch (generator.Next(3))
{
case 0:
return "No matter where you go, there you are.";
case 1:
return "Once I thought I'd made a mistake, but I was wrong.";
case 2:
return "I used to think I was indecisive; now I'm not so sure";
default:
throw new IndexOutOfRangeException();
}
}
}
}
class InstanceFactory
{
private static Dictionary<Type, FactoryCallback> typeCallbacks =
new Dictionary<Type, FactoryCallback>();
public static void Register(Type type, FactoryCallback callback)
{
typeCallbacks.Add(type, callback);
}
public static Object InstanceOf(Type type)
{
return typeCallbacks[type]();
}
}
public class RandomMessage
{
public static void Main()
{
IMessageProvider provider =
InstanceFactory.InstanceOf(typeof(IMessageProvider)) as IMessageProvider;
Console.WriteLine(String.Format("The message is:\n{0}", provider.Message));
}
}
This program will not run successfully as is because the MessageProvider never actually registers with the InstanceFactory.
Obviously, a call to MessageProvider.Register could be added to the beginning of RandomMessage.Main. However, that now requires RandomMessage to have knowledge of MessageProvider and defeats the whole purpose of the InstanceFactory class which is intended to separate how to create something from what that something does.
I would like the MessageProvider to be able to automatically register with the InstanceFactory before RandomMessage.Main tries to create an IMessageProvider instance.
How could this be accomplished?
The registration of service IMessageProvider and component MessageProvider with InstanceFactory is not the responsbility of the MessageProvider implementation, it is an infrastructure concern for the application, therefore should be done inside of the Main method.
public class RandomMessage
{
public static void Main()
{
// Register services with InstanceFactory at the start of Main method
InstanceFactory.Register(typeof(IMessageProvider), () => new MessageProvider());
IMessageProvider provider = InstanceFactory.InstanceOf(typeof(IMessageProvider)) as IMessageProvider;
Console.WriteLine(String.Format("The message is:\n{0}", provider.Message));
}
}
If you somehow referenced MessageProvider before calling InstanceFactory.InstanceOf(), you could just add a static constructor to MessageProvider class:
static MessageProvider()
{
Register();
}
If it's not an option, you can do it via reflection by adding a custom attribute to all classes you want to register and calling Register() for all of them in static constructor of InstanceFactory like described here.
Consider using some Inversion of Control library. like Unity (but it might be overkill) or SimpleContainer.
Then you will 'Register' instance of interfaces while your app start (in examples you should have file like 'bootstrapper.cs' )

How to model this scenario using OOP? (inheritance issue)

I have a lot of different engines that implement different algorithms. All of them implement the same interface but have different Configuration methods. Most of them are configured without parameters, some of them with one integer and even less with two integers. There is a small probability that in the future we will have with three or even four integers.
I need to create a Engine controller that decides when it has to start or stop the engine as this is common for all of them. The options I thought are the following:
Create an unique interface with as much parameters as the biggest Configure method available and ignore the not needed ones at the engines. This way I'll have just only one EngineController.
Create an Interface for each of the different configure methods and create a EngineController for each one of the different interfaces (but this will make me create a lot of classes that only differ on the number of parameters and will require 2 new classes each time a new parameter is added to an engine.
...
I really don't feel comfortable with any of the two solutions as passing unneeded parameters looks 'ugly' and due to the high number of classes generated with the second option (that only have very minor differences).
Any design or pattern that avoids this problem?
EDIT (Thanks for the answers, this edit answers all of them and clarifies the question):
Just to give an example, these are the engines.
abstract class EngineBase
{
public void Start() {...}
public void Stop() {...}
}
class EngineOne : EngineBase
{
public void Configure(int parameter1) {...};
}
class EngineTwo : EngineBase
{
public void Configure(int parameter1, int parameter2) {...};
}
class EngineThree : EngineBase
{
public void Configure(int parameter1, int parameter2, int parameter3) {...};
}
As all the engines have the same logic to decide when to start or end I want to create a new class that handles them, called EngineController. The controller will call the Configure, the Start and the Stop when needed:
class EngineController
{
EngineBase _engine; ??? or what?
void SuperviseEngine() { ... _engine.Configure(x,x,...) ... _engine.Start() ...
}
The first idea I has is to add to the EngineBase class the next method:
abstract class EngineBase
{
public void Start() {...}
public void Stop() {...}
public void Configure(int parameter1, int parameter2, int parameter3) {...}
}
class EngineController
{
EngineBase _engine;
void SuperviseEngine() { ... _engine.Configure(x,y,z) ... _engine.Start() ...
}
and ignore the unneeded parameters but I don't like the idea. Then I thought on doing the following:
interface I1ParameterConfigurable
{
public void Configure(int parameter1) {...};
}
interface I2ParameterConfigurable
{
public void Configure(int parameter1, int parameter2) {...};
}
interface I3ParameterConfigurable
{
public void Configure(int parameter1, int parameter2, int parameter3) {...};
}
and then create 3 different controllers for each kind of engine:
class EngineController1Parameter
{
EngineBase _engine;
I1ParameterConfigurable _configurableEngine = _engine as I1ParameterConfigurable;
void SuperviseEngine() { ... _configurableEngine .Configure(x) ... _engine.Start()
}
class EngineController2Parameter
{
EngineBase _engine;
I2ParameterConfigurable _configurableEngine = _engine as I2ParameterConfigurable;
void SuperviseEngine() { ... _configurableEngine .Configure(x, y) ... _engine.Start()
}
You get the idea, but I feel that this will create a lot of interfaces / classes when maybe there is way to avoid this.
Thanks to your answers I have a third option that is similar to the 1st one but using an array (or IEnumerable or whatever) to pass a undefined number of parameters. The idea is not bad but then I'll lose the parameter names. But maybe it's the best option until now.
Will that help you.
interface IEngine
{
void startEngine(params int[] engineParam);
}
Maybe I don't fully understand but I think you want something like this:
public interface IEngineController //I dont see a need to expose the enigine here in this pseudo code
{
void Start();
IConfiguration Config { get; }
}
public interface IEngine
{
void Start();
}
public interface IConfiguration
{
bool IsOkToStart { get; }
}
public class Configuration : IConfiguration
{
public Configuration(List<IConfigurationParameter> configurationParameters)
{
ConfigurationParameters = configurationParameters;
}
public bool IsOkToStart
{
get { return ConfigurationParameters.All(cfg=>cfg.IsOkToStart); }
}
protected List<IConfigurationParameter> ConfigurationParameters { get; private set; }
}
public interface IConfigurationParameter
{
bool IsOkToStart { get; }
}
public interface IMaxTemp : IConfigurationParameter
{
double MaxTemp { get; }
}
public interface ISafetyParameter : IConfigurationParameter
{
ISafetyCondition SafetyCondition { get; }
}
This got a little long, I omitted Stop() for brevity. The idea is:
The controller has an IEngine (not exposed in the interface) and an IConfig
IEngine has the Start() method.
A Configuration is a list of IConfigparameters that has a bool is ok to start (if all parameters are ok).
Each parameter has an IsOkToStart that is calculated depending on some condition
Maybe this provides flexibility for you? Combine the parameters you need and possibly add ned parameters in the future. I believe it is a good thing that the interfaces are extremely small and cohesive. Maybe even split them into IStartParameter and IStopParameter and just combine to the desired config?
I would model it similar to this:
public interface IEngine1 {
}
public interface IEngine1Config {
int Param1 {get;}
}
public Engine1 : IEngine1 {
IEngine1Config _config;
public Engine1(IEngine1Config config) {
_config = config;
}
}
You could then optionally choose to have one class implementing the different engine configurations:
class AllEnginesConfig : IEngine1Config, IEngine2Config {
int Param1 {get;set;}
// ... etc
}
(of course, it may be better in your situation to implement the configs in separate classes also)
If you have a lot of engines, I would use an IoC container to register all the different types, and let it wire up all the dependencies.
container.Register<IEngine1, Engine1>();
var theOneAndOnlyConfig = new AllEnginesConfig() {}; // properly initialized, of course
container.RegisterInstance<IEngine1Config>(theOneAndOnlyConfig);
container.RegisterInstance<IEngine2Config>(theOneAndOnlyConfig);
// ...
Then, to instantiate an engine, you simply use the container:
container.Get<IEngine1>();
IOC containers to invoke a engine you require or bunch of engines you require and inject them at run time and you can use them in combination with optional parameters while invoking containers. I have seen usage of Optional parameters in many attributes of .NET FW. or use an list of object parameter to get all inputs and when called can parse the list and decide which engine it was intended to invoke. None of them will be hard to grasp and use

How to overload a method at run-time or other ideas in C#

Maybe overloading a method is not exactly what is necessary but this is the best i could come up with.
I have a class:
public class Worker {
private string jobType;
public Worker(string jt)
{
this.jobType = jt;
}
public void ProcessJob()
{
if(jobType.Equals("Pizza") MakePizza();
else if (jobType.Equals("Burger") MakeBurger();
}
private void MakePizza()
{
// make pizza
}
private void MakeBurger()
{
// make burger
}
}
The above is just an example of illustration. When the class is constructed, it is constructed with a specific job type, and that won't change. However it may need to perform millions of jobs, always of the same type. The ProcessJob() will be called all the time, but the caller won't know what type of worker this is. I would like to avoid running the if check every single time, there has to be a way to do that check only once and prep it.
In my case, making child classes (pizza worker, burger worker, etc.) is not an option, as in my real case, the class is large and there is only one tiny difference. Changing it will impact the whole architecture so it needs to be avoided.
Create an abstract base class, which contains common things a worker can do. Then declare derived classes for specialized workers.
public abstract class Worker
{
public abstract void ProcessJob();
}
public class PizzaWorker : Worker
{
public override void ProcessJob()
{
// Make pizza
}
}
public class BurgerWorker : Worker
{
public override void ProcessJob()
{
// Make burger
}
}
Now you can create workers of different types and let them do their job:
var workers = new List<Worker>();
workers.Add(new PizzaWorker());
workers.Add(new BurgerWorker());
foreach (Worker worker in workers) {
woker.ProcessJob();
}
This will automatically call the right implementation of ProcessJob for each type of worker.
Note: If-else-if cascades and switch statements are often an indication that the code works in a procedural rather than object-oriented way. Refactor it to be object-oriented!
You could use a delegate created when the object is constructed, this way the dispatch is done automatically:
public class Worker
{
private delegate void MakeSomething();
private MakeSomething makeWhat;
private string jobType;
public Worker(string jt)
{
this.jobType = jt;
switch (jt)
{
case "Pizza":
makeWhat = new MakeSomething(MakePizza);
break;
case "Burger":
makeWhat = new MakeSomething(MakeBurger);
break;
default:
throw new ArgumentException();
}
}
public void ProcessJob()
{
makeWhat();
}
private void MakePizza()
{
//make pizza
}
private void MakeBurger()
{
//make burger
}
}
I would still recommend to use sub classes. If you cannot inherit from Worker then create new class hierarchy that is used inside the worker. This way anyone using Worker class doesn't have to know that there are sub classes. If you really really hate sub classes or you have some other reason you don't want them you can use dictionary. It contains job type as key and Action as the method it calls. If you need more jobs just create the private method and register it in the RegisterWorkers method.
private Dictionary<string, Action> actions = new Dictionary<string, Action>();
public Worker(string jt)
{
this.jobType = jt;
this.RegisterWorkers();
}
private void RegisterWorkers
{
this.actions["Pizza"] = this.MakePizza;
this.actions["Burger"] = this.MakeBurger;
}
public void ProcessJob()
{
var action = this.actions[this.jobType];
action();
}
No, I don't think it should be avoided. Any common functionality should go in a base class. I think you need a static factory method, that returns a child class based on the string parameter.
public abstract class Worker {
public virtual void ProcessJob();
public static Worker GetWorker(string jobType) {
if(jobType.Equals("Pizza")
return new PizzaWorker();
else if (jobType.Equals("Burger")
return new BurgerWorker();
else
throw new ArgumentException();
}
// Other common functionality
protected int getFoo() {
return 42;
}
}
public class PizzaWorker : Worker {
public override void ProcessJob() {
// Make pizza
int y = getFoo() / 2;
}
}
public class BurgerWorker : Worker {
public override void ProcessJob() {
// Make burger
int x = getFoo();
}
}
So to use this:
Worker w = Worker.GetWorker("Pizza");
w.ProcessJob(); // A pizza is made.
This is exactly why there are patterns: Command, Strategy, Decorator.
I believe the command pattern is what you are looking for. First you have a basic 'command' template:
public interface IJob {
void ProcessJob();
}
Different jobs would then be performed as follows:
public class MakePizza : IJob {
// implement the interface
public void ProcessJob() {
// make a pizza
}
}
Now, you could have a JobFactory as follows:
public static class JobFactory {
public static IJob GetJob(string jobType) {
if(jobType.Equals("Pizza"){
return new MakePizza();
} else (jobType.Equals("Burger") {
return new MakeBurger();
}
// to add jobs, extend this if-else-if or convert to switch-case
}
}
Worker can now look like this:
public class Worker {
private IJob job;
public Worker(string jt) {
job = JobFactory.GetJob(jt);
}
public void ProcessJob() {
job.ProcessJob();
}
}
If you don't have access to code to make these changes, then another pattern you may want to look into is the Adapter.
You're talking about basic inheritance here. There are a couple of ways that you could do this.
Make a Base Class that is
public class Job
{
virtual void ProcessJob();
}
Then a MakePizza class
public class MakePizza : Job
{
public void ProcessJob()
{
//make Pizza
}
}
Then in your worker class instead of having a JobType as a string which will lead to all kinds of potential bugs.
public class Worker{
private Job jobType;
public Worker(Job jt){
this.jobType = jt;
}
public void ProcessJob()
{
Job.ProcessJob();
}
}
If you have to pass through a string you could simply load up the JobType through reflection, throwing a error if the type doesn't exist.
having to change other classes means you need to change code, not that you need to change architecture. the best answer is just to change the code. in the long term, the maintenance burden of having to write this in a less-than-ideal fashion will cost you more than just changing the code. use inheritance and bite the bullet on making the change now. if you have iterators that will have problems with dealing with subtypes, your iterators are doing more than being iterators, and you are better off fixing that than going forward with them. if the other classes care about what subtype of worker they are dealing with, that's a problem in and of itself that you should fix. ultimately, the dependent code should not care which type of worker it is. that's really what you are after anyway. the instance of a type that has work as its base type is still a worker and that is all the class using a worker should care about.

Categories

Resources