lundi 4 septembre 2023

Java - Building a contract between a library and its client

I am working on creating a library in Java for recording arguments of a method before and after the execution, as below:

Library code:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RecordArgs {
}

@Aspect
public class RecordMethodArgsAspect {

    @Before("@annotation(RecordArgs)")
    public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable {
         //record method arguments i.e. Item object in below example
    }
}

Application code (client of library)

class Item {
    private String name;
    private String id;
    // mutable private fields

    public Item(String name, String id) {
        this.name=name;
        this.id=id;
    }

    // getter and setters

}

class ItemVisitor {
    @RecordArgs
    public void visit(Item item) {
        // export item object
    
        // business logic which mutates item

        // export item object
    }
}

Question: I want to provide a way to the application code i.e. class 'Item' in this case to specify what field values or what data should be recorded when 'logMethod' is invoked, the idea being that in future if the structure of 'Item' class changes then there shouldn't be a need to change the library. How can I achieve this?

Aucun commentaire:

Enregistrer un commentaire