Search code examples
javaoopdomain-driven-design

Access non-static outer context from within inner record


DISCLAIMER it's been a while since I've asked a question here, so be gentle with me please :)

I'm trying to produce a state from my business object, which should ideally stay encapsulated. My idea was to define a class with an internal representation and to have a way to return a state object, which would be later mapped onto different view representations. So I imagined something like:

State state = order.State();

where Order and State are defined like:

public class Order {
    private String identifier;

    record State(String number) {
        public State() {
            this(identifier);
        }
    }
}

So my question is how do I define relationship between my inner record and my outer class, so that I can access instance properties (ideally using the with the default record constructor) and map them onto immutable structure without running into static, non-static context issues?

(I left out the possibility to create an additional method like: toState(), on the outer class)


Solution

  • Move the method from the record up to the class.

    public class Order {
        private String identifier;
    
        public State state() {
            return new State(identifier);
        }
    
        record State(String number){}
    }