Issue
I have a method name getProjectswithPriority
that has two input parameters: key
and priority
and it has a API call in it to get data from the database:
public Projects getProjectswithPriority(String Key, String priority) {
// Here is an API to get records from db
}
In another method, I want to get Projects with the same key but 3 values of priority, the way I implemented this is calling the function (obviously and its API) 3 times:
public Projects MY_FUNCTION (KEY){
///...
Projects HighProjects = getProjectswithPriority(KEY, "High");
Projects CriticalProjects = getProjectswithPriority(KEY, "Critical");
Projects HighestProjects = getProjectswithPriority(KEY, "Highest");
/// ....
}
I believe there is a more convenient way to implement this method, in order to decrease the number of API calls, such as using a for and getting all the projects and loop over them. But I don't know about the possible solutions to optimize this code. Could anyone help with this?
Solution
I would suggest the following changes:
- Callers have hard-coded references to specific values from what appears to be a stable set of enumerable priorities. This makes them a good candidate for an
enum
type. - Alter (or overload) the
getProjectsWithPriority()
API to accept a set of priorities. - Alternatively, use varargs to send a set of priorities.
enum Priority { LUDICROUS, NEGLIBLE, TRIVIAL, LOW, MEDIUM, HIGH, CRITICAL, HIGHEST }
public Projects getProjectsWithPriority(String key, Set<Priority> priorities) {
/* Get projects from database... */
}
Set<Priority> important = EnumSet.of(Priority.HIGH, Priority.CRITICAL, Priority.HIGHEST);
Projects projects = getProjectsWithPriority(key, important);
Answered By - erickson
Answer Checked By - Pedro (JavaFixing Volunteer)