I have a single connection being used by multiple devices, and I'd like to filter the messages so that each device only reacts to messages intended for it. This can be done with an unique ID field in the messages. I have two options.

Option #1: Have each object filter the data from the connection themselves:

class MyDevice {

  func onMessage(msg: Message) {
    if (msg.targetId != this.id) {

var myConnection = new MyConnection("")
var dev1 = new MyDevice(id: 1, connection: myConnection)
var dev2 = new MyDevice(id: 2, connection: myConnection)

Option #2: Create a filtered subconnection at creation level:

var myConnection = new MyConnection("")
var dev1 = new MyDevice(id: 1, connection: myConnection.subconn(msg.targetId = 1))
var dev2 = new MyDevice(id: 2, connection: myConnection.subconn(msg.targetId = 2))

The question I have is about responsibilities; is it the device's responsibility to always check each message, or is it the creator's responsibility to ensure that the device only gets a stream of correct messages?

I understand there isn't necessarily one correct solution, but I'd like to hear when one option would be favorable over the other, or if there are any industry standards for this kind of behavior.

1 Answer 1


I think this problem is in need of another layer of abstraction.

Sounds to me like you are in need of a ConnectionFilter object. That a device will link to the main connection. And it filters the correct messages to the device as an intermediary.

So the main connection will receive the messages. And then those messages will get distributed and filtered to the correct devices via the filter objects.

Arguments can be made either way but I would probably lean towards each device being responsible for setting up its own filter. The device knows best what messages it needs. The main connection’s job is to receive messages properly. It doesn’t care what things DO with those messages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.