(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.)
The amount of code I see where people preemptively extract methods and even add methods they don't use to prepare for a hypothetical future situation that never comes is staggering.
I think some of these methods might be ok in a public helper class ("go here if you want to know the correct way of finding these kinds of objects so we have a single extension point"), but not as private methods...
The irony here is they try to let you read the main codepath top down, but because they unnecessarily obscure details they force you to jump back and forth between a ton of methods instead, completely ruining any benefit.
I love code that lets you actually read it sequentially, but then it needs to actually let you do that.
What does YAGNI even mean if it can stand in opposition of DRY? If it just means "you don't need to do that," and "that" can mean whatever you want, then it's not a useful guiding principle.
Example of a YAGNI violation: You're writing a piece of code whose purpose is to download some kind of asset for whatever thingamajigga you're working on. It just needs to HTTP GET the resource from your official server. To future-proof it, you also add support for using any of the HTTP verbs as well as adding custom request headers. Not only have you written useless code that will likely never be needed, you've leaked implementation details (all these HTTP details don't make sense if a future version wants to use a different protocol).
Example of what is not a YAGNI violation: Your asset downloader also needs to parse some sidechannel information that the server returns as custom response headers. You just assume that header names are capitalized the way your server sends them and don't bother with case-insensitivity. That isn't following "YAGNI," that's leaving a ticking time bomb behind.
YAGNI is about functionality, DRY is about structure.
def find_admin_role
Roles.find_by(name: 'admin')
end
Assuming your application consistently uses `name`, and is consistent about class names, `find_admin_role` is not saving you complexity over Roles.find_by(name: 'admin'). People familiar with Ruby ORMs and tasked with finding an admin role will go looking for finders in the Role class. They're not likely to find your method, and so are likely to write their own.The former introduces complexity that is only warranted to me if 1) the method of finding the admin role grows more complex so it's non-obvious, 2) the method you DRY it up into is actually being used at least twice, 3) it's placed in the most appropriate class.
And it's that second where YAGNI comes in. By all means, DRY up logic. But don't do it before it actually stops you repeating yourself in a way that is actually significant.
To #3, that "find_admin_role" method really should be `Roles.find_admin` if it's allowed to exist at all - there it's at least somewhat defensible even if it is only a single line method, because others are likely to find it there, and even if it seems relatively redundant, at least there it serves to document that this is indeed the canonical name for an admin role.
> YAGNI is about functionality, DRY is about structure.
I absolutely see where you’re coming from and I agree, the reason DRY caught on and YAGNI hasn’t is indeed the vagueness of YAGNI. But I would equally argue that the simplicity of DRY is what gets you in trouble if you over-optimize for DRY regardless of context.
DRY can be about functionality: if you’ve already implemented a feature, even if it’s a library maintained by another team, as long as the tests encourage your use case, you should re-use existing functionality over creating yet another abandoned half-baked attempt at something.
YAGNI, by opposition, might suggest that the effort spent learning the other team’s library and maintaining a connection to what might be brittle code is itself overhead. A similar debate can be found in using an npm library. DRY would argue if you already use the library, keep using it. YAGNI would argue if the library is only used in one place, rip it out for simplicity and replace it, especially if the code is old.
Taken to extremes, DRY is how we end up with a left-pad module on npm while YAGNI is using padStart built-in to modern JS. Likewise taken to extremes, YAGNI may result in missing functionality and unmaintainable spaghetti code, while DRY is one possible approach to taming complexity in codebases. Both are essential principles, neither actually more important than the other.
I agree with JUCS, but it’s even less defined than YAGNI ;-)
An example of DRY would be: You're using libraries "foo" and "baz," and whenever foo::get_bar() returns 1, 2, or 3, you need to call (for your use-case) baz::qux(9), baz::qux(31), or baz::qux(-5), respectively. So you create one function that either handles both calls completely, or at least maps the return value from get_bar to the argument required by qux. The violation of DRY would have switch statements littered throughout the code that all do the same mapping manually.
A build-or-"buy" decision isn't about being DRY or not.
If you want to test all paths on a multi-line function, you have to do a lot of duplication and sometimes a lot more setup for each variation you're trying to test.
But another source of complexity is OOP itself. Mixing code and data is a horrible affliction we have accepted. All we need is some data structure (which can be a rigid class/struct, and then a module of appropriate operations which work on that data structure (or even elements of that structure).
We can have mostly pure functions that are 100% covered by tests... and if we choose appropriate names for these functions it allows us to think in terms of higher level "steps" (each of which we really don't care about how they are implemented).
All that said, we're debating over relatively small differences of approach in Ruby. For a really good time (not), go look at Python codebases. Then some of the people here who are arguing for a single function with 10 lines that just does the full job will find themselves staring at 100 line Python functions and thinking, "we should break this into individual functions" :).
Therefore, there's no difference in terms of "implementation hiding (encapsulation)" between the original 4-line function [0] and the class I presented.
Also, there is no testability differences, unless you break encapsulation in your tests and test private methods directly with things like send(:find_admin_role). As much as this is seen in Ruby, this is not something that would pass a code review.
This class is just 9 methods in a trenchcoat pretending to be that 4-line function.
And in case you think this not a strawman example. I provide a real-world case in another message. [2]
In fact, in Ruby it hides less, because bypassing "private" is trivial, and manipulating an object's instance variables is trivial.
If you care about encapsulation, that makes this approach worse than a single method. If you need to maintain state across invocations (this example doesn't), then capturing local variables with a closure (lambda/proc) provides far tighter encapsulation than a regular object in Ruby.
Whether the contents of do_this_specific_thing() are just one line or 100 lines, that point is that we don't have to know or care. We just know that do_this_specific_thing presumably does what its name says, and we accept that and don't worry about HOW.
When you inline those tiny functions, as the author argues for, now the reader has to recognize what each implementation line means. Of course we might say it's obvious, but it's less consistent and clear than a series of calls to functions which are well-named and take arguments which are well-named.
And as software engineers of any experience, we know that eventually one of those "simple" actions will become more complex due to some new requirements. Then that one line becomes more lines, and then of course it will end up as its own function. Over time, many of those simple steps will become more complex out of necessity, and eventually we'll end up with all those individual private methods (with bigger bodies).
As for maintaining state, I personally argue against any OOP style. All of those action functions can just be functions in an appropriately-named module. They should all take input arguments (the data), and ideally not even mutate the input but rather return a value. That value could be a new version of the input data (can be memory/time expensive, so not always the best choice), or they can be just a data structure of changes.
I'm not a fan of lambdas, however, as they require more human memory to keep track of what's going on in a system.
ActiveRecord is MUCH better at "telling what's going on without telling the how" this than micro-functions.
-
> When you inline those tiny functions, as the author argues for, now the reader has to recognize what each implementation line means.
As a software maintainer, I can understand a simple ActiveRecord query better than find_user_role.
> Of course we might say it's obvious, but it's less consistent and clear than a series of calls to functions which are well-named and take arguments which are well-named.
If the action is obvious, then simply don't turn it into a micro-function. If it's not, then put it into a function of appropriate size.
Consistency is a piss-poor argument for treating everything like a hammer. If you don't start this practice in the first place, you can't even resort to "consistency" to defend it.
-
> And as software engineers of any experience, we know that eventually one of those "simple" actions will become more complex due to some new requirements. Then that one line becomes more lines, and then of course it will end up as its own function. Over time, many of those simple steps will become more complex out of necessity, and eventually we'll end up with all those individual private methods (with bigger bodies).
Nope. That is not true for the general case. In 99% of cases, micro-functions won't get more complicated.
And let’s not touch the maintainer nightmare of having to keep method names up to date with a complete description of what the method does. You might end up with twenty words or needing multiple methods that are no-ops if you ever call a shared library with any amount of complicated functionality. Alternatively, your description of what is done is so high level that it doesn’t actually describe what’s done in a detail sufficient for non-programmers to understand.
I guess where I’m going with this is that it’s like comments that describe what the method does. We’ve all been there when the comments don’t accurately reflect reality, because someone, maybe through automation, changed how the system works and didn’t update the comment.
It’s hard for me to see as much value in this presentation over an IDE that could auto-inline the function bodies and leave a comment above each with the method name.
To me, if someone tried committing that, I'd sit down with them to have a very long discussion about 1) why it will not be accepted into the code base ever, 2) which training steps to go through with them to level them up, because if they keep writing code like that, it'll be a negative effect on the whole team - at a minimum by forcing us to review and reject their code on a regular basis - and you can be 100% certain I would ding a developer on their performance reviews if they kept writing code like this (I would give them a chance to learn not to first, but if they kept it up?)
> When you inline those tiny functions, as the author argues for, now the reader has to recognize what each implementation line means. Of course we might say it's obvious, but it's less consistent and clear than a series of calls to functions which are well-named and take arguments which are well-named.
Each of those are obvious to anyone familiar with Ruby ORMs, while the methods calls are not for the very reason you go on to give:
> And as software engineers of any experience, we know that eventually one of those "simple" actions will become more complex due to some new requirements.
This is exactly why hiding the simple calls in a method is an awful code stink, because it signals there may be more to it than just a single method call, and so to be sure I know what is going on I will need to chase down each method call.
That's fine if the method calls are actually encapsulating complexity. It's not fine when they're hiding simplicity.
When the complexity grows, then you've justified a separate method.
> As for maintaining state, I personally argue against any OOP style. All of those action functions can just be functions in an appropriately-named module. They should all take input arguments (the data), and ideally not even mutate the input but rather return a value. That value could be a new version of the input data (can be memory/time expensive, so not always the best choice), or they can be just a data structure of changes.
Ruby doesn't have functions, only methods of an object. You can pretend a method in a module isn't a method of the module object and doesn't carry state, but it does, and ignoring that means throwing away what makes Ruby powerful. E.g. making use of those abilities makes implementing monads, composition/currying etc. trivial to achieve, and sometimes having that ability is valuable and improves the ability to instrument code for example.
Put another way: If I call SomeNamespace.foo, I don't know from the fact that it looks like a module or class whether it carries state or not, because SomeNamespace is just another object, and as long as you're disciplined about how you use it, that's a good thing.
But whether or not you prefer that is besides the point. The point was that if you need or want your "user creator" to maintain state, in Ruby an object with instance variables leaves the instance variables accessible no matter what you try to do. If you're fine with that (or want that), use a regular class. If you want to prevent any tampering, use a lambda. Either way, if a class has only a single reasonable action to take on it, the method name by convention ought to be `call`. Those were the points I was making about state. You don't need to use it, but it's something to be aware of.
> I'm not a fan of lambdas, however, as they require more human memory to keep track of what's going on in a system.
A lambda in Ruby is just an object of the class Proc representing a closure. It does not inherently contain any more or less state than any other object. However it gives the benefit of being possible to pass to anything that either expects a Proc or expects to be able to `.call` an object, and when used properly that allows for a powerful level of composeability.
And here’s a bonus: the testability is exactly the same in both cases too (unless you’re breaking encapsulation in your tests — another thing that’s awfully common in Rails).
The only difference is the readability. With a 6-line function you have perfectly readable code without jumping around.
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.