293 points · by feross · 3y ago · 181 comments
I'm psyched for this feature. As someone who has worked primarily with Ruby and Elixir, I really appreciate the design and safety affordances of immutable data. I'm glad there's a bit more immutability in Ruby and that, in general, the language keeps progressing. Thank you Ruby language devs.
Measure = Data.define(:amount, :unit) do
def initialize(amount:, unit: '-none-') = super
endI'd rather see incremental additions to this minimal Data API than trying to do too much at once. Lots of love for the Ruby dev team but they don't always have the clearest idea of what problems their users are trying to solve.
I've worked with Ruby for nearly ten years and have been hearing some variation of "Ruby is dying" since forever.
Ruby is a flawed language (I especially dislike the lack of real namespaces) but the hate it gets is often not based in reality.
That said the serious reason I don't try it out is because I fear it would be like Python, and I don't need two Pythons in my life. If Ruby had been dominant I'd likely be using Ruby and thinking the same of Python.
It's like when a game/band/tv show becomes popular, the more popular the more toxic the community becomes, and the louder the hate seems to be. I don't want to pull names out of hats, but pick any of the most used languages and you'll be able to find people banging on about objectively bad parts of the language, and yet they're still the most popular languages.
Admittedly, I don't really prefer Ruby over other languages, but just like PHP I wish people would stop being so dramatic over it. It's plenty good enough to get shit done, if someone likes working with it power to them.
Let’s make a very simple naive test using Google search, "I love Ruby" matches 98,400 results, while "I hate Ruby" returns 7,740 results (from my current terminal).
There is even a book named "I love Ruby" it seems.[1] Compare that to the existence of "The UNIX-HATERS Handbook".[2]
Can you be more precise about what features you miss in Ruby modules compared to "real namespaces"?
[1] https://i-love-ruby.gitlab.io/ [2] https://en.wikipedia.org/wiki/The_UNIX-HATERS_Handbook
Vaguely similar in performance to Python and PHP (not an order of magnitude off), slower than Java and .NET (for typical web based workloads with mainstream frameworks, .e.g Rails vs Django vs Laravel vs Spring Boot vs ASP.NET), still good enough for most web projects out there.
Even Rails just seems like your average flagship framework, if not an entire platform - certainly on the heavy side, with its own quirks and opinions, but definitely a safe option for getting things done.
It's jarring to see Ruby's popularity be on the decline, though you could also say the same about PHP in many cases.
And there aren't many good Ruby developers. There are too many noobs who write Ruby code that make my eyes bleed. I know, because I have to see this at work and they're supposedly "rockstar" developers. Ha! I swear most so-called "engineers": 0. don't grok software engineering, 1. weren't formally-trained in software engineering AND computer science, and 2. happily push shitty code that there will be no incentive to refactor through automated means.
If you want to enforce coding standards in Ruby, you better learn LISP / S-expressions, because that's what Rubocop uses.
Ruby, having at least million users around the world, is in immortal category.
What fascinated me in the original post is "...data model on the principles of the Value Object, introduced by Martin Fowler."
I mentioned Haskell because there is a long, long history of the use of immutable objects in computing science, dating back to Church and Turing's communication. The immutability is what differentiates lambda calculus and Turing machine.
That is why I remembered Haskell and the video above.
Yet, it is "introduced by Martin Fowler," for some reasons.
This is very sad.
This is maybe going to sound snarky, but honestly I really am being serious: at this point, what else do you expect from this website? HN has a well-earned reputation of being a bunch of kneejerk-critics and naysayers.
For better or worse HN is my community. Its given me so much over the years, even as it's infuriated me much of the time. As I recognize patterns of dysfunction I highlight them, so that the community can understand & overcome them.
And I do think I see incremental progress. Not to say I caused that progress, I have no idea what if any role I played from my modest soap box (I suspect very little), but I think there's every reason to hope for the better.
Yes, there are critics who are not ‘in the arena’, but for the rest I see a lot of care (AKA taste as defined in Ira Glass’ words on “The Gap”) put in to the comments.
I have had/seen this conversation over and over again on HN:
Commenter: This topic sucks, I wish people would stop posting it to HN.
Me: I understand this topic isn't interesting to you. Why don't you ignore it and click on something else?
Commenter: I care so deeply for this community, I hate to see this topic reduce it's SNR.
Does the commenter care about HN? Presumably. Does that make their complaint legitimate? No. They're bothered by how a subset of people on the site want to discuss some topic, and they're manufacturing a reason that sounds better than, "I don't want to see it."
But no one is entitled to have articles that are to their taste posted to HN. Sometimes this is expressed more like, "this isn't appropriate for the HN audience." But the audience of an HN post isn't what anyone imagines HN looks like, it's the subset of HN members who find that post in particular to be interesting and worthy of discussion.
If I just need a bundle of attributes and don't care about immutability then I will continue to use Struct.
If I do need immutability I will continue to use dry-struct (https://dry-rb.org/gems/dry-struct/1.0/) which has much deeper guarantees of immutability and type enforcement.
You should not worry about what top-level comments are.
Regarding this feature, it's cool but I'm surprised they introduced a new concept just to add immutable structs.
ES6 suffers from this disease to a fairly extreme degree, and you can see this schism in the JS community back to the semicolon war in the early 2000s. Kotlin as well, unfortunately, as it's otherwise generally a really nice language.
There are so many language structures and shortcuts. And unless you spend a large amount of time becoming truly fluent in all of them, you're never going to be able to read all the "clever" code that uses them.
These structures are not common across languages, either, so if you jump between codebases in multiple languages... good luck.
tl;dr: Readability über alles.
The amount of time I have lost because of some piece of code (a block) that gets executed somewhere else and I have no clue how that works is insane. And every time I need to go and dig in the implementation details to identify the params passed in because there is no enforcement at write time. I want my types!!! Why would you voluntarily write code where you throw out the types. The thing that is most useful...
That alone is enough reason to create a separate class. Struct has completely wrong ergonomics for certain things.
I’m sure there are a bunch of other reasons but I didn’t feel the need to dig further.
* ImmutableStruct: Immutable struct where values are set at construction and cannot be changed later.
* MutableStruct: Synchronized, mutable struct where values can be safely changed at any time.
* SettableStruct: Synchronized, write-once struct where values can be set at most once, either at construction or any time thereafter.
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.
https://bugs.ruby-lang.org/issues/16122
Ed:
https://ruby-doc.org/core-2.5.0/Data.html
> Data
> This is a deprecated class, base class for C extensions using Data_Make_Struct or Data_Wrap_Struct.
Vs
https://ruby-doc.org/core-2.4.0/Data.html
> Data
> This is a recommended base class for C extensions using Data_Make_Struct or Data_Wrap_Struct, see doc/extension.rdoc for details.
Seems like an area of concern / gotchas. Either restrict Data to not allow mutable nested objects, or provide immutable versions of stdlib object types as well and enforce that those types are used.
Yet another Rubocop-that-should-just-be-built-into-the-language coming in 3...2...1...
Rust is the main exception I'm aware of, and it had deep immutability from the get-go.
Scala gives you immutable data types but unless I'm mistaken there's no way to say "recursively disable mutating functions for all elements in this list"—you just have a list that cannot be mutated. If you stick a Java object in a Scala list, it's liable to mutate, so Scala has shallow immutability.
It would be interesting if mutability was actually part of Scala's type system, for example if immutable Seq was defined as
class Seq[T <: Immutable]They absolutely do, in part because you son’t even have a type system you’d need to undermine in order to achieve mutation.
There are “immutability first” dynamically typed langages, and they work rather well (erlang, clojure).
const is JS is referring to the reference and has nothing to do with the value, it's not even shallow immutability, there is none at all.
const arr = []
arr.push(1)
is valid JavaScript.Bit nitpicky maybe, but wouldn't want people to get the impression const gives you any sort of immutability.
const makes the binding immutable but not the object. Object.freeze makes the object immutable but not it’s children.
To take Python tuples (which are morally pretty close to Data)
my_data = ([],false)
my_data[0].push(1)
tuples are immutable, but this happens, because the "immutability" is in the same vein as JS's const: "we are always pointing to the same object".The only conceptual difference between this and JS's `const` is that you can't use `const` to declare object properties immutable; for that you need Object.freeze().
C and C++ have deep immutability too, but both come with many other footguns as baggage.
Actually doing so breaks the covenant of Data, but an enforced prohibition breaks the language. As with Struct before it, a data class is merely a shorthand.
Fortunately in my almost 20 years of ruby, dark magic does not survive a reasonable amount of sunlight. Most of the time someone (including me) has written impolite ruby, they know what they are doing and why (laziness 90% of the time) and respond appropriately to a gentle prod to be more polite.
Ruby gives you footguns and you can certainly do ill-advised things... but in practice I just don't see it happening very often either in open source projects or in private corporate stuff.
Why?
Because IME there's rarely even a need to go down those paths at all, unless you are writing a framework or doing something else "meta."
99.99% of Ruby I have actually seen is either simple scripts or bog standard OO stuff.
The numeric and character types in Common Lisp are immutable value types. The standard says they may be copied at any time, so the object equality operator (eq) may or may not return true on them. There is a separate equality operator, eql, that performs value equality on value types (so two numbers whose value is the same integer, even if they are bignums with a representation stored on the heap, will return true when compared with eql.) Eql has the same meaning as eq on types that are not immutable value types.
While this is not standardly possible in CL, it would be nice if users could extend operators like eql with new methods, thereby defining new immutable value types.
A nice thing about these value types is they play well with distributed computation or with saving of values to offline storage.
break everything that came before
How is this breaking anything, let alone everything?I'm not sure I see the value of Data either, but I also don't see how it breaks anything. One of us is severely misunderstanding it.
- https://ruby-doc.org/core-3.1.1/Object.html#method-i-freeze - https://www.rubyguides.com/2016/01/ruby-mutability/
> (irb):5:in `<main>': undefined method `name=' for <...> (NoMethodError)
> Did you mean? name
This error message is a bit roundabout. I assume the implication is that `name` is the getter and `name=` is the setter. And so, immutable objects don't have the setter method? But definitely could be worded much better than NoMethodError.
Disclaimer: I'm more of a Python/JS/TS person, and haven't used Ruby much.
(All Ruby operators work this way: something like `foo + bar` is short for `foo.+(bar)` for example.)
john.instance_variable_set(:@name, "John Doe")
john.send(:"instance_exec") do @name = "John Doe" end
I love ruby.Yes. This is extremely conventional/idiomatic Ruby. You'd be likely to come across this pattern not long after Hello World.
But that is the root cause - there is no such method.
The thing about 'Did you mean? name' is just a guess to help you.
And instead it throws anyone who hasn't extensive experience with Ruby's quirks into a spiral of misery.
(Or more realistically, your IDE underlines your error in red and you never even see the error message)
What do you think it should have said? Because this:
john.name = "John Doe"
is, literally, calling `name=` on `john`. But there is no such method.
I was.
I'm confused. How can an immutable object be extensible?
In Java parlance, would that mean something like:
public /*not final!*/ class GinormousData {
// all public final immutable members
public final String name;
public final int name;
...
}
Then, you are supposed to extend it? Weird. I never saw this style once. Is it a good idea?The scary part, since the class is not final, you need to constantly worry if someone did something crazy like inherit and add mutable fields. Then legacy code that operates on references of GinormousData is clueless.
If I need to compose value objects, I would do this:
public final class GinormousData {
// all public final immutable members
public final String name;
public final int name;
...
}
public final class EvenBiggerData {
public final GinormousData gdata;
// other public final immutable members
}
Regardless of my language concerns above, this is great new feature for Ruby.When I write Python, I go wild with namedtuples and dataclasses(frozen=True). Love them immutable data objects -- so easy to reason about when reading code.
> Did you mean? name
Is that the best they could do to express that `person.name` is readonly?
The "did you mean" part especially is really where they could add info that would make sense to a human, but clearly that didn't happen.
It could be improved--not easily; a setter method does not necessarily have to map to a data type, and Ruby itself doesn't know what you mean here because the Data type is in the stdlib but doesn't appear to be a compiler special case--but this is a bit nitpicking, and I would perhaps gently push back on changing the error message because it's representing what you really do need to know in Ruby once you're past the level one "driving Rails" usage of Ruby. Getting an error message other than this one would obfuscate what's happening and leave me as a long-time Ruby user pretty confused.
I guess it would then also provide a better message for `attr_reader` vs `attr_accessor` usage, too, right?
object.attr = 1
is
object.send(:attr=, 1)
And yes, setters can take multiple arguments. They are just methods. Nothing special about them.
?> def you_are_wrong=(a)
?> a * 2
>> end
=> :you_are_wrong=
>> send(:you_are_wrong=, 24)
=> 48
However yes, the `foo.bar = 24` expressions translates to `(foo.send(:bar=, 24); 24)`.The reason is so that `foo = bar.baz = 12` works as you expects, it's absolutely not some kind of cruft or black magic.
tldr You tried to call name= on an object that has no such method defined on it. So you get...NoMethodError. name is defined, however, so you got a "is this the typo you made?" message.
Isn't "Data" the worst possible name one could use for anything in programming? I am not exaggerating; it is literally the example I have always used.
If Data is an immutable struct, call it ImmutableStruct. If that's too long, there's ImmuStruct or IStruct. Any of those names is better than Data. They are all more concise.
Hence
Product = Data.define(:name, :price)
creates a Product class, most likely during initialisation; then in application code we could subsequently write cheese = Product.new("Wensleydale 200g", 499)
and here it's cheese that is immutable; the point being, we're still naming our domain objects purposefully.In that light, I think it's appropriate for a language to use generic terms for fundamental elements. For example, almost everything is descended from Object and we're fine with it.
IMO ImmutableStruct is exactly as verbose as BasicObject, something that has been in Ruby for a long time now. ImmutableStruct is a massively better name for this.
The article explains the reason they didn't do that:
Ruby maintainers decided that Struct could not be made to suit the requirements of a value object. The core Struct class is a “somewhat alike” value-object; it is compared by value and is,
mutable
collection-alike (defines to_a and is Enumerable)
dictionary-alike (has [] and .values methods)
are they trying to say that martin fowler invented immutable data structures???
* An immutable composite value that
* Has an equality operation not based on pointer identity
Those have been known for a long time, at least 30 years. It is the default type of value of Haskell, a language that is older than Ruby.
Straight from the horse's mouth: https://martinfowler.com/bliki/ValueObject.html