Loose coupling of static stuff - c#

I have a class, ClassA that uses a client I wrote to send text messages, TextClient, to send some text messages via a call to the static method
TextClient.Send(string text, string destination)
// where destination is a phone number
However, I also have a mail client class, MailClient, which sends emails with the same signature:
MailClient.Send(string text, string destination)
// where destination is an email address
I would like to "inject" which of these clients should be used - is this possible?
(Note: I'm aware of problems that might arise when there are entirely different rules for what values destination can hold and be considered valid, but the values are fetched from someplace else, so this class doesn't need to bother. That's why I want to abstract this away in the first place.)

Basically, get rid of the static methods. Create an interface (IMessageClient) and then two implementations (TextClient and MailClient) with instance methods implementing the interface. Then you can inject the appropriate IMessageClient into the rest of the application with ease.
You certainly can use delegates to avoid creating the interface here - but I would definitely change to using interfaces instead:
The names involved (the interface name, method name and parameter names) convey information when you're using them
It allows for multiple methods in the same interface
It prevents methods which happen to have the same argument types but a completely unrelated meaning from being used accidentally

Sure, make your clients implement some sending interface.
public interface IMessageClient
{
public void Send(string text, string destination);
}
public class TextClient : IMessageClient
{
public void Send(string text, string destination)
{
// send text message
}
}
public class MailClient : IMessageClient
{
public void Send(string text, string destination)
{
// send email
}
}
public class ClassA
{
private IMessageClient client;
public ClassA(IMessageClient client)
{
this.client = client;
}
}
Same as Jon Skeet's answer, but he beat me by not typing out the code.

It's generally better to avoid static classes when designing such services because it makes it more challenging to decouple from other code.
If you have control over the design and implementation of the TextClient and MailClient classes, I would suggest considering making them singleton instance classes rather than static classes. You could then implement a common interface IMessageSender (see below) in both and pass that as an instance to the object that needs to make the call.
public interface IMessageSender
{
void Send( string message, string destination );
}
public class TextClient : IMessageSender { ... }
public class MailClient : IMessageSender { ... }
If you don't have control over the implementation of those classes (or can't change them at this point), you could pass a delegate into the object that needs to make the call:
class SomeConsumer
{
private Action<string,string> m_SendDelegate;
public SomeConsumer( Action<string,string> sendDelegate )
{
m_SendDelegate = sendDelegate;
}
public DoSomething()
{
// uses the supplied delegate to send the message
m_SendDelegate( "Text to be sent", "destination" );
}
}
var consumerA = new SomeConsumer( TextClient.Send ); // sends text messages
var consumerB = new SomeConsumer( MailClient.Send ); // will send emails

Don't make the methods static, create an interface with the Send()method and implement this interface on TextClient and MailClient. Now you can just inject an instance using the interface.
If it is not possible to make the methods non-static you can just write to thin wrappers around the static method call both implementing the said interface.

I would have thought so. If you have an interface as such
public interface ISender
{
void Send(string text, string destination);
}
Then just use dependency injection to pick up which sender to use.

Related

Confusion in implementing adapter pattern

I am learning Adapter pattern, and used following link to see code. Difference in my code and example code is, I removed ITarget interface, and directly created object in Client.
I know importance of using Interface, but is it really necessary to use interface, more specifically, by not creating interface, am I violating Adapter Pattern rule?
Adapter Pattern Example
My Code (without interface)
class Program
{
static void Main(string[] args)
{
Adapter obj = new Adapter();
Client client = new Client(obj);
client.MakeRequest();
}
}
public class Client
{
private Adapter _target;
public Client(Adapter target)
{
_target = target;
}
public void MakeRequest()
{
_target.MethodA();
}
}
public class Adaptee
{
public void MethodB()
{
Console.WriteLine("MethodB called");
}
}
public class Adapter
{
Adaptee _adaptee = new Adaptee();
public void MethodA()
{
_adaptee.MethodB();
}
}
Thanks.
The whole point of an adapter is that the adaptee can be used wherever a certain type is needed which is not the adaptee's type.
Assume that you have a method MyMethod(MyParameterType m). This method expects a parameter of type MyParameterType. But you don't have an object of this type. Instead you have an object that has similar functionality (maybe from a third-party library). However, this object is not of type MyParameterType, but of type MyOtherType. Of course, you can't directly pass the object to the method. That's where the adapter comes into play.
You need an object to pass to the method. Hence, it is essential that this object is of type MyParameterType; may it be an interface or class. So the Adapter has to implement or inherit this type. Otherwise, it does not make sense. You would just have another class with the same functionality as the object of type MyOtherType, but you can't use it anywhere.
Summarizing, the adapter is used to bridge architectural mismatch. This often occurs when you have several libraries that need to play together but were not supposed to do so. If you have only code that has been developed by yourself, adapters are rarely necessary because you can let the objects just implement the interface you need. This is not possible in third-party code. So you introduce adapters for that. So in the end, the adapter disguises an object to look familiar to a client, even if it is not. The interface is necessary to make it familiar. So yes, your code is not an adapter.
The problem here is you've explicitly coupled Client to the Adapter and implicitly to the behavior of how that adapter works.
Interfaces and this pattern pay off when you start using dependency injection.
Assume I have:
public Client(IAdapter target) ...
Now I can change the behavior of the adapter implementation without the Client class being changed at all:
interface IAdapter
{
void MethodA();
}
interface IAdaptee
{
void MethodB();
}
class Adapter<TAdaptee> : IAdapter where TAdaptee : IAdaptee, new()
{
private TAdaptee _adaptee;
public Adapter()
{
_adaptee = new TAdaptee();
}
public void MethodA()
{
_adaptee.MethodB();
}
}
class AdapteeA : IAdaptee
{
public void MethodB()
{
Console.WriteLine("AdapteeA");
}
}
class AdapteeB : IAdaptee
{
public void MethodB()
{
Console.WriteLine("AdapteeB");
}
}
Then with something like NInject you bind up your system:
class Program
{
private static StandardKernel _kernel;
static void Main(string[] args)
{
_kernel = new StandardKernel();
_kernel.Bind<IAdapter>().To<Adapter<AdapteeA>>();
var adapter = _kernel.Get<IAdapter>();
adapter.MethodA();
}
}
You can change your adapter and your adaptee, without client ever knowing the difference. i.e. Client is decoupled from both.
Again to make this point I can change to AdapteeB:
_kernel.Bind<IAdapter>().To<Adapter<AdapteeB>>();
It does go further too, with things like contra-variance, but that is beyond scope.

Is there any reason to prefer mocking an interface rather than a class with overridable members?

I have a external library used to exchange messages.
In this library I have an Object named Channel.
This is the result after decompiling the dll:
public class Channel
{
public State CurrentState { get { /*Only for code compiling, the value depend on the TCP Connection state.*/return State.ERROR; } }
public bool Send(string message)
{
//Some stuff with TCP connection.
return true;
}
public enum State
{
DISCONNECTED,
CONNECTED,
ERROR
}
}
Now in my code I use this Channel in a class for sending messages, the class looks like this :
public class ClientConnection
{
private Channel MyChannel;
public ClientConnection(Channel channel)
{
MyChannel = channel;
}
public bool Send(string message)
{
bool result = false;
if(MyChannel.CurrentState == Channel.State.CONNECTED)
{
result = MyChannel.Send(message);
}
return result;
}
}
So my goal is to test it, verifying that the method send is called, and checking that the arguments matches my input.
The problem here is that there is no interface and the method are not virtual, so mocking is not possible directly.
What did I do
I created a wrapper with overridable Property and Method like this :
public class ChannelWrapper
{
private readonly Channel channel;
public ChannelWrapper(Channel channel)
{
this.channel = channel;
}
public virtual Channel.State CurrentState { get { return channel.CurrentState; } }
public virtual bool Send(string message)
{
return channel.Send(message);
}
}
And changed in ClientConnection the type Channel to ChannelWrapper in the constructor and the property.
The Question
I fell that I should have created an extra interface that matches both Channel and ChannelWrapper, and mock using interface instead of overridable members.
And at the same time I really don't see the point of adding a new interface for nothing.
Is there any reason to prefer mocking an interface rather than a class with overridable members?
(I am thinking in term of performance mainly too).
The main reason you normally want to mock an interface rather than a concrete type is that, in the case of the concrete type, your mock will have bits and pieces of the actual implementation, potentially leading to unpredictable / undesired behaviour.
For example, the Send method on the Channel currently has "//Some stuff with TCP connection." inside it. What if the Channel class instantiates some web connections and stores them as fields? That means that your mock object now contains actual web connections, even though they might never be used. This might be more serious if we're talking database connections etc.
It may be that this isn't the case in your particular example, but you should think more that you've 'gotten away with it' this time, rather than that being the rule. These concerns mean it's normally much cleaner to mock an interface; you know that your mock object doesn't contain anything that you didn't put there in your test.
I would also see this very similar question: Mocking classes that aren't interfaces

