Skip to content

New concept: Optional #2913

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 19 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,13 @@
"generic-types"
],
"status": "beta"
},
{
"slug": "tim-from-marketing-2",
"name": "tim-from-marketing-2",
"uuid": "a6cfc286-8c62-4f5b-8e59-f6bfc4374092",
"concepts": [],
"prerequisites": []
}
],
"practice": [
Expand Down
25 changes: 25 additions & 0 deletions exercises/concept/tim-from-marketing-2/.classpath
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="bin/main" path=".meta/src/reference/java">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/starterSource" path="src/main/java">
<attributes>
<attribute name="gradle_scope" value="starterSource"/>
<attribute name="gradle_used_by_scope" value="starterSource"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/starterTest" path="src/test/java">
<attributes>
<attribute name="gradle_scope" value="starterTest"/>
<attribute name="gradle_used_by_scope" value="starterTest"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin"/>
</classpath>
11 changes: 11 additions & 0 deletions exercises/concept/tim-from-marketing-2/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Hints

## 1.- Print the name of all the employees

WIP


Check failure on line 7 in exercises/concept/tim-from-marketing-2/.docs/hints.md

View workflow job for this annotation

GitHub Actions / Lint Markdown files

Multiple consecutive blank lines

exercises/concept/tim-from-marketing-2/.docs/hints.md:7 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2] https://github.com/DavidAnson/markdownlint/blob/v0.37.4/doc/md012.md
## 2.- Print the name and department of a given employee

WIP

31 changes: 31 additions & 0 deletions exercises/concept/tim-from-marketing-2/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Instructions

In this exercise you will be writing code to print all the names of the factory employees.

Employees have an ID, a name and a department name, like in the [tim-from-marketing](/exercises/concept/tim-from-marketing) exercise.

Check failure on line 5 in exercises/concept/tim-from-marketing-2/.docs/instructions.md

View workflow job for this annotation

GitHub Actions / Lint Markdown files

Trailing spaces

exercises/concept/tim-from-marketing-2/.docs/instructions.md:5:134 MD009/no-trailing-spaces Trailing spaces [Expected: 0 or 2; Actual: 1] https://github.com/DavidAnson/markdownlint/blob/v0.37.4/doc/md009.md
Assume that the ID of the first employee is 0, the ID of the second employee is 1, and so on. The three fields of an employee may be empty, that's why they are declared as Optional<T> types.
The class constructor receives a parameter of type List<Optional<Employee>>, which is populated in the tests.

## 1.- Print the names of all the employees

Implement the `printAllEmployeesNames()` method to print the names of all the employees, together with their id. If the employee does not exist, print "[id] - No employee found".

```java
"
1 - Tim
2 - Bill
3 - Steve
4 - No employee found
5 - Charlotte
"
```

## 2.- Print the name and department of a given employee

Implement the `printEmployeeNameAndDepartmentById(id)` method to print the name and department of a given employee, together with their id. If the employee does not exist, print "[id] - No employee found". You will have to call the method `getEmployeeById(int employeeId)`, which returns an Optional<Employee> and it's already defined.

```java
printEmployeeNameAndDepartmentById(1) => "1 - Tim - Marketing"
printEmployeeNameAndDepartmentById(3) => "3 - Steve - Engineering"
printEmployeeNameAndDepartmentById(4) => "4 - This employee does not exist"
```
92 changes: 92 additions & 0 deletions exercises/concept/tim-from-marketing-2/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Introduction

## Optional

## Introduction

The **Optional<T>** type was introduced in Java 8 as a way to indicate that a method will return an object of type T or an empty value. It is present in type signatures of many core Java methods.

Check failure on line 7 in exercises/concept/tim-from-marketing-2/.docs/introduction.md

View workflow job for this annotation

GitHub Actions / Lint Markdown files

Trailing spaces

exercises/concept/tim-from-marketing-2/.docs/introduction.md:7:196 MD009/no-trailing-spaces Trailing spaces [Expected: 0 or 2; Actual: 1] https://github.com/DavidAnson/markdownlint/blob/v0.37.4/doc/md009.md

Before Java 8, developers had to implement null checks:

