=================
== The Archive ==
=================

Article Weekly, Issue 18

Period

2024-04-28 ~ 2024-05-04

4 Software Design Principles I Learned the Hard Way

What if null was an Object in Java?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Test
public void nullIsNotAnObject()
{
    // Assert things about null
    Assertions.assertFalse(null instanceof Object);
    final Set<?> set = null;
    Assertions.assertFalse(set instanceof Set);

    // Assert things about exceptions thrown when calling methods on null
    Assertions.assertThrows(
            NullPointerException.class,
            () -> set.getClass());
    Assertions.assertThrows(
            NullPointerException.class,
            () -> set.toString());

    // Assert things about a non-null variable named set2
    final Set<?> set2 = new HashSet<>(Set.of(1, 2, 3));
    set2.add(null);
    Assertions.assertNotNull(set2);
    Assertions.assertNotNull(set2.getClass());
    Assertions.assertTrue(set2 instanceof Set);

    // Filter all of the non-null values from set2 in the Set named set3
    // Uses a static method refererence from the Objects class
    final Set<?> set3 = set2.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toUnmodifiableSet());
    Assertions.assertEquals(Set.of(1, 2, 3), set3);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
testNilIsAnObject
  |set setNoNils|

  # Assert things about nil
  self assert: nil isNil.
  self assert: 'nil' equals: nil printString.

  # Assert things about the set variable which is nil
  set := nil.
  self assert: set isNil.
  self assert: set equals: nil.
  self assert: set class equals: UndefinedObject.
  self assert: (set ifNil: [ true ]).
  self assert: set isEmptyOrNil.

  # Assert things about the set variable which is not nil
  set := Set with: 1 with: 2 with: 3 with: nil.
  self deny: set isNil.
  self assert: set isNotNil.
  self deny: set equals: nil.
  self deny: set isEmptyOrNil.
  self assert: set class equals: Set.

  # Select all the non-nil values into a new Set name setNoNils
  setNoNils := set select: #isNotNil.
  self assert: (Set with: 1 with: 2 with: 3) equals: setNoNils.

References

Categories:

Tags: