1. Summary
  2. Files
  3. Support
  4. Report Spam
  5. Create account
  6. Log in

ChaplinIntro

Lesson 7: Concerns

In contrast to side effects a concern is a wrapping message receiver which is intended to affect the subsequent message processing. It is allowed to change both the input arguments and the replies to the message, ie. the return value. Furthermore, any exception thrown by the concern's logic interrupts the message processing. Concerns are mainly used as filters or constraints for input and output values. In this example I show how to develop a simple concern which assures that the length of the message, which is to be printed, does not exceed a given length. Therefore I named the concern's class PrinterProtector:

public class PrinterProtector implements MessagePrinter {

    private final int maxLength;

    public PrinterProtector(int maxLength) {
        this.maxLength = maxLength;
    }

    @ToContext(mode = InvocationMode.concern)
    public void printMessage(String message) {
        if (message.length() > maxLength) {
            message = message.substring(0, maxLength);
        }

        $next(message);
    }
}

In the body of the concern the input value is checked. Then the subsequent processing is triggered by calling $next operator. In this case we pass the validated argument to this operator. As I said earlier concerns are allowed to change input values. The fact that the message receiver is a concern is indicated by ToContext annotation having its mode attribute set to InvocationMode.concern.

Now we can assemble the composite. The PrinterProtector component is passed as the second argument in the '$' operator, right after the diagnosing side effect.

public class GreetingApp {

    public static void main(String[] args) {
        PrinterDiag diag = new PrinterDiag();
        GreetingService greetServ = $(diag,
                                      new PrinterProtector(10), 
                                      new DefaultMessagePrinter(),
                                      new DecoratorPrinter());
        greetServ.setTitle("Chaplin");
        greetServ.sayHello();
        greetServ.sayGoodBye();

        System.out.println("Time spent by printing:" + diag.getTotal() + " ns");
    }

}

In this example we limit the length of the printed message to 10 characters.


Lesson 6: Side effects Lesson 8: Constraints