```java
public Employee getEmployee(String name) {
// Assume that getEmployeeByName retrieves an Employee from a database
Employee employee = getEmployeeByName(name);
if (employee != null) {
return employee;
} else {
return throw new IllegalArgumentException("Employee not found");
}
}
```

With the Optional API, the code above can be simplified to:

```java
public Optional<Employee> getEmployee(String name) {
// Assume that getEmployeeByName returns an Optional<Employee>
return getEmployeeByName(name)
.orElseThrow(() -> new IllegalArgumentException("Employee not found"));
}
```

If a default value must be returned, the `orElse` method can be used.

```java
public Optional<Employee> getEmployee(String name) {
// Assume that getEmployeeByName returns an Optional<Employee>
return getEmployeeByName(name)
.orElse(new Employee("Daniel"));
}
```

Other commonly used method is `ifPresentOrElse`, which is used to handle the case where the value is present and the case where the value is empty.

```java
public Optional<Employee> getEmployee(String name) {
// Assume that getEmployeeByName returns an Optional<Employee>
return getEmployeeByName(name)
.ifPresentOrElse(
employee -> System.out.println(employee.getName()),
() -> System.out.println("Employee not found")
);
}
```

Provided all the invoked methods return Optional objects, many methods can be chained without having to worry about null checking:

```java
public Optional<Integer> getEmployeeAge(String name) {
Optional<Employee> optionalEmployee = getEmployeeByName(name);
return getEmployeeByName(name)
.map(employee -> employee.getAge())
.orElse("No employee found");
}
```

It is important to understand that the Optional API does not eliminate the null checking, but it defers it until the end of a series of methods, as long as all those methods return an optional object.

Check failure on line 67 in exercises/concept/tim-from-marketing-2/.docs/introduction.md

View workflow job for this annotation

GitHub Actions / Lint Markdown files

Trailing spaces

exercises/concept/tim-from-marketing-2/.docs/introduction.md:67:201 MD009/no-trailing-spaces Trailing spaces [Expected: 0 or 2; Actual: 1] https://github.com/DavidAnson/markdownlint/blob/v0.37.4/doc/md009.md

The fields of the Employee class have an Optional type. Notice that this is not recommended, as explained by one well-known Java language architect in [this SO answer](https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type)

## Flatmap operation

The **flatMap** method flattens a List of Optional objects into a List of those objects. In other words, extracts the value of each list element, discarding empty Optionals. For example:

```java
List<Optional<String>> listOfOptionals = Arrays.asList(
Optional.of("Java"),
Optional.empty(),
Optional.of("Kotlin")
);
```

