Logic around a method

Some code belongs around many methods rather than inside them: timing, logging, permission checks, transactions, caching. This page times a method in plain Dart and in Spring for Dart, then widens the same idea to many classes.

Timing one method

Plain Dart, a decorator. A second class implements the same interface, does the extra work and calls the real one. Every method of the interface must be written out, also those that are not timed.

abstract interface class Purchases {
  Future<Purchase> place(Basket basket);
  Future<List<Purchase>> history(String email);
}

class TimedPurchases implements Purchases {
  TimedPurchases(this._inner);
  final Purchases _inner;

  @override
  Future<Purchase> place(Basket basket) async {
    final watch = Stopwatch()..start();
    try {
      return await _inner.place(basket);
    } finally {
      log.info('place: ${watch.elapsedMilliseconds} ms');
    }
  }

  @override
  Future<List<Purchase>> history(String email) => _inner.history(email);
}

final purchases = TimedPurchases(PurchaseService(repository));

Spring for Dart, an aspect. An annotation marks the method; one aspect says what runs around every marked method.

class Timed {
  const Timed();
}

@Aspect()
@Component()
class TimingAspect {
  @Around('@annotation(Timed)')
  Future<Object?> time(ProceedingJoinPoint call) async {
    final watch = Stopwatch()..start();
    try {
      return await (call.proceed()! as Future<Object?>);
    } finally {
      log.info('${call.signature.name}: ${watch.elapsedMilliseconds} ms');
    }
  }
}

@Service()
class PurchaseService implements Purchases {
  @Timed()
  @override
  Future<Purchase> place(Basket basket) async { /* ... */ }

  @override
  Future<List<Purchase>> history(String email) async { /* ... */ }
}

What changes: PurchaseService keeps one line of extra code, @Timed(). The generator writes the proxy that the decorator was, and the container injects it wherever Purchases or PurchaseService is asked for. For a single class, the hand-written decorator is about as long, and it is plain code anyone can step through.

Timing many classes

Plain Dart, a wrapper function. A higher-order function avoids a decorator class per service, but every call site has to use it.

Future<T> timed<T>(String name, Future<T> Function() body) async {
  final watch = Stopwatch()..start();
  try {
    return await body();
  } finally {
    log.info('$name: ${watch.elapsedMilliseconds} ms');
  }
}

Future<Purchase> place(Basket basket) => timed('place', () async {
  // ... the real work
});

Future<Stock> reserve(String sku) => timed('reserve', () async {
  // ... the real work
});

Spring for Dart, a pointcut. The aspect selects the methods itself, by class, name, annotation or bean name. The classes are not edited at all.

@Aspect()
@Component()
class TimingAspect {
  // Every Future method of every @Service class.
  @Around('@within(Service) && execution(Future *(..))')
  Future<Object?> time(ProceedingJoinPoint call) async {
    final watch = Stopwatch()..start();
    try {
      return await (call.proceed()! as Future<Object?>);
    } finally {
      log.info('${call.toShortString()}: ${watch.elapsedMilliseconds} ms');
    }
  }
}

Other pointcuts: execution(* PurchaseService.*(..)) (every method of one class), within(*Repository) (classes by name), bean(purchase*) (beans by name). Several can be combined with &&, || and !, and a malformed expression stops the build or the start with a message.

What changes: the wrapper function needs an edit at each method, and a forgotten one goes unnoticed. The pointcut covers new services as they are added. The cost is that the rule is in another file: reading PurchaseService alone does not tell you it is timed.

Built-in aspects

The starters use the same mechanism for their own annotations, so these work without writing an aspect:

Annotation Package Around the method
@Transactional() spring_boot_starter_data Commits when the Future completes, rolls back when it fails
@Cacheable, @CachePut, @CacheEvict spring_boot_starter_cache Returns a cached result, or stores or evicts one
@PreAuthorize, @PostAuthorize, @Secured spring_security_core Checks the caller's authorities before or after the call
@Validated() on the class spring_core_dart Checks the arguments' and the result's constraints
@Service()
class PurchaseService {
  @Transactional()
  @PreAuthorize("hasRole('CUSTOMER')")
  Future<Purchase> place(Basket basket) async { /* ... */ }

  @Cacheable('purchases', key: '#email')
  Future<List<Purchase>> history(String email) async { /* ... */ }
}

In plain Dart, each of these is a decorator or a wrapper you write and keep in step with the class.

What the proxies cost

Spring for Dart has no runtime reflection to lean on, so the generator writes a proxy class for each advised bean at build time. That has consequences:

In short

Decorator class Wrapper function Spring aspect
Code per advised method a full method in the decorator a call to the wrapper none, or one annotation
Methods not advised must be forwarded by hand nothing nothing
New classes a new decorator each an edit per method covered by the pointcut
Where the rule lives next to the class at each method in the aspect
Debugging plain calls plain calls through a generated proxy
Self-calls skip the decorator wrapped skip the advice
Build step none none build_runner

A decorator or a wrapper is the right choice for one or two classes, or for logic that only makes sense for one interface. An aspect pays off when the same concern spreads over many classes, or when you want the built-in transaction, cache and security annotations.

See also