vendredi 12 juillet 2019

Partial Object Instantiation Design Pattern

Currently I have an endpoint which returns a a fairly large data object. This call for all objects of that type can generate 20MBs of data. However not always the clients need all the information in the object, quite often a subset of data is all that is required. I want to give the client the option to pass in some parameters to determine what parts of the object they require. For example, specifying an array of restriction fields with each field itself a group of instance members on the object, a user can restict how much f the object they want. Looking at the figure Object below, restriction field value r1 may refer to instance members a and b.

MyObject(){
a;
b;
c;
d;
e;
f;
g;
h;
}

So with that in mind, I created an ENUM to model the restriction fields and the subset of instance members which each instance field represents. Now on the DB query I want to use the ENUM(s) values to decide which parts of the object I want.

So the select query will select the Object and the object can be partially instantiated by calling whatever get/set methods are required. I have implemented this on the query side by using the request params(i.e. groupings of instance members) and performing reflection on the object returned from the DB to get/set the instance fields on the object to return.

I am however, unsure if there is an already existing design pattern for this problem other than a refactor or create a new endpoints for the "lighter" objects. I dont want to argue that case, I just want to discuss for the problem at hand, is reflection a valid method of fulfilling the requirement and if not why not and what are the alternatives.

I believe this solution can cater for change easily, Only the enum needs updated if instance members change or a restriction grouping needs adapting. The rest layer or data layer requires no change. However I am unsure of the performance impact, i only implemented this today so I havent been able to benchmark yet.

Below is psuedo of how i implemented the select aspect below.

select(MyObj obj){
 //get all the restricted fields from the request
// Instantiate new object
// for each restriction field(i.e. instance member)
//         use reflection to invoke the set method passing the get method of the method argument
}

Aucun commentaire:

Enregistrer un commentaire