Search code examples
javaclassooppropertiespojo

How to add properties to a property?


I have a Pojo with various properties, such as

class Book {
  public String title;
}

(Getters and setters left out for brevity.)

Now I want to have properties for such properties, e.g. "this title value was read from config.yaml line 3 column 5". (That's the use case I have, but I guess there are more.)

I could add a title_src property no problem.
Doing that for dozens of properties is a lot of boilerplate though.

There's also coupling. In the above example, error messages need to know about the meta-property, actual processing does not.

A Map from property to meta-property? That would decouple, but I see no good way to construct a key without going through reflection, and the key would have to be an object/propertyname combination.

A StringWithSource type? That's going to make every usage of the property know about the type, so we have very strong coupling, though reflectionless.

I need a way to describe more information about my properties.


Solution

  • Now I want to have properties for such properties, e.g. "this title value was read from config.yaml line 3 column 5"

    It seems like that your properties should be decomposed into something more than just a simple value (String, int, or other), since you've talked about the need for a title source, a title line, a title column, and probably even more, for the title property alone.

    A solution could be to refactor your title property into a more complex class, for example TitleInfo, exhibiting the following properties: value, src, line, column, etc.

    class TitleInfo {
        private String value;
        private String src;
        private int line;
        private int column;
    
        ...
    }
    
    class Book {
        private TitleInfo title;
    }
    

    However, if we push this idea even further, we could generalize it and extend it to the other dozen of fields of your Book class. As a matter of fact, you could create a generic class PropertyInfo<T> that could represent a generic property of value T accompanied by all its details (src, line, column, etc.).

    class PropertyInfo<T> {
        private T value;
        private String src;
        private int line;
        private int column;
    
        ...
    }
    
    class Book {
        private PropertyInfo<String> title;
        private PropertyInfo<String> author;
        private PropertyInfo<BigDecimal> price;
    
        ...
    }