I have the following method which prints lines to the console.
public void MyMethod() {
try {
Console.WriteLine("Hello!");
Console.WriteLine("My name is MyMethod");
}
finally {
Console.WriteLine("Bye.");
}
}
I have a few of these methods and they all do the same thing (i.e. try { "Hello"; Something; } finally { "Bye." }). To avoid redundancy and make my code clearer, I came up with the following:
public void SayHello(Action myName) {
try {
Console.WriteLine("Hello!");
myName();
}
finally {
Console.WriteLine("Bye.");
}
}
public void MyMethod2() {
SayHello(() => Console.WriteLine("My name is MyMethod"));
}
I like this technique, but I think it could be even better by using an attribute. Here is what I would like to ultimately achieve:
[SayHello]
public void MyMethod2() {
Console.WriteLine("My name is MyMethod");
}
It would be great if I could simply add a method attribute to help me eliminate redundancy (i.e. try { "Hello"; Something; } finally { "Bye." }). Is it possible in C# to create such attribute?
You should look at AOP techniques, specifically PostSharp
Vote this up:
"CompileTimeAttribute to inject code at compile time"
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=93682
Related
I'm trying to make a method, MethodA, only accessible when bool, executable, is true. Otherwise an other method, MethodB, is accessible. For example:
private bool executable = true;
public int MethodA(); <-- // Is accessible from outside of the class because executable is true
public string MethodB() <-- // Is not accessible because executable is true
The main reason I'm trying to do this is because the 2 methods return 2 different types. So my question is, is this even possible?
Option #1
You may be able to get what you want using Polymorphism and Generics. This would also allow you to add additional method strategies if needed.
public interface IMethodStrategy<out T>
{
T DoSomething();
}
public class MethodOneStrategy : IMethodStrategy<string>
{
public string DoSomething()
{
return "This strategy returns a string";
}
}
public class MethodTwoStrategy : IMethodStrategy<int>
{
public int DoSomething()
{
return 100; // this strategy returns an int
}
}
// And you would use it like so...
static void Main(string[] args)
{
bool executable = true;
object result = null;
if (executable)
{
MethodOneStrategy methodA = new MethodOneStrategy();
result = methodA.DoSomething();
}
else
{
MethodTwoStrategy methodB = new MethodTwoStrategy();
result = methodB.DoSomething();
}
}
Option #2
Another option could be a simple proxy method to wrap the worker methods.
// proxy class to wrap actual method call with proxy call
public class MethodProxy
{
public object DoMethodWork(bool executable)
{
if (executable)
{
return MethodA();
}
else
{
return MethodB();
}
}
private int MethodA()
{
return 100; // returns int type
}
private string MethodB()
{
return "this method returns a string";
}
}
// used like so
static void Main(string[] args)
{
var methodProxy = new MethodProxy();
object result = methodProxy.DoMethodWork(true);
}
Use conditional compilation for this.
#if RELEASE
public string MethodB() ...
#endif
Although I have my doubts about whether you need this or not. Your rationale doesn't make much sense.
You can use different Build Configurations to manage your conditional compile symbols.
if(executable)
MethodA();
else
MethodB();
OR
if(executable)
MethodA();
MethodB();
not entirely sure what you are trying to do but this could be one way, probably not the most efficient way but could work depending on what you are trying to do?
public int MethodA(executable)
{
if(executable = true)
{
//do stuff
}
else
{
return -1;
}
}
public String MethodB(executable)
{
if(executable = false)
{
//do stuff
}
else
{
String error = "MethodB cannot be used right now";
return error;
}
}
I have a class which exposes some functionality,
and I want to ensure exceptions will be handled by a custom ErrorHandler class.
Currently I can achieve this by a try / catch statement per each method, and process the exception by the error handler there.
My question is if there is a better way / design pattern to do it.
Code:
public class BasicErrorHandler
{
public void ProcessException(Exception ex)
{
//Does error handling stuff
}
}
public class Manager
{
BasicErrorHandler _errorHandler;
public Manager()
{
_errorHandler = new BasicErrorHandler();
}
public void MethodA()
{
try
{
//Does Something
}
catch(Exception ex)
{
_errorHandler.ProcessException(ex);
}
}
public void MethodB()
{
try
{
//Does Something Else
}
catch(Exception ex)
{
_errorHandler.ProcessException(ex);
}
}
}
In keeping with DRY principles, you could just wrap your try...catch logic into into own method which takes a predicate of the actual work to do:
public class Manager
{
BasicErrorHandler _errorHandler;
public Manager()
{
_errorHandler = new BasicErrorHandler();
}
public void MethodA()
{
DoWork( () => {
// do something interesting here
});
}
public void MethodB()
{
DoWork( () => {
// do something else interesting here
});
}
private void DoWork(Action action)
{
try
{
action();
}
catch(Exception ex)
{
_errorHandler.ProcessException(ex);
}
}
}
I've crafted this quickly and without thinking too much in the implications, but if you want to avoid all the try/catch blocks, you could do something like:
public class BasicErrorHandler
{
public void ProcessException(Exception ex)
{
//Does error handling stuff
}
public void Do(Action act)
{
try
{
act();
}
catch(Exception ex)
{
ProcessException(ex);
}
}
}
And then use it like:
public class Manager
{
BasicErrorHandler _errorHandler;
public Manager()
{
_errorHandler = new BasicErrorHandler();
}
public void MethodA()
{
_errorHandler.Do(() => {
//Does Something
});
}
public void MethodB()
{
_errorHandler.Do(() => {
//Does Something Else
});
}
}
Design patterns are there to solve a problem. Which problem are you trying to solve? What is wrong with the Try Catch blocks?
Only thing I can imagine is you want to have more clean code. Some answers suggest a helper method with an action. Given the helper methods that encapsulate a delegate: Do consider the impact on your stack trace and debugging sessions using these delegates. It might make logging etc more hard to understand.
If your intend is to do separation of concern, I would say If you can't handle it, just don't catch the exception. Let the class invoking the method handle it. If you insist to have a handler in your class, I would suggest Inversion of Control. That way, your class is not in control of determining which class should handle its exceptions.
Rx .net is for You. Advanced error handling gives You the ability to highly customize Your error handling. Check out the pages about that.
For example:
var source = new Subject<int>();
var result = source.Catch<int, TimeoutException>(tx=>Observable.Return(-1));
result.Dump("Catch");
source.OnNext(1);
source.OnNext(2);
source.OnError(new ArgumentException("Fail!"));
You'll get the following output:
Catch-->1
Catch-->2
Catch failed-->Fail!
The number of retries, the handling of how much time a method can take, everything can be configured.
The following is an Aspect oriented method of soling the problem, this makes use of PostSharp to do the weaving.
[Serializable]
public class HandleExceptionsAttribute : OnExceptionAspect {
/// <summary>
/// Initializes a new instance of the <see cref="HandleExceptionsAttribute"/> class.
/// </summary>
public HandleExceptionsAttribute() {
AspectPriority = 1;
}
public override void OnException(MethodExecutionArgs args) {
//Suppress the current transaction to ensure exception is not rolled back
using (var s = new TransactionScope(TransactionScopeOption.Suppress)) {
//Log exception
using (var exceptionLogContext = new ExceptionLogContext()) {
exceptionLogContext.Set<ExceptionLogEntry>().Add(new ExceptionLogEntry(args.Exception));
exceptionLogContext.SaveChanges();
}
}
}
}
[HandleExceptions]
public class YourClass {
}
How can I write an extension method for an existing method like :
static class Extensions
{
public static void RunAsThread(this Action func)
{
Thread t = new Thread(delegate()
{
try
{
if (func != null)
func();
}
catch (ThreadInterruptedException tie) { }
catch (ThreadAbortException tae) { }
catch (Exception ex)
{
Logger.LogDebug(ex);
}
});
t.Start();
}
}
is there any way that i can run this methods perfectly in the way i wanted
class WorkingClass
{
public void Work()
{
//Works fine
((Action)DoSomething).RunAsThread();
//Works fine
Extensions.RunAsThread(DoSomething);
//But I really need this to work
DoSomething.RunAsThread();
}
private void DoSomething()
{
//Do Something
}
}
I really wanted to make DoSomething.RunAsThread() work.
I tried to change "static void RunAsThread(this delegate .... or this Delegate)".
Could not do it properly.
Is there any work around for that? Is there any way for that?
No, you can't do this, as DoSomething is not a type, it's a method.
Also, just because you can attach an extension method to a type it doesn't mean you should..!
If DoSomething doesn't have to be an actual method, a slight tweak would make this compile:
class WorkingClass
{
public void Work()
{
//Works fine
((Action)DoSomething).RunAsThread();
//Works fine
Extensions.RunAsThread(DoSomething);
//But I really need this to work
DoSomething.RunAsThread();
}
private Action DoSomething = () =>
{
//Do Something
};
}
Whether that fits in with everything else you're writing or not, I couldn't say.
DoSomething is just a "Method group" it will be implicitly converted to Action or compatible delegate type whenever possible.
DoSomething itself not a Delegate, so not possible. but you could do the following with the help of implicit method group conversion.
Action a = DoSomething;
a.RunAsThread();
I have class with many methods:
public class A {
public string method1() {
return "method1";
}
public string method2() {
return "method2";
}
public string method3() {
return "method3";
}
.
.
.
public string methodN() {
return "methodN";
}
}
I would like to add call to doSomething() in each method, for example:
public string methodi() {
doSomething();
return "methodi";
}
What is the best way to do so? Is there any suitable design pattern?
This is a typical use case for AOP (aspect oriented programming). You'd define the insertion points for the method calls and the AOP engine adds the correct code to the class file. This is often used when you want to add log statements without cluttering your source files.
For java you could add the aspectj library
For C# and .NET have look at this blog. Looks like a good starter.
Using AOP is already a good answer, it was my first idea too.
I tried to figure out a good way doing it without AOP though and came up with this idea (using the Decorator pattern):
interface I {
String method1();
String method2();
...
String methodN();
}
class IDoSomethingDecorator implements I {
private final I contents;
private final Runnable commonAction;
IDoSomethingDecorator(I decoratee, Runnable commonAction){
this.contents = decoratee;
this.commonAction = commonAction;
}
String methodi() {
this.commonAction().run();
return contents.methodi();
}
}
You could then decorate the construction of A (which implements I):
I a = new IDoSomethingDecorator(new A(),doSomething);
It is basically no rocket science and in fact results in more code than your first idea, but you are able to inject the common action and you separate the additional action from the class A itself. Further, you can turn it off easily or use it only in tests, for instance.
Why not having a single function?
public string methodi(int i) {
doSomething();
return "method" + i.toString();
}
Or you may write a function which takes an Func parameter and call this function instead of your functions.
public string Wrapper(Func<string> action)
{
doSomething();
return action();
}
and call your functions from this function;
string temp = Wrapper(method1);
You could use reflection.
public String callMethod(int i) {
doSomething();
java.lang.reflect.Method method;
try {
method = this.getClass().getMethod("method" + i);
} catch (NoSuchMethodException e) {
// ...
}
String retVal = null;
try {
retVal = method.invoke();
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) { }
return retVal;
}
The Conditional Attribute in .NET allows you to disable the invocation of methods at compile time. I am looking for basically the same exact thing, but at run time. I feel like something like this should exist in AOP frameworks, but I don't know the name so I am having trouble figuring out if it is supported.
So as an example I'd like to do something like this
[RuntimeConditional("Bob")]
public static void M() {
Console.WriteLine("Executed Class1.M");
}
//.....
//Determines if a method should execute.
public bool RuntimeConditional(string[] conditions) {
bool shouldExecute = conditions[0] == "Bob";
return shouldExecute;
}
So where ever in code there is a call to the M method, it would first call RuntimeConditional and pass in Bob to determine if M should be executed.
You can actually use PostSharp to do what you want.
Here's a simple example you can use:
[Serializable]
public class RuntimeConditional : OnMethodInvocationAspect
{
private string[] _conditions;
public RuntimeConditional(params string[] conditions)
{
_conditions = conditions;
}
public override void OnInvocation(MethodInvocationEventArgs eventArgs)
{
if (_conditions[0] == "Bob") // do whatever check you want here
{
eventArgs.Proceed();
}
}
}
Or, since you're just looking at "before" the method executes, you can use the OnMethodBoundaryAspect:
[Serializable]
public class RuntimeConditional : OnMethodBoundaryAspect
{
private string[] _conditions;
public RuntimeConditional(params string[] conditions)
{
_conditions = conditions;
}
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
if (_conditions[0] != "Bob")
{
eventArgs.FlowBehavior = FlowBehavior.Return; // return immediately without executing
}
}
}
If your methods have return values, you can deal with them too. eventArgs has a returnValue property that is settable.
I believe this would be a very simple way of doing what you described:
public static void M()
{
if (RuntimeConditional("Bob"))
{
Console.WriteLine("Executed Class1.M");
}
}
Thanks