Sunday, January 13, 2013

Google Nexus Developer Options menu



I was trying to enable the developer settings in Nexus Tablet, but alas I couldn't find the developer options menu. Guess what the following trick actually worked and I would like to share it with you.

Settings->About phone
scroll down to the bottom until you see Build number
click on Build number 7 times

You are now a developer. 

Go back to the main settings menu and you'll find the developer menu. Google you are just great !

Tuesday, January 8, 2013

Javascript Object/Variable type detection


            This articles discusses about discovering the type of variables/objects in javascript, we can also look into Javascript (and Ecmascript)basics. A loosely type programming language is one which does not require us to define a type for a variable to hold values.

var a;
a = 1;       
alert(a);    // 1
a = "Test";
alert(a);   //  Test
a=null;
alert(a);   //  null

The above example shows us that javascript is a loosely typed language. So now this gives the freedom to easily assign values to those variable without having to care about their type. But we do face situations where we need to know the type of the variable we are dealing with, so how does javascript handle the situation ?

There are many ways of doing this, lets look upon them one by one

1) instanceof

The very basic method is to use the 'instanceof' operator. It is used to test whether the argument supplied to  it belongs to a particular type. It returns either true or false. It works well for variables created by constructors but not for most literals.

new String('test') instanceof String     //true
'abc' instanceof String                  //false

new Number(10) instanceof Number         //true
10 instanceof Number                     //false

new Boolean('true') instanceof Boolean   //true
true instanceof boolean                  //false

2) typeof

The next method is to use 'typeof'. The typeof operator takes an argument in front and returns the type of the argument as a response string.

typeof 999          // Number
typeof 'test'       // String
typeof function(){} // Function
typeof true         // boolean

But the disadvantage with typeof operator is that

It fails with Arrays
typeof ['abc', 'def', 'ghij', 21]; // "object"
It returns only 'object' for all instance of the object which is not useful
typeof new String('test'); // "object"
typeof new Date();         // "object"
typeof new Number(999);    // "object"
typeof new Boolean(true);  // "object"
It fails with most of the core objects
typeof Math;    // "object"
typeof Array;   // "function"
typeof Number;  // "function"
typeof Object;  // "function"

Note:
typeof operator on null returns object. This is because it the result specified in the standard table for null. Brendan Eich felt that 'null' mostly used with object unlike 'undefined' and hence added this entry to the standard table to return 'object' although ECMA-262-3 standard defines type of null as Null.

3) duck typing

The 'typeof' and 'instanceof' are of not too useful and thus has forced us to follow 'duck typing'.

Wikipedia states 'duck typing is a style of dynamic typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface'

Duck testing -  If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

Similarly if the object can identified by testing if it responds to particular methods. This requires us to define unique methods for every object to identify them easily,
for ex:
In java script

function isString(arg) {
  return arg.charAt !== undefined;
}
function isArray(arg) {
return arg.pop !== undefined;
}

We pass the argument and test if the object contain the properties, and return the corresponding results. This is a better way of testing for objects types than instanceof or typeof.
However if we resort to duck typing we may have to write a function for every different type or if we have a single function to check for types, we may have to add new checks for new classes. This is a disadvantage of duck typing when we want to have a generic solution.

4) Object prototype method -toString(args)

One of the best and recommended ways to discover variable type is to use the core object, Object's prototype method - toString(arg). It checks and returns the type of the argument.

Object.prototype.toString('abc'); // "[object String]"
Unlike 'typeof' it works both with instances of core objects (created with constructors) and with literals
Object.prototype.toString(new String('test')); // " [object String]"
Object.prototype.toString('test'); // "[object String]"

Object.prototype.toString(new Number(999)); // " [object Number]"
Object.prototype.toString(999); // " [object Number]"

Unlike 'typeof' it can also (native) objects such as Math and Date

Object.prototype.toString(Math);       // " [object Math]"
Object.prototype.toString(new Date()); // " [object Date]"

