AS3: Conditional statement with a non-boolean variable as the condition - actionscript-3

I've seen conditional statements where the condition is just a variable, which is not a boolean variable. The variable is for an object.
if (myVariable) {
doThis();
}
It seems to be checking if myVariable is null or not. Is that all it is doing? Is this good programming practice? Wouldn't it be better to do this?
if (myVariable != null) {
doThis();
}
It seems much clearer that way.

To properly answer your question:
Using an if statement with an object like that, will check if the object exists.
So if object is null or undefined it will evaluate to the equivalent of false otherwise it will be the equivalent of true.
As far as "good programming practice" goes, that is very opinion based and best left out of StackOverflow.
There is no performance hit and you will find it very common in ECMAScript based languages (like AS3 and JS) - However, many stricter languages (like C# for instance) require an explicit Boolean check so if you program in multiple languages you may find it easier to be consistent.
It's entirely up to you!
Here are some additional examples you may want to consider:
var str:String;
if(str) //will evaluate as false as str is null/undefined
if(str = "myValue") //will evaluate true, as it will use the new assigned value of the var and you're allowed to assign values inside an if condition (though it's ugly and typically uneccessary)
var num:Number;
if(num) //will evaluate as false
num = 1;
if(num) //will evaluate as true
num = 0;
if(num) //will evaluate as false since num is 0
num = -1;
if(num) //will evaluate as true
var obj:Object
if(obj) //will evaluate false
obj = {};
if(obj) //will evaluate true (even though the object is empty, it exists)
var func:Function;
if(func) //false
func = function(){};
if(func) //true - the function exists
function foo():Boolean { return false; }
if(foo) //true - the function exists
if(foo()) //false, the return of the function is false
function foo1():void { return; };
if(foo1()) //false as there is no return type

if (myVariable) // fine but not really explicit.
I usually use:
if (myVariable !== null) // more readable to me

Related

What is the use of two not (!!) operator on a variable

I am following a tutorial on browser detection which is using two !! not operator in return. I want to know what is the significance of using 2 !! in a code.
function supports_geolocation() {
return !!navigator.geolocation;
}
I believe !!navigator.geolocation === navigator.geolocation.
Correct me if not and let me know the significance of using two not operator here.
It force returns boolean value.
// navigator.geolocation is GeoLocation object
navigator.geolocation === true // return false
!!navigator.geolocation === true // returns true

Scala: How to write a generic check function that evaluates any function that returns boolean?

I'm struggling a bit with this: I need a function that takes any function
of type fun(Any*) : Boolean as parameter, evaluates the function and returns true or
false, depending on the success of the function evaluation.
Essentially, what I need is a function type that allows any number and any type of parameter but the function must return Boolean.
Which would allow me to write functions like:
def checkLenght(str : String, length : Int) : Boolean ={
if (str.lenght == length)}
or
def ceckAB(a : Int, b : Int) : Boolean = {
if(a < b && a >= 23 && b < 42) }
so that, for example
eval(checkLenght(abc, 3)) //returns true
eval(ceckAB(4,1)) // returns false
I thought, a function type of:
type CheckFunction = (Any*) => Boolean
may does the trick but I struggle with writing the generic eval function.
Any advise?
Thank you
Solution:
The function requires
1) Another function of return type Boolean: "(func : => Boolean)"
2) Return type Boolean ": Boolean"
3) Returns the value of the passed function-parameter: " = func"
Altogether the function is:
def eval(func : => Boolean) : Boolean = func
It amazes me over again how simple simple things are in Scala.
As pointed out by the comments, this is a rather unusual function with no obvious
sense. Just a word about the underlying reasons.
Motivation:
There were a lot of question about the underlying motivation, so here a short
summary why such a function is needed.
Essentially, there are two reasons.
First one is about moving the failure handling away from the function itself
into a handler function. This preserves the purity of the check function and even allows
re-usage of generic checks.
Second, it's all about "pluggable failure handling". This means, the eval function only
tells if a failure happened (or not). In case of a failure, a handler is called through an interface. The implementation of the handler can be swapped using profiles as required.
Why?
Swapping profiles means, I code my checks and functions as usual but by switching the
profile, I switch the handler which means I can chose between full-stop, console print out, email alert, SNMP notification, push message... you name it. To do so, I need to decouple the check function from its evaluation and from its handling. That's the motivation for such a rather strange looking eval function.
And for the sake of completeness, I've already implemented all that stuff but was I facing the limitation of only handling trivial checks i.e. check(Boolean*) which is neat but often I would prefer to write a function to do more sophisticated checks.
Solved
The function is defined by returning the value of the passed function:
def eval(func : => Boolean) : Boolean = {func}
I can't say that I really understand your motivations for wanting to do what you want to do, but I guess that's beside the point. Maybe the eval function will check something before invoking the supplied function and not invoke that other function (like a fast fail) given some certain condition. Maybe you do some post checking after invoking the function and change the result based on something else. Either way, I suppose you could accomplish something similar to what you want with code looking like this:
def main(args: Array[String]) {
val str = "hello world"
println(eval(checkLength(str, 3)))
println(eval(intsEqual(1,1)))
}
def eval(func: => Boolean):Boolean = {
//Do whetever you want before invoking func, maybe
//not even invoke it if some other condition is present
val fres = func
//Maybe change something here before returning based on post conditions
fres
}
def checkLength(s:String, len:Int) = s.length() == len
def intsEqual(a:Int, b:Int) = a == b
If you really want the eval function to be able to support any function that takes any types of args and returns a Boolean, then using a by-name function like this, and then leveraging closure inside the by-name function to pass any params along to whatever actual function you want to invoke. A better way to demonstrate this is as follows:
def checkMyString(str:String, len:Int) = {
eval(str.length == len)
}
It's probably hard to see that the check str.length == len is not invoked unless eval decides to invoke it until you expand it to it's true form:
def checkMyString(str:String, len:Int) = {
def check = {
str.length == len
}
eval(check)
}
Here, the nested function check has access to str and len due to closure, and this will allow you to get around the requirement that eval must be able to invoke a function with any params that returns a Boolean.
This is just one way to solve your problem, and it might not even be suitable given your needs, but I just wanted to throw it out there.
If your input functions only have 2 arguments, like your two examples, you can write a semi generic function take takes all functions with two arguments of any type:
def eval[A,B](func: (A,B) => Boolean, arg1: A, arg2: B) = {
func(arg1, arg2)
}
def checkLength(str: String, length: Int) : Boolean = {
str.length == length
}
eval(checkLength, "ham", 4)
res0: Boolean = false
But if you want to support functions with more arguments, you would have to write one eval function for three arguments, four arguments, etc
Maybe there is a better way that can handle all cases?