Is an interface with no members suitable for indicating an "opaque handle" to library users?

Lets say I have an abstract object which can be implemented by multiple, separate plugin authors. (For instance, a bug database connection) I don't want consumers of my bits to have to deal with each specific plugin type.
I also want to separate the process of parsing a configuration file from the process of actually initializing database plugins and other such things.
To that end, I came up with something like this:
public interface IConfiguration
{
// No members
}
public interface IConnection
{
// Members go in here
void Create();
void Update();
void Delete();
}
public interface IConnectionProvider
{
// Try to interpret file as a configuration, otherwise return null
IConfiguration ParseConfiguration(Stream configurationContents);
IConnection Connect(IConfiguration settings);
}
public class ThingyRepository
{
// Lets say there is a constructor that initializes this with something
List<IConnectionProvider> providers;
// Insulates people from the actual connection provider
KeyValuePair<IConfiguration, IConnectionProvider> Parse(string filename)
{
IConnection result = null;
IConnectionProvider resultProvider = null;
foreach (var provider in this.providers)
{
using (Stream fs = OpenTheFileReadonly(filename))
{
IConnection curResult = provider.ParseConfiguration(fs);
if (curResult == null)
{
continue;
}
else
{
if (result == null)
{
result = curResult;
resultProvider = provider;
}
else
{
throw new Exception ("ambguity!");
}
}
}
}
if (result == null)
{
throw new Exception ("can't parse!");
}
return new KeyValuePair<IConfiguration, IConnectionProvider>(
result, resultProvider);
}
}
My question is, I've got this empty interface which is supposed to serve as an opaque handle to whatever settings were loaded from the indicated file. The specific implementer of IConnectionProvider knows what bits it needs in its configuration that it would load from a file, but users of this library should be insulated from that information.
But having an empty interface seems strange to me. Does this sort of thing make sense or have I done something horribly wrong?
The basic concept of an interface with no members, that simply identifies implementors as being something instead of the interface's normal job of identifying what an object has or does, is known as a "flag interface". It has its uses, but use them sparingly. I, for instance, typically use them in a hierarchical format to identify domain objects that should be persisted to a particular data store:
//no direct implementors; unfortunately an "abstract interface" is kind of redundant
//and there's no way to tell the compiler that a class inheriting from this base
//interface is wrong,
public interface IDomainObject
{
int Id {get;}
}
public interface IDatabaseDomainObject:IDomainObject { }
public interface ICloudDomainObject:IDomainObject { }
public class SomeDatabaseEntity:IDatabaseDomainObject
{
public int Id{get;set;}
... //more properties/logic
}
public class SomeCloudEntity:ICloudDomainObject
{
public int Id{get;set;}
... //more properties/logic
}
The derived interfaces tell me nothing new about the structure of an implementing object, except that the object belongs to that specific sub-domain, allowing me to further control what can be passed where:
//I can set up a basic Repository pattern handling any IDomainObject...
//(no direct concrete implementors, though I happen to have an abstract)
public interface IRepository<T> where T:IDomainObject
{
public TDom Retrieve<TDom>(int id) where TDom:T;
}
//... Then create an interface specific to a sub-domain for implementations of
//a Repository for that specific persistence mechanism...
public interface IDatabaseRepository:IRepository<IDatabaseDomainObject>
{
//... which will only accept objects of the sub-domain.
public TDom Retrieve<TDom>(int id) where TDom:IDatabaseDomainObject;
}
The resulting implementations and their usages can be checked at compile-time to prove that an ICloudDomainObject isn't being passed to an IDatabaseRepository, and at no time can a String or byte[] be passed into the repository for storage. This compile-time security isn't possible with attributes or properties, which are the other primary ways to "flag" a class as having some special significance.
So in short, it's not bad practice per se, but definitely ask yourself what you want out of the flag interface, and ask yourself if any state or logical data that would commonly be implemented on an IConfiguration (perhaps the name or other identifier of said configuration, or methods to load or persist it to the chosen data store) could do with some enforced standardization.
I think this is entirely valid. I'm designing an API where the caller has to first get an opaque "session" object and then pass it in to subsequent calls.
Different implementations of the API will use totally different implementations of the session object, so the session object clearly isn't an abstract class with different subclasses; it's an interface. Since the session object has no behavior visible to the caller, it seems to me the only logical model for this is an interface with no members.

