24 ms·
"Useless Ruby sugar": Endless (one-line) methods
- polygamous_bat 3y agoAm I the only one whose soul hurts looking at this syntax? Not a ruby user, but as soon as I saw the use of = to define the function body I immediately thought of all the ambiguous statements one could write with that. And voila, the whole irks and quirks section validated those fears. Please explain to this ruby noob if you have time, why use =? Why not some other less used symbol or symbol pair instead? What are they trying to achieve with this?
- stouset 3y agoI’ve been using Ruby professionally for 15 years, and have a deep love for the language. This entire syntax was unnecessary, undesired, and is flat-out a mistake. I’ve felt this way about most of the syntax changes since 2.0, with the exception of named parameters.
- progne 3y agoJust 12 years full time with Ruby here, I'm a noob. But when I see that I could replace def initialize(text) @text = text end def inspect "#<#{self.class} #{text}>" end def ==(other) other.is_a?(Word) && text == other.text end with def initialize(text) = @text = text def inspect = "#<#{self.class} #{text}>" def ==(other) = other.is_a?(Word) && text == other.text I start drooling a little. That's 3 lines to replace 11. We have a soft limit on class length of 100 lines, and I like the extra conciseness this allows. You can also do it like define_method(:inspect) { |text| "#<#{self.class} #{text}>" } and we do that in some places, but that extra verbosity makes for more lines.
- Pxtl 3y agoI feel like I'd still want the body on its own line from the signature definition just for readability. And with the parser problems described in TFA, I'd say that parens should be mandatory coding-style enforced by linter. def initialize(text) = (@text = text) def inspect = ("#<#{self.class} #{text}>") def ==(other) = (other.is_a?(Word) && text == other.text) seems like a good compromise. edit: this is similar to our standard when writing one-liner methods in C#. A bit noisier because of types and visibility, but still pretty concise, imho. public void Initialize(string text) => Text = text; // I actually hate the above a bit because "=>" // originally implied functional/no-side-effects // in C#, but the world moves on. public string Inspect() => $"{this.GetType().Name} {text}>"; public static bool operator== (Word a, Word b) => a.Text == b.Text;
- vidarh 3y agoPersonally I'd never let your first example through a code review. If you're going to break it up, use end. Where the one line format makes sense is when the body is trivial and often when there are multiple related methods that can be lined up to highlight their similarities and differences in the single line format.
- Pxtl 3y agoHah, I'm a firm "no alignment allowed, indent only" reviewer, so that use case would never even occur to me.
- vidarh 3y agoI can't stand that. It dramatically reduces code readability to me.
- Pxtl 3y agoI tend to agree with Google on this one: https://google.github.io/styleguide/jsguide.html#formatting-horizontal-alignment https://google.github.io/styleguide/jsguide.html#formatting-... > Terminology Note: Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines. > > This practice is permitted, but it is generally discouraged by Google Style. It is not even required to maintain horizontal alignment in places where it was already used. > > Here is an example without alignment, followed by one with alignment. Both are allowed, but the latter is discouraged: { tiny: 42, // this is great longer: 435, // this too }; { tiny: 42, // permitted, but future edits longer: 435, // may leave it unaligned }; > Tip: Alignment can aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings. That one-line change now has a "blast radius." This can at worst result in pointless busywork, but at best it still corrupts version history information, slows down reviewers and exacerbates merge conflicts.
- mschuster91 3y ago> We have a soft limit on class length of 100 lines, and I like the extra conciseness this allows. The "compact" line format is something that is very information dense and really really hard to parse for a human's eye, compared to the clearly visually structured prior format. Personally, if I'd see something like that outside of a code golf tournament, I'd run because that kind of code density means that at least one of the developer(s) believes themselves to be some kind of code wizard who loves Matrix-style display, and it means that new developers have a very steep learning curve ahead of them.
- kbenson 3y agoWhat can be good, but requires discipline, is to replace some of the syntax that's no longer needed with a comment to help explain the what and why and goal. You reduce or eliminate the line savings, but overall may increase the information and understanding of intent. I do this commonly in the Perl I write. If I'm using a complex set of maps and greps to reorganize a structure, doing that inline can be useful to the developer because it can match mental state, but the later reader may be somewhat lost when seeing it depending on how much of the data state they've internalized. A nice comment to explain the intent is useful, and when you're already saving space by eliding syntax, keep a good ratio of action to code on the screen (which is really what we're optimizing for here most times anyway, right?)
- stouset 3y agoUnnecessarily cramming more density into one line to avoid soft limits seems like a poor tradeoff. Ask any typesetter. Blank space used well gives text breathing room, making it easier to parse visually. In the former example, it is extremely easy to pick out what each method name is and a decent idea of what it does at a glance. In the latter, I have to read to even see the method names.
- kazinator 3y agoAsk a typesetter? No thank you. What is a typesetter? Someone or something which takes tree-structured sentences, cranks them into a linear sequence of words, which is arbitrarily chopped into a rectangular form, with the goal being that the rectangle appear evenly gray from a distance. Sometimes ugly hyphens are inserted into the middle of tokens.
- sdf4j 3y ago> We have a soft limit on class length of 100 lines, and I like the extra conciseness this allows I'd recommend your team to stop code-golfing... Even better: with this new syntax you MUST reduce the soft limit to around 50 lines per class, right?
- progne 3y agoI agree that it shouldn't be used for anything complex, even if it reduces to one line. But I do like it for simple things. Maybe it's staring at very similar code all day, but such short statements read fluently for me. And even if an extra line of separation is used, it's still 6 lines instead of 11.
- jlarocco 3y agoSeems counter productive to me. The first snippet is much easier to read, and using this technique to get around your 100 line rules seems to be missing the point of the rule - or purposely subverting it.
- kazinator 3y agoTXR Lisp: 1> (defstruct (word text) () text (:method print (me stream pretty-p) (put-string `#<@(typeof me) @{me.text}>` stream)) (:method equal (me) me.text)) #<struct-type word> 2> (new (word "abc")) #<word abc> 3> (equal *2 "abc") t You wouldn't define a print method for a struct like this, because it's counterproductive. You're throwing away print-read consistency in exchange for no benefit. I usually define print methods for complex structures with many slots, that are not expected to be externalized. Particularly if they are linked in a graph structure, where (even if you have the circular printing turned on to handle the cycles) the prints get large. You know, you wanted to just print the banana, but it was pointing to a gorilla, and basically a dump of the whole jungle ensued.
- vidarh 3y agoYou wouldn't define an `inspect` method for this simple example in Ruby either, because Ruby provides a default inspect that'd do just fine in this example. The exact same tradeoff for when to define inspect as for when you'd define print methods exist. In other words, that wasn't the point.
- vidarh 3y ago19 years here, and my terminal, editor, file manager and X window manager are all pure Ruby so as you can tell I love Ruby a lot, and frankly I love these changes - they've allowed me to reduce the size of my code in ways that makes it clearly more readable. Nobody forces you to use them. I for one is extremely happy with most of the changes in recent years.
- stouset 3y agoI am forced to read them and fix bugs related to the ambiguous syntax parsing. “Nobody forces you to use it” can justify just about any insane addition to a programming language. Nobody forces you to use any of C++’s zillion and one features, but because they exist you have to contend with their consequences even if you try to limit yourself to modern conventions. We didn’t need two ways to define methods, one of which parses insanely in order to save a few keystrokes. Adding this didn’t make the language better, it made it more complicated for virtually zero net gain.
- vidarh 3y agoIf you're not in a team where you're in a position to influence the choices used, this will be far down the list of your problems. My sympathies. We have several more ways to define methods already, and always have. If you think this gives us two perhaps the problem is you don't know the language very well. Choices like this, to create options to adjust how the code reads has always been central to the design of Ruby. It's an odd thing to be annoyed with Ruby over. "Parses insanely" is highly subjective. It parses exactly as you should expect it to if familiar with Ruby. Some of it is not ideal, and will likely be addressed with adjustments to the grammar. In the meantime the simple fix is to add parentheses whenever in doubt.
- stouset 3y ago> We have several more ways to define methods already, and always have. If you think this gives us two perhaps the problem is you don't know the language very well. Resorting to semantic-lawyering doesn’t add to your argument, it detracts from it. You know the point I was making.
- deleted 3y ago[deleted]
- giraffe_lady 3y agoI've never seen this used, it's obscure and seems to be disliked/avoided by most people who do know of it. Flat out against the style guides of a lot of ruby codebases.
- SideburnsOfDoom 3y agoC# has something similar, but uses the existing lambda syntax, with "=>" to the left of the body or expression, e.g. int AddOne(int x) => x + 1; or void SetXToZero() => x = 0;
- polygamous_bat 3y agoExactly what I am talking about when I say use some other unambiguous token. = is so incredibly overused in a programming language, why give it even more jobs?
- Pxtl 3y agoimho the "def" keyword saves it from being too ambiguous, since it's clearly defining a function/method. def [functionname] = [body] seems fine to me. The big flaw (that it can't tell the difference between the end of the body and the end of the statement line) would be the same with any token, I think. From what I'm seeing, though, they should've made parentheses mandatory around [body] until they could fix the parser problem. They could easily make them optional in some hypothetical future where they've corrected the issue. That said, it seems like C# wins at solving this problem, where the `=>` syntax is used for both lambdas and one-liner functions.
- deleted 3y ago[deleted]
- Someone 3y agoNot a Ruby user, I expect it is because they want as few implementation details as possible to seep into the syntax. If you’re thinking functional, everything looks like a function. Examples (pseudocode that may be valid Ruby) x = 3 def x = 3 def x() return 3 end all define a parameterless function called that always returns 3. So why would you use different syntax for them? There’s only one reason: impure functions. For these 3: x = rand() def x = rand() def x() return rand() end The first would call rand() once, the other two each time they get called. That, I expect, is why Ruby still has def. In scala, there’s similar thinking, which also let to them using () not only for specifying function arguments, but also for indexing into arrays or dictionaries. After all, an immutable array x = [10,20,30] behaves the same as def x(i) switch i case 0 return 10 case 1 return 20 case 2 return 39 otherwise throw indexOutOfBounds end Of course, if you unify notation, you’d also have to make these things perfectly interchangeable everywhere. Not being able or wanting to do that is a good reason for keeping syntax different. Another one is that you may want to expose the pesky detail that indexing into an array typically is a lot faster than calling a function to the programmers, so that they can get a decent idea about the performance of code they read. That can only work if you keep your execution model simple, though, and if your programmers can reasonably predict what the compiler does, and how that will run on the cpu. That worked fine for C in the 1970s, but not so well anymore today. I think Golang is an attempt to get back there.
- ysavir 3y agoThis is my reaction as well. I like the idea of collapsing a simple method into a single line, but the `=` makes it such a weird thing to actually parse. I wonder what prevented them with using a proc-like braces syntax, which would be intuitive for those familiar with the language (and the `def` to set it apart from procs)
- vidarh 3y ago{} is already overloaded for both blocks and Hash literals, both of which commonly occur at the end of the argument lists. It seems like it'd create far more opportunities for making the code hard to read.
- kagakuninja 3y agoNot a Ruby guy, but Scala uses that syntax for all method declarations: // type annotations are optional, if the compiler can infer them def foo = 42 def bar(x: Int): String = { // stuff } It works fine IMO. Scala 3 introduced Python-style syntax, in which {} is optional: def bar(x: Int): String = // stuff end bar // end is optional
- lolc 3y agoIt's amusing how they released it without nailing the arity first. Amusing in the sense of aaah good old Ruby still having the same development style that made me stop using it long ago.
- mcphage 3y ago> without nailing the arity first What do you mean here?
- lolc 3y agoSorry I was short. I mean operator precedence was not considered. In the first implementation, 'def =' has higher precedence than 'if'. Which leads to surprising behaviour with tailing ifs. The if is evaluated to determine whether the method should be defined, instead of being part of the expression. The fact that they released this and are now considering a change in precedence is a showcase of the haphazard development of the lang. If the feature were useful, somebody could have tried using it and noticed the issue before they released it. But it's just a clever hack that adds another way how methods can be written. Nobody sane will use it, but the golfers cheer it into the release.
- PH95VuimJjqBqy 3y agoI can't speak for ruby development, but I can tell you literally every RoR project I've ever taken on has me losing even more respect for the community as a whole. Somehow I always seem to find the ruby projects where everything stopped being supported years before.
- vidarh 3y ago"def =" isn't operator. It doesn't have a precedence. "=" is an operator, and has a precedence, and in ruby "def some_method ... if something" is an entirely valid expression, and not one you can arbitrarily ban for all def expressions because it is occasionally used (not a fan of using a trailing if here, it's rarely obvious). It's not haphazard. It was an intentional tradeoff knowing that introducing new rules into the parser that would address this would delay introducing the feature, and that it might make sense to defer changing it until the currently ongoing process of replacing the parser is complete, and deciding that it was useful enough this way in the meantime. That there are corner cases was well-known before it was released. If you're going to criticise how this was handled, at least understand the issue before you jump to conclusions. It's perfectly fine to disagree with the tradeoff, but that tradeoff was intentional.
- frou_dh 3y agoThe following already worked in Ruby for single-line method definitions: def foo(s) s.upcase * 3 end foo "Hey" # => "HEYHEYHEY" No ; and no =
- lcnPylGDnU4H9OF 3y agoI'm not sure when the author added their update but they responded to this point: > What can I say! Once in a while, I forget how to Ruby :) This does not make the argument invalid (this way of writing methods is still frowned upon and never used; and still, reads like “several phrases”), but it probably should’ve been centered around the community’s view at `;`.
- stouset 3y agoIntroducing new, ambiguously-parsed syntax to avoid an “ugly” semicolon or a bare `end` for code-golfing purposes is an extremely poor trade.
- lcnPylGDnU4H9OF 3y agoI don't disagree, per se, but I think the point is stated too strongly. Linting rules can help to enforce careful use of this syntax even on team projects. The ambiguity can be avoided or explicitly removed as demonstrated with the parentheses around the expressions. It's just another syntax option for defining a method of appropriate simplicity. Ruby already allows for some heinous things: class Foo private # Not actually private def self.bar 'bat' end end define_method(:".38 Special, the band?") { name == '.38 Special' } Be smart about how you use it. A knife manufacturer ships sharp blades despite the possibility that a chef might cut themself with it.
- trealira 3y ago> A knife manufacturer ships sharp blades despite the possibility that a chef might cut themselves with it. This is usually said about necessary but dangerous or easily abusable features, like the use of raw pointers, C++ templates, or global mutable state. I would say that adding potentially confusing syntactic sugar to a programming language is more like adding a feature to a Swiss army knife that is redundant and makes it unnecessarily more complex to use.
- lgkk 3y agoI have always struggled with languages like ruby. def something do end. Swift JS Go Java etc just feel a lot easier for me to read if that makes sense. Not sure why. I’ve worked with ruby in the past, but never liked the syntax. Same with python.
- owlstuffing 3y agoAgreed. It’s not like readability is purely subjective either. Ruby and to a bit lesser extent Kotlin sacrifice readability for conciseness, which in my view is a terrible trade-off. We read code much more often than we write it. Conciseness is great if it’s reducing boilerplate. But when it hides type information and linkage, it tends to obfuscate more than clarify.
- vidarh 3y agoThat's funny, because to me what I love about Ruby is above all that it is the easiest to read language I have worked with, of several dozen.
- oglop 3y agoI like Ruby for my own projects because of how descriptive it is for when i come back to code later and need to understand what i did, and it requires possibly the fewest keystrokes of any modern language, which is a plus for my RSI hands. But, for large projects I've learned I don't care for it. Not unless the project, and team working on the project, follow guidelines and conventions. Otherwise it will devolve into a mess, guaranteed. And too many rubyist are hesitant to simply use rubocop to enforce this at a PR or something similar. It's like most of them forgot about `rake` and just having a formatting or linting task. But i digress. I like all these changes, but it's just me (i wouldn't use them on an actual open source project yet). So Matz is right to know the `end` may end ruby (seriously, my students just _hate_ it) but i'm more curious to see if the community will agree and follow along. Also, endwise is a great extension to abstract away most those `end`s being typed anyway.
- t0mek 3y agoThis is similar to Kotlin single-expression functions, which are actually pretty useful: fun double(x: Int) = x * 2 https://kotlinlang.org/docs/functions.html#single-expression-functions https://kotlinlang.org/docs/functions.html#single-expression... However, in Kotlin there's no single-line constraint, so it's possible to define an expression function e.g. with a long chain of collection methods: `filter().map().findFirst()...`
- dragonwriter 3y agoThere's no single line constraint in Ruby, either, as the article mentions; its a single expression, as in Kotlin, not a single line.
- adamgordonbell 3y agoYeah, I'm a fan of this. Was a bit of fun in scala to see if you could rewrite something to be a single statement. Sometimes the single statement version wasn't clearer, but sometimes it really was. Point free programming takes this to code golf type territory and can be fun as a puzzle if not for real world code. Maybe ruby just doesn't do it well?
- MrBuddyCasino 3y agoOne of my least favourite Kotlin features. Breaks the uniformity of method declarations for minuscule gains, making it harder to visually parse a class body quickly.
- marcellus23 3y agoI don't really understand what makes that better than something like (from e.g. Swift): func double(x: Int) -> Int { x * 2 } It just seems less readable because it's introducing not only an additional syntax for declaring functions, but also a secondary meaning for the "=" operator. edit: in my original version of this comment I forgot to add the return type syntax, "-> Int", which Swift needs. I suppose eliding the return type is a bit more terse. You could also assign a closure in Swift to avoid that, like: let double = { (x: Int) in x * 2 } which is about as short as the Kotlin version, and has the advantage of not being "special" in any sense from any other Swift syntax (i.e., it's just assigning a standard closure to a variable).
- mvdtnz 3y agoHideous language, just hideous.
- trealira 3y agoHideous? Why? Are the "do ... end" blocks really that bad? It's surprising for me to hear this, because IMO, Ruby is among the most aesthetically pleasing programming languages.
- mvdtnz 3y agoIn this case, hideous because of the overloading of =. But in general it's just an ugly inconsistent mess of a language. It can't decide if it's supposed to be expressive and read like English (begin, end, rescue, unless, etc) or needlessly terse by omitting random vowels (elsif, strftime, uniq). And then there's the utter mess that large codebases get into with metaprogramming.
- trealira 3y agoThose are fair critiques. Thanks for the response.
- trevor-e 3y agoFor my brain it's an incredible amount of noise to parse through compared to {}. Especially in addition to the amount of things you have to keep in your head since there is no typing to rely on.
- vidarh 3y agoTo me the incessant {} adds an incredible amount of noise. And I don't think I ever go around worry about types. If the typing isn't obvious, then that's a big warning sign to me about how the code is structured.
- whstl 3y agoMy problem with Ruby is not so much the syntax. I kinda like this one-line-function feature, and I enjoyed it when using in C#. My problem is the fact Ruby practitioners have a tendency ABUSE the usage of one-line-methods with LOTS of side-effects. So it's not like Haskell one-line-methods. Things that could be a function with 5 or 6 lines can become a class with as many methods. And instead of local variables, you now have to use instance variables (class fields). For example, this is common in lots of codebases: class UserCreator def initialize(email) @email = email end def create_user create_user_object assign_admin_role assign_invite_permission call_invite_template end private attr_reader :email, :user def create_user_object @user = User.create(email) end def assign_admin_role user.roles << find_admin_role end def assign_invite_permission user.permissions << find_invite_permission end def call_invite_template find_invite_template.call(user: user) end def find_admin_role Roles.find_by(name: 'admin') end def find_invite_permission Permissions.find_by(name: 'invite') end def find_invite_template Templates.find_by(name: 'invite') end end Sorry but this is not readable nor reasonable. I encountered this in about 4 companies so far. Only one Ruby company I worked didn't do it. That was the company that actually had a very maintanable backend.
- ht85 3y agoI call it "assembly ruby", where registers start with "@" and opcodes are defined with "def". So dreadful.
- cratermoon 3y agohttps://thomascothran.tech/2023/11/readability/ https://thomascothran.tech/2023/11/readability/
- JasserInicide 3y agoWhat is wrong with this example exactly? This is what you want in a service object.
- 3y ago
- eurekin 3y agoHaven't worked in ruby in years, but reading it just feels nice: > return [] if denied? So strikingly simple and expressive, I miss that :)
- lemper 3y agoin the ruby's ticket page that is linked in the article, one guy (who seems to be a respectable gentleman, I must add), this feature adds more cognitive load, requires all ides to support this syntax, and encouraging less readable code. coming from other programming language, I don't think that this feature is adding more cognitive load. especially when I believe any Ruby off Rails developer is also write js code. nor I do believe that it encourages less readable code, even though I don't deep dive into ruby's traditions, I believe stupid long one liners are the enemy of "happy developers".
- Lammy 3y agoI don't think "one line" should get associated with endless methods. I really love endless methods for any situation where the first statement in my method is also intended to be the return value. It lets me avoid my most hated pattern, where you instantiate a thing with a temporary variable, do some stuff to it, and then return the instantiated object with a hanging call to the temporary variable. I've always found it very ugly and also fragile if the order of operations gets mixed up by later edits. This pattern: def do_the_thing(with_me) thing = MyThing.new thing.do_something_that_does_not_return_self(with_me) thing end I also love to use it to avoid "double ends" for methods consisting entirely of control-flow statements: def do_the_thing(with_me) case with_me when rofl then ... when lol then ... when lmao then ... else ... end end With endless methods I would write these two examples as: def do_the_thing(with_me) = MyThing.new.tap { _1.do_something_that_doesnt_return_self(with_me) } def do_the_thing(with_me) = case with_me when rofl then ... when lol then ... when lmao then ... else ... end
- hoosieree 3y ago“how much of it fits in one page” matters. This doesn’t mean that cramming everything into tight subsequent paragraphs, like a serious book, is a good idea: code isn’t supposed to be primarily read paragraph-by-paragraph. On the other hand, a two-words-per-line, twenty-words-per-page nursery rhyme-like layout means that one might need to scroll through dozens of pages to get “what’s this all about.” I disagree that code is "supposed to" be any particular way, but in general I agree with this point. And I think it's gradually being forgotten. Automatic code formatters and mandatory style guides are becoming more common, and while they do raise the floor (by preventing some interpretation of "bad" style) they also lower the ceiling. Uniformity isn't bad, but sometimes you really need certain things to stand OUT!
- mhink 3y agoThis is my biggest gripe with the widespread use of Prettier over in JS/TS land, especially when using React. It always seems to introduce *more* formatting inconsistency because it's only looking at line length to decide when to format. So in the same block of code I'll have things like: const foo = useMemo(() => { // code }, [ alfa, bravo, charlie, ]); const bar = useMemo(() => { // code }, [delta, echo]); const quux = useCallback( (arg0: string, arg1: number): SomeType => { // code }, [foxtrot, golf, hotel] ); Which is infurating because it's not visually consistent so the code starts to look like syntactic soup. It's the same thing with components, really.
- kevincox 3y agoThis is also my main gripe with automatic formatting. Since they don't really understand the code they almost all work based on number of characters in a line. However I really don't care about characters in a line (except for at the extremes). What is much more important is how many ideas are in the line. If I have an array with 3 very interesting elements I don't want them on the same line even if they happen to be quite short.
- JohnFen 3y ago
- michaelteter 3y agoMany people still argue that loops are more readable than collection operations ("comprehensions" in Python). And many of us here, myself included, would argue that there are plenty of perfect cases for 1-line collection operations (such as each/map etc.) Any langauge feature can be used well or poorly, so singling out some of these newer language features - just to show bad use cases - is kind of misleading. It would be better to stop using intentionally inflammatory words like "useless" and instead show "when to use". The one-line "endless" functions are perfect for actual functions that fit on one line without additional punctuation. For example, custom string manipulation utility functions read like documentation. def string_of_tags(tags) = tags.join(', ') def fullname(person) = [person.first_name, person.last_name].join(' ')