Created
September 12, 2023 05:17
-
-
Save sb8244/1193cf71f0e28b207e8d6de636a9cb78 to your computer and use it in GitHub Desktop.
Immutability Lecture (Activity 1)
This file contains hidden or 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
import java.util.HashMap; | |
// This class is broken, follow the TODOs | |
public class ImmutableDemo { | |
// TODO: How to prevent external actors from accessing the map directly? | |
public HashMap<String,String> map; | |
public ImmutableDemo() { | |
this.map = new HashMap<String, String>(); | |
this.map.put("Important", "OKAY"); | |
} | |
public boolean isOkay() { | |
return this.map.get("Important").equals("OKAY"); | |
} | |
public HashMap<String, String> getMap() { | |
return map; | |
} | |
// TODO: How to fill out this method so that the test passes? | |
public HashMap<String, String> getImmutableMap() { | |
return map; | |
} | |
} |
This file contains hidden or 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
import static org.junit.jupiter.api.Assertions.*; | |
import org.junit.jupiter.api.Test; | |
class ImmutableDemoTest { | |
@Test | |
void isOkayCantBeChanged_Wrong() { | |
ImmutableDemo demo = new ImmutableDemo(); | |
assertTrue(demo.isOkay()); | |
// This is bad! The ImmutableDemo has been corrupted from the outside. | |
// Hint: how can we get the same map out, but prevent changes from affecting it? | |
demo.getMap().put("Important", "NOPE"); | |
assertFalse(demo.isOkay()); | |
} | |
@Test | |
void publicVariableChanged_Wrong() { | |
ImmutableDemo demo = new ImmutableDemo(); | |
assertTrue(demo.isOkay()); | |
// This is bad! The ImmutableDemo has been corrupted from the outside. | |
// Hint: once fixed, you will need to update this test to demo.getMap().clear(); | |
demo.map.clear(); | |
assertThrows(NullPointerException.class, demo::isOkay); | |
} | |
@Test | |
void isOkayCantBeChanged_Fixed() { | |
ImmutableDemo demo = new ImmutableDemo(); | |
assertTrue(demo.isOkay()); | |
demo.getImmutableMap().clear(); | |
assertTrue(demo.isOkay()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment