Questions about snippets of code:
- 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);
});
}
}
- About Type Erasure, what's the output of this Java snippet, and why?
ArrayList<Integer> li = new ArrayList<Integer>();
ArrayList<Float> lf = new ArrayList<Float>();
if (li.getClass() == lf.getClass()) // evaluates to true
System.out.println("Equal");
- 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);
}
}
if
s and in general conditional statements lead to procedural and imperative programming. Can you get rid of thisswitch
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;
}
}
}
- Can you get rid of these
if
s 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 == "") || (rewrittenUrl == "")) {
return "";
}
Foo knownFoo = fooRepository.getFooByXmlFileName(rewrittenUrl);
if (knownFoo == null) {
return "";
}
return knownFoo.DoThat(file);
}
}
- How to 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;
}