```java
// Using flatMap to extract present values
List<String> result = listOfOptionals.stream()
.flatMap(language -> language.stream())
.collect(Collectors.toList());

System.out.println(result); // Output: [Java, Kotlin]
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Introduction

%{concept:optional-types}

%{concept:flatMap-operation}
18 changes: 18 additions & 0 deletions exercises/concept/tim-from-marketing-2/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"authors": [
"josealonso"
],
"files": {
"solution": [
"src/main/java/EmployeeService.java"
],
"test": [
"src/test/java/EmployeeServiceTest.java"
],
"exemplar": [
".meta/src/reference/java/EmployeeService.java"
],
},
"icon": "nullability",
"blurb": "Learn to use the Optional class by helping Tim print details of his company employees."
}
47 changes: 47 additions & 0 deletions exercises/concept/tim-from-marketing-2/.meta/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Design

## Goal

The goal of this exercise is to teach the student how to use the Optional API.
We will use the most common methods: `ifPresent`, `orElse`, `ifPresentOrElse`, `orElseThrow`.

Check failure on line 6 in exercises/concept/tim-from-marketing-2/.meta/design.md

View workflow job for this annotation

GitHub Actions / Lint Markdown files

Trailing spaces

exercises/concept/tim-from-marketing-2/.meta/design.md:6:94 MD009/no-trailing-spaces Trailing spaces [Expected: 0 or 2; Actual: 1] https://github.com/DavidAnson/markdownlint/blob/v0.37.4/doc/md009.md
The `isPresent` and `get` methods are not presented, since they do not provide any value over an ordinary null check.

Some methods of the Stream API are needed. This is a bit problematic, since they have not been explained in the current Java track.

## Learning objectives

- Know what optional types are.
- Know how to use Optional<T> fields.
- Know how to use methods that return an Optional<T> type.
- See the utility of some Stream methods, `flatMap` specifically.

## Out of scope

- Streams API.

## Concepts

This Concepts Exercise's Concepts are:

- `Optional<T>` class and some methods that mimic a null check.

## Prerequisites

This Concept Exercise's prerequisites Concepts are:

- `custom classes`.
- `generic-types`.
- `streams`.

## Analyzer

This exercise could benefit from the following rules in the [analyzer]:

- `actionable`: If the solution uses `null` in any method, encourage the student to use `Optional<T>` instead.
- `actionable`: If the solution uses the `get` or `isPresent` methods of the Optional<T> API, encourage the student to use `orElse`, `orElseThrow` or `ifPresentOrElse` instead.

Check failure on line 41 in exercises/concept/tim-from-marketing-2/.meta/design.md

View workflow job for this annotation

GitHub Actions / Lint Markdown files

Trailing spaces

exercises/concept/tim-from-marketing-2/.meta/design.md:41:177 MD009/no-trailing-spaces Trailing spaces [Expected: 0 or 2; Actual: 1] https://github.com/DavidAnson/markdownlint/blob/v0.37.4/doc/md009.md
- `informative`: TODO.

If the solution does not receive any of the above feedback, it must be exemplar.
Leave a `celebratory` comment to celebrate the success!

[analyzer]: https://github.com/exercism/java-analyzer
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import java.util.Objects;
import java.util.Optional;

class Employee {
private final int id;
private final String name;
private final String department;

public Employee(int id, String name, String department) {
this.id = id;
this.name = name;
this.department = department;
}

public Optional<Integer> getNullableId() {
return Optional.ofNullable(id);
}

public Optional<String> getNullableName() {
return Optional.ofNullable(name);
}

public Optional<String> getNullableDepartment() {
return Optional.ofNullable(department);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id &&
Objects.equals(name, employee.name) && Objects.equals(department, employee.department);
}

@Override
public int hashCode() {
return Objects.hash(id, name, department);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import java.util.List;
import java.util.ArrayList;
import java.util.Optional;

class EmployeeService {

// This list is populated in the tests
private List<Optional<Employee>> nullableEmployeesList = new ArrayList<>();

public EmployeeService(List<Optional<Employee>> listOfEmployees) {
nullableEmployeesList = listOfEmployees;
}

public Optional<Employee> getEmployeeById(int employeeId) {
return nullableEmployeesList
.stream()
.flatMap(employee -> employee.stream())
.filter(employee -> employee.getNullableId()
.map(id -> id == employeeId)
.orElse(false))
.findFirst();
}

/* I could use IntStream.range(0, nullableEmployeesList.size()) instead of a for loop, but
understanding the Optional API is difficult enough.
I do not use method references for the same reason. */
public String printAllEmployeesNames() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < nullableEmployeesList.size(); i++) {
stringBuilder.append(i).append(" - ");

nullableEmployeesList.get(i)
.flatMap(employee -> employee.getNullableName())
.ifPresentOrElse(
name -> stringBuilder.append(name).append("\n"),
() -> stringBuilder.append("No employee found\n")
);
}
return stringBuilder.toString();
}

public String printEmployeeNameAndDepartmentById(int employeeId) {
Optional<Employee> employee = getEmployeeById(employeeId);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(employeeId).append(" - ");
// Handle Optional values
employee.ifPresentOrElse(
e -> {
e.getNullableName().ifPresent(name ->
e.getNullableDepartment().ifPresent(department ->
stringBuilder.append(name).append(" - ").append(department)
)
);
},
() -> stringBuilder.append("No employee found")
);
return stringBuilder.toString();
}

}
34 changes: 34 additions & 0 deletions exercises/concept/tim-from-marketing-2/.project
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>tim-from-marketing-2</name>
<comment>Project tim-from-marketing-2 created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
<filteredResources>
<filter>
<id>1739322795991</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
connection.project.dir=../tim-from-marketing
eclipse.preferences.version=1
Loading
Loading