Reputation: 997
So I have an existing piece of code that looks like this:
Metrics metrics = null;
try {
metrics = metricsService.getCurrentMetrics();
} catch (SQLException e) {
e.printStackTrace();
}
//Do some stuff with the metrics
I have recently implemented a seperate mechanism as a way to track API metrics under a separate class, cleverly called APIMetrics.
So, with this change, the code would look something like this:
Metrics metrics = null;
APIMetrics apiMetrics = null;
try {
if(user.isAPI())
apiMetrics = metricsService.getCurrentAPIMetrics();
else
metrics = metricsService.getCurrentMetrics();
} catch (SQLException e) {
e.printStackTrace();
}
//Do some stuff with the metrics
The issue is that the code below, the "do some stuff with the metrics" is all written in terms of using the metrics object. Is there a way I can possibly set this up so that the "metrics" object refers not to just the object of type Metrics, but whatever object is the one we want to use?
So, for example, if we have a non-API user, we would want metrics to be of type Metrics and the result of metricsService.getCurrentMetrics(). However, if we have an API user, we would want metrics to be of type APIMetrics and the result of metricsService.getCurrentAPIMetrics().
Is there any good way to go about this? The Metrics and APIMetrics class share all methods. I know there may be a way to do this using inheritance or polymorphism, but I couldn't figure out exactly what to do. Thanks!
Upvotes: 0
Views: 779
Reputation: 68
Yes, as per the above answer you can make both classes implement an interface which declares all the methods.
public interface MetricsInt(){
// declare common methods
}
And in your code you can introduce a factory method that will take the user as an input and return the expected type of Metrics instance. Since the variable is of the type MetricInt, both type of objects can be set to it.
MetricsInt metrics = null;
try {
metrics = metricsService.getCurrentMetricsForUser(user);
} catch (SQLException e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 85779
Make both classes Metrics
and APIMetrics
implement the same interface. Then, declare a single variable whose type will be this interface, initialize it accordingly and use it through the code.
Upvotes: 5