Generic Interfaces and Type Parsing

I am trying to pass messages between several classes that communicate through interface. However, as I like to go as generic as possible, I ran into problems because the message type of incoming messages may be different from the outgoing type. I pasted some code to make it clearer.
The code below does not compile because the interface implementation passes a different type than the type of the blocking collection to which it is supposed to add incoming messages. I want to be able to send types potentially different from incoming types (incoming types obviously always match the type of the elements in the blocking collection). Can I somehow get around any sort of casting or parsing even if that means I need to redesign my interface or class?
I am still quite fresh when it comes to working with interfaces and struggled with recursions, stack overflow errors, and the like. So, if you have suggestions what I can improve design wise or just a quick fix then please help me to learn. Am very eager to understand how to implement a better pattern.
Thanks
public interface IClientMessaging
{
void MessagePassing<U>(U message);
}
public class InProcessMessaging<T> : IClientMessaging
{
private Dictionary<Type, List<IClientMessaging>> Subscriptions;
public BlockingCollection<T> MessageBuffer;
public InProcessMessaging(Dictionary<Type, List<IClientMessaging>> subscriptions)
{
//Setup Message Buffer
MessageBuffer = new BlockingCollection<T>();
//Subscribe
Type type = typeof(T);
if (subscriptions.Keys.Contains(type))
{
subscriptions[type].Add(this);
}
else
{
subscriptions.Add(type, new List<IClientMessaging>());
subscriptions[type].Add(this);
}
Subscriptions = subscriptions;
}
public void SendMessage<U>(U message)
{
//Send message to each subscribed Client
List<IClientMessaging> typeSubscriptions = Subscriptions[typeof(U)];
foreach (IClientMessaging subscriber in typeSubscriptions)
{
subscriber.MessagePassing<U>(message);
}
}
public T ReceiveMessage()
{
return MessageBuffer.Take();
}
public bool ReceiveMessage(out T item)
{
return MessageBuffer.TryTake(out item);
}
//Interface Implementation
public void MessagePassing<U>(U message)
{
MessageBuffer.Add(message); //<-"Cannot convert from U to T" [this is because I want
//to send messages of a different type than the receiving type]
}
}
I'm struggling to understand your goal here, but perhaps MessagePassing<U>(U message) should be MessagePassing(U message) and interface IClientMessaging should be interface IClientMessaging<U>.
Then InProcessMessaging<T, U> : IClientMessaging<U> - but I don't see why InProcessMessaging implements IClientMessaging AND manages subscriber lists of IClientMessaging. Seems to me that one class would manage the subscribers and another IS a subscriber (IClientMessaging).
You say U and T are different types. Well - are they related? Is one wrapper for the other? Sounds like maybe U is either a wrapper for T, a generic class itself that contains the T but adds extra info. In that case, void MessagePassing<T>(Wrapper<T> message);
UPDATES
Based on the comments so far ...
interface IClientMessage {}
interface IClientMessage<U> : IClientMessage { /* ... */ }
But rename those to:
interface IConsumer {} // (Or ISubscriber?)
interface IConsumer<TConsumed> : IConsumer{ /* ... */ }
and add:
interface IGenerator { }
interface IGenerator <TGenerated> : IGenerator {
event EventHandler<TGenerated> ItemGenerated;
}
Then:
class Manager
{
Dictionary<TConsumed, IConsumer> consumers = new ...
/* Code for attaching ItemGenerated event handlers to clients */
}
class MyClient : IGenerator<string>, IConsumer<Foo>, IConsumer<Bar>
{
event IGenerator<string>.ItemGenerated ...
void IConsumer<Foo>.Consume(...) ...
void IConsumer<Bar>.Consume(...) ...
}
Yes, this would use reflection to invoke IConsumer<TConsumed>.Consume(). Or you can leave off the generics and just use object as your types. Better yet, IClientMessage can have a Consume(object message) which in your implementation can ensure that object is a TConsumed before attempting to process it.
You could otherwise create direct client-to-client links through C# events, but you seem intent on a central dispatcher. It is the central dispatchers need to keep track of these different and unbounded number of types that is either going to require reflection OR be unaware of the types being passed (as described in the previous paragraph)
You should look at Reactive Extensions and the Observer pattern for ideas as well.
I removed my comments because it was getting too chatty.