How can I create a default boolean value for a configuration using BND

I am using BND annotations to assist with creating a configuration managed by OSGI cm.
Here is my simple config
#Meta.AD(required = false, type = Type.Boolean, deflt = "false")
boolean enabled();
I have used the BND configuration annotation library quite a few times, but this is the first time that I would like to use a boolean type.
I have read through this
And it talks about an integer or other alternative number based handling of booleans for convenience. The thing is the deflt method always returns a string value, if my type was an integer I would do "2" (these are parsed). But booleans don't seem to be parsed in the configurable BND code up to this assignment point.
if (resultType == boolean.class || resultType == Boolean.class) {
if ( actualType == boolean.class || actualType == Boolean.class)
return o;
if (Number.class.isAssignableFrom(actualType)) {
double b = ((Number) o).doubleValue();
if (b == 0)
return false;
else
return true;
}
return true;
I would like to further know why this returns true when the deflt value is never even parsed. I expected this to more closely follow the spec and return false, since cm would try to do Boolean.parseFrom, so anything not "true" equal ignore case is false.
All of this isn't a complete failure because if I change the value through cm it works correctly after setting to true, and then false again, but obviously that was just an effort at wondering if it would ever work.
Simply I would like to know if anyone knows how to set a BOOLEAN default value using BND's configuration annotations.
Thanks

if ( object != null ) instead of if ( object ) in AS3

Is there any reason to use if ( object != null ) in a conditional instead of the more concise if ( object ). I see the former more often, but it seems like the two are equivalent and the latter shorter.
different objects are treated differently. there are some values that can never be null and might erroneously trigger false when you don't want it to.
Booleans can never be null.
if a Boolean is defined but not given a value it is treated as false;
var bool:Boolean;
trace(bool); // false
bool = true;
trace(bool); // true
int can never be null as well.
if an int is defined but not given a value, it is treated as 0;
var i:int;
trace(i); // 0
trace(Boolean(i)); // false
i = -1;
trace(Boolean(i)); // true
i = 0;
trace(Boolean(i)); // false
i = 1;
trace(Boolean(i)); // true
Number act similar to int.
if a Number is defined but not given a value, it is treated as NaN
var num:Number;
trace(num); // NaN
trace(Boolean(num)); // false
num = -1.1;
trace(Boolean(num)); // true
num = 0;
trace(Boolean(num)); // false
num = 1.1;
trace(Boolean(num)); // true
Strings are the worst.
if a String is defined but not given a value, it is treated as null!
var str:String;
trace(str); // null
trace(Boolean(str)); // false
str = ""
trace(Boolean(str)); // false
str = "hello";
trace(Boolean(str)); // true
it is very rare in my code that i only do 'if (obj)' since most of the time there is something more specific that i truly care about.
The following code will have an object evaluate to false, even though the object is not null:
class SomeWrapper
{
var value: Object;
SomeWrapper(Object value)
{
this.value = value;
}
/// Overriden method from Object, see ActionScript 3 reference
function valueOf()
{
return value;
}
}
var myWrapper = new SomeWrapper(false);
if(myWrapper)
{
trace("myWrapper evaluates to true.");
}
else
{
trace("myWrapper evaluates to false.");
}
The else block will execute in the example above, because myWrapper evaluates to false (its valueOf method returns whatever value the wrapper contained, in this case false) even though myWrapper is not a null reference. The problem is that the above does not only test nullability of reference, it implicitly invokes valueOf method, courtesy of Flash Player virtual machine. This behavior of course may or may not be what you wanted - do you want to test whether myWrapper is a null value or whether it carries a null value? (or both perhaps).
Verbosity in this case is your friend, otherwise you gain code readability in return for potential runtime errors.
if (expression) tests the truthiness of expression by getting its boolean value. Since null and undefined are both falsy, if (object) "works" for making sure object isn't null.
Problem is, though, 0, false, and '' are also falsy. When you use if (object), the code you're trying to keep from running when it's null would also be ignored when object is zero, an empty string, or the actual boolean false. Often, that's not what you want.
If you can't guarantee that object is either null or a type other than string, number, or boolean (or their respective object types), then if (object != null) is less likely to mean something unintended.

Whats wrong with these beginner style codes?

I'm a beginner and I was reading https://stackoverflow.com/questions/237241/what-coding-mistakes-are-a-telltale-giveaway-of-an-inexperienced-programmer. I didn't get few things.
1.Why writing something like this is frowned up on?
if (IsAManMan == true) {
Console.WriteLine("It's a MAN, man!");
}
2.what about this?
if (test) {
return true;
}
else {
return false;
}
I don't write code like above. Should it be written this way: return test? or for readability I sometimes write it like return test?true:false or return (test==true)? true:false
In this example:
if (IsAManMan == true) {
Console.WriteLine("It's a MAN, man!");
}
In most languages, if conditions always evaluate a Boolean expression, which means IsAManMan can only either be true or false. Comparing to true or false is thus unnecessary because it's implied. So we just write this instead:
if (IsAManMan) {
Console.WriteLine("It's a MAN, man!");
}
And in this example:
if (test) {
return true;
}
else {
return false;
}
Following the above example, this means test can only either be true or false, which is like saying:
if (true) {
return true;
}
else { // If it's not true, it's false
return false;
}
That's again unnecessarily verbose code, so we just
return test;
instead.
In the end, it's still a matter of preference and readability. For example, if you think if (IsAManMan == true) is easier to interpret than if (IsAManMan), you can still write it that way and the compiler won't mind.
It's just a tautology. If it rains and If it's true that it rains is exactly the same and therefore, you can (or should) leave out superfluous comparisons, checks and returns.
In both cases you're testing the value of a boolean variable. Because your value is already a boolean, there's no need to explicitly test against true because it's implied in the if statement (and similar constructs that contain a boolean test, like loops)
For example
if(isAManMan == true){
//...
}
could evaluate to
if(true == true){ //answer: true
//...
}
or
if(false == true){ //answer: false
//...
}
which is the same as just writing
if(isAManMan){
//...
}
In your 2nd example, you're examining the value of another boolean value before deciding what boolean to return.
Again,
if (test) {
return true;
}else {
return false;
}
could evaluate to
if (true == true) { //returns true
return true;
}else {
return false;
}
or
if (false == true) { //returns false
return true;
}else {
return false;
}
The if statement is redundant, because the variable already holds the value you want to return, hence this is equivalent, and preferred:
return test;
It's important to note though, that your examples are completely valid, however a good compiler will optimise them into the improved versions I gave, so ultimately it comes down to readability and convention. I believe the versions I gave are more readable and closer to the generally accepted conventions.
These codes do same things. In my opinion, its just readability.
Due to this being tagged language-agnostic:
There are languages where keywords can be used for variable names. In FORTRAN, this is a valid statement: IF IF THEN THEN ELSE ELSE.
If true is defined to be a boolean variable with value false, the proposed shorthand solutions are not the same as the more verbose ones. Neither if test, IsAMan, true, and false are not boolean values in the first place.
A real world example in Python 2.0
>>>True = False
>>>True
False
Tongue in cheek.
Say you want to return a boolean, and not the actual value of test for the 2nd case.
You could do
return !!test
in most languages, or something like
return bool(test)
which is more explicit and readable.