68

In many instances, I have seen code that is poorly formatted or all in one line (like below using R). Is it appropriate to edit the code so that it is more legible? I know in some instances these are necessary edits that would improve the post (according to here and here).

However, recently, someone nicely pointed out that I was doing too many small/minor edits on questions (as I usually fix issues when I see them), but I did not realize I was bumping some questions up in the active queue. So, I am trying to make sure my edits are "necessary".

One example that I recently saw was where someone provided their data (a dataframe in R), but it was all in one line, such as:

df <- structure(list(Site = structure(c(1L, 1L, 1L), .Label = "Agriculture", class = "factor"), CowId = 1000:1002, Result = list(c("A", "B"), "C", "C")), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -3L), groups = structure(list( Site = structure(c(1L, 1L, 1L), .Label = "FarmA", class = "factor"), CowId = 1000:1002, .rows = structure(list(1L, 2L, 3L), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame" ), row.names = c(NA, -3L), .drop = TRUE))

So, in this case, is it worth formatting the code so that the data structure is more visible? Something like this:

df <-
  structure(
    list(
      Site = structure(c(1L, 1L, 1L), .Label = "Agriculture", class = "factor"),
      CowId = 1000:1002,
      Result = list(c("A", "B"), "C", "C")
    ),
    class = c("grouped_df", "tbl_df", "tbl", "data.frame"),
    row.names = c(NA,-3L),
    groups = structure(
      list(
        Site = structure(c(1L, 1L, 1L), .Label = "FarmA", class = "factor"),
        CowId = 1000:1002,
        .rows = structure(
          list(1L, 2L, 3L),
          ptype = integer(0),
          class = c("vctrs_list_of", "vctrs_vctr", "list")
        )
      ),
      class = c("tbl_df", "tbl", "data.frame"),
      row.names = c(NA,-3L),
      .drop = TRUE
    )
  )

I am just wondering where the balance is for improving posts but not causing frustration to people when things get bumped up in the active queue.

This could be a duplicate question, but was not able to find an immediate answer.

16
  • 16
    "as I usually fix issues when I see them" - if you're doing it naturally it won't be a problem. You don't need to worry about the edit queue because you can unilaterally make edits. Active posts is potentially more of a concern, but if you're editing in moderation (read: not editing 10+ posts per hour (actual number subject to opinion)) then chances are nobody will notice. Commented Jan 11, 2022 at 0:47
  • 13
    Please don't do this if it breaks an answer as was done to me Commented Jan 11, 2022 at 5:08
  • 5
    In this case it seems overkill to change the formatting on the dput structure since most people (I assume) just copy and paste it directly into R and see the structure there - the layout on the page probably doesn’t really matter. But splitting one liners into several lines is good.
    – user438383
    Commented Jan 11, 2022 at 5:27
  • 49
    @user438383: I disagree for exactly that reason. Stack Overflow has worked hard against just being the place people come to copy and paste snippets that they don't fully grasp, and instead focus more on helping people understand the code and the syntax so they can modify it to their needs, or write similar code in the future. That's why we discourage code-only answers. But it's also why it's useful to make sure code is in a readable format. (Maybe there's some really narrow case here where no one needs to understand this code in R, but that seems unlikely?) Commented Jan 11, 2022 at 6:27
  • 5
    @jeremy it’s code that’s only purpose is to serve as reproducible data for the question answerer - see of it like a table of numbers in code form that makes it easier for the person answering the question to make sure they are using the same data as the person asking the question. How it’s formatted isn’t important IMO as long as it can be easily copied - it’s not even really designed to be human readable in a sense.
    – user438383
    Commented Jan 11, 2022 at 7:58
  • 10
    @AmitJoshi: ”It is responsibility of author to make sure their post (including code) is readable” Ideally, sure. But if that were the whole story, we wouldn’t even have the ability to edit posts in the first place. The entire concept of editing is to treat posts as a kind of wiki so we can improve their readability regardless of whether the contributor is responsive or cooperative. I.e., we shouldn’t rely on one person’s follow-through to ensure the content is useful for everyone else. Further, editing can also be an effective way to show contributors how to format posts by example. Commented Jan 11, 2022 at 8:38
  • 1
    @dave_thompson_085 Why does the edit not show up in the revisions, the only edits I can see are by you?
    – user692942
    Commented Jan 11, 2022 at 9:50
  • 2
    @user692942 They meant this revision of the question...
    – Tomerikoo
    Commented Jan 11, 2022 at 11:05
  • 9
    @dave_thompson_085 So why don't you just roll back the bad edit? You have plenty of rep there...
    – J...
    Commented Jan 11, 2022 at 11:36
  • 13
    Just be aware of what language(s) you're working with. I make edits to JSON 1-liners all the time, because not only does it make it easier to read in general, but it's much easier to find formatting errors in it (missing brackets or braces, "true" where they're expecting true, etc.). However, if the language is whitespace-aware, like Python, my code edits only consist of adding code fences where necessary and deleting excessive numbers of blank lines. Anything else may cause issues.
    – MattDMo
    Commented Jan 11, 2022 at 12:34
  • 8
    That's a dput, which isn't meant to be read so much as copied over to a script in order to make reproducible data. This is one case where domain knowledge matters—no matter how you format it, we don't ask for dputs in order to read them, we ask for them precisely because you can copy them over
    – camille
    Commented Jan 11, 2022 at 17:07
  • 1
    Just to clarify, for the specific example provided, R is not whitespace-aware. I'm sure most contributors would have the good sense to not edit code formatting on posts where they know this might be an issue. Commented Jan 12, 2022 at 3:22
  • 1
    This issue comes up a lot in various SQL tags where I work. The problem is this: when a user posts code like const query = 'SELECT yadda, yadda2 FROM some vast list of stuff;' it's hard to reformat the question without teaching the user how to use multiline strings in whatever language. So I just repeat the query, formatted line by, in the answer, and suggest the user look up multiline strings.
    – O. Jones
    Commented Jan 12, 2022 at 11:47
  • What about small screens (mobile phones)?
    – Flimm
    Commented Jan 12, 2022 at 15:42
  • 1
    Things would be much simpler if SO provided at minimum the ability to block indent and block dedent code. Often I paste in a snippet of code from the IDE and it is too far indented. To dedent it it's easier to fire up VIM, format and then repaste. Commented Jan 13, 2022 at 9:52

6 Answers 6

92

Yes, if you're improving the quality of the post, you should make the edit. Code on a single line is not very readable, so formatting it is an improvement. Make sure that when formatting the code you don't accidentally change its semantics, of course.

As usual, try to improve everything you can about the post. This is very important if you don't have full editing privileges, as you're creating work for others when you make an edit, so incomplete or trivial edits should be avoided in that case. If you have editing privileges, this is not as important, though it's still preferable.

Don't worry too much about bumping a post on the active page. Stack Overflow gets a lot of activity, and you're unlikely to make much of a difference by making edits.

10
  • 4
    Agree, except with the last paragraph. That's a bit like saying, “a lot of people are voting in the elections, so why should I?” Commented Jan 11, 2022 at 7:11
  • 18
    @leftaroundabout the conclusion is different from your analogy, though. cigien is saying that "your edit is only one among many, so don't be afraid that it will disturb people, just edit it", while your analogy is "your vote is only one among many, so don't bother to vote, it doesn't make a difference".
    – justhalf
    Commented Jan 11, 2022 at 8:42
  • 1
    There was a recent similar question here (although I can't now find it) about whether a question containing a screenshot of code should be edited to provide a transcription of the code in the screenshot. The consensus was a clear 'no' because of the possibility that the edit could introduce mistakes. Given that a screenshot cannot be 'run' anyway, I would have thought the risk/consequence of introducing mistakes that way is less than in reformatting text code here - at least here the version in the original question is definitive. So that implies a strong 'no' to should I reformat it.
    – Ian Goldby
    Commented Jan 11, 2022 at 8:57
  • 2
    Personally, I disagree with both accepted answers. In the screenshot case, surely providing a transcript cannot make the question any worse by introducing an error. (The screenshot isn't runnable in the first place.) But in this case introducing an error would certainly make the question worse.
    – Ian Goldby
    Commented Jan 11, 2022 at 8:59
  • 3
    There's a big difference when reviewing an edit. If the user has typed code from an image, the reviewer needs to check every single character to know whether or not the edit has fundamentally changed the question. Adding whitespace to a single line of code is much safer because it's fairly clear in the markdown view whether or not there are any non-whitespace changes.
    – Tim
    Commented Jan 11, 2022 at 9:32
  • 1
    To my mind, the issue is less about being able to run the code, and more about the possibility of changing what the question is. Introducing a typo when transcribing an image fundamentally changes a question into a typo hunt, making it unlikely to be useful to anyone (including the OP, who didn't have the typo in the first place). Improving the formatting of existing code also doesn't change how easy it is to run the code, but does make it a lot easier to read the code and consider the actual question which is being asked.
    – Tim
    Commented Jan 11, 2022 at 9:34
  • @IanGoldby In the screenshot case, surely providing a transcript cannot make the question any worse by introducing an error: Are you sure?
    – BDL
    Commented Jan 11, 2022 at 15:56
  • "Don't worry too much about bumping a post on the active page" specially if you are improving the post. Self limiting yourself because someone might complain about you improving the content on the site makes no sense.
    – Braiam
    Commented Jan 11, 2022 at 16:45
  • 1
    I think formatting for readability is 99 and 44/100 % of the time a good thing. Programmers/Developers/whatever are not (contrary to managements ideas) machines. We need to be able to read the code if only to see if we can help. Having said that, if you edit someone's code, be nice when you talk to them about it. Too often someone goes all militant about it and that can have a detrimental affect overall. Thanks,
    – John
    Commented Jan 11, 2022 at 21:32
  • @BDL My point was that a question with only a screenshot doesn't allow the issue to be reproduced any more than a transcription containing errors would do, which is why I said a transcription is no worse. But I accept Tim's point that a transcription creates a (possibly) unreasonable amount of extra work for someone reviewing the edit.
    – Ian Goldby
    Commented Jan 12, 2022 at 11:29
44

In general, my answer would be "yes, but...", but in this case it would be "probably not." It depends on the purpose.

The probably not: You used a very specific example from where I know you & I both spend time. The code you included is the output of calling dput on some object, and it has one purpose, which is to replicate that object (generally a dataset) and its metadata exactly from one person's computer to another. Asking people to post a dput is in our most-used tag guidance and the tag wiki. Those of us who curate (or nag, depending on your perspective) the R tag ask for dputs precisely to be able to copy it over to our own workspaces. It's an improvement over the dozens of questions a day that post text that's supposed to represent a datatype that is otherwise lost in translation, but it's mostly meant to be machine-readable, not human-readable. I often ask for people to just post the dput of their data at the point of the actual code needing to use it, rather than 20 lines of preprocessing.

Formatting a dput adds little to nothing of value, since it isn't meant for reading or presentation, and it takes up a lot more space, potentially cluttering the question and distracting from the code that the question is actually about (again, that's a lot of the reason why we ask for a dput in the first place). If I found a post where the only edit was to format a dput, I'd consider rolling it back, especially if it took away from reading the code that's actually relevant.

The yes, but: Like I said, that's a very specific example for a pretty broad issue. But that's part of the problem—knowing that formatting a dput isn't helpful is domain-specific, and probably even spend-way-too-much-time-on-R-SO specific. And I assume R isn't unique in that, either as a language or a tag community. So if you're certain your formatting edits will maintain the integrity of the code and are useful for asking & understanding a question, by all means do it. But keep in mind that languages have their quirks—think of it as metadata—that might not be legible or apparent to you.

7
  • 6
    Agreed, it is a peculiar example to give, as dput() output is probably the single piece of code where having it all on a single line makes it easier for the answerer.
    – user438383
    Commented Jan 11, 2022 at 19:26
  • 2
    Thank you to both @user438383 (in the comments) and camille for clarifying that bit about dput(). That makes good sense—and is certainly a consideration I was ignorant of. Commented Jan 11, 2022 at 21:14
  • Agreed. This almost deserves its own question: Should Data be edited so that it is visible... And I'd respond that it probably shouldn't.
    – code11
    Commented Jan 11, 2022 at 21:51
  • 3
    @code11 I think if it is in a form that can easily be read by a human and can be formatted to be read on the screen, you often might as well. In fact, just a minute ago I edited a post to, among other things, split the creation of a data frame across 2 lines instead of 1, but I could do that because it just came from 2 lists of 10 or so numbers. But yeah, a lot of the time it's a bonus but not strictly necessary
    – camille
    Commented Jan 11, 2022 at 21:57
  • Hmm. Maybe. If there's a huge chunk of json, lets say, squashed at the top which initializes the code below, and expanding it would crowd out the actual code, I can see an argument for keeping it condensed.
    – code11
    Commented Jan 12, 2022 at 17:17
  • 1
    @code11 I think it is often a good idea to make data more readable, so that readers can quickly verify that the code matches up with the data without having to load it onto their own machine. With JSON, it's easy enough to load the badly-formatted data & dump it back out with decent formatting. Of course, if you discover a bug in the JSON, then you abandon the edit & post a comment telling the OP to fix it. If the data is so huge that reformatting it crowds out the actual code, tell the OP to trim it down to a more manageable size to make a proper MCVE.
    – PM 2Ring
    Commented Jan 12, 2022 at 17:32
  • Of course, I'm only talking about data that's intended to be human-readable, not stuff like the dput data that camille focuses on in this answer.
    – PM 2Ring
    Commented Jan 12, 2022 at 17:44
16

I agree with what cigien has said, but I want to focus on the concern of introducing errors while reformatting.

I think that possibility is actually a significant risk, especially if you're doing things by hand. I think the solution might be: don't do it by hand. Many languages have automatic formatting tools. I imagine there is one for R. Use those rather than relying on not making a mistake.

That being said, obviously don't just mess with the formatting because it's slightly off. This is for the case where it's all on one line, or in a format that is clearly detrimental to its readability.

@bta and @Shadow have brought up two other major considerations if using linters. Firstly, they will sometimes complain if there is a syntax error. This can be useful for helping OP find out whats wrong with their code.

However, one should be careful not to edit that fix into the question itself. Ie, the code should be presented in a readable way in the question but should still retain any errors originally present.

3
  • 3
    This is the rule that I normally follow. As a bonus, some code formatters will barf when they encounter a syntax error, which can point you towards what the original problem might be.
    – bta
    Commented Jan 11, 2022 at 19:59
  • 9
    Adding to this concern - be careful not to fix errors when doing this either.
    – Shadow
    Commented Jan 12, 2022 at 4:14
  • 1
    Since I primarily work in r, I generally just do ctrl + shift + a (on Mac) to format code. However, sometimes it will put every element from a list on its own line after the comma, which then makes it unnecessarily long. So usually for the purpose you describe, I will many times just leave it alone. However, there are several instances if I see %>% or + that I know that I can enter down, so that the code is more readable.
    – AndrewGB
    Commented Jan 13, 2022 at 0:02
5

This depends a little bit on the post. If the post would be good quality if the formatting was fixed, then by all means edit. If it's a good post anyway, I wouldn't worry too much about making it active again.

If a post is low quality anyway, it may be worth considering whether it's even worth your time to do the edit. It's not necessarily wrong to put lipstick on a pig, but it's probably best to save yourself the time and frustration. In this case, it's probably best to downvote (and possibly VTC if it's a question) and move on.

I would also like to emphasize cigien's point about making sure that you don't accidentally change the semantics (especially for questions). This is particularly true for languages like Python where whitespace is significant, and where defects sometimes just arise from the OP having the wrong indentation. In cases like this, improving the readability would not only hurt the clarity of the post, it would make it effectively incoherent because it would erase the bug that the OP is asking about. (In cases like this, it's probably best to just VTC as a typo).

For answers, I'd probably tend to be slightly less worried about this, as long as you aren't introducing a bug. If you correct a bug, that's great - you've helped the answerer (and future readers). You obviously don't want to blatantly conflict with the user's intent, but if you can substantially improve the clarity of the post you're doing everyone involved a favor.

Also, in my opinion, heavy-handed edits of questions that would otherwise likely be closed might be justified under some circumstances (e.g. if the OP appears to have poor English skills and you happen to understand the question). Personally, I've done several admittedly heavy-handed edits where the OP was grateful that I salvaged the post and saved it from being downvoted and close-voted into oblivion - it's better for everyone involved because it allows the OP to potentially get an answer and it allows future readers to understand the question more readily.

1

I was faced with the same problem on my Perl one-liner page https://perl1liner.sourceforge.io/ Since both Shell and Perl allow multi-line strings naturally, i.e. without horrible work-around syntax, I generally format the longer ones as many-liners. But then they are not true to my moniker...

What I came up with was a (checkbox hack, no JavaScript) solution of a custom <n-l> tag wrapping the newline. Depending on the checkbox it is either white-space: pre or white-space: nowrap with an embedded backslash becoming display: none in the latter case.

Works like a charm – except on iOS, which unlike Android browsers doesn't emulate hover to access the veggie-burger menu! But that's just because of my no-JavaScript approach, the technique itself would work everywhere.

Maybe stackoverflow can implement a similar option, so readers can decide themselves what formatting they would like.

1
  • 2
    That seems like a useful tool, but the question was should we reformat code, not how do we reformat code more easily
    – camille
    Commented Jan 14, 2022 at 0:16
1

You are definitely improving the visual experience for the community! I've learned that one long line doesn't go with the good programming habits! At least here in my country! Keep up with the good work my friend!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .