Thursday, February 27, 2014

C#: Inconsistent behavior of equality

Learning AngularJS; Guide for beginners:

In C# equality is quite confusing, you might see many cases where obvious thing result in an unexpected result.










Here are some cases to illustrate a bit of different output of equalities.

see here demo

int _Int = 1;
short _Short = 1;
object _objectInt1 = _Int;
object _objectInt2 = _Int;
object _objectShort = _Short;
Console.WriteLine(_Int == _Short);   // case 1 true
Console.WriteLine(_Short == _Int);   // case 2 true
Console.WriteLine(_Int.Equals(_Short));   // case 3 true
Console.WriteLine(_Short.Equals(_Int));   // case 4 false
Console.WriteLine(_objectInt1 == _objectInt1);   // case 5 true
Console.WriteLine(_objectInt1 == _objectShort);  // case 6 false
Console.WriteLine(_objectInt1 == _objectInt2);   // case 7 false
Console.WriteLine(Equals(_objectInt1, _objectInt2));  // case 8 true
Console.WriteLine(Equals(_objectInt1, objectShort)); // case 9 false

How these cases are working?


Console.WriteLine(_Int == _Short); // case 1 true
Console.WriteLine(_Short == _Int); // case 2 true


For case one and two we must first determine what the == operator means here. C# defines over a dozen different built-in == operators:
string == string
object == object
ulong == ulong
uint == uint
int == int
long == long
...
There is no comparison operator for different data types comparison i.e, int == short or short == int, So for this there other possibilities in available operator will be determined, the best match for the case is int == int or short == short but implicit conversion of int to short is not possible and error prone. So the short is converted to int and then the two values are compared as numbers. They are therefore equal as both holds the same value.

Console.WriteLine(_Int.Equals(_Short)); // case 3 true


In case three we must first find which overloaded methods from available methods is invoked here. The Equals() here is called by a type int and it has three methods named Equals:
Equals(object, object) // static method from object
Equals(object)         // virtual method from object
Equals(int)            // Implements IEquatable.Equals(int)
The first one we can eliminate because there are different count of arguments, Of the other two, the unique best method is the one that takes an int; it is always better to convert the short argument to int than to object. Therefore we call Equals(int), which then compares the two integers again using value equality, so this is true.

Console.WriteLine(_Short.Equals(_Int)); // case 4 false!


In scenario four we again must determine what Equals means. The receiver is of type short which again has three methods named Equals
Equals(object, object) // static method from object
Equals(object)         // virtual method from object
Equals(short)          // Implements IEquatable.Equals(short)
Overload resolution eliminates the first because there are too few arguments and eliminates the third because there is no implicit conversion from int to short. That leaves short.Equals(object), which has the moral equivalent of this implementation:
bool Equals(object z)
{
  return z is short && (short)z == this;
}
That is, for this method to return true the argument passed in must be a boxed short, and when unboxed it must be equal to the receiver. Since the argument is a boxed int, this returns false. There is no special gear in this implementation that says “well, what if I were to convert myself to the type of the argument and then compare?”

Console.WriteLine(_objectInt1 == _objectInt1); // case 5 true
Console.WriteLine(_objectInt1 == _objectShort); // case 6 false!!
Console.WriteLine(_objectInt1 == _objectInt2); // case 7 false!!!



In scenarios five, six and seven operator overload resolution chooses the object == object form, which is equivalent to a call to Object.ReferenceEquals. Clearly the two references are equal in case five and unequal in cases six and seven. Whether the values of the objects when interpreted as numbers are equal does not come into play at all; only reference equality is relevant.


Console.WriteLine(Equals(_objectInt1, _objectInt2)); // case 8 true
Console.WriteLine(Equals(_objectInt1, objectShort)); // case 9 false

In scenarios eight and nine operator overload resolution chooses the static method Object.Equals, which you can think of as being implemented like this:
public static bool Equals(object x, object y)
{
    if (ReferenceEquals(x, y)) return true;
    if (ReferenceEquals(x, null)) return false;
    if (ReferenceEquals(y, null)) return false;
    return x.Equals(y);
}
In scenario eight we have two references that are unequal and not null; therefore we call int.Equals(object), which as you would expect from our previous discussion of short.Equals(object) is implemented as the moral equivalent of:
bool Equals(object z)
{
  return z is int && (int)z == this;
}
Since the argument is of type int it is unboxed and compared by value. In scenario nine the argument is a boxed short and so the type check fails and this is false.


