Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 26287aa

Browse filesBrowse files
refactor: add equals, hashCode, null safety and tests
1 parent 1c41504 commit 26287aa
Copy full SHA for 26287aa

2 files changed

+35-2Lines changed: 35 additions & 2 deletions

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎immutable/src/main/java/com/iluwatar/immutable/ImmutableObject.java‎

Copy file name to clipboardExpand all lines: immutable/src/main/java/com/iluwatar/immutable/ImmutableObject.java
+18-2Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
package com.iluwatar.immutable;
2+
import java.util.Objects;
23

34
/**
45
* Immutable Object pattern.
@@ -14,9 +15,9 @@ public ImmutableObject(
1415
final String name,
1516
final int age,
1617
final String email) {
17-
this.name = name;
18+
this.name = Objects.requireNonNull(name, "name cannot be null");
1819
this.age = age;
19-
this.email = email;
20+
this.email = Objects.requireNonNull(email, "email cannot be null");
2021
}
2122

2223
public String getName() { return name; }
@@ -31,4 +32,19 @@ public String toString() {
3132
+ ", email='" + email + '\''
3233
+ '}';
3334
}
35+
36+
@Override
37+
public boolean equals(Object o) {
38+
if (this == o) return true;
39+
if (!(o instanceof ImmutableObject)) return false;
40+
ImmutableObject that = (ImmutableObject) o;
41+
return age == that.age
42+
&& Objects.equals(name, that.name)
43+
&& Objects.equals(email, that.email);
44+
}
45+
46+
@Override
47+
public int hashCode() {
48+
return Objects.hash(name, age, email);
49+
}
3450
}
Collapse file

‎immutable/src/test/java/com/iluwatar/immutable/ImmutableObjectTest.java‎

Copy file name to clipboardExpand all lines: immutable/src/test/java/com/iluwatar/immutable/ImmutableObjectTest.java
+17Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,21 @@ void testImmutability() {
3232

3333
assertNotSame(obj1, obj2);
3434
}
35+
36+
@Test
37+
void testEquality() {
38+
ImmutableObject obj1 =
39+
new ImmutableObject("A", 1, "a@gmail.com");
40+
ImmutableObject obj2 =
41+
new ImmutableObject("A", 1, "a@gmail.com");
42+
43+
assertEquals(obj1, obj2);
44+
}
45+
46+
@Test
47+
void testNullName() {
48+
assertThrows(NullPointerException.class, () -> {
49+
new ImmutableObject(null, 1, "a@gmail.com");
50+
});
51+
}
3552
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.