Ruby adds a core class called Data to represent simple immutable value objects
blog.saeloun.com
blog.saeloun.com
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.
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.
I speak from a good deal of experience with this. Active listening was a good crutch for me in a lot of ways, but it works very poorly with people more and more often these days (especially online) and by the time you reach texting and forum posting, you basically just have to read walls of text before you can respond.
I hate to say it but sometimes I just need to interrupt you! Same goes the other way. Please, PLEASE, chime in with some reverb or retaliation. (Hell, maybe one day I'll earn a slap on the back ;)
Then you have the next problem. It spirals... like a positive feedback loop. You find yourself in a thrilling conversation/argument with someone only to have completely alienated the rest of the room. Now what? Is anyone else even paying attention? Would they have liked to, but you both just flew past them and dove straight into your threads?
I think this stuff is insanely hard in the real world sometimes, and only harder online. I like HN partially just because I feel like a lot of people here kinda get that.
P.S. I'm also the kind of person who types really long emails, then spends a while trying to edit them down. Sometimes I just don't have the energy. Sorry for the hypocrisy.
I'm open to this criticism I'm just not entirely sure I'm correctly interpreting you. (It certainly wouldn't be the first time I was told I was unclear or long-winded.)
I don't mean to speak out of turn, but just to offer you information, your experience really reminds me of how friends have described ADHD to me. I'm just putting that out there in case it's useful, make as much or as little of it as you care to.
I can't speak to how often this happens for people without ADHD, but it is a very common trait for those with ADHD (and describes me rather well on most days).
For what it's worth, my interpretation was that they were criticizing you so much as elaborating/describing/explaining a different perspective on the same phenomenon you described (or at least, a similar phenomenon)... and then that turned into its own tangent. of a tangent of a tangent.
So, bringing these tangents all the way back to the OP: ADHD is hard, communication is hard--especially with people. Communication patterns are context sensitive. Toxic communities are easy, toxic communication patterns are easy, and establishing constructive communication patterns for a broad community of people is hard. Ruby's community tends to be mostly nice, although it's a lot less popular and energetic than it was 12 years ago. Ruby itself is marvelous--haters be damned--even when there's a little truth in the criticism. I think that its positive impact on the industry as a whole is hard to measure (almost every commonly used web framework before Rails, Rails, almost every commonly used web framework before Rails; and the languages like Rust and Elixir are hugely influenced by the idioms, ergonomics, and aesthetics of Ruby, IMO). And adding Data in ruby 3.2 is a great little building block and will probably replace 90% of my Struct usage. And I've been wondering if I should backport it, wait for all of my projects to hit 3.2+--I'm hoping there will be a good implementation in the "backports" gem soon--or just use one of the gems that will create an adapter layer over it (I'm sure one or more of the dry-* gems will be built on it, and I'm using them in a few places anyway).
So, I was going to type a six word reply ("yeah, this is a common ADHD trait.") and this accidentally got blurted out. So yeah. ADHD. ;)
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...
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.
Regarding this feature, it's cool but I'm surprised they introduced a new concept just to add immutable structs.
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.
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, 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.
Or do people think that before Java we didn't have any architecture astronauts on large corporations?!?
For comparison, i've spent many months to hack on Java framework in a company before to deliver a hackable feature.
By the same time, i also released 3 production applications from scratch with Rails.
The issue is not Java is impossible to have such productivity, it's the mindset, the culture issues from Enterprisey people.
Had Ruby and Rails been embraced at the same scale, you can bet there would exist a comparable flavour of Ruby EE.
If you're at work and want to get shit done fast for the salary reason: There's no reason NOT to use Rails.
If you want to go enterprise, use something lightweight and modular, composable instead. Throwing a bunch of inheritable BeanClass serves no purpose on the job.
UNIX philosophy came long ago, before JAVA.
CORBA was born on UNIX, original implementation targeted C, C++ and Smalltalk.
Java was years away to be created, again by a UNIX company.
Java EE, was reborn from an canceled Objective-C project created by Sun and NeXTSTEP, again two UNIX companies.
You don't solve problem by solving it. You solve it by decomposing it, and compose again.
On the enterprise mines, the minions do what they say.
> The issue is not Java is impossible to have such productivity, it's the mindset, the culture issues from Enterprisey people.
I do think that a lot of it will depend on what sorts of projects people work with, as well as how old the frameworks are. Some design choices made in the development of those will certainly show their age. Consider this article, for some nice arguments in that regard: https://earthly.dev/blog/brown-green-language/ (I'd say this also applies to frameworks, not just languages themselves)
I actually recently used Dropwizard to create a proof of concept system for storing and querying millions of files by their metadata and using Java wasn't too bad in the end: https://blog.kronis.dev/tutorials/1-4-pidgeot-a-system-for-m...
I'd vaguely rank the frameworks and libraries as follows:
- Java/Jakarta EE: pretty dated at this point, you'll mostly see it in legacy projects, generally not a "modern" feeling experience, if you need to configure a separate web server instead of an executable .jar file, you're going to have a bad time
- Spring: if you see plain old spring, you'll have a bad time, it's the definition of "enterprise" code and will waste lots of your time
- Spring Boot: can be good if you start a new project with a recent version, still somewhat enterprise but lots of integrations are just plug & play
- Dropwizard: takes a bunch of idiomatic Java packages and glues them together, comparatively lightweight, you can even get by without dependency injection, most of the cruft that you need to deal with ends up being because of the language itself instead of a framework with bunches of weird dynamic class loading and reflection
- Quarkus/Vert.X/...: new frameworks and libraries that try to build something more modern and performant, generally you can look in the direction of these for many of the modern projects that you want to do, though their lack of maturity might show sometimes (e.g. if you try doing something unsupported, or just run into their learning curve, e.g. how the Vert.X event loop works)
I guess I can sum up my thoughts with: Is Java as a language inherently a bit more annoying to work with than some of the other web dev languages? Definitely.
Have its frameworks and the language itself gotten better in the past years, especially after newer versions than Java 8 came out? Yes.
Are many out there going to pick it for its decent static type system, good runtime performance (JVM is great) or bunches of stable packages? Sure.
Are some going to be pigeonholed into working with horrible legacy projects that are absolutely demotivating and show off the worst of the language? Sadly, also yes.
Are others going to look in the direction of something like Kotlin, which attempts to solve some of its nuisances, or maybe other languages altogether? Also yes.
But at the end of the day, a lot of it comes down to familiarity: if you feel like you'll be more productive in .NET, Node, Ruby, Python or another language, and there aren't external external factors that force your hand in a particular direction, pick whatever fits your needs the best.Java could be a much nicer language with much less allowance for architectural space programs.
Type classes were introduced into Haskell as early as 1988-1989. At 1991 you could have programming in language with parametric polymorphism, type inference and principled (albeit called ad-hoc) overloading, there was at least one.
The ST monad, one of the first effect-containing abstractions, was introduced as early as 1992 - I think it was close to introduction of IO monad.
So, at the time Java was introduced in 1995, it could have all these nice properties which greatly simplify programming and make architectures easier to understand and more future-proof (Haskell's solution to an Expression Problem [1] is one of the simplest, it uses what was available in 1995, more or less).
[1] https://en.wikipedia.org/wiki/Expression_problem
Thus, we could have a programming language that makes architecture rocket launch much harder. But we did not.
The slogan was "write once, run anywhere" without any regards on how much is needed to be written or how to safely compose what is written.
These feature flags are not "architecture space odyssey," though. Usually they reduce boilerplate, often significantly.
They are also artifact of Haskell being "research language," as mentioned in video above.
To be fair, there has been some effort to ease the insanity. Record classes, lambdas, and the like lessen the pain of trying to write Java against its original orthodoxy. But before that, a simple "sort list of lists by first value" method involved making a class available in the current scope that implemented Comparator<List<X>> which contains a method "compare".
As opposed to "sortby (comparing fst) list_o_lists"
There was no Java when GoF book came out, CORBA and DCOM were used all over the place, SOAP was initially driven by Microsoft and its COM/.NET group (see Don Box), when enterprise architects get FP into the enterprise, scalaz happens.
Ruby is a flawed language (I especially dislike the lack of real namespaces) but the hate it gets is often not based in reality.
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.
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.
a particular era of hipster web and app
development, ~2007-2010. I don't know why
but it's not quite attractive.
That was a really fun era.~1997-2007 was fun but it was a mess. It seemed like every project was its own bespoke "framework" and everything was a Java or PHP spaghetti monstrosity.
2007-2014 was the era when "majestic monolith" MVC frameworks with a strong emphasis on automated tests really began to coalesce. Rails led the way here, I think. It was a brief island of sanity if you ask me. MVC may not be perfect but it's a fine choice most of the time for anything CRUD.
I suppose there was kind of a "hipster" aesthetic around Ruby/Rails (Ruby devs kind of prided themselves on being quirky or whatever, as opposed to staid corporate Java drones, I guess?) but I did not find it to really be a factor.
2015-present has been a nightmare. Nearly every web application is now two apps: front and back-end. For apps with highly interactive UIs this is an obvious win but for the vast majority of web applications it has been a disaster. User-facing performance of the modern web is awful and I have never felt less productive as a developer. Every developer thinks they need to do things "like Amazon" or "like Facebook" and just.... no. The Javascript community has absolutely lost all connection with sanity and the era of the full-stack developer is over.
First of all, regardless of what everyone says regarding how "inovative" Rails was, Tcl and Python did it first, with AOLServer and Zope.
During the .com wave, I was part of a startup with a product for CMS development, that was basically inspired from AOLServer, although we did our own thing.
It supported Windows 2000/NT, Aix, HP-UX, Solaris, Linux (only for dev purposes), SQL Server (Sybase and Microsft variants), Informix, Oracle, Access (only as demo concept), and we were in the process of adding DB 2 support as well.
We went down in the .com crash, and Lisbon isn't SV, so hardly anyone heard of us, but it doesn't change the fact we were already better than Rails v1.0 in 1999.
Second, I know Python since version 1.6, so Ruby hardly brings anything other to the party than a Smalltalk inspired workflow, without the IDE experience.
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.
You should not worry about what top-level comments are.
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.
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.
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.
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.
"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."
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.
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.
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.
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().
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".const makes the binding immutable but not the object. Object.freeze makes the object immutable but not it’s children.
The same argument doesn't apply to Data's shallow immutability. It will give you errors when mutating at least some of the fields. If your code can catch you mutating a number, then you can notice the bug and be reminded to make deep copies etc. It's an improvement, just like Object.freeze.
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).
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.
We do find such horrors lurking in the bowels of Rails, unsurprisingly. ActiveSupport clamps on to several fundamental modules, but Rails only inflicts the worst of its metaprogramming gymnastics either upon itself, or client objects/classes that expect a ton of magic (viz. models, controllers, views). When peeking at some of the machinery I'm sometimes unsure whether to be appalled or astounded.
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.
- https://ruby-doc.org/core-3.1.1/Object.html#method-i-freeze - https://www.rubyguides.com/2016/01/ruby-mutability/
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.
> (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.
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)
Though, to be honest, rather than an "instructive" error message... I sort of wish the language syntax itself forbade that space and simply forced you to write `foo.bar= 123` instead of `foo.bar = 123`.
I wonder if Matz himself has ever second guessed that choice he made in the 90s? =)
This syntactic sugar is definitely a bit weird, but it seems necessary in the "everything is an object" design, and to simultaneously meet Ruby's prime directive of maximizing developer happiness.
Can you imagine the howling from the haters if `x = 1` was a syntax error?
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.
What matters isn't "is" but "can act like".
IMO the root issue is the language syntax allows you to write `foo.bar = 123` instead of `foo.bar= 123` which kind of obscures the fact that `bar=` is a method.
If you've never written Ruby I 100% agree that the NoMethodError is perhaps confusing. However as others have noted this is just a really simple core concept you learn right away! This is your standard "oops, I called something that doesn't exist" message and contains everything you need to see where you went wrong.
99% of the time that message is all you need; for the other 1% you can use a debugger to pause things and see e.g. what methods `foo` does support.
I was.
Yes. This is extremely conventional/idiomatic Ruby. You'd be likely to come across this pattern not long after Hello World.
(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.But IMO/IME Ruby strikes a good balance here. You can break the rules but it really sticks out like a sore thumb. We avoid these backdoors like the plague.
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?
`#set_table_name` was replaced by `#table_name=` in ActiveRecord, so (especially around the time this changed when you might have projects in older and newer versions) it would be a likely mistake to make. I'm reasonably certain this is not the only case where a setter existed without `=` as part of the name where later library updates changed it to one with `=` (or the other way around).
My point is that would be different, and as a rule, different is surprising and surprising is wrong.
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.
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.
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.
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)
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.
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