My home work assignment is to figure out:
- What this code does
- What potential problems there are
Code
/// Enum
public enum Event {
TORNADO, THUNDERSTORM, TSUNAMI, RAIN, SNOW, WIND, COLD, HEAT;
public final static String CRITICAL = "Critical";
public final static String SEVERE = "Severe";
public final static String MEDIUM = "Medium";
public final static String LIGHT = "Light";
private String severity;
private String location;
public void setSeverity(String severity) {
this.severity = severity;
}
public void setLocation(String location) {
this.location = location;
}
public String toString() {
return super.toString() + ":" + severity + " at " + location;
}
}
///Interface
public interface IEventListener {
void eventReceived(Event event);
}
///Class
public class EventPublisher implements IEventListener {
Map<Event, Collection<IEventListener>> listeners = new HashMap<Event, Collection<IEventListener>>();
@Override
public synchronized void eventReceived(Event event) {
for (IEventListener listener : listeners.get(event)){
listener.eventReceived(event);
}
}
public synchronized void register(IEventListener listener, Event event){
Collection<IEventListener> list = listeners.get(event);
if (list == null) {
list = new LinkedList<IEventListener>();
listeners.put(event, list);
}
list.add(listener);
}
public synchronized void deregister(IEventListener listener, Event event) {
listeners.get(event).remove(listener);
}
public String toString() {
String ret = "";
Iterator<Event> i = listeners.keySet().iterator();
while (i.hasNext()) {
Iterator<IEventListener> j = listeners.get(i.next()).iterator();
while (j.hasNext()) {
ret = ret + i.next() + "::" + j.next() + "\n";
}
}
return ret;
}
}
I went through the code and figured out that this code tries to produce the weather report and classify the weather condition based on eventReceived (Event can be registered/deRegistered).
I however cannot see any problems with the code. My teacher insists that there are issues. Can anyone help me?
First of all,
Eventshould not be anenum. Since its members are effectively singletons; by changing the e.g. severity of oneTORNADO, you’d change the severity of all of them. You should have an enum forEventType, one forSeverity, and anEventclass that uses them.Then, your map inside the event publisher will change…
Also, the
deregistermethod could throw a null reference exception…