We discussed nine different methods that two things can be compared for equality, despite the fact that we have always same input of 1 in both side of comparison, equality is true in only half the cases. If you think this is crazy and confusing, you’re right! Equality is tricky in C#.

Monday, February 24, 2014

JavaScript Best Practices: Why to avoid global variables and objects in JavaScript?

Learning AngularJS; Guide for beginners:

In this article I would try to explain the issue can be occurred due to global variable declaration if it is not declared global intentionally.

As we discussed in previous article JavaScript Best Practices : Strict mode In JavaScript if you are not using strict mode of ECMAScript 5 then assigning value to a variable which is not declared yet, then a global variable of that name will automatically be created.



See demo here.



(function() {
  myVar = 'Hello, Undeclared Variable!';
  alert(foo)  //=>; Hello, Undeclared Variable
})();

alert(myVar)  //=>; Hello, Undeclared Variable

So it is important to always declare your variables before initialization.

See demo here.

(function() {
  var myVar = 'Hello, Undeclared Variable!';
  alert(foo)  //=> Hello, Undeclared Variable
})();

//on accessing out side of scope ReferenceError: myVar is not defined
try {
  alert(myVar)
} 
catch (e) {
  alert("Error :" + e);
}

How it can cause error?


When global variables sneak into your code they can induce troubles. Particularly in applications with concurrency.

In the following example two different function using counter in loop without declaration which causes both to point same global variable.

see here without concurrency

var countOnetoTen = function() {
console.log("countOnetoTen started");
for (counter = 1; counter <= 10; counter += 1) {
         console.log(counter);
     }
 };
  countOnetoTen();  //=> 1 2 3 4 5 6 7 8 9 10

var countEleventtoTwenty = function() {
console.log("countEleventtoTwenty started");
for (counter = 1; counter <= 10; counter += 1) {
         console.log(counter+10);
     }
 };
  countEleventtoTwenty(); //=> 11 12 13 14 15 16 17 18 19 20// 
Both loops increment counter at the same time, which causes strange behavior in concurrency. With small amount of loops counter it is not observable, but it can be problematic in any case. As if two function working concurrently and accessing the same global variable. There can be a situation
  1. countOnetoTen() started set counter = 1
  2. countOnetoTen() : printed counter and increment counter++ //counter = 2
  3. countOnetoTen() : printed counter and increment counter++ //counter = 3
  4.  countEleventtoTwenty() started and set counter = 1
At this point counter is set to 1 while countOnetoTen() already have printed 1 2 and in next iteration it will find counter set to 1 and will print 1 again.
window.setTimeout(countEleventtoTwenty , 10);
window.setTimeout(countOnetoTen, 10);  //=> 2 3 7 8 9
  
this Keyword as global object

Sometime you can use 'this' in method definitions to refer to properties of the method's object.
var obj = {
prop: 'foo',
myFun: function() {
alert(this.prop);
}
};

obj.myFun();  //=> print foo
But 'this' does not conform the normal rules of scope in JavaScript. One might expect 'this' to be available with the same value via closure in the callback specified inside the method here. see here demo
var obj = {
  prop: 'foo',
  myFun: function() {
    window.setTimeout(function() {
      alert(this.prop);
    }, 3000);
  }
};

obj.myFun(); //=> alert undefined
Here in callback 'this' got bound to the global object which do not contains the definition of prop. To get around this, assign the object reference to a regular variable that will have the same value inside the callback definition. see here demo
var obj = {
prop: 'foo',
myFun: function() {
  var that = this;
  window.setTimeout(function() {
    alert(that.prop);
  }, 3000);
 }
};

obj.myFun();  //=> alert foo
The keyword 'this' is actually dynamically assigned whenever a function is invoked. When a function is invoked as a method, i.e. obj.method(), 'this' is bound to 'obj'. But when a function is invoked by itself 'this' is bound to the global object.
var text = 'Hello, world!';
var printText() {
alert(this.text);
}

