Created
June 7, 2015 09:00
-
-
Save jamie-allen/bfc1052ea0e3d93d09a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A simple Java data class with two immutable fields. If I want | |
* to add a third field (e.g. seconds), I have to update a ton of | |
* places and remember them all, because a compiler will not tell | |
* you what you missed. If I generate equals/hashCode/toString, I | |
* have to remember to do so with every change. And I cannot | |
* overload constructors and assume default values for parameters, | |
* because in this class, each field is an int and they'd have the | |
* same signature, so I have to use the Builder Pattern to do | |
* default values. This is a maintenance nightmare compared to | |
* the equivalent Scala case class code: | |
* | |
* case class TimeImpl(hours: Int = 0, minutes: Int = 0) | |
*/ | |
public class TimeImpl implements Time | |
{ | |
private final int hours; | |
private final int minutes; | |
public TimeImpl(int hours, int minutes) | |
{ | |
this.hours = hours; | |
this.minutes = minutes; | |
} | |
public int getHours() | |
{ | |
return hours; | |
} | |
public int getMinutes() | |
{ | |
return minutes; | |
} | |
@Override | |
public boolean equals(Object obj) | |
{ | |
if (obj == null) | |
{ | |
return false; | |
} | |
if (getClass() != obj.getClass()) | |
{ | |
return false; | |
} | |
final TimeImpl other = (TimeImpl)obj; | |
return com.google.common.base.Objects.equal(this.hours, other.hours) | |
&& com.google.common.base.Objects.equal(this.minutes, other.minutes); | |
} | |
@Override | |
public int hashCode() | |
{ | |
return com.google.common.base.Objects.hashCode(this.hours, this.minutes); | |
} | |
@Override | |
public String toString() | |
{ | |
return com.google.common.base.Objects.toStringHelper(this) | |
.addValue(this.hours) | |
.addValue(this.minutes) | |
.toString(); | |
} | |
public static class TimeBuilder | |
{ | |
private int hours = 0; | |
private int minutes = 0; | |
public TimeBuilder() | |
{ | |
} | |
public TimeBuilder setHours(int hours) | |
{ | |
this.hours = hours; | |
} | |
public TimeBuilder setMinutes(int minutes) | |
{ | |
this.minutes = minutes; | |
} | |
public Time build() | |
{ | |
return new TimeImpl(this); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment