What to call an if where the condition is always true, like below?
if (functionThatAlwaysReturnsTrue()) {
// Some code that always runs
}
This is for a commit message, explaining when and why this bit of code came to be.
In the world of logic, these are known as tautologies.
In logic, a tautology (from the Greek word ταυτολογία) is a formula that is true in every possible interpretation.
For example, the function...
function isHungry() {
return true;
}
Will always evaluate to true, and would be considered a tautological function.
Related
so, theres a technique I use in a fair amount of programming languages and projects; and I'm wondering if it has a general, language-agnostic "official" term to describe it.
basically, I nicknamed it "trip switch checking." Its where if you need to check that several variables have specific values, possibly of different types, you first set a boolean to "false" and then in either a loop or several if statements, you check what you need to by setting the boolean to true if any of the other variables don't meet your requirements.
I call it trip-switching because the boolean remains false if the "switch" isn't "tripped," using an analogy from a common safety mechanism on industrial machinery where if something moves too far or gets too close or etc. a physical switch is actually bumped into and it shuts the whole thing down. the idea is not to switch it back off until the obstruction is cleared- the machine cant turn itself back on automatically.
pseudocode example, a function that returns true if the trip switch wasn't hit:
function tripswitchcheck()
{
boolean tripswitch = false
if(idontnwantthis == true)
{
tripswitch = true
}
if(iwantthis == false)
{
tripswitch = true
}
//...etc...basically do stuff to check stuff. if any values are undesired, true the tripswitch.
return !tripswitch
}
It may be bad practice depending on the language and nature of the project, but it works, and that's outside of the scope of this question.
First of all, why would you not just have a positive flag in that example:
function tripswitchcheck()
{
boolean success = true;
if(idontnwantthis == true)
{
success = false;
}
if(iwantthis == false)
{
success = false;
}
//...etc...basically do stuff to check stuff. if any values are undesired, falsify success
return success
}
Secondly, why check the conditions if you already know you have failure. Say that we don't have a forward goto in the language, or else, or early returns (or we don't want to return because something else is done based on the success flag before returning):
function tripswitchcheck()
{
boolean success = true;
if(idontnwantthis == true)
{
success = false;
}
if(success && iwantthis == false) // if success is false, fall through
{
success = false;
}
if(success && !othercondition()) // likewise
{
success = false;
}
//...etc...
return success
}
There are reasons not to use else if some of the conditions make use of earlier results.
Anyway, this just comes from basic logic and scientific reasoning: we have a hypothesis and look for reasons why it is not true.
The name for it is perhaps "single exit rule" and such: the function exits through a single return statement.
I have this coffee script
#open_login_dialog = () ->
opt = {
autoOpen: false,
modal: true,
width: 'auto',
focus: function(e) ->
$(this).dialog('option', 'width', $("#loginBox").width())
}
Rails is reporting the cryptic error, “SyntaxError: [stdin]:184:12: reserved word 'function’”. It doesn’t tell me a line, but when I comment out the “focus:function” part everything works, which leads me to believe that’s the culprit. How do I write the above so that it plays nicely with coffee script?
As per #muistooshort's comment, You need to use coffeescript function syntax, which replaces function(a,b,c) with (a,b,c) ->
Secondly, you need to continue using : for assignment inside an object.
I would also suggest brushing up a little on coffeescript. This is my favourite resource on the language. A linter would also help to catch these basic syntax errors.
Your code can be further cleaned up:
#open_login_dialog = ->
opt =
autoOpen: false
modal: true
width: 'auto'
focus: ->
$(this).dialog 'option', 'width', $('#loginBox').width()
Explanation
If you don't expect any parameters, you can leave out the () from the function definition and just use the arrow ->.
You don't need {} brackets to define an object
When defining an object over multiple lines, there is no need for trailing commas
You aren't using the eventObject e in the focus listener, so that can be left out too.
Parenthesis are optional when calling functions and passing them parameters.
I was wondering if it was possible to pass a function foo() as an attribute func="foo()" and have it called this.func() inside of the polymer element?
<foo-bar func="foo()"></foo-bar>
Polymer({
is: 'foo-bar',
properties: {
func: Object,
},
ready: function() {
this.func();
}
});
I've been trying to get this working for ages with no luck.
Thanks in advance.
<foo-bar func="foo()"></foo-bar>
Polymer({
is: 'foo-bar',
properties: {
func: {
type: String, // the function call is passed in as a string
notify: true
},
attached: function() {
if (this.func) {
this.callFunc = new Function('return '+ this.func);
this.callFunc(); // can now be called here or elsewhere in the Polymer object
}
});
So the trick is that "foo( )" is a string when you first pass it to the Polymer element. I fought with this for a while as well and this is the only way I could find to get it done. This solution creates a function that returns your function call, which you assign as the value of one of your polymer element properties.
Some people might say you shouldn't use the Function constructor because it is similar to eval( ) and.... well you know, the whole 'eval is evil' thing. But if you're just using it to return a call to another function and you understand the scope implications then I think this could be an appropriate use-case. If I'm wrong I'm sure someone will let us know!
Here's a link to a nice SO answer about the differences between eval( ) and the Function constructor in case it can help: https://stackoverflow.com/a/4599946/2629361
Lastly, I put this in the 'attached' lifecycle event to be on the safe side because it occurs later than 'ready'. I'm not sure if an earlier lifecycle event or 'ready' could be used instead of 'attached'. Perhaps someone can improve this answer and let us know.
I'm using a library called react-forms in my React app. To better understand how it works I've been reading the code, but a convention keeps popping up which confuses me. Here's the ES6/JSX code:
'use strict';
var React = require('react/addons');
var cx = React.addons.classSet;
var Checkbox = React.createClass({
propTypes: {
/...code.../
},
render(): ?ReactElement {
/...code.../
},
onChange(e: {target: {checked: boolean}}) {
/...code.../
}
});
module.exports = Checkbox;
Note render(): ?ReactElement {}. That's the part which is confusing me. Could someone offer guidance on where to learn more about this syntax? I've hit a lot of dead ends via Google.
If you go to the package.json of react-forms, and look at the browserify section:
"browserify": {
"transform": [
[
"reactify",
{
"es6": true,
"target": "es5",
"stripTypes": true
}
]
]
},
stripTypes is enabled. It strips out things like ?ReactElement, which means it maybe returns a ReactElement (and otherwise null or undefined)
The {target: {checked: boolean}} means e has a target property, which has a checked property which is a boolean.
These are hints for the Flow type checker. You'll also see #flow in a comment at the top of all files that should be type checked. A type checker is a tool – like unit tests – that makes you more confident of your program's correctness, in a way that doesn't require manual testing. In many cases those little type annotations replace unit tests we'd otherwise write.
If you use flow in your project and try to do something like:
<Checkbox />
It would give you an type error because value and onChange are required props. Unlike the runtime props check, this happens without actually running the code (often as soon as you save the file).
I saw this code and I'm not clear what the '!' does in this line of jQuery code on the return on the jQuery object:
$('#remove').click(function() {
return !$('#select2 option:selected').appendTo('#select1');
});
EDIT
What is a good case to do this?
It converts the result of $('#select2 option:selected').appendTo('#select1') to a boolean, and negates it.
However, as the result of appendTo is always a jQuery object, and an object (jQuery or not) is always truthy, the result of !$('#select2 option:selected').appendTo('#select1') is always false.
So what we have is effectively:
$('#remove').click(function() {
$('#select2 option:selected').appendTo('#select1');
return false;
});
Returning false in a jQuery event handler will stop the default event action occuring (e.g. the submission of a form/ navigation of a hyperlink) and stop the event propagating any further up the DOM tree.
So what we have is effectively:
$('#remove').click(function(e) {
$('#select2 option:selected').appendTo('#select1');
e.preventDefault();
e.stopPropagation();
});
Using return false instead of e.preventDefault(); e.stopPropagation(); is OK, but using the return !$(..) as a shortcut for the first example is ridiculous, and there is no need to do it.
Just to reiterate my point, the most important thing to note here is that there is never, ever a good reason/ case to do this.
Links:
Docs for bind() (alias for click())
Docs for preventDefault()
Docs for stopPropagation()