printText();  //=> Hello, world!
This is true even of functions that were defined as a method.
var obj = {
  prop: 'foo',
  myFun: function() {
   alert(this.prop);
  }
};
When the subroutine is invoked without reference of object ie obj with it, 'this' becomes the global namespace.
var myFun = obj.myFun;
myFun();  //=> undefined
Method invocation and function invocation are two of the invocation patterns in JavaScript. A third is apply invocation, which gives us control over what 'this' will be assigned to during function execution.
myFun.apply(obj, null);  //=> foo
'apply' is a method on Function. The first argument is the value that 'this' will be bound to. Successive arguments to apply are passed as arguments to the function that is being invoked. The last invocation pattern in JavaScript is a constructor invocation. This Pattern was projected to offer a means to make new objects that would seem familiar to programmers who are used to programming with classes.
var Duck = function(name) {
this.name = name;
};
Duck.prototype = {
query: function() {
  alert(this.name + ' says, "quack"');
}
};
When a instance is created with new keyword in front of it, a new object is initiated and is linked to 'this' keyword when function executed.
var donald= new Duck('Donald');
  donald.query();  //=> donald says "quack"
When a new object is created with 'new', the prototype of the new object is set to the prototype of the constructor function. So the new object inherits all of the attributes of the constructor's prototype value. In this case, new duck objects inherit the 'query' method from Duck.prototype.
var daffy = new Duck('Daffy');
daffy.query();  //=> Daffy says "quack"
If a constructor function is called without the 'new' keyword, it is invoked with the ordinary function invocation pattern. So 'this' is assigned to the global object instead of to a newly created object. That means that any attributes assigned to the new object by the constructor function become global variables!
var gotcha = Duck('gotcha!');
gotcha.query();  //=> TypeError: gotcha has no properties
Constructor invocation is pretty complicated and prone to disastrous global variable creation. Here is a neater path to produce new objects that inherit from other targets This defines Object.create, a method that simplifies the behavior of the 'new' keyword. This method was invented by Douglas Crockford.
if (typeof Object.create !== 'function') {
Object.create = function(o) {
var F = function() {};
F.prototype = o;
return new F();
};
}
Object.create(obj) returns a new object that inherits all of the attributes of obj. The 'duck' prototype object here defines a 'clone' method that wraps around Object.create to customize new 'duck' objects as they are created.
var duck = {
query: function() {
print(this.name + ' says "quack"');
},
clone: function(name) {
var newDuck = Object.create(this);
newDuck.name = name;
return newDuck;
}
};

var buffy = duck.clone('buffy');
buffy.query();  //=> buffy says "quack"
In addition to inheriting 'query', new ducks also inherit 'clone'.
var buffy2 = buffy.clone('buffy2');
buffy2.query();  //=> buffy2 says "quack"
Methods and attributes are inherited, not copied. If you change the definition of 'clone' on 'duck' at this point, the change will be reflected in duck objects that have already been created.
buffy2.hasOwnProperty('clone')  //=> false
buffy.hasOwnProperty('clone')  //=> false
duck.hasOwnProperty('clone')  //=> true

Saturday, February 15, 2014

The strict mode restriction and exceptions

The Strict Mode of ECMAScript

