-
-
Notifications
You must be signed in to change notification settings - Fork 716
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
base: main
Are you sure you want to change the base?
New concept: Optional #2913
Changes from 5 commits
e88392b
fbe3f46
0abf443
5c143e1
26a1397
f94749a
4c5e540
4b7a800
9d4cd39
6db542e
53cbbda
145d49b
9b20d73
c227af5
8f2afa8
27b6662
f047509
ec171ee
41076df
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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> |
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
|
||
## 2.- Print the name and department of a given employee | ||
|
||
WIP | ||
|
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
|
||
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" | ||
``` |
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
|
||
josealonso marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Before Java 8, developers had to implement null checks: | ||
josealonso marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
```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"); | ||
} | ||
} | ||
``` | ||
|
||
josealonso marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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
|
||
|
||
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} |
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." | ||
} |
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
|
||
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. | ||
josealonso marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
## 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. | ||
josealonso marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- `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
|
||
- `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; | ||
|
||
josealonso marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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); | ||
} | ||
} |
josealonso marked this conversation as resolved.
Show resolved
Hide resolved
|
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(); | ||
} | ||
|
||
} |
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 |
Uh oh!
There was an error while loading. Please reload this page.