Skip to main content

Use Clock to get present time

Medium
Javadate

Static methods now() of java.time should not be used with no parameter.

Using the Clock parameter makes the date testable.

Examples

Example 1:

Negative

Incorrect implementation that violates the practice.

package dev.best.practices;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

public class Zoo {
private final List<Animal> animals = new ArrayList<>();

public List<Animal> getAnimals() {
return animals;
}

public void registerAnimalBirth(String name, Species species) {
final Instant birthday = Instant.now();
final Animal baby = new Animal(name, species, birthday);
this.animals.add(baby);
}
}