The strict mode restriction and exceptions
  •  The identifiers "implements", "interface", "let", "package", "private", "protected", "public", "static", and "yield" are classified as FutureReservedWord tokens within strict mode code.
  • A conforming implementation, when processing strict mode code, may not extend the syntax of NumericLiteral to include OctalIntegerLiteral as described in B.1.1.
  • A conforming implementation, when processing strict mode code, may not extend the syntax of EscapeSequence to include OctalEscapeSequence as described in B.1.2.
  • Assignment to an undeclared identifier or otherwise unresolvable reference does not create a property in the global object. When a simple assignment occurs within strict mode code, its LeftHandSide must not evaluate to an unresolvable Reference. If it does a ReferenceError exception is thrown ]. The LeftHandSide also may not be a reference to a data property with the attribute value {[[Writable]]:false}, to an accessor property with the attribute value {[[Set]]:undefined}, nor to a non-existent property of an object whose [[Extensible]] internal property has the value false. In these cases a TypeError exception is thrown.
  • The identifier eval or arguments may not appear as the LeftHandSideExpression of an Assignment operator  or of a PostfixExpression  or as the UnaryExpression operated upon by a Prefix Increment or a Prefix Decrement operator.
  • Arguments objects for strict mode functions define non-configurable accessor properties named "caller" and "callee" which throw a TypeError exception on access.
  • Arguments objects for strict mode functions do not dynamically share their array indexed property values with the corresponding formal parameter bindings of their functions.
  • For strict mode functions, if an arguments object is created the binding of the local identifier arguments to the arguments object is immutable and hence may not be the target of an assignment expression.
  • It is a SyntaxError if strict mode code contains an ObjectLiteral with more than one definition of any data property.
  • It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code or if its FunctionBody is strict code.
  • Strict mode eval code cannot instantiate variables or functions in the variable environment of the caller to eval. Instead, a new variable environment is created and that environment is used for declaration binding instantiation for the eval code.
  • If this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object.
  • When a delete operator occurs within strict mode code, a SyntaxError is thrown if its UnaryExpression is a direct reference to a variable, function argument, or function name.
  • When a delete operator occurs within strict mode code, a TypeError is thrown if the property to be deleted has the attribute { [[Configurable]]:false }.
  • It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code and its Identifier is eval or arguments.
  • Strict mode code may not include a WithStatement. The occurrence of a WithStatement in such a context is an SyntaxError.
  • It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the Catch production is eval or arguments
  • It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression
  • A strict mode function may not have two or more formal parameters that have the same name. An attempt to create such a function using a FunctionDeclaration, FunctionExpression, or Function constructor is a SyntaxError.

  • An implementation may not extend, beyond that defined in this specification, the meanings within strict mode functions of properties named caller or arguments of function instances. ECMAScript code may not create or modify properties with these names on function objects that correspond to strict mode functions.
  • It is a SyntaxError to use within strict mode code the identifiers eval or arguments as the Identifier of a FunctionDeclaration or FunctionExpression or as a formal parameter name. Attempting to dynamically define such a strict mode function using the Function constructor will throw a SyntaxError exception.
Above details taken from and ECMAScript Complete specification available here.

JavaScript Best Practices : ECMAScript 5 Strict Mode

JavaScript allows developer to do tricks which many other languages do not allow to code. This behavior of JavaScript sometime causes some confusion in JavaScript code and unexpected behaviors. To overcome this in ECMAScript 5 has introduced Strict mode which is supported with all latest browsers and also do not conflict with old browsers.

What Strict Mode is?

Strict Mode is a new feature that allows developer to place code in a strict operating context which prevents certain ambiguous and confusing action from being taken and prompt with more information by throwing exception.

Strict mode gives advantage to developer in following ways:
  • Strict mode disabled the feature which are confusing.
  • Strict mode throws exception on coding mistakes.
  • Strict mode prevent developers by throwing exception if unsafe actions like accessing global object are being made
ES5 specification has detailed information about change in [PDF] or you can see here.


How strict mode works?

Simple. Toss this at the top of a program to enable it for the whole script:
Using strict mode is simple, to make complete script file in strict mode put at the top of script:
"use strict";

Or to make certain functions or context to be strict put the string in that context.
function myFunctionToBeStrict(){
"use strict";
// ... your code ...
}
Enabling strict mode is really a simple just put the string at the top of your any script and that is it. If browser support the strict mode it will start working, and old browsers working with ECMAScript 4 or previous will ignore it as string and keep working as they were.

You can work in dual mode by placing all of your code to execute in strict mode in a context and made that context strict. All the code outside of that context will works in non-strict mode.
// Non-strict context...

(function(){
"use strict";

// strict code context...
})();

// Non-strict context...

What Strict Mode prevents you to code?

Variables

If you try assignment to variable (e.g, myVar = "hello undeclared function";) which is not declared will throw exception. Previously it allows to assign and create a property to global object (e.g, window.myVar). This really prevents some unexpected situation to occur.

see demo here

myVar = "hello undeclared function";
alert("Without strict mode ::: " + myVar);

(function () {
 "use strict";

 try {
 testVar = "hello undeclared function";
 alert("With strict mode ::: " + testVar);
 } catch (ex) {
 alert("Strict mode Exception ::: " + ex);
 } 
})();

Properties

ECMAScript made properties more easily manageable and prevent some coding bloop causing unexpected behavior.

