Hot answers tagged

121

You can find several published promotions or rejections of no-brace styles at here or here or wherever bike sheds are painted. Stepping away from the bike sheds, remember the great OS X/iOS SSL bug of 2014? if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0) goto fail; if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != ...


57

Uncle Bob has many layers of defense against such a mistake that were not as commonplace when "always use braces" was the prevailing wisdom: A strong personal preference for single-line conditionals, so multi-line ones stand out and receive extra scrutiny. An editor that automatically outdents when you insert a second line. A complete suite of unit tests ...


32

Readability is no small thing. I'm of a mixed mind when it comes to braces that enclose a single method. I personally remove them for things like single-line return statements, but leaving such braces out did in fact bite us very hard at the last place where I worked. Someone added a line of code to an if statement without also adding the necessary ...


28

For the most-part this is personal preference, however there are some things to consider. Possible Bugs While it can be argued that bugs caused by forgetting to add-in braces are rare, from what I've seen that they do happen occasionally (not to forget the famous IOS goto fail bug). So I think this should be a factor when considering your code style (some ...


15

Years ago, I was brought in to debug some C code. The bug was crazy hard to find, but eventually it boiled down to a statement like: if (debug) foo (4); And it turned out that the person who had written it had defined foo as a macro. A macro with two lines of code in it. And of course, only the first of those two lines was subject to the if. (So the ...


12

"Uncle Bob" is allowed to have his opinion, you are allowed to have your opinion. No need to challenge him. If you want an appeal to authority, take Chris Lattner. In Swift, if statements lost their parentheses, but always come with braces. No discussion, it's part of the language. So if "Uncle Bob" starts removing braces, the code stops compiling. Going ...


10

I think the second variant could lead to more confusion. true should imply positive results, and false a negative result. The question in natural language is usually "Are you allowed to access the feature?", not "Are you not allowed to access the feature?". The response then is also consistent - "Yes you are allowed to access the feature" vs "Yes, you are ...


9

Let's consider both the general and the specific problem. In general the advice is usually to avoid negatives in names. The reason being: you note that it can be confusing to negate a thing; well, sometimes you have to negate a thing, and it is very confusing to negate a negative: if (!product.NotTaxable) ... Yuck. In the specific case you mention there ...


8

Assertions are not meant to replace checking method parameters or program state and throwing informative exceptions when facing an exceptional situation. Your program logic or your error handling logic shouldn't rely on them. The purpose an assertion is to force a program to fail when a simple self diagnosis shows there's something wrong with the program ...


8

My reasons for not removing braces are: reduce decision fatigue. If you always use braces, you never have to decide whether you are going to need braces or not. reduce development drag: even if you strive to eventually extract all multiple lines of logic to methods, having to convert a braceless if to a braced if to add logic is an annoying bit of ...


7

Unless you intend to process the entire inner loop whether an exception occurs or not, your code is essentially equivalent to try{ X x = blah; otherStuff; for (...){ f(x) } } catch(Exceptions1 e1){ ... } catch(Exceptions2 e2){ ... } which does not require nesting. If you still need the inner exception handling, refactor ...


7

The authoritative reason is because PEP-8 says so: Comparisons to singletons like None should always be done with is or is not, never the equality operators. Thus, if you ever find yourself in dire need of comparing exactly to True or False, you should also use is. Remember: in cases like these, 'truthiness' is generally preferred over comparison to ...


6

In software engineering, few insights are gained through science. Instead, experience and completely unfounded beliefs shape our decisions. This is partly due to the young age of our field (software engineering as a field emerged in the late 60s), but mostly due to the fact that human psychology can be quite difficult to measure. Many people have tried to ...


6

Programming is a skill like any other. Among other things, that means that learning it by following the outline of sites like codeacademy is probably unrealistic for some (most) people. That isn't to say that those people can't learn, rather that those sites by nature of their design tend to imply that if you've solved problem X you're proficient and ...


5

Because the C language is designed to be implementable on any platform, no matter what set of integer sizes it natively provides. In fact, none of the intN_t types are guaranteed to exist at all. Only an implementation which provides a two's complement signed integer of exactly N bits (no padding bits allowed) will define the corresponding intN_t type (see ...


5

If the language supports it, I'd opt for: f = b ? foo : bar; for (auto a : as) { f(a); } This approach avoids worrying about whether the if is repeatedly evaluated and avoids code repetition.


4

I think it was a language design choice. Some assertions can be time consuming, especially if they compare the output of some functions. Enabling assertions is like a "debug" flag. Whether that choice is a sensible one is a completely different matter. The way I usually code is that for external/public methods, arguments are checked and ...


4

I think a very maintainable way would be to define functions that take a tweet and return a boolean like this: def has_terms(*terms): return lambda tweet: any(term in tweet['text'] for term in terms) def complex_rule(tweet): return 'boo' in tweet['text'] and not any(y in tweet['text'] for y in no_words) Then you can set up your list of rules ...


4

If the e2 catch is, as you say, only to catch errors in initializing x and doing otherStuff you could extract it to a seperate method. This also seperates the logic nicely and allows you to potentially give a meaningful name to otherStuff. public X Foo() { try{ X x = blah; otherStuff; return x; } catch(Exceptions2 e2){ ...


3

I have a few observations on your question: In the example you provided you don't need exceptions at all. You would only need to check the string y, log any error, and exit the loop. Nothing is exceptional about y being invalid and needing to be logged. The fact you are using exceptions in this case is indication of code smell. Multi-Catch exceptions are ...


2

Joker if (b){ f = foo; } else { f = bar; } for (auto a : as) { f(a); }


2

According to Uncle Bob Negatives are just a bit harder to understand than positives. So, when possible, conditionals should be expressed as positives. For example: if (buffer.shouldCompact()) is preferable to if (!buffer.shouldNotCompact()) From Clean Code Chapter 17, Item G29 "Avoid Negative Conditionals" So your first example is the preferable ...


2

When you see a good move, look for a better one. —Emanuel Lasker, 27-year world chess champion It's a very good readability enhancement, but always look for the better move. In this case, you are likely often covering up problems with your responsibilities being misplaced. The principle of seeking to avoid those chains of identifiers has its ...


2

(My answer ignores the effects of optimization - I'm assuming there is a machine processing your code that can do decent optimization so that the extra variable being created for readability will not make a difference in performance.) In my experience, write your code to be understood. A short, meaningful name is definitely more acceptable than repeating a ...


1

No rule is absolute in software development and everything depends on context. That being said, I would not consider your example to be necessarily a good case for boolean arguments. An API like show(bool isLoggedIn) does not tell me what is going to happen without me reading documentation or code, whereas functionality of show(string messageToDisplay) ...


1

Not enough information is given. The first version assumes that b is invariant over foo() and bar() for all parameters a. The second version assumes that b is not necessarily so invariant and programs defensively. The compiler probably has no way of knowing that b is in fact invariant over foo() and bar(), and hence cannot translate the second version ...


1

I would not make a function for the sole purpose of renaming a ! operator because that's a complete disaster when it comes to interface minimalism and code maintenance with two different conventions, but if you have the choice from the start, make functions the way that's the most obvious to use. To me, that would be using the second form (and only this one),...


1

It can be difficult to learn given the outset of 'I want to learn to code'. However if you can give yourself a small project, like a basic calculator, you'll then have some context to learn the aspects of the language you have chosen. Then just think of new features to add which will give you reason to explore more of the toolbox. To begin with, try and ...


1

It's hard to answer this without veering off into general philosophy. What does it mean to not be able to learn something? Is it always just a matter of there being some missing link that all your teachers have taken for granted, or are some people genuinely incapable of learning certain things? How to teach programming is a major topic of interest in ...


1

Java may have just copied this practice from C/C++, where assertions are disabled in an optimized build, as a common practice. The reason for it to be this way in C/C++ is that assert creates additional branch in the code, which is not usually what you want in the release build. The reason it might not matter that much in Java is that JIT will probably ...



Only top voted, non community-wiki answers of a minimum length are eligible