104 points · by todsacerdoti · 3y ago · 125 comments
“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 thingsto
stand
OUT!
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.I mean, I agree that that's true at least in relative terms, but in my experience that's because it raises the floor from "bottomless pit" (eg IOCCC entry quality) to "much worse than we usually do", whereas lowering the ceiling a proverbial meter or two still means hitting my head on it (there's a upper bound on how readable code can be when you need to actually read it).
You can't code taste into every tool that might want to help you edit your source code.
That being said, almost all formatters have ways to tell them to go away in especially important stretches of code, with the tradeoff being ugly generated code fixups for that need hand massaging every time.
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.
Doesn't that already look 100x better?
class UserCreator
def create_user(email)
user = create_user_object(email)
assign_admin_role(user)
assign_invite_permission(user)
call_invite_template(user)
end
private
def create_user_object(email)
User.create(email)
end
def assign_admin_role(user)
user.roles << find_admin_role
end
def assign_invite_permission(user)
user.permissions << find_invite_permission
end
def call_invite_template(user)
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 def create_user(email)
user = User.create(email: email)
user.roles << Roles.find_by(name: 'admin')
user.permissions << Permissions.find_by(name: 'invite')
Templates.find_by(name: 'invite').call(user: user)
end
IMO this 4 line function is significantly better in terms of clarity, readability, and it avoids unnecessary state. Testability and encapsulation are the same.(I would argue that the encapsulation is better with a function, since encapsulation is way too easy to break in Ruby, but hey, that's me)
It provides some very marginal improvement, but doesn't address the actual problem of the code, which is the horrific verbosity. The use of attributes is the least of my problem with it. This is how I'd want it to look:
class UserCreator
# Arguably, I'd prefer *call* because that allows it to be interchangeable with a lambda
# But frankly this thing could *be* a lambda. E.g. you could replace the above class declaration
# with "UserCreator = ->(email) do" and ditch the "def"
# The exception, where I'd allow for an initialize and attributes would be in cases where you'd otherwise
# be passing a *lot* of *the same* state around between multiple methods
#
def self.create_user(email)
User.create(email).tap do |user|
user.roles << Roles.find_by(name: 'admin')
user.permissions << Permissions.find_by(name: 'invite')
Templates.find_by(name: 'invite').call(user: user)
end
end
end
The whole service object pattern is heavily abused by people who don't seem to understand which (limited) situations it actually provides benefits. This isn't one of them.I kinda like the Clean Code advice of small functions/methods, but they should pack a punch, not just encapsulate barely more than their own name.
E.g. here's a single-line method from the Window class of my Ruby X11 window manager:
def type = (@type ||= get_property(:_NET_WM_WINDOW_TYPE, :atom)&.value.to_i)
This does one thing: It queries the X server for the _NET_WM_WINDOW_TYPE atom attached to this window, and if a value is returned, it ensures the result is an integer (which will be 0 if what is returned is nil or somehow can't be parsed into an int, which would mean someone has been very naughty but defaulting to 0 is fine). It then ensures the value is memoised in `@type` (not doing more error checking here is fine, because failing is worse than defaulting to not knowing the window type, as we have no guarantee it's set in the first place)Tiny functions like that are fine, because they encapsulate a sufficient amount of non-obvious logic in a very concise result. Being able to write `my_window.type` without caring about that logic is great. Trying to reduce your methods to compact little methods is great when it makes you write little functions that tells you a lot.
Unfortunately - and so I agree with your reaction to Clean Code - adhering to the rest of the Clean Code advice won't leave you with a bunch of little methods that pack a punch and remove a bunch of complexity, but a bunch of little methods that each encapsulate barely more than their method names worth of complexity.
So dreadful.
If the functions are well named, you can read up to the "private" line and stop reading. You now know what this thing does, and you've not had to complicate your thought about HOW it does it. If you need to know how one of the primary actions is performed, you can jump to that source with a simple keypress. With some settings, you can simply hover to see the function expanded.
What's more, writing tests - 100% coverage - for this example is trivial and clean. If you want to put the actual lines all in the main function, your tests will be a lot uglier and will involve more lines of test code.
The unnecessary branching makes me need to keep an eye on the stack, and a lot of extra information in my head.
The additional state (in this case @email and @user) needs to be tracked from a distance. Local variables are 100x better. If there's any mutation, I must watch out during debugging two or three levels deep. Often there are more variables than that. If I had the "role" and the "permission" as a parameter, I would need two extra instance variables. With a regular function this is just two arguments, a couple lines away from the usage site.
The original code I wrote into ChatGPT to generate the code above shows me the what and the how with much more clarity:
def create_user(email)
user = User.create(email)
user.roles << Roles.find_by(name: 'admin')
user.permissions << Permissions.find_by(name: 'invite')
Templates.find_by(name: 'invite').call(user: user)
endThe point of this pattern is to extract each operation into its own described-by-name method because they're each longer and more complicated than just a `<<` operator or whatever.
(Edit to add: another way of justifying the above service design pattern is to suggest that the code is DRY because you’ve extracted common sections to methods. This is taking DRY to an illogical extreme. You _should_ repeat yourself if your method calls are simple enough, and if you actually do need to repeat some logic in multiple places requiring a private method, you might find a better place to put it - for example, a filter method.)
Oftentimes when I suggest to change a rubocop default it leads to epic arguments as if you’re desecrating the bible. In fact, it’s just silly to not apply critical thinking to the quality of your toolchain, and that includes questioning the decisions of your linter’s maintainers.
A simple 4-line function instead of the 6-7 methods allows for the same functionality, the same level of encapsulation and for the same testability, without the “jumping around”.
Here's the original text I inputted into ChatGPT that generated the code above:
def create_user(email)
user = User.create(email)
user.roles << Roles.find_by(name: 'admin')
user.permissions << Permissions.find_by(name: 'invite')
Templates.find_by(name: 'invite').call(user: user)
end
Pretty much anyone writing this kind of class would be able to understand the same code if it were written in a 4-line function in one glance. This here, however severely obscures the intent, the code flow and the operations. fun double(x: Int) = x * 2
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()...`
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).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?
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?
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.
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.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.
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; 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.
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?
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.
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.
Nobody forces you to use them. I for one is extremely happy with most of the changes in recent years.
“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.
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.
int AddOne(int x) => x + 1;
or
void SetXToZero() => x = 0;
// 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 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.
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.
> return [] if denied?
So strikingly simple and expressive, I miss that :)
Amusing in the sense of aaah good old Ruby still having the same development style that made me stop using it long ago.
What do you mean here?
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.
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.
Somehow I always seem to find the ruby projects where everything stopped being supported years before.
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(' ')
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.
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.
def foo(s) s.upcase * 3 end
foo "Hey" # => "HEYHEYHEY"
No ; and no => 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 `;`.
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.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 ...
endIt's surprising for me to hear this, because IMO, Ruby is among the most aesthetically pleasing programming languages.
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.