patternjavaMinor
Proper naming for a Time class
Viewed 0 times
timefornamingproperclass
Problem
Which of these names is better:
time.getHours() or time.hours()? And why?public class Time implements Serializable {
private final int hours;
private final int minutes;
public static Time from(Calendar calendar) {
int hoursIn24HourFormat = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
return new Time(hoursIn24HourFormat, minutes);
}
public Time(int hours, int minutes) {
this.hours = hours;
this.minutes = minutes;
}
// or may be getHours() name is better?
public int hours() {
return hours;
}
// or may be getMinutes() name is better?
public int minutes() {
return minutes;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof Time)) {
return false;
}
Time other = (Time) obj;
return (hours == other.hours) &&
(minutes == other.minutes);
}
@Override
public int hashCode() {
return toMinutesOfDay();
}
private int toMinutesOfDay() {
return hours * 60 + minutes;
}
@Override
public String toString() {
return twoDigitString(hours) + ":" + twoDigitString(minutes);
}
private static String twoDigitString(int timeComponent) {
return (timeComponent time.toMinutesOfDay();
}
public boolean within(Time fromIncluded, Time toIncluded) {
return (!fromIncluded.after(this)) && (!this.after(toIncluded));
}
}Solution
It is a matter of taste, so there is no 'better'. But more common seams to be
If you work in a team, I would discuss the naming conventions to use with them.
time.getHours(); because often the conventions of JavaBean are used.If you work in a team, I would discuss the naming conventions to use with them.
Context
StackExchange Code Review Q#39444, answer score: 4
Revisions (0)
No revisions yet.