jeudi 18 juin 2020

From sub class to super class and back again

So imagine this,

Given a class hierarchy:

S (abstract)
A extends S
B extends S

Let's say we have a chain of connected components handling objects of types of A and B. For example: K1.handle(A) -> K2.handle(A) -> K3.handle(A) meaning that K1 takes in A and calls K2 with A which calls K3 with A.

Similarly we have: K1.handle(B) -> K2.handle(B) -> K3.handle(B)

Thing is K2's logic does not depend on the sub type of S. So we could replace K2.handle(A) and K2.handle(B) with K2.handle(S). But the problem is that at some point we need to do type checking of the actual object type to call correct K3 method.

How does one solve this without doing if or switch etc. statements that inspect the type/properties of the actual objects?

Is it the visitor pattern I need to look into?

To give a concrete example of the case. Let's say K1 is a REST controller with different POST endpoints for A and B. It deserialises the payload and validates the data, then it passes the object to K2 for further processing. All the steps included in K2 (and other components it calls) are happy to work with objects of type S only. But in the very end at K3 we need to know the actual type of S.

Aucun commentaire:

Enregistrer un commentaire