Field Initialisation Vs Constructor Initialisation
[!note]
Field initialisation will happen before constructor intialisation.
Use field intialisation for things that's not likely to change.
Use constructor intialisation for things that is likely to change (in the case we have multiple constructor)
Example:
public class RateLimiterService {
private final RateLimitingAlgorithm rateLimitingAlgorithm;
private final Scheduler scheduler = createScheduler();
public RateLimiterService(BucketTokenConfig config) {
rateLimitingAlgorithm = new BucketToken(config, scheduler);
}
public RateLimiterService(LeakingBucketConfig config) {
rateLimitingAlgorithm = new LeakingBucket(config, scheduler);
}
private Scheduler createScheduler() {
Timer timer = new Timer();
ExecutorService executorService = Executors.newSingleThreadExecutor();
return new AlgorithmScheduler(executorService, timer);
}
public boolean apply(Request request) {
return rateLimitingAlgorithm.apply(request);
}
public int getCapacity() {
return rateLimitingAlgorithm.getCapacity();
}
}
In here, since Scheduler
is shared between several constructor, we use field initalisation.
Since RateLimitingAlgorithm
is dynamic between the constructor, we use constructor initalisation