Unlike duck typing we need not add functions or new checks for classes as we can have a single function that takes any arguments and returns the get the type of the  returned.

Thus core object, Object's prototype method - toString(args) proves to be a better solution when we need to determine the type of a javascript variable/object.

Note:
Ecmascript has totally 9 datatypes, out of which only 6 are directly accessible in the language,
  1. Undefined
  2. Null
  3. String
  4. boolean
  5. Number
  6. Object
Everything except the object are represented in implementation directly on a low level in the language. They do not have any properties or constructors.
Objects on the other hand are collection of un ordered set of key, value pairs. Each object has properties and constructor. They are the only type that represents the Ecmascript objects. The keys represent the properties and the value can either be primitives, other objects or function (called as object's method).

the other 3 that can be realized in the language are
  1. Reference
  2. List
  3. Completion   
Reference is used during the use of operators such as 'delete', 'typeof' and consists of a base object.
List describes the behaviour of argument list, such as in new and function calls.
Collection type is used in explanation of break, continue, throw statments.


References and Sources -


Javascript vs Ecmascript - http://stackoverflow.com/questions/912479/what-is-the-difference-between-javascript-and-ecmascript
http://www.examplejs.com/?tag=object-prototype-tostring
http://www.youtube.com/watch?feature=player_embedded&v=v2ifWcnQs6M

Friday, January 4, 2013

Wednesday, January 2, 2013

Short JavaScript Quiz

Give the output of  the following and define the scope of variables

<script>


// a _____-scoped variable
var a=1;

// ______ scope
function one(){
    alert(a); 
}

// ______ scope
function two(a){
    alert(a);
}

// ______ scope
function three(){
  var a = 3;
  alert(a);
}

// Intermediate: 
Does javascript have a block scope ?
function four(){
    if(true){
        var a=4;
    }

    alert(a);
}


// Intermediate:  ______ ______ properties
function Five(){
    this.a = 5;
}


// Advanced: closure
var six = function(){
    var foo = 6;

    return function(){
        // javascript - "closure" means I have access to foo in here,
        // [ to be updated ]
        alert(foo);
    }
}()


// Advanced: __________ scope resolution
function Seven(){
  this.a = 7;
}

// [object].______ loses to [object].______ in the scope chain
Seven.prototype.a = -1; // ______ get reached, because __ is __ in the constructor above.
Seven.prototype.b = 8; // ______ get reached, even though __ is ___ set in the constructor.


one();
two(2);
three();
four();
alert(new Five().a);
six();
alert(new Seven().a);
alert(new Seven().b);


</script>
The best ever examples given by Triptych - on Stackoverflow.com
Source:
http://stackoverflow.com/questions/500431/javascript-variable-scope

Tuesday, January 1, 2013

Question 4


Given a Family Tree, (not necessarily a Binary Tree) print the details of all person in order of generation level.

                                         Jim
                                    /              \

                                /                     \

                             /                          \

                          /                                \

                       /                                     \
                  Martha                                Joe
                 /   |  \                                   /      \
            Sally Andrew Stewart       Kimmel   Walsh
            /
         Peter
       /   |   \
    Meg  Chris  Stewie

Note:[ There's no sibling pointer, each node points to its children]

Expected O/p:
Gen 1: Jim
Gen 2: Martha
       Joe
Gen 3: Sally
       Andrew
       Stewart
       Kimmel
       Walsh
Gen 4: Peter
Gen 5: Meg
       Chris
       Stewie

Comparing Objects in Java

In real world, we tend to compare everything around us. Mom's car is smaller than my car. His Xbox has more memory than my Xbox. He is more higher than me. In Object Oriented language like Java we can define our own logic to compare objects.

In Java, every class extends implicitly extends from Object class. There various ways of comparing objects, they are

 ==

'==' is used between reference variable. eg: { (a==b) , (a!=b) }
It compares only the references of the two variable, and returns true if they are same and returns false if they are different.
It does not compare the values of the objects.
It may be used for comparing two enum values. This works because there is only one object for each enum constant.
But in our real life scenario we may not need to compare objects only by checking reference, we might have to check based on business logic too.

In order to perform comparison between them we need to be able to compare objects based on the criteria  we need to compare them.

equals()

'equals' method is a instance method that is available for every class since they all extends from Object implicitly.
It can be used to check values for equality in classes, but however it doesn't perform any intelligent operation unless the class override this function. If not overridden it just checks the reference of the two Objects and returns true if they are same and false it they are not.
But if you want to implement equality based on logical way or a bussiness logic, JAVA requires us to override both equals and hashcode method.

In addition to this the object equal method has to satify the following properties too,

1) Reflexive : Any object must be equal to itself.
2) Symmetric : If a.equals(b) is true then b.equals(a) must also be true.
3) Transitive : If a.equals(b) is true and b.equals(c) is true then c.equals(a) must also be true.
4) Consistent : multiple invocation of equals() method must result same value until any of properties are modified. So if two objects are equals in Java they will remain equals until any of there property is modified.
5) Null comparison : comparing any object to null must be false and should not result in NullPointerException. For example a.equals(null) must be false

