These two classes are part of a networking layer module that I am building:
public abstract class BaseRequest {
protected RequestCreator mCreator;
public BaseRequest() {
setupRequestCreator();
}
private setupRequestCreator() {
mCreator = new RequestCreator.Builder()
.headers(getHeaders())
.parser(getParser())
.build();
}
public abstract Headers getHeaders();
public abstract Parser getParser();
}
public class UserRequest extends BaseRequest {
private Headers mHeaders;
private Request<User> mRequest;
private interface UserService {
@GET("/users/{id}")
User getUser(String id);
}
public UserRequest(Headers headers) {
mHeaders = headers;
mRequest = mCreator.createRequest(UserService.class);
}
@Override
public Headers getHeaders() {
return mHeaders;
}
@Override
public Parser getParser() {
return null;
}
}
The framework that I am using requires me to configure/build a RequestCreatorRequestCreator
for each type of Request that I am going to use.
To make the process of adding new classes for different requests as pain-free as possible, I moved the building logic of the RequestCreatorRequestCreator
in an abstract class so this. This way I'll only have to extend it and override some methods that indicate how the RequestCreatorRequestCreator
should be configured - sort of a Template Methodtemplate method pattern.
The actual problem is this: when someone creates an instance of UserRequestUserRequest
, super()super()
gets called right before UserRequestUserRequest
's member variables are set. What this means is that the RequestCreatorRequestCreator
will already be built by the time mHeadersmHeaders
are set. This is wrong because the buldingbuilding process needs a reference to mHeadersmHeaders
in order for it to behave as intended.
One way to get around this is to leave BaseRequestBaseRequest
's constructor empty and to call setupRequestCreator()setupRequestCreator()
in the UserRequestUserRequest
's constructor, but only after setting the instance variables first; thisfirst. This however feels "hacky" because other people will have to be aware of this when they are creating new subclasses.
I tried other workarounds too, but nothing felt quite right. I was hoping someone could provide me with a better solution.