161 points · by danjoc · 9y ago · 93 comments
Seriously though, it's super hard to avoid deeply-indented code in some languages (cough Java, JavaScript).
@Override
protected void onDestroy() {
super.onDestroy();
if(someCrap != null) {
PendingResult<MessageApi.SendMessageResult> pending = Wearable.MessageApi.sendMessage(mGoogleApiClient, mPhoneNode.getId(), path, data);
pending.setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
@Override
public void onResult(MessageApi.SendMessageResult result) {
runOnUiThread(new Runnable() {
....Breaking up code doesn't always make it more clear and readable.
The same goes for OOP and desperately creating objects from things that don't represent real world entities.
I much prefer inlined code that reads from top to bottom, rather to have to jump all over the place into single purpose functions.
Factoring things out into single-use subroutines is a real mixed bag. It's not a clear win at all, not at all.
http://number-none.com/blow/blog/programming/2014/09/26/carm...
if(someCrap == null) {
return;
}
I like that Swift makes this more explicit with the guard statement, but I've found it useful to reduce the "mental stack" in other languages, too.But generally, if the code is too onerous to modify due to e.g. excessive use of closure-captured data, then the code usually deserves a long, hard ಠ_ಠ to make sure it doesn't deserve a (╯°□°)╯︵ ┻━┻. Hard to test, hard to fix, hard to control.
Also, consider using static imports for `Wearable.MessageApi.sendMessage` and `MessageApi.SendMessageResult`.
I needed to a fix a particular kernel protocol subsystem so I could use Linux at work. I sat down with the spec and a non-Linux computer that implemented it. I spent 8 weeks (I thought it would take a couple days--HAH!), and I wrote it and wrote the very nice test suite which included the single test case I couldn't handle (handling would have required major changes to the kernel).
It's a protocol. The word protocol means "state machine". Especially when hardware dudes design something.
However, state machines mean "indentation". One level for current state, one level (at least) for output variables, and a couple of levels for input variables. My code was well documented, tested, and easily changeable if you needed to add a new state.
"But, that's more than two levels of indentation. Rewrite it.".
After I pulled my jaw up off the floor, swore a couple of times, I replied: "No. This code is properly written, well-tested, and very amenable to changes when the spec gets updated. This code does what I need and what a bunch of people need. I will happily distribute it to them and you will have a bunch of users of this subsystem happily telling everybody to not use mainline because they are a bunch of tossers. If you wish to rewrite it to your indentation spec, feel free, but I will not sign off until it passes all of the tests."
So, they did. They decided to rewrite it to remove the indentation. Lots of early returns (full of bugs). State cases that got "simplified" by sharing common code (full of uninitialized variable bugs). And, because of all the sharing, it became difficult to add cases when the spec changed (which it did--regularly).
But, eventually they got their two levels of 8 character indent. After SIXTEEN WEEKS.
My question, of course, was "Why not just pull each state into a function? It was the obvious way to get what you want. It would have been much easier."
The response: "Well, we tried that. But there are so many variables per state, that the function calls were all exceeding an 80-character line length and we had to wrap them too much."
I had a bruise on my forehead that day.
Yeah, formatting rules exist and have good reasons. But please remember that the goal is "code quality and readability"--not formatting rules.
if(someCrap != null) {
followed by indentation on the following block, would be turned by the programmer into something like:
if(someCrap == null) return; //nothing to do
without an indent following.
thereby saving the indent and having to have the reader keep track of another level.
How many times have you seen:
}
}
}
}And is it really that great?
Breaking it into line by line is actually easier to follow than nested conditions. (You don't have to worry about proper indentation or matching braces properly, it's simply easier to write.)
I think it's easier to read as well.
if(someCrap == null) {
try {
CrapSurface mCrapSurface = CrapGenerator.generateSomeCrap(CrapGenerator.CRAPPY, new CrapFactory.CrapOptions(new CrapOptionsCallBack() {
@Override
int getHeight() { return 5; }
@Override
int getWidth() { return 9; }
}));
someCrap = CrapSurface.getCrap();
}
catch (SomeException e) {
try {
someOtherFailSafeButInefficientWayToGenerateTheCrap();
} catch (WeirdExceptionThatWillSeriouslyNeverHappenButStupidJavaRequiresMeToHaveATryCatchClauseAnyway f) {
// do nothing because this exception will never happen and if it happens the user deserves it
}
}
} else {
... the other code I had before ...
} if(someCrap == null) {
someCrap = makeNewCrap();
}
That's more readable and less indented. It's also self documenting. } catch (WeirdExceptionThatWillSeriouslyNeverHappenButStupidJavaRequiresMeToHaveATryCatchClauseAnyway f) {
// do nothing because this exception will never happen and if it happens the user deserves it
}
Nice joke, don't do this. I don't believe it's the user's fault, and even so either print the stack trace or name the exception `ignored`. It's not that hard to pipe all ignored exceptions in a single catch.Also, somebody made the conscious decision of making that exception checked, which means it's the implementor's fault for forcing you to catch it. If you want, you can use lombok's `@SneakyThrows`.
- Is there a way to use an early return? (In your case early return if == null) - How can I get around using an `else` ?
And I am happy this works so well. Of course there are sometimes if/elseif constructs but exclusive if/else is rare.
Though that could be dangerous.
Although you could just have a build step that waits for a human if the formatted doesn't match submitted.
Often this does involve pulling out blocks of code into a methods that's only called once, but as discussed elsewhere in the thread this is still an improvement in perceived complexity and readability.
0: https://en.wikipedia.org/wiki/Cyclomatic_complexity 1: https://github.com/bbatsov/rubocop
if (items === null) { return 0; }
at the start. Which is fine if that's the preferred style, but if it is, then you should do it regardless of how deeply nested the dependent stuff is.https://medium.com/@matryer/line-of-sight-in-code-186dd7cdea...
It's one of my peeves to be following code paths and oh look, now we're in a situation where it's if (OK) { if (OK) { if (OK) { if (OK) { ... } } } } and I'm trying to remember what all the conditions were to get here since it's long since scrolled off the page. I always find myself thinking "why, why didn't you just return way up there!?"
Spell checks on the other hand are invaluable, especially since you can extend the dictionary to cover new words like "deserialization."
Someone I know used something called Cream, which they said was Vim with a simplified GUI-based interface (I know; what's the point?). But it had one nice feature: If you indented a line, then Cream would draw an unobtrusive vertical line, extending down from the indent's left-most character (I forget how far the lines extended or what that logic was, but they went far enough to be useful). You could easily see how many tabs 'in' you were and line up a current line with one (not directly) above.
I also use the following options in my vimrc:
" set indentline style
let g:indentLine_char = '│'
let g:indentLine_color_term = 66
let g:indentLine_color_gui = '#4f5b66'
" fix performance issue with long lines
let g:indentLine_faster = 1Might go crazy if using this while developing though.. (stop harassing me, EDITOR)
In the extreme, with pure text editor, you want all details together where you effortlessly see them. Helper function means manual search and scroll.
It is really weaker with sublime or vim, at least from what I have seen. They often did not found right function even when it was in the same file and there was no ambiguity - leading to harder to read code with deep nesting and loooong functions (that really should have been split into named steps).
It does not do that at all when vim user did not bothered to configure right plugins or did not bothered to learn them.
https://youtu.be/D1sXuHnf_lo?t=2m57s
Slightly NSWF.