by dheera · 9y ago · 0 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.
connection = establish_connection_given_these_conditions(cond1, cond2)
Vs the many lines of checking, creating the ConnectionFactory, passing in the the conditions to the ConnectionConditionFactory, and generally having a new statement every time you want to blow your nose. What were we doing again? I dunno.
I've used it. I'll defend it. It's better than comments when done properly as above.
Factoring things out into single-use subroutines is a real mixed bag. It's not a clear win at all, not at all.
Arguments sometimes make this practice messy, especially if you find out that your detached subroutine requires 5 different arguments from its parent. But IDEs or smart editors with tooltips or goto-definition make this an almost no-brainer in most cases. Besides that, many languages allow you (or even force you in the case of Smalltalk and Objective C) to solve the argument readability problem at the language level. When it's really naked 'true', you could just use keyword arguments.
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.In the embedded world, I imagine it would be a good standard to force people to consider refactoring functions to their truth table.
Generally, I strongly favor coding standards to combat bad coding habits. Curious how MISRA works out in practice.
[1] https://spin.atomicobject.com/2011/07/26/in-defence-of-misra...
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`.
throw new RuntimeException(e);It also pushes you ever closer to the dex method cap imposed by Android, unfortunately.
- 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.