What's the best practice for alternate solution of Multi-Inheritance in C#

I have some classes inherit from existing Windows Controls like TextBox and DateTimePicker, ..etc
I want to add custom functionalities for these classes like (Read, Alert, ...etc)
these added functionalities are the same in all these classes
The problem is: these classes inherited from difference parents so I can't put my added functionalities in the parent class,
What's the best practice in this case:
repeat the code in each inherited
class
Use a separated class have the
functionalities as Static Methods
with parameter from an interface, implement this interface for the classes and
then pass them.
Use a separated class like the second approach but with Dynamic parameter (which added in C# 4.0)
or other !!
Thanks in advance
I'd consider option 4: composition.
First, define your set of functionality. We'll assume that your partial list is exclusive, so "Read" and "Alert."
Second, create a single class that implements this functionality, something like MyCommonControlBehaviors. I'd prefer this implementation not be static if possible, though, it may be generic.
public MyCommonControlBehaviors
{
public Whatever Read() { /* ... */ }
public void Alert() {}
}
Third, use composition to add an instance of this class to each of your custom control types and expose that functionality through your custom control:
public class MyCustomControl
{
private MyCommonControlBehaviors common; // Composition
public Whatever Read() { return this.common.Read(); }
public void Alert() { this.common.Alert(); }
}
Depending on specifics, you can get creative to the degree necessary. E.g., perhaps your custom behaviors need to interact with private control data. In that case, make your control implement a common ICommonBehaviorHost interface that your common behaviors need. Then pass the control into the behavior class on construction as an instance of ICommonBehaviorHost:
public interface ICommonBehaviorHost
{
void Notify();
}
public class MyCommonControlBehaviors
{
ICommonBehaviorHost hst = null;
public MyCommonControlBehaviors(ICommonBehaviorHost host)
{
this.hst = host;
}
public void Alert() { this.hst.Notify(); } // Calls back into the hosting control
// ...
}
public class MyCustomControl : ICommonBehaviorHost
{
private MyCommonControlBehaviors common = null;
public MyCustomControl() { common = new MyCommonControlBehaviors(this); }
public Whatever Read() { return this.common.Read(); }
public void Alert() { this.common.Alert(); }
void ICommonBehaviorHost.Notify() { /* called by this.common */ }
}
Use Composition instead of Inheritence!
If you must, what I would probably do is create extension methods for each class and then reference the actual coded needed for these in some other object all the extension methods can call.
This way the code isn't duplicated, and the extension methods make it look like the methods should be in the object.
It's the same essentially by creating a static method and doing: Functions.DoSomething(my_Object);
But I always like: my_Object.DoSomething() better in an OO language.
I would suggest defining an interface for the behaviors, and then (to keep from repeating yourself) create extension methods on that interface definition for your shared methods. (Kinda like your second option, only with extension methods instead of totally static methods).

Categories