add method call to each method in a class - c#

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;
}

Related

Is it possible to have method only accessible after certain conditions are met?

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;
}
}

Java Equivalent code in C#

I am trying to write some equivalent C# code to the following Java one:
public class XLexer extends antlr.CharScanner implements TokenStream {
protected int stringCtorState = 0;
public String mString() { return ""; }
public Token nextToken() {
resetText(); // exists in CharScanner class
return null; // will return something
}
public TokenStream plumb() {
return new TokenStream() {
public Token nextToken() {
resetText(); // exists in CharScanner class
if (stringCtorState >= 0) { String x = mString(); }
return null; // will return something
}
};
}
}
Can anyone give me an hint how to do it in C# because I am getting errors when defining the method nextToken inside the return statement.
thanks!
There are no anonymous classes in C# (in the sense you need). If you want to return an instance of a custom implementation of TokenStream, you need to define it and give it a name.
Eg.:
public MyTokenStream {
public Token nextToken() {
// ...
}
}
public TokenStream plumb() {
return new MyTokenStream();
}
See:
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
http://www.25hoursaday.com/CsharpVsJava.html (anonymous inner classes are listed in the "Wish You Were Here" section; "this section describes language features and concepts that exist in Java and have no C# counterpart").
for reference.
As kan remarked, in C# (and Java 8, too) you would typically use a delegate or a lambda instead.
If all that TokenStream does is returning a nextToken, it could be implemented like so:
public class TokenStream
{
}
public class SomeClass
{
public Func<TokenStream> Plumb()
{
// I'm returning a function that returns a new TokenStream for whoever calls it
return () => new TokenStream();
}
}
static void Main(string[] args)
{
var someClass = new SomeClass();
TokenStream stream = someClass.Plumb()(); // note double brackets
}
Think first-class functions in JavaScript, if it helps to grok it.
New Java brings functional interfaces, which is similar: http://java.dzone.com/articles/introduction-functional-1
Use delegates instead. An example here: http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
Not sure if this is your desired result.
but the way I see it is you just want to return a TokenStream object which has the method of nextToken which returns an object Token
public class TokenStream
{
public Token nextToken()
{
return new Token();
}
}
that would be your TokenStream class and then you could have a method/function else where which does the following
public TokenStream plumb()
{
return new TokenStream();
}
the usage of which would be
TokenStream ts = plumb();
Token t = ts.nextToken();

return type in C#

I have two classes named ROAD and PATH
public class ROAD
{
public string getData()
{
return "Marlton Road";
}
}
public class PATH
{
public string getData()
{
return "Tagore Path";
}
}
Also i have a function named FETCH() in my Static Void Main
FETCH() contains following code
public returnType FETCH(bool flag)
{
if(flag)
{
ROAD obj=new ROAD();
return obj;
}
else
{
PATH obj=new PATH();
return obj;
}
}
Now my question is what should be the return type of function FETCH().
Or is there any other way to implement this logic.
It would have to be object in this case, as PATH and ROAD have no common base type. (They also don't follow .NET naming conventions - something which should be fixed, along with your getData method, and your FETCH method. Even in sample code, it's worth trying to make your names follow the normal conventions).
Consider making the two classes implement an interface or give them a common base class. That common type could then be the return type of the method. It looks like you could probably have an interface with your getData method in, for example. Hopefully in your real classes it could have a more meaningful name - something to do with both paths and roads.
I suggest you create an interface that both PATH and ROAD implement (e.g. IGetData) then have both classes implement it, and have FETCH return an IGetData.
Object, and then you cast to ROAD or PATH. Or, if they share a common base class, return that. See also.
But you probably don't want to do this. ROAD and PATH should each have their own static factory method:
class ROAD {
static ROAD newRoad() { return new ROAD(); }
}
class PATH {
static PATH newPath() { return new PATH(); }
}
Or some other, better pattern, depending on why you're doing it this way.
using interface would be the best way:
public interface IData
{
string getData();
}
public class ROAD : IData
{
public string getData()
{
return "Marlton Road";
}
}
public class PATH : IData
{
public string getData()
{
return "Tagore Path";
}
}
public IData FETCH(bool flag)
{
if (flag)
{
ROAD obj = new ROAD();
return obj;
}
else
{
PATH obj = new PATH();
return obj;
}
}
How about this:
interface IWithData
{
string GetData();
}
class Path: IWithData
{
public string GetData()
{
return "Tagore Path";
}
}
class Road: IWithData
{
public string GetData()
{
return "Marlton Road";
}
}
class SomeOtherClass
{
// ...
public IWithData FETCH(bool flag)
{
if(flag)
{
Road obj=new Road();
return obj;
}
else
{
Path obj=new Path();
return obj;
}
}
// ...
}
It's object. If you want it to be something else, you just have to have those classes share a common base or implement a common interface. For example:
public class Road : IPavedSurface
{
// members
}
public class Path : IPavedSurface
{
// members
}
// then
public IPavedSurface Fetch(bool flag)
{

Using method attributes to eliminate redundant code

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

Can I conditionally control method calls at runtime with attributes?

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

Categories

Resources