开发者

Action on each method's return value

What I'd like to do is take some action using the value returned by every method in a class.

So for instance, if I have a class Order which has a method

public Customer GetCustomer()
{
 Customer CustomerInstance = // get customer
 return CustomerInstance;
}

Let's say I want to log the creation of these - Log(CustomerInstance);

My options (AFAIK) are:

  1. Call Log() in each of these methods before returning the object. I'm not a fan of this because it gets unwieldy if used on a lot of classes with a lot of methods. It also is not an intrinsic part of the method's purpose.

  2. Use composition or inheritance to layer the log callon the Order class similar to:

    public Customer GetCustomer()

    {

    Customer CustomerInstance = this.originalCustomer.GetCustomer(); Log(CustomerInstance);

    return CustomerInstance;

    }

    I don't think this buys me anything over #1.

  3. Create extension methods on each of the returned types:

    Customer CustomerInstance = Order.GetCustomer().Log();

    which has just as many downsides.

I'm looking to do this for every (or almost every) object returned, automatically if possible, without having to write double the 开发者_JAVA技巧amount of code. I feel like I'm either trying to bend the language into doing something it's not supposed to, or failing to recognize some language feature that would enable this. Possible solutions would be greatly appreciated.


You need to look into Aspect Oriented Programming:

Typically, an aspect is scattered or tangled as code, making it harder to understand and maintain. It is scattered by virtue of the function (such as logging) being spread over a number of unrelated functions that might use its function, possibly in entirely unrelated systems, different source languages, etc. That means to change logging can require modifying all affected modules. Aspects become tangled not only with the mainline function of the systems in which they are expressed but also with each other. That means changing one concern entails understanding all the tangled concerns or having some means by which the effect of changes can be inferred.

Adding logging is one of the uses of this methodology.


You should check Microsofts Enterprise Library.

Think you may find usefull the Policy Injection Application Block.


Your option 1 is, in my opinion, the way to do it. Even if this will be at the end of each method, that's what is done. I would not add extra layers of obscurity because it's 'not an intrinsic purpose' of a method.

By the way, Aspect Oriented Programming addresses exactly this issue that you have (see ChrisF's answer), but then we're not talking C# anymore.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