by corytheboyd · 4y ago · 0 comments
Whatever, I still love you Ruby. You can always just not use these things and life goes on.
Take @dataclass in python for example, that’s similar to Struct for Ruby.
‘Data’ documentation from the GitHub PR (https://zverok.space/ruby-rdoc/Data.html):
Data provides no member writers, or enumerators: it is meant to be a storage for immutable atomic values. But note that if some of data members is of a mutable class, Data does no additional immutability enforcement
See also Struct, which is a similar concept, but has more container-alike API, allowing to change contents of the object and enumerate it.From a cursory look data classes seem to do a lot more than structs. Structs seem like a mutable version of namedtuples, or js objects, down to behaving like a collection / iterable.
They were intended (going back at least to C++) to convey different things. A struct is a light abstraction of related things. So instead of having int x, int y everywhere you have Struct Point.
A class has responsibilities, implies state, implies interfaces.
Given the signaling that structs send they should be value objects and as such the original Ruby struct is a bad implementation. The Data object is basically a concession of this with an understanding that changing struct would break "all the things" that already use struct.
The parent indicated they didn't understand why both struct/class exist because there is so much overlap. The primary reason is to signal intent. This has largely been lost as the masses just use classes for everything or they use simple data types like hashes.
I love it that I can now use it from the language instead. It saves me just one class. At most five methods.
But it saves me having to explain and defend this for colleagues who insist that an email is Just A String, or a price being a float (i know) has worked Just Fine. I can now point them at stdclass documentation. And it being part of std weighs far more than the opinion of that contractor that keeps on nagging about design patterns and crap.
"Glad we'll have a built-in struct class that's not Enumerable. I remember passing a Struct instance to a method which had a check for object.is_a?(Enumerable), and then proceeded to do something else than what I intended. It's fine to offer a way to iterate over attributes, but it was unnecessary to make the whole Struct Enumerable."
With this new data class... Idunno I'm shrugging my shoulders. The whole mutability/immutability debate has always seemed so pointless. Don't go assigning shit so willy-nilly?
This is especially helpful when code gets complicated and you have a lot of hashes being thrown around.
Instead of trying to document and enforce a nested hash structure through multiple layers, you can use Structs to make mini classes that do that for you.