Skip to content

Instantly share code, notes, and snippets.

@AniketSK
Last active July 5, 2018 08:03
Show Gist options
  • Save AniketSK/fe97e889efbde7fbdc01b912c10753a7 to your computer and use it in GitHub Desktop.
Save AniketSK/fe97e889efbde7fbdc01b912c10753a7 to your computer and use it in GitHub Desktop.
A demonstration of setting and accessing time in a unit-safe way.
import java.util.concurrent.TimeUnit;
public class ExerciseJava {
private long duration;
public void setDuration(long duration, TimeUnit unit) {
this.duration = TimeUnit.MILLISECONDS.convert(duration, unit);
}
public long getDuration(TimeUnit unit) {
return unit.convert(duration, TimeUnit.MILLISECONDS);
}
}
@AniketSK
Copy link
Author

AniketSK commented Jul 5, 2018

Alternatively, if it makes sense. You could declare the unit and it's bindings more explicitly, but this I feel is a tradeoff for clarity.

public class ExerciseJava {

    private long duration;
    private final TimeUnit defaultUnitMillis = TimeUnit.MILLISECONDS;

    public void setDuration(long duration, TimeUnit unit) {
        this.duration = defaultUnitMillis.convert(duration, unit);
    }

    public long getDuration(TimeUnit unit) {
        return unit.convert(duration, defaultUnitMillis);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment