2

I'm currently designing a communications system and would like some advice on my OOP approach.

It's very simple - it takes data off a serial port, divides that data up into messages and then parses those messages into something the rest of the code can use. For example, a message might be "LightSensorReport", which contains data gathered from several sensors; the data in this case is just integer values, but there are cases where the data is more complex.

So, I think of the serial port as a class that implements a stream interface. My class for parsing the stream is then responsible for taking data off that stream, figuring out where message boundaries are and then sending those messages to another class which converts the binary data of the message into an object such as "LightSensorReport".

My question has come from thinking about that final data class and what it actually is - the "LightSensorReport" in this case. To me, it's not quite an object - it only has state, but it doesn't do anything to that data (so it's really a data structure). Is this a smell? Does this fit with good OOP?

My rationale for making LightSensorReport just data is just that - it's data only. It doesn't really DO anything on it's own, but other classes would use it (for example, another class might have to serialize it to a different protocol format; I wouldn't place this responsibility on LightSensorReport because it doesn't know anything about binary protocols).

So, does this kind of class fit with good OOP design or is it a sign that I'm thinking about something the wrong way?

Matt C
  • 233
  • 1
  • 9
  • An int is an object, and it doesn't "do" anything. It's data only. I think what you are doing is just fine. It's just a complex data type. – Josh Nov 14 '13 at 20:49
  • In Smalltalk, Integers _are_ objects and they offer arithmetic operations as behaviours that they understand. In Java, `int` is a primitive, which broke the pure OO model for performance reasons; `Integer` instances can convert to other primitives. Classes without behaviour typically indicate code smells. It's perfectly fine for `LightSensorReport` to know how to serialize itself. https://stackoverflow.com/a/901571/59087 – Dave Jarvis Feb 25 '22 at 17:49

1 Answers1

2

Your approach is perfectly fine. For you, LightSensorReport is an object that encapsulates data cohesively. You are not forced to add behavior to the classes you create in OOP, but Objects is what the paradigm provides you with, it also applies for encapsulating data. Furthermore, once you have your entity, you may add behavior to it in the future.

Some languages already define behavior in the objects you create. For example, in Java, even if you don't define methods in your LightSensorReport class, it will inherit the ones from the superclass Object, so it will have behavior at the end.

user3001267
  • 304
  • 1
  • 4