1- adding a property to an object whose extensible attribute is set to false.

see demo here

var myObj = new Object();
Object.preventExtensions(myObj);
myObj.name = "Smith";

console.log("without strict mode ::: "+ myObj.name);

(function () {
 "use strict";

 try {
 var strictObj = new Object();
 Object.preventExtensions(strictObj);
 strictObj.name = "Smith";
 console.log(strictObj.name);

 } catch (ex) {
 console.log("Strict mode Exception ::: " + ex);
 }
})();

2- Attempt to change a property value whose writable attribute is set to false.

see demo here

var myObj = new Object();

Object.defineProperty(myObj, "myVar", {
 value: 10,
 configurable: false
});

delete myObj.myVar;
console.log("Without Strict mode ::: " + myObj.myVar);

(function () {
 "use strict";

 try {
 var myStrictObj = new Object();

 Object.defineProperty(myStrictObj, "myVar", {
 value: 10,
 configurable: false
 });

 delete myObj.myVar;
 } catch (ex) {
 console.log("Strict mode Exception ::: " + ex);
}
})();
3- Try delete a property whose configurable attribute is set to false.

see demo here

var myObj = new Object();

Object.defineProperty(myObj, "myVar", {
 value: 10,
 configurable: false
});

delete myObj.myVar;
console.log("Without Strict mode ::: " + myObj.myVar);

(function () {
 "use strict";

 try {
 var myStrictObj = new Object();

 Object.defineProperty(myStrictObj, "myVar", {
 value: 10,
 configurable: false
 });

 delete myObj.myVar;
 } catch (ex) {
   console.log("Strict mode Exception ::: " + ex);
 }
})();
will result in an error . Previously there was no error when any of these actions are attempted, it will just fail silently.

Deleting variable, function, or argument

Deleting a variable, a function, or an argument will result in an error.
var myVar = "test";
function myFunc(){}

delete myVar; // Error
delete myFunct; // Error

function myFunc2(myArg) {
  delete myArg; // Error
}
In large objects where you defined multiple properties there is possibility of coding duplicate property. With ECMAScript 5 strict mode defining a property more than once in an object literal will cause an exception to be thrown.
// Error because prop1 is twice
var testObj = {
    prop1: 10,
    prop2: 15,
    prop1: 20
};

eval in Strict Mode

The string "eval" cannot be used as an identifier (variable or function name, parameter name, and so on).
// All generate errors...
obj.eval = ...
obj.foo = eval;
var eval = ...;
for ( var eval in ... ) {}
function eval(){}
function test(eval){}
function(eval){}
new Function("eval")
Adding new variable using eval is not allowed in strict mode.
eval("var addVar = false;");
console.log( typeof addVar ); // undefined

Functions in Strict Mode


Attempting to overwrite the arguments object within a function will result in an error(also Arguments as an identifier is not allowed):
function myArgs(myArg) {
    arguments[0] = 20; //not allowed
}
Defining two arguments of identical name is not allowed.
function myArgs(myArg,myArg) {
   //code
}
Access to arguments.caller and arguments.callee now throw an exception. Thus any anonymous functions that you want to reference will need to be named, like so:
function (testInt) {
    if (testInt-- == 0)
        return;
    arguments.callee(testInt--);
}
Defining and calling arguments and caller properties of function is not longer exist.
function myFunc(){
function myInnerFunc(){
// Don't exist, either
myFunc.arguments = ...; // Error
myInnerFunc.caller = ...; // Error
}
}


Eliminates this Coercion


Another important change is a this-value of null or undefined is no longer coerced to the global. Instead, this remains its original value, and so may cause some code depending on the coercion to break.


For example:


window.prop = "foo";
function sayProp() {
    alert(this.prop);
}

// Throws an error in strict mode, "foo" otherwise
sayProp();

// Throws an error in strict mode, "foo" otherwise
sayProp.call(null);
this value of any context must be assigned a value or else it remains undefined, so calling object without new keyword also throw error:
function Person(name) {
    this.name = name;
}

// Error in strict mode
var me = Person("Smith");
Since this is undefined causing error.

with(){}

with(){} statements are not usable when strict mode is enabled. It cause syntax errors.
with (location){
  alert(href);
}
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,