The contract between equals and hashcode method states that
1) If two objects are equal, then their hashcode should be the same
2) If two objects have the same hashcode, they may be equal or different

This contract has to be honored when overriding the equal method of custom classes with our own logic.

Usage:

-Used extensively in Java core library like they are used while inserting and retrieving Object in HashMap
-To avoid duplicates on HashSet and other Set implementation
-Whenever we need to compare objects

Comparable<T> interface

The Comparable interface is used for classes that have a natural ordering. Since helps us to order elements, it greatly used for sorting. It will allow us to compare values and tell us if they are less than, equal to or grater than the other value, thus making a class comparable.

In order to implement this, the class has to implement the Comparable<T> interface and define the method CompareTo(Object o). The method returns a int value of 0,negative or positive integer based on whether the value is less,equal or greater. The method any object as parameter to compare, but me make sure we do not compare unrelated objects like we can't compare a person with a bike. 

Usage:

- Sorting of strings in array can be done simply by java.util.Array's sort method 
- Sorting of strings in collections such as ArrayList can be done by java.util.Collection's sort method
- But if we have a custom defined class such as person which we need to sort we cannot do so with either java.util.Array's sort and java.util.collection's sort. We need to implement Comparable interface and defince the CompareTo(Object o) method in the class. Then we can use either of the sort method based on the data structure we store our values in. 

Comparator interface

 Often we may have to compare objects on different basis, so having just one CompareTo(Object o) may not suffice. For example, if we have a person class we could have comparison based on
(i) age
(ii)first name
(iii)lastname
This means we might need different comaparing functions. This could be achieved with the Comparator interface which is used to compare the value of two objects in many ways.
In order to create many version of the comparing functions we need to write class that implement Comparator interface and define the compare method which has the following signature

public int compare(Object o1,Object o2) 

The method returns negative or 0 or positive number based on whether the objects is less,equal or greater than the other.

Once these classes have been defined based on unique comparing logic, we can use them in our java.util.Array's and java.util.Collections's sort method

Array.sort( <array>, <comparator_class>)

Note:If your class have only one way of sorting like number, you may not need this.

Usage:

- Allows us to define multiple ways of comparing objects. eg: age,firstname, lastname
   Arrays.sort(persons, new LastNameComparator());
   Arrays.sort(persons, new FirstNameComparator());
   Arrays.sort(persons, new AgeComparator());
- Also used for providing comparator classes to methods that we have no control over, ex: If we wanted compare strings based on their length, we could write our own custom comparator and pass it to
   Array.sort( <string>, <string_length_comparator>) 
- Very useful in Strategy Design Pattern, where we store different algorithms as different objects, that can be used later on based on the situation.



Common errors:

When comparing two objects you should know when to use to == and equals.

Equals - Objects can be different but the properties are same (Values are same)
     == -      Objects are same [ both refer to same object in memory ]


Reference-