Structs vs classes

I promise you are NOT going to hell for using structs.

In the picture below, one class fully encapsulating its contents versus one open, plain struct. And yes I used square as rectangle on purpose so don’t be that guy and keep your eyes on what’s important.

I had once a very concerned engineer refactor 40 lines of my code, mostly market data messages as structs, into 2,000 lines of “properly wrapped” classes. It was a hard conversation because he was taught this was the way, he just needed to hide everything. So I felt there would be someone else here that would benefit from an alternative perspective.

Somewhere, someone spread the myth that everything needs to be encapsulated into classes and the member needs to be hidden.

The underlying motif is that the user is dumb and we should lock down the code as much as we can. Jokes on us, more often than not, the user is you.

Although there are clear benefits on complexity encapsulation, the example below is, in my opinion, not one of them.

Unnecessary encapsulation is not a victimless crime. Here are the consequences:
1. Code bloat leads to more lines of code to be maintained
2. More lines of code means more chances of bugs
3. More lines of code means less logic on screen, you lose the “panorama benefit” where one can see all the logic on one page without scrolling
4. You are creating effectively a new API that will need to be documented and consulted, an extra burden to the user
5. Changes to any fields will require changes in the interface as well
6. Think about memory, user memory. Instead of 2 symbols (height, width) you are adding 4 more (getHeight, getWidth, setHeight, setWidth). It seems negligible but on bigger sets like market data templates with hundreds of messages, it can easily become overwhelming.

And here are the benefits of using a struct:
1. The entire logic is apprehended with a single glance
2. Changes are straightforward
3. Documentation is straightforward
4. Automated tools have an easy time
5. Your users will have an easy life
6. Faster time-to-market

So every time you create a new class think if it can be just a struct. Keep in mind that OOP is just an abstraction and abstractions do not belong to the real world so don’t feel bad about killing them.
Abstractions are here to help you code faster and deliver faster products with higher quality.

You need to be the master of your code, not the servant. The language is just a tool to get ideas transformed into machine language bytes. If you are being the slave of your own abstractions, this is a perversion of what the language is supposed to be.

Above all, have the confidence to question everything. OOP is not the only way.

post photo preview