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 RequestCreator
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 RequestCreator
in an abstract class. This way I'll only have to extend it and override some methods that indicate how the RequestCreator
should be configured - sort of a template method pattern.
The actual problem is this: when someone creates an instance of UserRequest
, super()
gets called right before UserRequest
's member variables are set. What this means is that the RequestCreator
will already be built by the time mHeaders
are set. This is wrong because the building process needs a reference to mHeaders
in order for it to behave as intended.
One way to get around this is to leave BaseRequest
's constructor empty and to call setupRequestCreator()
in the UserRequest
's constructor, but only after setting the instance variables first. 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.