code-readability

What are the benefits to using anonymous functions instead of named functions for callbacks and parameters in JavaScript event code?

老子叫甜甜 提交于 2019-11-26 18:53:37
问题 I'm new-ish to JavaScript. I understand many of the concepts of the language, I've been reading up on the prototype inheritance model, and I'm whetting my whistle with more and more interactive front-end stuff. It's an interesting language, but I'm always a bit turned off by the callback spaghetti that is typical of many non-trivial interaction models. Something that has always seemed strange to me is that in spite of the readability nightmare that is a nest of JavaScript nested callbacks,

Gracefully avoiding NullPointerException in Java

。_饼干妹妹 提交于 2019-11-26 10:58:35
问题 Consider this line: if (object.getAttribute(\"someAttr\").equals(\"true\")) { // .... Obviously this line is a potential bug, the attribute might be null and we will get a NullPointerException . So we need to refactor it to one of two choices: First option: if (\"true\".equals(object.getAttribute(\"someAttr\"))) { // .... Second option: String attr = object.getAttribute(\"someAttr\"); if (attr != null) { if (attr.equals(\"true\")) { // .... The first option is awkward to read but more concise

`if key in dict` vs. `try/except` - which is more readable idiom?

孤街浪徒 提交于 2019-11-26 09:26:35
问题 I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case: I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue on. Which way is better? try: A[\"blah\"] = B[\"blah\"] except KeyError: pass or if \"blah\" in B: A[\"blah\"] = B[\"blah\"] \"Do and ask for forgiveness\" vs. \"simplicity and explicitness\". Which is better and why? 回答1: Exceptions are not conditionals

Python list comprehension - want to avoid repeated evaluation

喜欢而已 提交于 2019-11-26 07:38:53
问题 I have a list comprehension which approximates to: [f(x) for x in l if f(x)] Where l is a list and f(x) is an expensive function which returns a list. I want to avoid evaluating f(x) twice for every non-empty occurance of f(x). Is there some way to save its output within the list comprehension? I could remove the final condition, generate the whole list and then prune it, but that seems wasteful. Edit : Two basic approaches have been suggested: An inner generator comprehension: [y for y in (f