Writing code with multiple overlapping side effects with a straight face
blogs.msdn.microsoft.com
blogs.msdn.microsoft.com
How does one go about countering that mentality in some rule of thumb fashion if at all possible? Could a disassembly illuminate identical push/pop operations on the memory stack as explicit intermediate variables would? Maybe a simple intermediate result expansion timing profile side by side the terse code's profile?
For performance enhancements where code readability suffers big time, I always want /proof/ by comparing the instructions (and some benchmarks help too).
Having fewer lines, or having the most often called routines at the start of the program would speed up programs, potentially a lot.
Not to mention the simple fact that, for old interpreted languages, the entire program text had to fit inside memory and so terseness literally saved you working memory.
This probably applies to similar languages (like Ruby) as well.
Sometimes you can help people become better programmers. Sometimes you can't. Try not to stick around in positions where you don't have the ability/opportunity to make a positive contribution, is my best advice.
But assuming that the person is willing to listen to you, all of the above seem like good approaches.
It was an embedded system with a proprietary language. The compiler didn't clear the variables when they were created (again, for performance reasons). For some crazy reason, the language allowed you to declare a pointer without initialising it. So what would happen is that the pointer would end up being whatever happened to be on the stack previously. The reason that it didn't crash in testing was because most of the code in the system was essentially copy and pasted from other parts of the system. As long as the previously run function had a pointer in the same location that happened to allocate some memory in the heap, and then deallocate it, this function would end up using the same memory and it would be fine. And this is exactly what happened in this case (because most of the functions had similar shapes and pointers were declared at the top of the stack frame). The main reason they were reluctant to change the code was because they had copied it from somewhere else and didn't understand how it worked. Because it didn't crash, they didn't want to touch it.
Alternatively, just ask them to prove it. If it's faster, they can benchmark before and after, and prove that it's faster? No proof means you're full of shit. This is the Right Answer in that it's what you should be doing anyhow to avoid performance regressions, but it's way more combative and can cause problems within the team, so must be done tactfully.
That goes bad very fast. I've worked with someone who tried winning arguments with one-line microbenchmarks; They even tried to convince me that I should always use undefined over null in JS since one is faster than the other (forgot which).
> Introduce them to the concept of static single assignment form
I failed with this as well; some coders don't trust the compiler/runtime at all. I had people tell me that garbage collectors don't deal with cyclic dependencies or that "simple comparisons" (<, >, ==) are faster than "compound comparisons" (<=, >=).
This was wrong on a number of levels.
I met some people who were trying their best to make everything a oneliner because "shorter is better" or whatever reason they had at the time. The real reason I always saw was that it was making the code "hacker-like" (and completly unreadable) and they could brag about how clever they were.
Funnily enough, their argument always seems to be "it's easier to read this, since I'm accustomed to
for (x;y;z) if (foo ||(bar && baz)) lorem = ipsum;
as a pattern."But on the other hand I also find that writing code is the same as speaking normal language. We each have our preferences, vocabulary, diction, style etc. I also jumped on the Linq wagon, but cringe when I see for example a Swift etc. reducer. So as long as that person writes his page of code at a decent pace with limited/no bugs I won't hold it against him.
I think it is a pathological corner-case in an otherwise generally useful interest in, and appreciation of, innovative and economical problem solving.
a -= a * a;
which evolved from a *= a;
after the author thought "I need to subtract its square from itself, not just square it". I can see how this could occur in numerical code.I've noticed there are two opposing schools of thought on issues of "insane code" like this; on one side there's "use the language to the fullest if it makes sense to", and on the other is "avoid anything that might be the slightest bit confusing". I think that taking either of those to their logical conclusion is not a good idea --- in the former case, you'll end up with extremely dense and (initially) difficult-to-understand code, but the latter case will cause a gradual degradation of code into something approaching the verbosity of Asm, but with none of the benefits (e.g. "ternary operators are confusing, don't use them; multiple levels of precedence are confusing, so always fully parenthesise expressions; nested parentheses are hard to read, so don't use them either and only do one operation per statement; boolean expressions are confusing, so always use if/else; nested if/else are confusing, so don't nest and always refactor to use a function call, etc. etc.)
It does seem that different languages vary in where they are on this scale, with more "exotic" ones like APL tending highly towards the former (interesting related discussion: https://news.ycombinator.com/item?id=13565743 ) and C#/Java towards the latter. The ideal is probably somewhere in the middle.
there's a simple rule of thumb - if you can't immediately and unabmiguously deskcheck the expression as it is written, it's too complicated and should be simplified.
This is a false dichotomy. How about "use the language to it's fullest, within reason (avoiding things like multiple side effects per source line), but when non-obvious code is written, document it."
At least, I'd say that describes my approach.
At my $dayjob, I have a problem with a cow-orker with a position slightly superior to mine ("first among equals", former team lead of the group of projects to which I'm assigned) taking results of static analysis too seriously - to the level of cargo culting. When bored, he'd introduce "fixes" to reduce number of issues reported by SonarQube - "fixes" I have to revert every now and then, because they reduce quality of the code (sometimes also introducing bugs through carelesness), all to optimize the Sonar metric.
To be clear: tools are fine. It's people that are the problem (as usual).
But I've yet to see one of those code-visualizing tools based on metrics that convinces me. The results I've seen so far are either obvious ("I already knew that, thanks") or inconclusive and hard to interpret. So, to me those tools seem to be more of a way to try and convince your manager that you should be given time for refactorings than actual utilities.
I've been wondering if there could be a benefit in analyzing the commit history of a project instead so that one could somehow at least visualize obvious problem areas ("every third bugfix has to touch this piece of code, so we should really have a proper cleanup there...").
result = boolean_flag
? do_this()
: do_that();
I think it's less noisy and nicer to look at then an if-else, provided the statements aren't too long. God forbid multiple side effects though, even in languages with less complicated sequencing rules than C/C++.So:
auto result = boolean_flag ?
compute_property() :
compute_another_property();
if (boolean_flag) {
do_this();
} else {
do_that();
}Personally i dislike the latter form because it requires me to spend extra time reading what is boilerplate that is functionally identical to a ternary.
Edit: Not impressed by the down-voting of an earnest question of someone trying to learn more about how other people see things, HN.
If-else is the only option if you want to have multiple statements in a {} block, instead of only one function call.
So it seems more consistent to use ternary for expressions and if-else for statement control flow.
I'm sorry, but i really don't follow your logic, can you try to explain it more clearly?
The classic languages with ternary (C, C++, Java, PHP, JavaScript) all have the deficiency of distinction between statements and expressions. When everything in your language is an expression, the need for ternary disappears.
Python has a ternary operator, which does return a value. It just so happens this operator uses the tokens `if` and `else`. But it's the same thing what you'd write in C or Javascript as `C ? T : F`, would be written `T if C else F` in Python. Different order of arguments and tokens, but it's still the ternary operator and not an if/else block.
You can't get a result from block statements in Python. Just because the ternary operator uses the same tokens as the if/else block, doesn't mean it's the same thing.
let x = if true { 5 } else { 6 };Languages with very different syntax like Python are of course going to have different style preferences. Eg. Python doesn't have a ?: operator at all, just an inline if-else expression, so the entire discussion of "should you use ?: for control flow" is meaningless for Python.
boolean_flag
? do_this()
: do_that();
It seems so terse as to be impossible to misinterpret.The only possibly feasible way i see for it doing something unexpected would be if it were the last statement in a function in a language that implicitly returns the value returned by the last statement in a function; but users of such languages usually are aware that can happen.
How do they suggest that?
As far as i am aware ternaries put no restriction whatsoever on what kind of code you can put in its branches.
I don't buy the comparison with getX either, since ternaries have no name, they're just some punctuation, and even if implemented as if/else word pairs are completely vague.
It might be a convention in some circles. I don't think it's a well-established one, though.
For me, ternaries strongly suggest "expressions being run for its return value", but without any indication whether or not it's side effect-free. In practice, most of the time such expressions end up being side effect-free (getters, finders, etc.), but every now and then you do want to have a stateful expression (e.g. getting something from a map, and storing a default value there if the key is missing in the map). I believe such stateful expressions are fine to use with ternaries as well.
You just called someone out for this:
"If you're restricting what you're saying to a specific language say that bold and as the very first thing (...)"
Are you talking about a specific language now? Because some languages do put restrictions on that. Python makes a clear distinction between statements and expressions, so you don't even get the option to use a ternary in place of an if/else block.
That said, (in general) I disagree that ternaries suggest side-effect free. However, they do suggest that you care about the return value of the ternary expression. Some languages enforce this suggestion, others don't. But even for languages that don't, a ternary that silently discards its return value feels like a "cute hack" to me.
So as an example of doing both, consider following Java pseudocode (simples example that comes to my mind now):
Foo value = someCondition()
? map1.computeIfAbsent("key", defaultValueProvider)
: map2.computeIfAbsent("key", defaultValueProvider);
This both gets a value and changes state of the map; which map is queried/altered is determined by the condition. I personally don't mind such code, and prefer it to if/else version. Foo value = ( someCondition() ? map1 : map2 ).computeIfAbsent("key", defaultValueProvider);
Or some kind of moral equivalent?For clarity, let's rewrite it as:
Foo value = someCondition()
? map1.computeIfAbsent("key", defaultValueProvider)
: list1.get(42);Seriously though, there's nothing in ternary operator that says it should only be used for side-effect free code. Especially in C++ (or Java), which doesn't even differentiate between stateless and stateful code on the language level.
IMO ternary is a perfect solution for the case where you want to assign or return a different value based on a boolean condition. Whether or not the code in branches is side-effect free is irrelevant.
Personally, where I try to avoid using ternary operator, is places where I don't care about returned value. So "yes" for:
auto foo = [condition] ? possibly_stateful_then() : possibly_stateful_else();
no for: [condition] ? then_statement() : else_statement();As i asked below: Why though?
Also,
> in languages we're discussing
Don't bury that lede. If you're restricting what you're saying to a specific language say that bold and as the very first thing, so people don't end up wasting their time parsing your post in a different context. Rude.
I like to think of it as using the dedicated tool for a job it was designed for. In my mind, it's a good rule of thumb because it enhances readability (compare "the principle of least surprise").
> Don't bury that lede. If you're restricting what you're saying to a specific language say that bold and as the very first thing, so people don't end up wasting their time parsing your post in a different context. Rude.
Why? Come on, at this point in the thread we'll still discussing C++ derivatives. I thought it was obvious.
Also: if a lanuguage has an if/else as an expression and has a ternary operator, then IMO there's a problem with that language being cluttered with duplicate syntax for the same thing.
My primary language, Object Pascal, even goes to the length of naming functions (return values) and procedures (don't return values) differently. It really helps to focus the mind on the purpose of each: one almost always expects procedures to do something and, most likely, modify something that may introduce side effects. Functions are almost always side-effect-free in "decent" Object Pascal code.
Using ternaries only when it is free of side-effect can both helo avoid a class of unnecessary errors, and add meaningful semantic information that some code is, or should be, side-effect free.
It would be great if the compiler(s) in various languages supported enforcing it, but sometimes you take whatever you get.
result = if boolean_flag
then do_this()
else do_that();
then I'm sure no one would find it as bad as they do now. The way you formatted the ternary with line-breaks helps a lot, too, I think! let result = if boolean_flag {
do_this()
} else {
do_that()
};
Rust actually doesn’t have a ternary operator. result = do_this() if boolean_flag else do_that() result = if boolean_flag do_this(); else do_that(); end
Though it does have the ternary ?: operator too. z <- if (x > y) 5 else 7
And of course this is trivial in Lisp: (setf z (> x y) 5 7)What you meant is:
(setf z (if (> x y) 5 7))
A nicer thing that I like about Lisp's "everything is an expression" is something that is considered as code smell by some: (setf foo (or var (compute-default-value) +some-default-constant+))
This works in Common Lisp, where the only value considered logically false is NIL, because or will short-circuit (as expected), returning not T, but the value of the first logically true result.So e.g.
(let ((a nil) (b 2) (c :foo))
(or a b c))
returns 2.To me it works in short expressions that do return a value so number_of_things = some_type ? 5 : 1
x = x ? (n ? m : w) : (b ? c : x);
This doesnt seem too bad with variables, but now imagine this.
int killMe = Factory.Omg ? (isFuckedUpped ? Leet.YES : Leet.NO) : (youGetTheIdea ? yep : nope);
My opinion is that code should be written in a way that makes it possible for an intern to read and update. I work with interns and fresh-out-of-college grads, and I need them to be productive too.
I'd first look for a way to try and avoid the whole situation, if possible.
After that, what I feel is more readable depends on what formatting the language allows, length of identifier names, what the subexpressions look like, etc.
Then, after careful consideration, I'll just follow any style guide and thus prefer if/else blocks, especially if a ternary would silently discard its result.
int killMe = Factory.Omg
? (isFuckedUpped ? Leet.YES : Leet.NO)
: (youGetTheIdea ? yep : nope);
it doesn't look bad IMO. Definitely more readable than if-else alternative. total_cost = p->base_price + p->calculate_tax();
> This would raise the warning because the compiler observes that the calculate_tax method is not const, so it is worried that executing the method may modify the base_price, in which case it matters whether you add the tax to the original base price or the updated one. Now, you may know (by using knowledge not available to the compiler) that the calculate_tax method updates the tax locale for the object, but does not update the base price, so you know that this is a false alarm.I think the warning in that case is still fair, and I'd be perfectly happy to get it. calculate_tax() could be modified to affect base_price with this compilation unit being none the wiser.
[0]: https://github.com/v8/v8/wiki/TurboFan
EDIT: added information about `ast_node_count()`
1. Code is a communication system : between you and the next person to touch it. You are telling the other person how you made this work. Invest in this because the next person will probably be you in six months.
2. Compilers and type systems are your friends. Write code that extracts errors from the compiler by explicitly constraining things as much as you can afford to do. Avoiding typing or checking via long methods or low level datatypes is bad. Short typed, functional methods and high level data types are good.
If I feel particularly smart and proud after writing a piece of code, I look at it again and remove some smartness in favour of readability.
Unless it's absolutely performance critical, in which case I try to comment the hell out of what's going on.
I have found it pedagogical to read some more difficult programs, without trying to find ways to make them necessarily "read" better. In particular, generic and/or high performance versions of algorithms.
To your point, this is precisely why I will refuse to generalize some parts of my code on the first pass. First, solve my problem specifically, then try and generalize. (This is not a waterfall style approach, but I do try and keep it somewhat phased.)
Otherwise, just leave the specific version in and stick some info in the comments (like a link to the high level description of the algorithm, if it's a common one that has a name, plus some pointers to your specifics).
I'm reminded of a section in Programming Pearls where they explore several versions of a function, each time improving it. Too often I'm impatient and want the final solution first.
After spending months looking at disassembled FreeBSD kernel C code in a profiler, trying to hunt down cache misses, I'm realize that it is hard to count on anything and that my instincts, even after 25+ years of C programming, are often wrong.
If the described author could be identified? Perhaps not absolutely, but they do have some specific stylistic quirks combined with a particular sales level.
In my experience, this is accurate, but underscores a teaching opportunity. If you show Joe Beginner how to get the warnings, explain how they apply to the code and why the warning was good, they may slowly begin to appreciate the warnings. So that even if they don't understand, they won't necessarily dismiss the warning next time -- instead they'll go ask for help.
The R package "data.table" does a good job at this. Just scroll through https://github.com/Rdatatable/data.table/blob/master/R/data.... and search for "warning(".
“Nathan Reed
"July 19, 2017 at 4:34 pm
" Didn't you just write such code with a straight face yourself only yesterday? ;) In your bytecode interpreter example:
memory[NextUnsigned16()] = NextUnsigned8();
"Presumably the NextUnsigned8/16 functions have side effects of advancing a buffer pointer, so this is nearly the equivalent of p[x++] = ++x."NB it really is faster
edit: nvm, Crumb is way more that kind of thing: https://github.com/serprex/Crumb/blob/master/C3.py I forgot I concocted that little devil
I even did a C version https://github.com/serprex/Crumb/blob/master/Crumb.c which is a pretty boring implementation besides
while(p>q?(j=d==b?:i*q/p,i++<p):(i=c==a?:j*p/q,j++<q)) a -= a *= a;
Do?Looking through C# docs (which I assume this is, but don't have experience with), it seems A's value is changed to be the previous value of a, minus itself (ie 0) multiplied by a? In other words:
a = 0
? a = a * a
a = a - a
That would be the "least astonishing" outcome for me.{"some": "dict"}.setdefault("some", foo())
while expecting foo() to be short-circuited.
What are people expecting with that?
conf = {}
def get_conn():
return conf.setdefault("db_conn", expensive_creation_of_db_conn())Fun trick to learn exists. Though I would really like to know what led up to it, since it seems ... unhelpful.
Edit: Looking at other comments, I did try popping off that entry in the dict, and no, it didn't have anything in it (it doesn't make the dict anything like defaultdict).