9 ms·
My Beef with RuboCop
- red2awn 6y agoI worked at a place with RuboCop as part of the CI, it was a horrible experience. I spent more time fixing lint errors than actual work, and all it does is make my code less readable.
- vishbar 6y agoIs there not an autoformatter available? We use linting as part of our Python workflow and it works pretty well along with black. There's really not much linting work: just write your code, run black, and it's good to go.
- Xylakant 6y agoRubocop can autoformat the code it complains about.
- square_usual 6y agoNot all cops have autoformatters, though, and some formatters can cause breaking changes.
- hrktb 6y agoIf your team as a whole agrees it's less readable you can disable these specific rules. All the project I've seen had specific adjustments to blanket disable some rules (on the top of my head, ` > 0 -> positive?` for instance) and change de defaults of others (e.g. line length) The goal is tailor it to your needs, unlike other linters who have a much more oppiniated and rigid approach on what is supposed to be "right"
- zaphirplane 6y agoOne pass of rubocop with autofocus, commit, push Next time just have autocorrect on Save done
- JohnBooty 6y agoLikewise. In our case, we were permitted to disable Rubocop rules at-will via inline comments, which made it slightly bearable, but still onerous considering how slow our CI was (45+ minutes in many cases for a test run) My preferred method is: 1. As a matter of productivity, all coders are expected to have Rubocop enabled in their editor of choice, for the quickest possible feedback loop. 2. Use HoundCI or equivalent to highlight Rubocop complaints in Github's pull request conversation. Then they may become a matter of discussion. Obviously, this only works if the team is mature enough to avoid bikeshedding. 3. Rubocop failures do not, however, cause a hard failure during CI. 4. Haven't set this up yet, but ideally I'd configure things so that perhaps some egregious Rubocop failures (ie, tabs vs. spaces, SQL injection issues, etc) would cause CI failures. Whereas more subjective style issues would simply be flagged for developer attention/discussion. 5. Pull requests to modify the project's .rubocop.yml are always encouraged. Again, culture/maturity come into play here. I've been on teams that bikeshed this sort of thing to death. My current team does not.
- adverbly 6y agoI found it annoying until I added a git hook and got used to auto correcting. Its low friction for me now, and well worth it imo. If you run into a very large number of linting errors then you might naturally write code in an unidiomatic style, which unfortunately takes a while to adjust to.
- nathan_f77 6y agoYes, RuboCop would be awful if you're only running it as part of the CI build. I've been using RuboCop very heavily for the last few years. I've found it very useful as a solo developer, but it also makes it much easier to work with other developers since we never have to waste time talking about style issues. Here's all the ways I've integrated RuboCop and made it an amazing experience: I use VS Code with the ruby-rubocop extension, and I've enabled the "Format On Save" option. (This uses Prettier for most other file formats.) This would be unbearably slow with vanilla RuboCop, but I get a huge speed boost with rubocop-daemon. (Especially with the bash wrapper script that I wrote [2].) So now every time I save a Ruby file, the file is auto-formatted instantly to correct any warnings. In case it can't automatically fix a warning, I'll still the warning right in my editor, so I can immediately fix it before moving on. The second step is a git hook script in `.git/hooks/commit-msg`. I set this up to run RuboCop for Ruby, plus prettier and eslint for JavaScript. If RuboCop fails with a warning, the script retries with `rubocop -A` to automatically correct any errors. Then I run `git diff` to make sure everything looks good before committing the changes. The final step is to run `rubocop` as part of my CI build, to make sure I didn't miss any warnings (or for any developers who haven't set this up on their machines.) This almost always passes, because the previous two steps usually catch everything first. I disagree with a lot of the default cops, so I just disable lots of them. But I'm pretty happy with my current setup and RuboCop configuration. I totally agree that linters would be awful when you have a very slow feedback loop, and you have to wait anywhere from 10 - 60 minutes before you get a notification for a failed build. But they can be really pleasant experience when the feedback loops are under 100ms and most of the warnings are automatically fixed for you. I now lean on it really heavily, and I've even started to take some shortcuts and save keystrokes, because I know how the auto-formatter will tidy up the code. [1] https://github.com/fohte/rubocop-daemon https://github.com/fohte/rubocop-daemon [2] https://github.com/fohte/rubocop-daemon#more-speed https://github.com/fohte/rubocop-daemon#more-speed
- red2awn 6y agoBut a formatter can only format auto-fixable code right? I meant lints like high cyclomatic complexity, which requires me to extract out functions pointlessly. I was an intern at that time so didn't make a fuss about changing the config.
- adamzapasnik 6y agoI don't get what is the big problem. Just turn off the disturbing Cop. It's a linter not an AI-Linter to know what is expected. I don't even think that this is RuboCop's fault but Ruby's. Because you can write said code in a lot of different ways (like shown in the post).
- masa331 6y agoThe thing that you can write said code in a lot of different ways is not a fault but a feature for which Ruby is loved by many. As can be also seen from the article it lets a programmer to be neatly expressive in various different situations. Now if you personally don't like this feature you should probably use a language which feature is that you can write a thing only in one way and no other.
- rubyist5eva 6y agoExactly - you don't even need to turn it off globally, just add the magic comment and then an explanation for why you are being explicit about returning nil. ezpz
- jldugger 6y ago> I don't even think that this is RuboCop's fault but Ruby's. Because you can write said code in a lot of different ways (like shown in the post). Honestly, the problem is that rubocop was not designed by a community of experts. It started as the opinions of a singular person, one motivated to the point of writing a linter where none existed. As a result, it's heavily opinionated on trivial shit. Yes, you can configure it, but the out-of-box experience is overbearing. I generally prefer https://relaxed.ruby.style https://relaxed.ruby.style which is ... a lot more chill.
- 3pt14159 6y agoI completely disagree. I'm on two separate projects right now. One is a legacy mess of unnecessary if statements where none are required (in Django, but that's not the issue) and the other is one is a Rails project I took over from a reasonable developer. Rubocop is awesome. The -A flag does the right thing and the lint fixes really do make code easier to read. Even the examples in this post make me even more convinced of Rubocop's awesomeness. super if safe?(name, attrs) Seems reasonable to me. If I care about the return value I can check the parent class. The problem with "if statements for readability" is that as the implementation grows so do the if statements. You're pushing state into the program cursor instead of into local variables or data structures. It makes it harder to determine if you have full test coverage and it makes it harder to understand if you've caught every combination.
- paublyrne 6y agoOf no one will ever agree with every choice made by a linter, whether default or customized. I would rather work in a team that agrees to follow some set of conventions than than one in which everyone does things the way they prefer personally. For the examples in the post, by all means discuss as a team and agree to exclude them.
- bhaak 6y agoGood defaults are important. It is more difficult to find an agreement over changing a default than configuring a missing configuration option. Last time I raised a formatting change with our team, I got replies like "the default settings have been agreed with the community"(a blatant lie) or "I wasted enough time in my life discussing formatting" (okay, this guy has to write C# mostly, the standard formatting is already a lost cause there anyway).
- paublyrne 6y agoAgree that can be an issue. Often it's not worth the energy doing that. But without the linter there's a good chance you'll end up discussing the formatting in code review which doesn't really benefit anyone.
- wlll 6y ago> Of no one will ever agree with every choice made by a linter, whether default or customized. This comment comes with the the smell of the idea that there is a right and wrong way to format code, when in fact with, Ruby at least, there's a lot of nuance that can be added in the way the article describes. There are legitimate reasons for expressing the same functionality of code in different ways to express intent, something that Rubocop unfortunately isn't able to judge. > I would rather work in a team that agrees to follow some set of conventions than than one in which everyone does things the way they prefer personally. These aren't the only two options, there is a middle ground, in which you use cops that solve problems that are unambiguous, such as tabs/spaces for initial indentation, which brings me to the next point: > For the examples in the post, by all means discuss as a team and agree to exclude them. My main problem with Rubocop (which is a great tool) is that everything is enabled by default (and this seems to be encouraged) and the tool is overused. To me Rubocop smacks of the classic programmer problem of discovering you can do something, and so applying the solution to all the places the solution can be applied. "Because we can, not because we should".
- detaro 6y agoThe article really should start with the conclusion.
- BeetleB 6y agoIf you think that way, you likely are not part of the intended audience.
- hit8run 6y agoI personally like standardrb (https://github.com/testdouble/standard https://github.com/testdouble/standard). It is a set of sane defaults that I agree with mostly. Standard was also complaining a little but omitting the explicit else branch made it happy. Anyways you can customize RuboCop to your likings, use standardrb that comes with a lot of carefully considered defaults and uses RuboCop under the hood or don't use a linter at all and move on with your life.
- robotmay 6y agoWe use rubocop heavily at GitLab. I'm generally happy with it, and we have a largely sane set of linters. I think when your codebase gets to a certain size and you have a lot of engineers working on it, having some sane defaults is very beneficial and helps standardise the codebase a bit. Where I think rubocop really shines is in picking up _problem_ code, like potential bugs, performance issues, or errors, in advance. We also use it heavily when deprecating older modules/classes, like replacing JSON calls with our own wrapper. It does, however, sometimes suggest something totally bonkers: https://gitlab.com/gitlab-org/gitlab/-/issues/271570 https://gitlab.com/gitlab-org/gitlab/-/issues/271570, but it's fairly trivial to skip it. After all, humans should be allowed to say that the linter is wrong and either ignore it or suggest an improvement, and that's a process issue rather than a rubocop issue :) Not everyone is going to agree with every cop you enable, but the goal is standardisation rather than appeasing everybody. If something is particularly contentious then I would suggest removing/disabling that cop. Every few years at GitLab we do seem to get a singlequotes vs doublequotes cop argument crop up, which is why we (thankfully) still don't have any requirement around those. Team doublequotes represent! Edit: Oh and unrelated to the content of the article, but I really like the design and colour palette of the blog.
- monoideism 6y ago> Every few years at GitLab we do seem to get a singlequotes vs doublequotes cop argument crop up, which is why we (thankfully) still don't have any requirement around those So you randomly have single and double quotes throughout the codebase? I don't care which one a project uses, but it seems wise to pick one. Uniform syntax is very helpful for code readability.
- cptn_badass 6y agoDouble quotes allow you to do string interpolation, which is not possible with single quotes. So I assume one faction argues that everything should be double quoted because it's does not matter if there's interpolation or not, while the other group would rather only use double quotes when necessary, otherwise use single quotes. I'm personally part of the second group simply because my linter forced it, but at the end of the day, it's such a low impact we don't really care.
- wlll 6y agoThe issues raised here completely align with my problems with Rubocop. It seems that a lot of people think that one of the main goals for code linting is consistency, when that shouldn't be a goal at all. Consistency is merely a tool, the goal should be readability/maintainability. Consistency is just one tool that is available to us in persuit of that goal. I've hit similar issues to those mentioned in the article and it absolutely infuriates me when I have to jump through hoops (or worse, reduce the readability of my code) to push well thought out code that communicates intent, only to fall foul of a robot that doesn't understand nuance. Don't get me wrong, I think Rubocop is a great tool, it's just over-used, and that's in part because everything is on by default, and this seems to be encouraged by the general community. It seems that once programmers have found a solution to something they love to apply that solution to all places that it will work, regardless of the efficacy. My preference, and I suppose suggestion, is to let Rubocop handle things it knows about with a high degree of accuracy, such as tabs/spaces for lead indentation, security issues etc. and leave anything that requires nuance or subtlety to the programmer who wrote it, and the educational opportunity of the code review. After all, "Consistency is the last refuge of the unimaginative" :)
- drewcoo 6y agoThe point of linters is that most of us can imagine up more interesting problems to deal with. So we welcome the consistency and focus on something we care more about.
- wlll 6y ago> The point of linters is that most of us can imagine up more interesting problems to deal with. I wasn't saying that linters were a problem, I was saying that the over application of linters was a problem. In general, overly broad application of a tool is a problem, wether in programming or not. Linting is a tool, it is possible to over apply it, and I argue that this is regularly done with Rubocop. > So we welcome the consistency and focus on something we care more about. What is the goal of consistency?
- kryogen1c 6y ago
- jwr 6y agoEvery time Yet Another RuboCop Storm arrives, I wish that Bozhidar will eventually drop the whole thing and focus on other areas, where his work is very much appreciated by everyone — his Emacs work is unparalleled, and his work on CIDER (Clojure development environment) and nrepl is universally loved. These communities deeply appreciate the work and instead of recurring drama, provide sponsorship through OpenCollective (for CIDER) and directly to Bozhidar through Github Sponsors.
- square_usual 6y agoWhile certain RuboCop rules do cause drama, you'd be hard pressed to find anybody who doesn't appreciate the existence of Rubocop. It is absolutely ridiculous to state that discussions around specific cops and their applications are equivalent to any sort of hatred for Rubocop's creator.
- jwr 6y agoI do remember some of his tweets where he seemed to be rather discouraged by the drama.
- resonious 6y agoDefinitely just turn off the cop if you don't like it. But let's nitpick a bit. I find it interesting that the arguments made in the article are about the intention of the programmer. Perhaps an explicit nil does signal to me that the nil is intentional. But does that mean that all implicit nils are unimportant? For a skilled programmer like the OP, it probably does mean that! But how often do I actually know who wrote the code I'm reading? Of course I can git blame, but maybe the author left the org before I joined. What kind of programmer were they? Are implicit nils important or unimportant to them? Perhaps it's easy to argue that they should be unimportant. But in reality, I don't know what the author of a particular method was thinking while they were writing it. In fact even an explicit nil might be unimportant. Maybe somebody replaced a `raise SomethingError` line with `nil` to hot-fix an urgent bug. I guess from my perspective as a long-time Ruby developer, all nils are important. It doesn't matter what the intention of the programmer was. Ruby is very expressive and very dynamic - anything can return nil and there are a hundred ways to do it. If your nil is intentional, write a test case for it. If you have no test suite in a Ruby project, then may God have mercy on your soul.
- boyakasha 6y agoThat's something to keep in mind, but it's not the whole picture. Just because it's not guaranteed to be true doesn't mean that it's unpredictable. Like, you can't guarantee that the file for a Rails controller exists in `app/controllers/`, but that doesn't mean that they are randomly scattered across every directory of the project. It also doesn't mean that every developer puts them in a different folder depending on their personality. Sometimes you need to read carefully to determine the exact behaviour, but you only need rules of thumb to quickly navigate around a project.
- gls2ro 6y agoI am not sure what is the problem with me, but for me the code with the GuardClause is easier to read. class SanitizingFilter < HTMLFilter def render_element(name, attrs, content) return nil unless safe?(name, attrs) super end end The guard clause is easier to understand in plain English: return nothing unless safe else move on to next line. Maybe I find it easier because I started programming with Basic and based a lot of logic on GOTO line and then moved to assembler language where again it used JMP so I represent code with nodes and edges in my mind. Also, the original code - which the author prefers - has a positive ratio of language keywords over content (or logic) i.e extra 'end' and 'else' which does not bring too much information and makes me read it twice just to be sure I did not missed anything.
- adverbly 6y agoI agree with you that I find it more readable. However, I've spent a long time living with this exact RoboCop setting so I am probably very used to looking at this style. The author mentioned scanning by indentation which is likely something that I do not employ in the same way that someone who has not lived with similar robocut settings does.
- xorcist 6y agoStrongly agree. The point of stating an explicit nil in the article must be to reduce the chance of future changes erroneously leaving something on the stack, without realizing the implicit nil. The early return in your version makes it much more obvious why it is written the way it is.
- stouset 6y agoAgreed again. Also, the longer I write code the more I find myself avoiding anything but single-line if/unless statement modifiers. And I avoid if/else in almost all scenarios. For the first situation, most `if` branches fall into two categories: guard statements, or genuine branching logic. For the former, guard statement style greatly improves clarity and you only need the statement modifier form. For the latter, I find in almost all cases you either should be writing two methods (one for the true case, one for the false case), or the inner logic of the `if` should simply be its own method. return nil if thing? return true unless other_thing? logic() special_situation if another_thing? logic2() That just reads significantly easier to me than anything involving nested conditional logic. This isn't always the case, but it is often enough that I write a block-style `if` less than once a month. For `if`/`else`, I avoid them at all costs. If there's exactly two cases, odds are I probably want to separate methods (and can write a short method that chooses between the two if necessary). In almost all other cases, I'd infinitely rather prefer a `case` statement that can use tabular alignment for clarity. case foo when bar then baz when ham then spam else qux end That's way easier to parse visually than if/else/elsif/elsif/else blocks. Plus it makes sure that I keep absolutely minimal logic inside of the branched cases, and never have nested branching.
- WesolyKubeczek 6y agoFor me, guard clauses look more readable, especially that they can be easily added or eliminated, they separate main logic from edge cases, and they reduce nested clauses a lot. Stomping a foot about "branching must look like branching at all cost" reeks more of a religion than anything else. Or maybe, if the author has a custom style, they should make their own linter rules. Or maybe, just maybe, be hardcore and don't use linters at all. If you treat your code style as a form of art unto itself (which is not a bad thing at all IMO, depending on what you create), linters can be detrimental — they sure strip your code of a lot of its character.
- ryanbrunner 6y agoI don't think it's a case of guard clauses being more or less readable in and of themselves. The point the authour is trying to make is that guard clauses convey a different intent from a standard branch. It's a way of communicating "this method is not relevant / necessary (or sometimes invalid if you're raising) for this set of inputs". If what the guard clause is doing is the "point" of your method, you're losing that intent from someone reading it, and conveying something else. I don't think it's Rubocop's fault in this case - there's really no way that we can expect a linter to glean "what is this method really about". But structural issues like this probably don't make sense to use a linter for IMO.
- arto64 6y agoIn his case, the guard clause is completely appropriate, because "super" is "the rest of the method" the guard clause is protecting. It's not a filter method, it's a selective render method.
- ryanbrunner 6y agoSure, I can see that argument. But the larger point is that that can't be universally applied to every case that Rubocop flags.
- WesolyKubeczek 6y ago
- deleted 6y ago[deleted]
- Chris2048 6y ago> The explicit nil in the original implementation implies that the method is being called for its return value This kind of insight into the dev mind/process is interesting b/c it shows how code is actually consumed. It also reveals where the implicit logic exists, so we can consider if it should be more explicit - in this case if functions should declare return types.
- ericb 6y agoHandy bash alias: alias 'karen'="rubocop"
- 3np 6y agoalias 'karen-stfu'="rubocop -a --auto-gen-config --auto-gen-only-exclude"
- breatheoften 6y agorubocop config in this scenario is objectively wrong in my opinion -- a better config would be to flag "foo if bar?" as linter violation and just never use it. (I would also forbid "unless" statements -- why the hell does anyone need unless??) The only reasoning I need to support my opinion -- Ruby debuggers are not good enough to support mid line breakpoints -- so if you want to break only when the condition is true -- which is a very common thing if you are maintaining or debugging code you didn't write yourself -- you literally can't without changing the code or using a conditional breakpoint and duplicating the conditional inside the breakpoint definition -- this is very annoying when tracing unfamiliar code and trying to figure out what invariants are relevant to a given scenario (or missing). In my opinion - linters need an actual concept of a user that they are trying to help -- and ideally that concept should lead to objective opinions. Linters like rubocop that are just piles of functionality tend to be breeding grounds for time wasting arguments between insufficiently experienced developers over opinions that aren't supportable from any usefully pragmatic basis.
- dragonwriter 6y ago> The explicit nil in the original implementation implies that the method is being called for its return value — that it’s probably functional, with inconsequential side effects. > Making the nil implicit says that the return value is not important. This method now reads like it’s implemented by avoiding side effects within super. That's...not my understanding of idiomatic ruby conventions. The idea that a method is assumed to have no or inconsequential side effects and be called only for its return value with an explicit return, but to be called for side effects with an implicit one, is a Python idiom, not a Ruby idiom. As I understand Ruby idiom, it is basically "a method defined with `def` is assumed to have both significant side effects and a significant return value unless documented otherwise on either point, except that a method with a name ending in `?` is assumed to return a value meaningful in a boolean context and have no or inconsequential side effects." Concise function bodies with implicit nil returns are normal, including for functions called for their return value.
- pmiller2 6y ago@dang: I think we have another user with some reasonable looking comments who's been incorrectly shadowbanned: https://news.ycombinator.com/threads?id=Technically https://news.ycombinator.com/threads?id=Technically
- aczerepinski 6y agoI've read a million times that the difference between Python and Ruby is that in Python there is one right way to do things, and in Ruby there are many ways to express yourself. But then in the real world, most companies betting on Ruby add RubyCop.
- anamexis 6y agoI don't think the spirit of that maxim really applies at the same level as linters – after all, Python has linters too.
- amingilani 6y agoThe solution here would be to disable the cop with a magic comment, write an explanation accompanying the comment and move on. If you need an exception to Rubocop, that's available to you.