I want to do something like:
public void DoSomething()
{
if (!SomeStaticClass.CanDoWork)
{
return;
}
}
public void DoSomethingElse()
{
if (!SomeStaticClass.CanDoWork)
{
return;
}
// ....
}
I want to avoid duplication, since this would be present in a lot of class methods.
I tried looking into ConditionalAttribute but it seems that can't easily fix this issue.
Can this be done by Method attributes, or any other 'easy' way, if there isn't an 'easy' way, since the last approach would be to add an IF statement to every method.
with the context given by you, the first things that comes to my mind is to make a wrapping method that would contain the if statement. It would get the real method as parameter and excecute it condionally.
public class MyClass
{
public void DoSomething()
{
ConditionalExcecution(()=> DoSomethingOnlyCode());
}
private void DoSomethingOnlyCode()
{
// here the entire code
}
private void DoSomethingElseOnlyCode()
{
// here the entire code
}
public void DoSomethingElse()
{
ConditionalExcecution(()=> DoSomethingElseOnlyCode());
}
private void ConditionalExcecution(Action action)
{
if (SomeStaticClass.CanDoWork)
{
action();
}
}
}
This way you would have the if statement only in 1 place and hide the unconditional method code from the user of your API by private methods.
Depending on your context there might be better solutions to this dilema.
Related
I'm referencing a class that performs various demanding operations using callbacks rather than async operations. For example:
class CallbackClass : SomeSdkCallbacks
{
public void RequestData()
{
// We call this to request some data.
// After some time, this will trigger OnDataReturned to be called
}
public void OnDataReturned(DataObject data)
{
// This will be called automatically with returned data via SomeSdkCallbacks
}
}
There are many instances of this type of structure throughout this class.
What I'm trying to do is create a wrapper class around this one that simplifies it's usage. The structure that I'm going for at the moment is:
class MyWrapperClass
{
CallbackClass CallbackClass;
public MyWrapperClass()
{
this.CallbackClass = new CallbackClass();
}
public DataObject GetData()
{
this.CallbackClass.RequestData();
// Somehow wait until this.CallbackClass.OnDataReturned is called?
// Somehow get the data that would be passed in to this.CallbackClass.OnDataReturned()???
}
}
What is the best method of wrapping up a 'callback' architecture into a single asynchronous method?
Edit: To clarify, ideally I would like to package this up into a single method that can return the data in a single request. See the MyWrapperClass.GetData() method in my example for my ideal structure.
Edit 2: I'm aware that this desired architecture is bad form. Unfortunately that is the requested structure that has been asked of me.
I think this is what you want:
class CallbackClass<T>
{
private TaskCompletionSource<T> task = new TaskCompletionSource<T>();
public void RequestData()
{
}
public void OnDataReturned(T data)
{
task.SetResult(data);
}
public Task<T> Task { get { return task.Task; } }
}
class MyWrapperClass
{
public Task<DataObject> GetData()
{
var cls = new CallbackClass<DataObject>();
cls.RequestData();
return cls.Task;
}
}
Just note that TaskCompletionSource must be created per operation so you don't use the same one for two different calls. With this you can use the async keyword. This might help a bit more.
In your situation you can add some event on CallBackClass.
Like here:
class CallbackClass : SomeSdkCallbacks
{
public event Action<object> DataReturnedEvent;
public void RequestData()
{
// We call this to request some data.
// After some time, this will trigger OnDataReturned to be called
}
public void OnDataReturned(DataObject data)
{
DataReturnedEvent?.Invoke(data);
}
}
And you can use the event in the wrapper class
class MyWrapperClass
{
CallbackClass CallbackClass;
public MyWrapperClass()
{
this.CallbackClass = new CallbackClass();
CallbackClass.DataReturnedEvent =+ ProcessData;
}
private void ProcessData(object Data)
{
//some data processing
}
public DataObject GetData()
{
this.CallbackClass.RequestData()
}
}
Suppose I have various arbitrary sections of code to run, but before each section, I have to run a Start() method and then after each section I need to run a Complete() method. However, if an exception is thrown in the code section, I want to run a Fail(string message) method instead of Complete(). Is there a design pattern that elegantly encapsulates this to make it neat and easily repeatable?
For example, let's say I have a type called Thing that contains a Start() method that adds a row to a logging db table to reflect that a task is in progress, a Complete() method that changes that row to reflect that the task finished and a Fail(string message) method that changes the row to reflect that the task failed. These are just examples though, they could be doing any set-up and tidy up type tasks.
The naive implementation might be simply to call those methods manually:
public void DoStuff()
{
var thing = new Thing();
thing.Start();
try
{
DoImportantStuff();
thing.Complete();
}
catch (Exception e)
{
thing.Fail(e.Message);
}
}
But if I'm going to have to repeat this in a lot of different places, it ends up creating quite a lot of duplication and it might be easy to forget to call Complete or mess this up in some subtle way.
In C#, there's the using pattern, which provides a good way of encapsulating most of this. For example, if my Thing type looked like this:
public class Thing : IDisposable
{
public Thing(){
Start();
}
private void Start() { /* start */ }
private void Complete() { /* complete */ }
public void Dispose()
{
Complete();
}
}
My DoStuff() method could now be simplified to this:
public void DoStuff()
{
using(new Thing())
{
DoImportantStuff();
}
}
Which is much nicer. But it doesn't allow me to call Fail instead of Complete if an exception is thrown because (I think!) the Dispose method is essentially called in a Finally block.
I have thought of having a try/catch inside the using block and then setting a thing.HasFailed flag inside the catch block and then using that in the Dispose method to decide whether to Complete or Fail. But that seems a bit fiddly and I'd like the consumer of Thing to have to do as little as possible to make it work correctly.
So is there a design pattern that encapsulates what I want to do and avoids the need to manually write a try\catch each time?
You could have a Thing like this:
public class Thing
{
private void Start() { /* start */ }
private void Complete() { /* complete */ }
private void Fail(string message) {}
public void DoAction(Action action)
{
this.Start();
try
{
action();
this.Complete();
}
catch (Exception e)
{
this.Fail(e.Message);
}
}
}
And Use it like this:
Thing thing = new Thing();
thing.DoAction(this.DoStuff);
The pattern is called "template method". You can find your implementation under the title "aspect oriented programming".
(https://msdn.microsoft.com/en-us/library/aa288717(v=vs.71).aspx)
Using Delegates.
public class Thing : IDisposable
{
private void Start() { /* start */ }
private void Complete() { /* complete */ }
private void Fail(string _szMessage) {/* fail */}
public delegate void ProcessClientStuff();
private ProcessClientStuff m_delegateClientStuff;
public Thing(ProcessClientStuff _delegateClientStuff) {m_delegateClientStuff = _delegateClientStuff}
public void Dostuff()
{
Start();
try
{
m_delegateClientStuff();
Complete();
}
catch(Exception e)
{
Fail(e.Message);
}
}
}
void ClientStuff()
{
Console.WriteLine("Hello");
}
Thing oClientStuffProcessor = new Thing(ClientStuff);
oClientStuffProcessor.Dostuff();
I was wondering how I should decide to create an object, on method or class instance.Below a few examples to clarify. I want to the best approach to know how I should determine to choose between example 1 and 2.
IMPORTANT: Consider this a Windows Service (SVC) hosted in IIS.
Example 1
public class mySvcService
{
ReusableClass rClass = new ReusableClass();
public void MethodOne()
{
//Do Method One Stuff...
rClass.doSomething();
}
public void MethodTwo()
{
//Do Method Two Stuff...
rClass.doSomething();
}
}
public class ReusableClass
{
string valueOne;
string valueTwo;
string valueThree;
public void doSomething()
{
//DoSomeWork
}
}
Example 2
public class mySvcService
{
public void MethodOne()
{
ReusableClass rClass = new ReusableClass();
//Do Method One Stuff...
rClass.doSomething();
}
public void MethodTwo()
{
ReusableClass rClass = new ReusableClass();
//Do Method Two Stuff...
rClass.doSomething();
}
}
public class ReusableClass
{
string valueOne;
string valueTwo;
string valueThree;
public void doSomething()
{
//DoSomeWork
}
}
It is all about state. Will the object preserve some state between the two method calls, or even within the method, or not? If so, you should keep the object alive. Else, you can create a new object every time you call the method, or maybe even make the method static if there is never any state involved.
So:
Class preserves state that should be kept across methods: make a class variable or pass the object along the methods.
Class preserves state that should be kept within the same method: make a local variable.
Class doesn't preserve any state: make the method static, no instance needed.
The golden rule is to keep the scope as local as possible. From the second example if you are going to use doSomething() everywhere then it is better to create it once and have class level scope. If you need doSomething() only in one method, create the object locally within the method.
It is better to leave it inside of a method. Usually, it is being done inside of the constructor. This has the favor that it can incorporate a factory for different scenarios, or that it can be easily injected. I would strongly suggest to separate the responsibilities of the properties and let them be used as needed.
If you want to limit the scope of the object to a method, It can be done by using "Method injection" as shown below. You can use the other setter and constructor injection methods if the scope of the object is through out the class.
public interface IReusable
{
void doSomething();
}
public class Reusable: IReusable
{
public void doSomething()
{
//To Do: Some Stuff
}
}
public class mySvcService
{
private IReusable _reuse;
public void MethodOne(IReusable reuse)
{
this._reuse= reuse;
_reuse.doSomething();
}
public void MethodTwo(IReusable reuse)
{
this._reuse= reuse;
_reuse.doSomething();
}
}
Is there a way to modify the behavior of a static method at runtime?
for example:
Say I have this class
public class Utility {
public static void DoSomething(string data){
//...
}
}
Is there a way to do something like this:
typeof(Utility).SetMethod("DoSomething", (data) => { /*Do something else...*/ });
Such that if you call Utility.DoSomething it executes the new code?
What you want to do is pass the behavior you want as another parameter into the function.
public static void DoSomething(string data, Action<string> operation)
{
operation(data);
}
This is an oversimplified example, of course. What you actually wind up doing in your own code is going to depend on what operation actually does.
If you're trying to modify the behavior of an existing, compiled, in-production method, and cannot overload or override the method in the usual ways, the only way I know of to do that is CIL Rewriting, possibly using an Aspect Weaver.
Sure.
public class Utility {
public static Action<String> _DoSomething;
public static void DoSomething(string data){
if (_DoSomething != null) {
_DoSomething();
return;
}
// default behavior here.
}
}
And to mask the default behavior:
Utility._DoSomething = (data) => { /* do something else */ };
I don't see why you wouldn't just create a new class that inherits from Utility and define a new function that does what you want.
public class Program
{
static void Main(string[] args)
{
if (true)
{
Utility.DoSomething("TEST");
} else
{
Util1.DoSomething("TEST");
}
}
}
public class Utility
{
public static void DoSomething(string data)
{
//Perform some action
}
}
abstract class Util1 : Utility
{
public static new void DoSomething(string data)
{
//Perform a different action
}
}
I think although it is possible to do this you should ask yourself: "Why do I need this functionality"? Usually a method stays as is, and does what it is supposed to do according to its interface which is given by its name and signature. So while you can add additional logic by adding an Action<T>-parameter to your signature you should ask yourself if this won´t break the contract of the interface and therefor what the method was designed for.
Having said this you should consider either overwrite your method if the functionality you need is some kind of "making the same things differently then the parent-class" or extend it by adding a dependency into your consuming class and add some methods to that class that extent the functionality provided by the contained class (see also favour composition over inheritance)
class MyClass {
Utility MyUtility;
void ExtraMethod() { /* ... */ }
}
EDIT: As you´re using a static method the opportunity on overwriting is obsolete. However IMO that sounds like a great design-flaw.
I know the question can be answered by saying foreach(var item in items){item.doSomething()}; but what i'm after is slightly different. Here is the interface.
ManagableClass .cs
public interface ManagableClass : System.IDisposable
{
void Initialize();
}
and below is how I would like to see my code look like
MainManagerClass.cs
public class MainManagerClass: ManagableClass
{
private List<ManagableClass> minions;
public void Initialize()
{
TellMinionsTo(Initialize);
}
public void Dispose()
{
TellMinionsTo(Dispose);
}
private void TellMinionsTo(Action doSomething)
{
foreach (ManagableClass minion in minions)
{
minion.doSomething();
}
}
}
I know that this code that is here will not work, but it seems like this should be doable in C#. Anyone know if this can be done? If not it's not like it's the end of the world, I'll just do a foreach in each method.
The problem with your code is that you pass a delegate to a method of a certain instance (yourself), while what you want is to invoke a certain method on all minions.
You can use lambda expressions, something like
public void Dispose()
{
TellMinionsTo(minion=>minion.Dispose());
}
private void TellMinionsTo(Action<ManagableClass> doSomething)
{
foreach (ManagableClass minion in minions)
{
doSomething(minion);
}
}
I don't like using List's method directly. Tomorrow you'll have to work via an interface and your IList may not have to be a List at all.
What you are looking for is a Composite pattern. This pattern will allow you to have a class that will implement the correct method and differ it to a list of items. However, in your case, you need to modify your interface to implement the DoSomething() method. So, instead, this should look like this.
public interface ISomething
{
void DoSomething();
}
public class SomethingManager : ISomething
{
private List<ISomething> _items = new List<ISomething>();
public void DoSomething()
{
_items.ForEach(i => i.DoSomething());
}
}
Is that what you are looking for ?