Snippet Code Flashcards
1
Q
Beware the closure:
What’s the output of this Javascript function?
function hookupevents() { for (var i = 0; i < 3; i++) { document.getElementById("button" + i) .addEventListener("click", function() { alert(i); }); } }
A
2
Q
Type Erasure:
About Type Erasure, what’s the output of this Java snippet, and why?
ArrayList li = new ArrayList(); ArrayList lf = new ArrayList(); if (li.getClass() == lf.getClass()) // evaluates to true System.out.println("Equal");
A
3
Q
Memory Leak
Can you spot the memory leak?
public class Stack { private Object[] elements; private int size = 0; private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() { elements = new Object[DEFAULT_INITIAL_CAPACITY]; }
public void push(Object e) { ensureCapacity(); elements[size++] = e; }
public Object pop() { if (size == 0) throw new EmptyStackException(); return elements[--size]; }
/** * Ensure space for at least one more element, roughly * doubling the capacity each time the array needs to grow. */ private void ensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } }
A
4
Q
Kill the switch:
ifs and in general conditional statements lead to procedural and imperative programming. Can you get rid of this switch and make this snippet more object-oriented?
public class Formatter {
private Service service;
public Formatter(Service service) { this.service = service; }
public String doTheJob(String theInput) { String response = service.askForPermission(); switch (response) { case "FAIL": return "error"; case "OK": return String.format("%s%s", theInput, theInput); default: return null; } } }
A
5
Q
Kill the if:
Can you get rid of these ifs and make this snippet of code more object-oriented?
public class TheService {
private final FileHandler fileHandler;
private final FooRepository fooRepository;
public TheService(FileHandler fileHandler, FooRepository fooRepository) { this.fileHandler = fileHandler; this.fooRepository = fooRepository; }
public String Execute(final String file) { final String rewrittenUrl = fileHandler.getXmlFileFromFileName(file); final String executionId = fileHandler.getExecutionIdFromFileName(file); if (executionId.equals("") || rewrittenUrl.equals("")) { return ""; } Foo knownFoo = fooRepository.getFooByXmlFileName(rewrittenUrl); if (knownFoo == null) { return ""; } return knownFoo.DoThat(file); } }
A
6
Q
Kill the if-chain:
How would you refactor this code?
function() { HRESULT error = S_OK;
if(SUCCEEDED(Operation1())) { if(SUCCEEDED(Operation2())) { if(SUCCEEDED(Operation3())) { if(SUCCEEDED(Operation4())) { } else { error = OPERATION4FAILED; } } else { error = OPERATION3FAILED; } } else { error = OPERATION2FAILED; } } else { error = OPERATION1FAILED; }
return error; }
A