0

There is an interface

public interface ISomeInterface
{
     Task<int> SomeMethodAsync();
     Task<int> OtherMethodAsync();
}

and a class that implements it

public class SomeClass : ISomeInterface
{
    public async Task<int> SomeMethodAsync() {... return x; }
    public async Task<int> OtherMethodAsync() {... return y; }
}

I want to decorate the class to add some feature (e.g. logging) to some of the methods of it

public class LogDecoratedSomeClass : ISomeInterface
{
     private readonly ISomeInterface _decoratee;
     private readonly ILogger _logger;

     public LogDecoratedSomeClass(ISomeInterface decoratee, ILogger logger)
     {
         if (decoratee == null) throw new ArgumentNullException("decoratee");
         if (logger == null) throw throw new ArgumentNullException("logger");
         _decoratee = dedcoratee;
         _logger = logger;
     }

     public async Task<int> SomeMethodAsync()
     {
          _logger.log( <some message> );
          var result = await _decoratee.SomeMethodAsync();
          _logger.log( <even more messages> );
          return result;
     }

     public async Task<int> OtherMethodAsync()
     {
          return await _decoratee.OtherMethodAsync();
     }
}

the last method may be written as

public Task<int> OtherMethodAsync()
{
    return _decoratee.OtherMethodAsync();
}

which one of these two ways is better than another?

thanks

UPDATE:

what about webapi method?

public class SomeController : ApiController
{
     private readonly ISomeInterface _service;

     <constructor ...>

     [HttpGet]
     public async Task<int> Get()
     {
          return await _service.SomeMethodAsync();
     }
}
Ali
  • 1,982
  • 1
  • 15
  • 16
  • 1
    in the first (`async/await`) version you do nothing but adding overhead (the state machine for that method). I don't see a need for that, so your second version is clearly preferable. – René Vogt Jun 02 '16 at 10:06
  • `return await`, if that's the only `await` in a method, is generally seen as an anti-pattern. – Damien_The_Unbeliever Jun 02 '16 at 10:12
  • @Damien_The_Unbeliever, thanks for your reply. What about webapi method? – Ali Jun 02 '16 at 10:32
  • If you need to do more stuff after calling the asynchronous code, other than returning whatever it returned, then you must use `await`. If you're only going to either return what it returned, or exit the method (ie. end of method), then you should drop async/await and just return the task. – Lasse V. Karlsen Jun 02 '16 at 10:42

0 Answers0