Skip to content

Instantly share code, notes, and snippets.

@dschinkel
Last active June 21, 2022 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dschinkel/5ed2ea57c9a561caf5d6bd7d4e1e85ea to your computer and use it in GitHub Desktop.
Save dschinkel/5ed2ea57c9a561caf5d6bd7d4e1e85ea to your computer and use it in GitHub Desktop.
TDD a Java Set - Attempt 4
package set;
import java.util.Objects;
public class Set {
private String[] elements = new String[0];
private int next;
public boolean isEmpty() {
return next == 0;
}
public int size() {
return next;
}
public boolean add(String value) {
String[] newElements = extendArray(elements);
newElements[this.next] = value;
next++;
elements = newElements;
return true;
}
private String[] extendArray(String[] elements) {
String [] newElements = new String[ next + 1];
copyArray(elements, newElements);
return newElements;
}
private void copyArray(String[] elements, String[] newElements) {
for (int i = 0; i < elements.length; i++) {
newElements[i] = elements[i];
}
}
public boolean remove(String value) {
for (int i = 0; i < next; i++) {
if(Objects.equals(elements[i], value)){
elements[i] = value;
elements[next - 1] = null;
next--;
}
}
return true;
}
}
package set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SetTest {
private Set set;
@BeforeEach
void setUp() {
set = new Set();
}
@Test
void is_empty() {
assertTrue(set.isEmpty());
}
@Test
void empty_set_has_no_size() {
assertEquals(0, set.size());
}
@Test
void adds_one_element() {
set.add("one");
assertFalse(set.isEmpty());
assertEquals(1, set.size());
}
/*
this test sucks because it's not specific enough. There's a possibility where
if you did logic wrong, you could add nulls to the set and this still passes. We're
not checking that those specific values are in the set, so you could end up with a false positive here.
Next time around, lets try asserting on contains() here, but then that means I'd be implementing 2 functions at once (add and contains)
which feels like way too big of a step for TDD.
*/
@Test
void adds_multiple_elements() {
set.add("one");
set.add("two");
set.add("three");
assertFalse(set.isEmpty());
assertEquals(3, set.size());
}
@Test
void remove() {
set.add("one");
set.add("two");
set.add("three");
set.remove("two");
assertFalse(set.isEmpty());
assertEquals(2, set.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment