Home > Software design >  Optional variable take action based on its value
Optional variable take action based on its value

Time:03-16

I have a method which takes an Optional parameter and returns a list. I'll populate the list based on whether the Optional parameter is empty or not. What's the most accepted/standard way if any to write the following

public List<ProjectDTO> getProjects(Optional<String> analystId) {
    List<ProjectDTO> projects = new ArrayList<>();

    analystId.ifPresentOrElse(
            t -> projects.addAll(getProjectsByAnalyst(analystId)),
            () -> projects.addAll(getAllProjects())
    );

    return projects;
}

This code works, however I was wondering if there's a better way to do it

CodePudding user response:

Personally i would not pass an optional as parameter in this case.

In this case i would code it like

var projects = Optional.of("the-analyst-id)
.map(id -> getProjectsByAnalist(id))
.orElseGet(()-> getAllProjects());

you can optionally wrap that in a function (like you did before)

ifPresentOrElse does not return a value and is mainly an operator meant for running side effects. the .map.orElseGet() ideom is the similar but returns the value.

CodePudding user response:

You shouldn't use an Optional as a method parameter. The best solution would be to perform a simple null check and solve it like this.

public List<ProjectDTO> getProjects(String analystId) {
    final List<ProjectDTO> projects = new ArrayList<>();

    if (analystId == null) 
        projects.addAll(getAllProjects());
    else
        projects.addAll(getProjectsByAnalyst(analystId));
    return projects;
}
  • Related