I have the following code which executes in sequence, method after another.
I load the request, perform a couple of checks like checking if a response already exists for this request, if not, I call the service and receive the response which I save to the DB.
I was looking for a design pattern I can use in such a case, I thought of posting this here and get some ideas.
public class Manager
{
public void PutRequest()
{
//Do Something
if (loadRequest())
{
callService();
//Do Something
saveResponse();
}
}
private bool loadRequest()
{
bool isExist = checkIfResponseExists();
if (!isExist)
{
// If false, load request from DB
}
return !isExist;
}
private bool checkIfDataExists()
{
//Check if a response already exists in the DB for this request
}
private void callService()
{
//Call the service and receive the response
}
private void saveResponse()
{
//Store the response in the DB
}
}
Patterns are used for solving some problems. What problem your current code have? I don't see any duplicated code, beside names of methods. There is no pattern, which fixes method naming problem.
Yes, your code need some refactoring, but not to patterns. Better class and method naming is a first step. Also, I'd removed field isExist.
public class Manager
{
public void PutRequest()
{
//Do Something
if (!CheckIfResponseExists()) // returns boolean value
LoadRequestFromDB()
CallService();
//Do Something
SaveResponse();
}
}
Check the design pattern called Strategy, it defines an interface common to all supported algorithms and each concrete strategy implements an algorithm
http://www.oodesign.com/strategy-pattern.html
It seems like it'd be more useful for several of these methods to be functions. So instead of having a method who's responsibility is to both check for a condition and do some other actions, you have a function that checks for a condition then the method that called it does some action depending on the result. (Kind of the SRP applied to methods...)
public void DoAllTheThings!() // Oops, Ruby syntax creeping in :P
{
if(!WeCanDoIt())
{
MakeItSo(); // So that we can do it...
}
NowWeCanDoAllTheThings();
}
private bool WeCanDoIt() {}
private void MakeItSo() {}
private void NowWeCanDoAllTheThings() {}
Command + Composite.
Some people consider the use of an if/then Command - in your case that would be in putRequest - in a Composite a kind of Chain Of Responsibility.
While selecting a pattern you should consider scalability of the application
One of the pattern you can apply is state pattern
There will be two states.
Response is already there
Need to process the new response
Related
This is probably a newbie question but I couldn´t find a good answer even googling and reading a lot about the subject.
I have a generic method, lets call it Execute()
My code receives a message1:
{
serviceProvider: "Sever1",
serviceType: "query",
service: "authors"
}
and message2 could be:
{
serviceProvider: "Sever2",
serviceType: "query",
service: "bookTitles"
}
Now, I have
public void ProcessMessage(Message message)
{
switch (message.service)
{
case "authors":
Execute<Authors>();
break;
case "booTitle":
Execute<BookTitle>();
break;
}
}
I really don´t like this ProcessMessage method, as it does not look DRY at all. And if we add more types of services, then we need to keep adding to the switch.
How should I implement this thing? Do I need reflection? I´d rather not use reflection as the ProcessMessage can be called thousands of times and reflection would probably add a lot of overhead.
If you want to have a dynamic switch you don't need to resort to reflection, but you'd need to register the services you want to use.
Based on your question, here's what that might look like:
void Main()
{
this.Register("authors", () => Execute<Authors>());
this.Register("bookTitles", () => Execute<BookTitle>());
}
private Dictionary<string, Action> _registry = new Dictionary<string, Action>();
private void Register(string key, Action action)
{
_registry[key] = action;
}
public void ProcessMessage(Message message)
{
if (_registry.ContainsKey(message.service))
{
_registry[message.service]();
}
}
You can add as many actions as you need. And you can do that at run-time.
My answer will be split into Two sections:
Section 1: Tell you what you really need!
I think Services dont add so often, so you shouldn't optimize the Maintenence aspect of this code,
just add a strong ASSERT if a service call is not recognized,
so while testing, you know you forgot to add it to this function!
Section 2: give you what you asked for!
I think you can use reflection, but to compansate for performance,
you should cache the Function calls in a dictionary.
// psuedo C#
auto m_ServiceCache = new ConcurrentDictionary<string, SERVICE>()
public void ProcessMessage(Message message)
{
Action svcFunction;
if(!m_serviceCache.TryGetValue(message.service, out svcFunction))
{ // not found in cache
// create the service specific instanciation, and save it to cache!
// Take into account that the "message.service" needs to be a valid type name with namespace!
// Also note you should Sanitize the input as it is a very clear vaulnerablity to exploit
// totally abstract psuedo here
getGeneralType = typeof(SERVICE);
specificType = getGeneralType.CreateSpecificType(T=message.service)
specificObject = specificType.Instanciate();
m_serviceCache.Add(message.service, svcFunction);
svcFunction = specificObject;
}
svcFunction(); // call the cached service.
}
cheers
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.)
I have a class from a third-party assembly (so I can't edit it):
public class MyClass
{
private bool _loggedIn;
public void Login() {_loggedIn = true;}
public void Logout() {
if (!_loggedIn) throw new InvalidOperationException();
_loggedIn = false;
}
}
Now, suppose I have an instance of MyClass (for which I don't know _loggedIn), and I need call LogOut. Which of the following methods of avoiding a fatal exception will generally be faster? (any other method would be fine too):
To call LogOut, and if _loggedIn == false, just catch the exception
To use reflection to check that _loggedIn == true, and only call LogOut if so
It depends on the invariants you expect to see in your application.
1. If you expect to have a lot of MyClass having different state(logged in, logged off), then it is better to avoid overhead of exception (because exception is Exceptional situation) and use some specific public IsLoggedIn property (obviously to avoid Reflection) or some TryXxxxx-like methods.
And even if you can't modify the original code no one stops you from wrapping it:
public class MyWrappedClass
{
public Boolean IsLoggedIn {get; private set;}
private MyClass m_Log;
public MyWrappedClass ()
{
this.m_Log = new MyClass();
this.IsLoggedIn = false;
}
public void Log()
{
try
{
this.m_Log.LogIn();
this.IsLoggedIn = true;
}
catch
{
this.IsLoggedIn = false;
}
}
public void LogOut()
{
try
{
this.m_Log.LogOut();
this.IsLoggedIn = false;
}
catch
{
this.IsLoggedIn = true;
}
}
}
You could even go further and implement IDisposable interface with it to avoid manual LogIn-LogOut management:
public class MyWrappedClass
{
private class LogSessionToken : IDisposable
{
private MyWrappedClass parent;
public LogSessionToken (MyWrappedClass parent)
{
parent.LogIn();
}
public void Dispose()
{
parent.LogOut();
}
}
public IDisposable LogSession()
{
return new LogSessionToken (this);
}
// ...
}
And use it like
using (var logToken = wrappedInstance.LogSession)
{
// do the work.
} // No need to worry about manual LogOut
2. If you expect to use only few of MyClass in a proper fashion, then it would be a better idea to not handle exception at all - if something wrong happened then it is some programming error thus the program shall be terminated.
First, if your class doesn't expose at least a read-only property for LoggedIn, there sounds like a fairly large design flaw.
For speed, using reflection will generally be faster, particularly if you cache the FieldInfo or build a Func<bool> using System.Linq.Expressions. This is because Exceptions collect lots of debug information when thrown, including a StackTrace, which can be expensive.
As with anything, though, it is often best to test such operations, as there are sometime optimizations or other factors that may surprise you.
If the pattern if (CanFoo) Foo(); appears very much, that tends to imply very strongly that either:
A properly-written client would know when it can or cannot call Foo. The fact that a client doesn't know suggest that it's probably deficient in other ways.
The class exposing CanFoo and Foo should also expose a method which will Foo if possible and appropriate (the method should throw if unable to establish expected post-conditions, but should return silently if the post-conditions were established before the call)
In cases where a class one does not control should provide such a method but doesn't, the cleanest approach may be to write one's own wrapper method whose semantics mirror those the missing method should have had. If a later version of the class implements the missing method, changing one's code to use that implementation may be easier than refactoring lots of if (CanFoo) constructs.
BTW, I would suggest that a properly-designed class should allow calling code to indicate whether it is expecting a transition from logged-in state to logged-out state, or whether it wants to end up in logged-out state but it doesn't care how it gets there. Both kinds of semantics have perfectly legitimate uses; in cases where the first kind would be appropriate, having a LogOut method throw an exception if called on a closed session would be a good thing, but in cases where client code merely wants to ensure that it is logged out, having an EnsureLoggedOut method that could be invoked unconditionally would be cleaner than having to add extra client-side code for that purpose.
i probably dont have the right words but i have tried my best.
say i have a function in c# such as DoWork and within that function i want to call another function such as CheckScore(). However, CheckScore() is a generic function that i want to call from multiple places.
So in my class when i create another function DoWork2, DoWork3 is there any way i can execure CheckScore() as the first line instead of typing those everytime?
For eg. can i avoid
string DoWork2(){
CheckScore()
}
Instead just have
string DoWork2(){}
but CheckScore() is executed anyways?
One potential, though still not foolproof, method is to abstract your security checks into Attributes. This way you can decorate your methods with something like:
[CheckToken]
public string DoWork() {
....
}
This isn't necessarily the best answer because it still requires you to attribute the method. You could instead create an attribute for your web service class, which would execute the [CheckToken] on any method call of the class.
[CheckToken]
public class MyWebService {
...
}
The only issue here is if you have some methods where you want to execute different security checks, or no security checks.
A C# web service framework that has pretty good security features baked into the framework is Service Stack. http://www.servicestack.net/ It has security attributes already built in that you can use, and it promotes clean separation of concerns.
Another very robust option involves intercepting method calls. C# has a class "ContextBoundObject" which can be used for this purpose. You'd need to have your class inherit from ContextBoundObject, and then you can start to dynamically intercept method calls and perform your security checking based upon the context of the method call being made and its parameters. ContextBoundObject does add some overhead to your calls, so you'll need to factor that into your decision. Method interception is great for things like security, performance monitoring, health checks, method retries, and other cross cutting concerns.
Here's a simple getting-started article on ContextBoundObject (and Aspect Oriented Programming). http://www.codeproject.com/Articles/8414/The-simplest-AOP-scenario-in-C
For J...
I wouldn't have the method code query the result. Since we're talking about a web service, there's a pipeline involved where a request is initiated by a client, that request is sent to the service, that service initializes its handlers, deserializes the request, routes the request to the appropriate method, executes the method, serializes the response, and returns the response to the client (this is a big simplification..). Most frameworks I've seen have some hooks for you to specify attributes on your service methods that get checked at the point prior to method execution and can be used to handle security (ie, return a 401 http code for a web service). I believe he said he's using WCF and while it's been a while since I've used WCF, I know this can be done - see http://msdn.microsoft.com/en-us/library/ms733071.aspx
So he could derive his custom security attribute from some WCF security attribute and create his own authentication logic based upon some token, which he'd most likely have to grab from the headers of the request. ServiceStack makes this super easy, I'd imagine it's not that hard using WCF either. Chances are someone's already done this for WCF and the code is out there somewhere.
This may not be exactly what you are looking for, but I would associate the "CheckScore" with the getter for the property when the score is accessed. That way, when using the property it feels like you are not writing out the CheckScore a lot, and also you don't have a CheckScore function being called every time any old method is invoked in your application.
private int _score;
public int Score
{
get
{
CheckScore();
return _score;
}
}
public void DoWork1()
{
if (Score > 10) {
// Case 1
}
}
public void DoWork2()
{
if (Score < 20) {
// Case 2
}
}
Putting CheckScore in a property will still result in it being called a lot.
You could use a private readonly field and set it in the constructor. This will minimise the number of calls to CheckScore.
public class MyClass
{
private readonly int _score;
public MyClass()
{
_score = CheckScore();
}
public int Score
{
get
{
return _score;
}
}
public void DoWork1()
{
if (Score > 10) {
// Case 1
}
}
public void DoWork2()
{
if (Score < 20) {
// Case 2
}
}
}
Given the additional information in comments, one solution to this problem is to create a small class to encapsulate methods which require authentication :
abstract class AuthenticateClass
{
private bool AuthenticateUser(){
return true; // do your authentication
}
public int Perform(){
if (!AuthenticateUser()){
return -1;
} else
return AuthenticatedMethod();
}
protected abstract int AuthenticatedMethod();
}
This gives you a class that performs the authentication and, if successful, performs your method. Implement it like :
class SomeAuthentMethod : AuthenticateClass
{
protected override int AuthenticatedMethod()
{
return 10; // whatever method...
}
}
and use it like :
SomeAuthentMethod myMethod = new SomeAuthentMethod();
if (myMethod.Perform() = -1){
// unable to authenticate user, please log in, etc
}
If the authentication passes this returns 10, otherwise it returns -1 (authentication failed). This lets you generate any number of methods which automatically include authentication.
Alternatively, you might use a static class to do the authentication -- for example :
static class Authenticate
{
public delegate int MethodDelegate();
private static bool AuthenticateUser(){
return true; // do your authentication
}
public static int Perform(MethodDelegate MyMethod){
if (!AuthenticateUser())
{
return -1;
}
else return MyMethod();
}
}
Where you could then have :
private int myMethod(){
return 10; //whatever method...
}
and then implement like :
if (Authenticate.Perform(myMethod) = -1){
// unable to authenticate user, please log in, etc
}
Obviously you can extend both of these patterns to handle whatver "not logged in" or "not authenticated" action within the abstract or static class itself. This should, at least, provide a few ideas of how to approach the problem.
Consider this code.
public class Class1
{
public void ThisShouldNotCompileBecauseOrderWasVoilated()
{
Call2();
Call1();
}
public void ThisShouldCompileBecauseProperOrderIsPresent()
{
Call1();
Call2();
}
private void Call1()
{
// some code
}
private void Call2()
{
// some more code
}
}
What code (or attribute) should I add in Call1()/Call2() which ensures that compiler complains for 1st method and passes for 2nd method. There will be some rule list which compiler will have to refer if order is not correct. In this example the rule list can say "Call1 Call2", meaning call Call1() before Call2()
This is for C# language for .NET 4.0
Thanks!
There's nothing within normal C# that you can specify for this.
You may be able to use something like NDepend to detect this, but I'm not sure.
You can create your own attribute and mark your methods using it. Then create an FXCop rule. FXCop fully integrates with your build process, and as long as both calls are taking place within the same method, the rule should be fairly easy to flesh out.
the compiler can't enforce method call ordering, since in many cases it cannot determine statically what the call order is. For example:
public void whichOrder(boolean b)
{
if (b) call1();
if (!b) call2();
if (b) call2();
if (!b) call1();
}
If it's necessary that the methods are called in the correct order, you have a few choices:
document the call order, so that callers know what to do. This doesn't enforce the order, but at least makes coders aware of it.
add state to your object to remember which method was called last, and validate the current called method is allowed next. This enforces the method check at runtime.
Use a mock framework (e.g. Moq) to unit test your clients. This checks at build time that the order is correct.
Which approach you choose depends on how critical the correct ordering is, and the consequences of calling the methods in the wrong order.
An alternative is to rework your design so that method ordering doesn't become an issue. For example, wrap both methods up in a third, call3() that invokes call1() and call2() in the correct order. Or perhaps, have call2() invoke call1() if it has not already been executed, and have call1() check if it's already run, and return silently if it doesn't need to run. If clients invoke call2() then call1(), you still internally get the effect of call1() first (from call2()'s internal call to call1()) and the client's call to call1() results in a no op.
E.g.
public void call3()
{
call1();
call2();
}
or
public void call2()
{
call1();
// rest of call2's logic
}
private boolean call1Called = false;
pubic void call1()
{
if (!call1Called)
{
call1Called=true;
call1Impl();
}
}
This is not exactly what you are asking ... but you could introduce another class:
public class Another1
{
public Another2 Call1()
{
// some code
return new Another2();
// could pass 'this' to Another2 constructor so it has all state
}
}
public class Another2
{
public void Call2()
{
// some more code
}
}
Now, starting from an instance of Another1 you can only do obj.Call1().Call2() and never obj.Call2().Call1(). Better yet, this enforcement is in the IDE as you type. Take a look at 'fluent' patterns also.