1

Assume I have a class broadcaster to broadcast certain events. Eg:

List<Observers> observers = …

Public void broadcast(Event e) {
    for (each observer: observers) {
       observer.observe(e);
   }
}

Then I have a class called EventReceiver which does the following

public void processEvent(Event e) {
    saveToDatabase(e);
    broadcast(e);
}

Now: a new requirement comes up, saying that when Event is of type “foo”, we should save it to database but not broadcast it.

At which layer should I filter ? At broadcast.java or in EventReceiver.java ?

Eg:

Public void broadcast(Event e) {
If (event != foo) {
    for (each observer: observers) {
       observer.observe(e);
   }
 }
}

Or

public void processEvent(Event e) {
    saveToDatabase(e);
   If (event != foo) {
        broadcast(e);
   }
}
JavaDeveloper
  • 4,422
  • 9
  • 53
  • 96

4 Answers4

2

I'd say processEvent, your second sample. The responsibility to filter should come from the body of code first processing the event, before you decide to broadcast it. There's no sense in passing off an event to broadcast which will not, or should not, be broadcasted.

Michael
  • 2,500
  • 1
  • 13
  • 26
1

If you have 2 observers, one broadcasts and another writes to DB, then you can use a Decorator pattern to filter.

class Broadcaster implements Observer {
    public void process(Event e) {
        broadcast(e);
    }
}


class DbWriter implements Observer {
    public void process(Event e) {
        writeToDb(e);
    }
}



class FilterOutFoo implements Observer {
    private Observer decorated;

    public Filter(Observer decorated) {
        this.decorated = decorated;
    }

    public void process(Event e) {
        if (!e.isFoo())
            decorated.processs(e);
    }
}

observed.addObserver(new Broadcaster());
observed.addObserver(new FilterOutFoo(new DbWriter()));
0

The filter should be clearly implemented in EventReceiver.java as you could upgrade the Broadcast.java class later on to broadcast other events.

You could have many receivers, each one implementing their own filter depending on the use case.

Moreover, as Michael pointed out, there is no point in broadcasting an event that wont be broadcasted.

It would be like muting a cell phone tower instead of the cell phone itself. You'll never get any call. But if you mute your cell phone instead, you decide whenever to unmute it. (sorry for the coparison :))

Community
  • 1
  • 1
JuanGG
  • 741
  • 6
  • 11
0

Don't filter. Subclass. If there is an event of type Foo, then there should be a class FooEvent. Let observers register for FooEvent notifications, so that observers only receive notifications they care about.

The root of the problem is a single Event class representing multiple event types. Instead, each event type should have its own class and its own list of observers.

jaco0646
  • 11,033
  • 7
  • 47
  • 64