I have a scenario where I need to return a list of actions and represent them on a context menu.
The software has a standard list of actions, e.g:
Analyse
Design
Develop
Implement
I am tasked with extending the original software for a different client, who would like to add an extra action, e.g.:
Analyse
Design
Develop
Test
Implement
I would like to develop this conforming to the OCP, so I have written the following factory class:
internal class ActionFactory
{
public IList<Action> Create()
{
var actionProvider =
Composition.Entity.CreateProvider<ActionProvider, Client>()[CurrentlyRunningClient];
return
actionProvider != null
?
StandardActions.Concat(actionProvider.AdditionalActions).ToList()
:
StandardActions;
}
private IList<Action> StandardActions
{
get
{
return
new Action[]
{
new Analyse(),
new Design(),
new Develop(),
new Implement()
}
.ToReadOnlyCollection();
}
}
}
The ActionProvider will seek out anything that implements a certain interface using reflection, returning me this class (if running the client that requires the new action):
internal class ActionProvider
{
public IList<MedicationAction> AdditionalActions
{
get
{
return new Action[]
{
new Test()
}
.ToReadOnlyCollection();
}
}
}
As far as conforming to OCP goes -- so far, so good! If anyone else wants to introduce a new action, then they don't have to modify any existing code. But the factory returns the standard list of actions with any new ones just tagged onto the end.
How would I specify an order for these actions without having to write some sort of class that would know about every possible action? (as I see it, violation of the OCP).
Related
We have a Web API library, that calls into a Business/Service library(where our business logic is located), which in turn calls a Data access library (Repository).
We use this type of data transfer object all over the place. It has a "Payers" property that we may have to filter (meaning, manipulate its value). I have gone about implementing that check as such, but it feels dirty to me, as I'm calling the same function all over the place. I have thought about either:
Using an attribute filter to handle this or
Making the RequestData a property on the class, and do the filtering in the constructor.
Any additional thoughts or design patterns where this could be designed more efficiently:
public class Example
{
private MyRepository _repo = new MyRepository();
private void FilterRequestData(RequestData data)
{
//will call into another class that may or may not alter RequestData.Payers
}
public List<ReturnData> GetMyDataExample1(RequestData data)
{
FilterRequestData(RequestData data);
return _repo.GetMyDataExample1(data);
}
public List<ReturnData> GetMyDataExample2(RequestData data)
{
FilterRequestData(RequestData data);
return _repo.GetMyDataExample2(data);
}
public List<ReturnData> GetMyDataExample3(RequestData data)
{
FilterRequestData(RequestData data);
return _repo.GetMyDataExample3(data);
}
}
public class RequestData
{
List<string> Payers {get;set;}
}
One way of dealing with repeated code like that is to use a strategy pattern with a Func (and potentially some generics depending on your specific case). You could refactor that into separate classes and everything but the basic idea looks like that:
public class MyRepository
{
internal List<ReturnData> GetMyDataExample1(RequestData arg) { return new List<ReturnData>(); }
internal List<ReturnData> GetMyDataExample2(RequestData arg) { return new List<ReturnData>(); }
internal List<ReturnData> GetMyDataExample3(RequestData arg) { return new List<ReturnData>(); }
}
public class ReturnData { }
public class Example
{
private MyRepository _repo = new MyRepository();
private List<ReturnData> FilterRequestDataAndExecute(RequestData data, Func<RequestData, List<ReturnData>> action)
{
// call into another class that may or may not alter RequestData.Payers
// and then execute the actual code, potentially with some standardized exception management around it
// or logging or anything else really that would otherwise be repeated
return action(data);
}
public List<ReturnData> GetMyDataExample1(RequestData data)
{
// call the shared filtering/logging/exception mgmt/whatever code and pass some additional code to execute
return FilterRequestDataAndExecute(data, _repo.GetMyDataExample1);
}
public List<ReturnData> GetMyDataExample2(RequestData data)
{
// call the shared filtering/logging/exception mgmt/whatever code and pass some additional code to execute
return FilterRequestDataAndExecute(data, _repo.GetMyDataExample2);
}
public List<ReturnData> GetMyDataExample3(RequestData data)
{
// call the shared filtering/logging/exception mgmt/whatever code and pass some additional code to execute
return FilterRequestDataAndExecute(data, _repo.GetMyDataExample3);
}
}
public class RequestData
{
List<string> Payers { get; set; }
}
This sort of thinking naturally leads to aspect oriented programming.
It's specifically designed to handle cross-cutting concerns (e.g. here, your filter function cuts across your query logic.)
As #dnickless suggests, you can do this in an ad-hoc way by refactoring your calls to remove the duplicated code.
More general solutions exist, such as PostSharp which give you a slightly cleaner way of structuring code along aspects. It is proprietary, but I believe the free tier gives enough to investigate an example like this. At the very least it's interesting to see how it would look in PostSharp, and whether you think it improves it at all! (It makes strong use of attributes, which extends first suggestion.)
(N.B. I'm not practically suggesting installing another library for a simple case like this, but highlighting how these types of problems might be examined in general.)
FYI: the verbose preamble is to help explain why I am using Activator.CreateInstance. I have a number of entities (objects corresponding to database column information) that are "contained" in multiple databases, each of which has a different table/column setup. So I am able to retrieve an entity from each database, but the way I retrieve it is different per database. The database type is not known till runtime and could vary throughout execution. I have created the following setup:
First define the query operations each entity should support and each entity reader should support these operations.
public abstract class Operations<T> {
public delegate T findDelegate(int id);
public findDelegate find;
}
// there are many of these N=1,2,..., but here is one
// use abstract class since implementation of queries should be done by handlers
public class EntityNReader : Operations<EntityN> {
public Reader();
}
Define an interface for "Handler" classes, i.e. these classes implement the query operations listed above.
public interface IHandler<T> {
public string find(int id);
}
// there are many of these N,M=1,2..., but here is one
// use of interface is to force handlers to implement all query types
public class EntityNHandlerForDbTypeM : IHandler<EntityN> {
public string find(int id) {/*whatever*/}
}
This allows the developers to create a single class for handling EntityN query operations for DbTypeM. Now, create a Database class that contains the reader objects and binds the handler methods to the reader delegates.
public class Database {
// there are many of these, but here is one
public EntityNReader EntitiesN;
public Database(string dbType) {
// this is called for each EntityNReader
bindHandlers<Reader, TypeN>(MyReader, dbType);
// ...
// nullreferenceexception
EntitiesN.find(0);
}
// this is a factory that also performs late binding
private void bindHandlers<T,K>(T reader, string dbTypeM)
where T: Operations<K>, new()
{
// create instance of EntityNReader
r = (T)Activator.CreateInstance(typeof(T));
// r != null
// create instance of handler
IHandler<K> h = (IHandler<K>)(Activator.CreateInstance(
Type.GetType("namespace.to.EntityNHandlerForDbTypeM"),
new object[] { this }
));
// bind delegates
r.find = h.find;
}
}
As you can see in Databases constructor, the way the code is written now, I get a NullReferenceException even though instance r of EntityNReader is created and (verified to be) not null.
However, if I instantiate EntitiesN where it is declared in Database instead of within bindHandlers, the code compiles and everything works. The reason I don't just do this is that (subsequently) I would like to conditionally create readers/handlers inside of bindHandlers at the time the Database class is instantiated.
What is happening here? Link to actual code if necessary.
P.S. I am relatively new to programming, so I am open to hearing how an experience developer might design this component (especially if I am heading down the wrong path).
I realize your code was just samples, but I spotted this right off the bat...
if (supports[typeof(Entity1).Name]) { bindHandlers<Entity1Reader, Entity1>(Entities1, CamaDbType); }
if (supports[typeof(Entity2).Name]) { bindHandlers<Entity1Reader, Entity1>(Entities1, CamaDbType); }
Is it possible that you have a simple copy/paste mistake? Notice that Entities1 is passed in for both bindHandlers calls.
I am currently in the process of designing a new message translation system at work and have the following question concerning DI and Unity.
I have the following interface:
public interface ITranslate<TInput, TOutput>
{
TOutput TranslateMessage(TInput message);
}
With a concrete implementation of below (where InternalMessage is a custom class I have developed)
public class TestTranslate : ITranslate<byte[], InternalMessage>
{
InternalMessage Translate(byte[] message)
{
// Do the translation here and return the result....
}
}
However I want to using unity inject a translator instance into my Translator service through the constructor. To be used in a method within the service.
public class TranslatorService
{
private readonly ITranslator translator;
public TranslatorService(ITranslate translator)
{
this.translator = translator;
}
public byte[] DoTranslate(string message)
{
return translator.TranslateMessage(message);
}
}
However I have 2 questions:
1) Is it possible to have the ITranslate in the constructor without specifiying the types that the translator will deal with (I am trying to keep the Service
and Translator as generic as possible, so if another translation was needed I would only need to swap out the Concrete implementation of the Translator interface).
2) If this is possible how would I do it and then what would I have in my unity configuration to do that. Note I am using the XML configuration (not my choice) to
configure my dependenciues etc.
Thanks In Advance
Stuart
After some thinking, I assume you want to do the following:
At some point, messages of different types come in and have to be
translated to other types, somehow.
The component/client that receives these messages is and should be unaware of how different types of messages should be translated.
Therefore, you want to implement a generic TranslatorService-class that takes any message and magically translates is to the correct type, based on the input-message.
For each specific translation, you want to define a specific, generic Translator-class that is automatically instantiated and used by the TranslatorService-class, preferrably using dependency injection of some sort.
If my assumptions are correct, I would advise the following design.
First of all, define a generic interface that must be implemented by each specialized Translator-class. Only make the input-type generic:
interface IMessageTranslator<TMessage>
{
object Translate(TMessage message);
}
Then create the TranslatorService such that clients can just push in arbitrary messages and gives them back the result, if and only if a Translator for that message exists:
class TranslatorService
{
object Translate(object message)
{
}
}
Now the TranslatorService has to instantiate the correct IMessageTranslator<T> based on the type of message. You can do this with Unity by having the TranslatorService-class encapsulate a container that contains all IMessageTranslator<T>-types that you have implemented and then simply instantiate one based on the message type:
class TranslatorService
{
private readonly IUnityContainer _container;
public TranslatorService()
{
_container = new UnityContainer();
_container.RegisterType(typeof(IMessageTranslator<A>), typeof(MessageTranslatorA));
_container.RegisterType(typeof(IMessageTranslator<B>), typeof(MessageTranslatorB));
// Etc...
}
object Translate(object message)
{
if (message == null)
{
throw new ArgumentNullException("message");
}
var genericTranslatorDefinition = typeof(IMessageTranslator<>);
var translatorType = genericTranslatorDefinition.MakeGenericType(message.GetType());
var translator = _container.Resolve(translatorType);
var translateMethod = translatorType.GetMethod("Translate", new [] { message.GetType() });
return translateMethod.Invoke(translator, new object[] { message });
}
}
Note that this is a naive implementation as to whether a translator actually exists/is registered for the specified message, and also in the way it finds the Translate-method (better to get it through the InterfaceMap), but you get the idea.
If you want even more flexibility, you could create a mechanism that auto-fills your container by scanning the assembly for IMessageTranslator-implementors. That way, you just add a new implementation and you're ready to go.
I have a third party C# library for ldap operations. It does all operations on connection object as below:
LdapConnection connection = new LdapConnetion(Settings settings);
connection.Search(searchOU, filter,...);
which I feel is not readable. I want to write a wrapper around it so that I should be able to write code like below:
As I would like to have different Ldap classes like
public class AD: LdapServer { }
public class OpenLdap: LdapServer { }
and then
AD myldap = new AD(Settings settings);
myldap.Users.Search(searchOU, filter,...)
myldap.Users.Add(searchOU, filter,...)
myldap.Users.Delete(searchOU, filter,...)
I am thinking about Proxy design pattern, but things are not getting into my head about hot to go about it. What classes should I have etc.
Any help?
The solution posted above inherits from the LdapConnection. This is good if you want to maintain the inheritance chain, but I dont think that is necessary in your case. You simply want to customize and simplify the interface.
The proxy design pattern inherits from the underlying object so that the proxy object can be used anywhere that the underlying object is required, this is good if you want to "inject" extra functionality into the class without the clients of that class realising. I dont think this is your intention here?
The big problem with the solution posted above is that (because it inherits directly from LdapConnection) you can call search in two ways like so:
Settings settings = new Settings();
AD myAD = new AD(settings);
object results = myAD.Users.Search();
// OR
object results2 = myAD.Search();
As I'm sure you can see from the code, both of these call the exact same underlying method. But in my opinion, this is even more confusing to developers than just using the vanilla LdapConnection object. I would always be thinking "whats the difference between these seemingly identical methods??" Even worse, if you add some custom code inside the UsersWrapper Search method, you cannot always guarentee that it will be called. The possibility will always exist for a developer to call Search directly without going through the UsersWrapper.
Fowler in his book PoEAA defines a pattern called Gateway. This is a way to simplify and customize the interface to an external system or library.
public class AD
{
private LdapConnection ldapConn;
private UsersWrapper users;
public AD()
{
this.ldapConn = new LdapConnection(new Settings(/* configure settings here*/));
this.users = new UsersWrapper(this.ldapConn);
}
public UsersWrapper Users
{
get
{
return this.users;
}
}
public class UsersWrapper
{
private LdapConnection ldapConn;
public UsersWrapper(LdapConnection ldapConn)
{
this.ldapConn = ldapConn;
}
public object Search()
{
return this.ldapConn.Search();
}
public void Add(object something)
{
this.ldapConn.Add(something);
}
public void Delete(object something)
{
this.ldapConn.Delete(something);
}
}
}
This can then be used like so:
AD myAD = new AD();
object results = myAD.Users.Search();
Here you can see that the LdapConnection object is completly encapsulated inside the class and there is only one way to call each method. Even better, the setting up of the LdapConnection is also completely encapsulated. The code using this class doesn't have to worry about how to set it up. The settings are only defined in one place (in this class, instead of spread throughout your application).
The only disadvantage is that you loose the inheritance chain back to LdapConnection, but I dont think this is necessary in your case.
Ok, if you simply want to split the methods up into they objects that they act on (i.e. in your example add the .Users. before the method call) you can do something similar to this.. You'll need to get the method parameters and return types correct for your library, I've just used object here.
Is this the sort of thing you're looking for?
public class AD : LdapConnection
{
private UsersWrapper users;
public AD(Settings settings) : base(settings)
{
this.users = new UsersWrapper(this);
}
public UsersWrapper Users
{
get
{
return this.users;
}
}
public class UsersWrapper
{
private AD parent;
public UsersWrapper(AD parent)
{
this.parent = parent;
}
public object Search()
{
return this.parent.Search();
}
public void Add(object something)
{
this.parent.Add(something);
}
public void Delete(object something)
{
this.parent.Delete(something);
}
}
}
This can then be be used as follows:
Settings settings = new Settings();
AD myAD = new AD(settings);
object results = myAD.Users.Search();
Remember that this isn't strictly a "wrapper" because it actually inherits from the underlying class.
I'm writing some tests, and frequently I find myself having to look up generic parameters to pass explicitly pass along.
public class MyService : SecureService<RootEntity>
{
//Intentionally omitted does not provide information related to question
}
public DepedencyReplaceScope<IContextProvider> CreateMockScope<TRootEntity>
{
var mockCtx = Mock.Of<IContextProvider>(x => x.WriteContext<TRootEntity> == new FakeContext<TRootEntity>())
return new DependencyReplaceScope(mockCtx);
}
Currently when I'm creating mocks for my test, I have too go into the service and find out what it's root is to pass along. However, It would be a lot nicer if I could create a scope based on the service.
e.g (pseudo code)
public DepedencyReplaceScope<IContextProvider> CreateMockScopeFromService<TService>
where TService : SecureService<>
define TRootEntity : TService<()>
{
return CreateMockScope<TRootEntity>();
}
This won't work since I don't think there is a way to define a proxy for the Generic. Is there a way to create this scope solely from the TService (I don't want to use reflection directly to build it, but I don't mind using a hack with a moq since it abstracts the reflection)
The best thing I was able to come up so far was:
public static class MockScopeProvider
{
public static DepedencyReplaceScope<IContextProvider> CreateMockScopeFromService<U>(SecureService<U> dummy)
{
// your logic....
var mockCtx = Mock.Of<IContextProvider>(x => x.WriteContext<U>() == new FakeContext<U>());
return new DependencyReplaceScope(mockCtx);
}
}
With usage being like that:
MockScopeProvider.CreateMockScopeFromService(default(MyService));