Java Basics III: Methods and Encapsulation in Java

3.  Methods and Encapsulation in Java

3.1 Scope of Variables

The scope defines lifespan of a variable. There are four different scopes in Java:

  • Local variables
  • Method parameters
  • Instance variables
  • Class variables

3.1.1 Local Variables

Variables defined within a method. These are used mainly to store immediate results of a calculation. They have the shortest life span. In the following code, a local variable avg is defined within the method getAverage():


class Student {

     private double marks1, marks2, marks3;    //instance variables

     private double maxMarks = 100;     //instance variable

     public double getAverage() {

          double avg= 0;   //local variable avg

          avg= ((marks1 + marks2 + marks3) / (maxMarks*3)) * 100;
          //avg inaccessible outside getAverage

          return avg;
     }
}

The scope of a variable can be reduced to a for block or an if statement within a method:

public void localVariableInLoop() {

     for (int ctr= 0; ctr < 5; ++ctr) {  //ctr defined within the loop

          System.out.println(ctr);

     }

     System.out.println(ctr);//ctr inaccessible outside the loop, code would not compile

}
public double getAverage() {

     if (maxMarks > 0) {

          double avg = 0;  //avg local to block

          avg = (marks1 + marks2 + marks3)/(maxMarks*3) * 100;

     return avg;

}

     else {

          avg = 0;   //avg cannot be accessed from here, code would not compile

          return avg;

     }

}

3.1.2 Method Parameters

Variables that accept values within a method those are accessible only in the method that defines them.

class Phone {

     private boolean tested;

     public void setTested(boolean val) {

          tested = val;    //accessible only in setTested method

     }

     public boolean isTested() {

          val= false;   //this line won’t compile

          return tested;

      }

}

The scope of a method parameter may be as long as that of a local variable, or longer, but it can never be shorter.

3.1.3 Instance Variables

An instance variable is available for the life of an object. Declared inside the class, outside of the methods and accessible to all nonstatic methods within the class.

class Phone {
     private boolean tested;   //instance variable
     public void setTested(boolean val) { 
          tested= val;  //tested is accessible here
     }
     public boolean isTested() { 
           return tested;   //tested is accessible here
     }
}

The scope of instance variables is longer than that of local variables or method parameters.

3.1.4 Class Variables

A class variable is defined by using the keyword static. It belongs to a class and not to individual objects of the class, therefore it is shared across all objects.

package com.mobile;
class Phone {
     static boolean softKeyboard= true; //class variable
}
package com.mobile;

class TestPhone {
     public static void main(String[] args) {
          Phone.softKeyboard= false; //accessing variable by using class name
          Phone p1 = new Phone();
          Phone p2 = new Phone();
          System.out.println(p1.softKeyboard);//accessing variable by object name
          System.out.println(p2.softKeyboard);
          p1.softKeyboard = true;
          System.out.println(p1.softKeyboard);
          System.out.println(p2.softKeyboard);
     }
}

A class variable can be changed using the name of the class or an object.

3.1.5. Overlapping Variable Scopes

Different local variables can have different scopes. The scope of local variables may be shorter, equal or as long as the scope of method parameters. Local variables can have a shorter scope if declared in a sub-block in a method.
In order to prevent conflicts with variable names, some rules are necessary:
• A static variable cannot be defined with the same name of an instance variable within the same class.
• Local variables and method parameters cannot use the same name.

3.2.  Object’s Life Cycle

An object’s life cycle lasts from its creation until it goes out of its scope or is no longer referenced by a variable. When an object is accessible, it can be referenced by a variable and can be used by calling its methods and accessing its variables.

3.2.1.    An Object is born

An object is created when the keyword new is used.

class Person {}

class ObjectLifeCycle {

     Person person;    //declaring only a reference

}
class ObjectLifeCycle2 {

     Person person = new Person();//declaring and initializing a person type variable.

}

When an unreferenced object is created, it only executes the relevant constructors of the class, but it cannot be accessed using any reference variable.

class ObjectLifeCycle2 {

     Person person = new Person();  // unreferenced object

     ObjectLifeCycle2() {

          new Person();

     }

}

3.2.2.    Object is Accessible

Once an object is created, it remains accessible until it goes out of scope or its reference variable is explicitly set to null. Also if a reference variable gets reassigned to another object, the previous object becomes inaccessible.

class ObjectLife1 {

     public static void main(String args[]) {

          Exam myExam = new Exam();     //Object created

          myExam.setName("OCA Java Programmer 1");

          myExam = null;      //reference set to null

          myExam = new Exam();       //another object creation

          myExam.setName("PHP");

     }

}

After the reference variable gets assigned to null in the previous example, the first object is considered garbage by Java.

3.2.3.    Object is Inaccessible

An object can become inaccessible if it can no longer be referenced by any variable, if it goes out of scope, if an object’s reference variable is assigned an explicit null value or if it is reinitialized.

When an object can no longer be accessed it is marked as eligible to be garbage collected. A user cannot control or determine the execution of a garbage collector as it is controlled by the Java Virtual Machine. It can be never be determined when a particular object will be garbage collected.

3.3.  Create methods with arguments and return values

A method is a group of statements identified with a name. Methods are used to define the behavior of an object. A method can perform different functions:

3.3.1.    Return type of a method

A method may or may not return a value, a void method does not return a value, a method can return a primitive value or an object of any class. The return type can be any of the eight primitive types defined in Java, the name of any class or an interface.

A void method result cannot be assigned to a variable, in that case the code would not compile. The assigned variable must also be compatible with the returned value.

3.3.2.    Method Parameters

Method parameters are the variables that appear in the definition of a method and specify the type and number of values that a method can accept. No limit exists on the number of parameters that can be put within a method, but it is not a good practice to use more than five or six. A parameter that can accept variable arguments can be defined with ellipsis (…). The ellipsis indicates that the method parameter may be passed as an array or multiple comma-separated values. It can only be done once per method and must be the last variable in the parameter list:

Public int daysOff(int… days){

     Int daysOff = 0;

for(int i = 0; i < days.length; i++ )

          daysOff += days[i];

     return daysOff;

}

 

3.3.3.    Return Statement

This statement is used to exit from a method, with or without a value. If a method returns a value, the return statement must be followed by a return value. Methods that do not return a value (void) are not required to define a return statement. The return statement must be the last statement to execute in a method, the compiler will fail to compile if there’s code after it:

 

void setNumber(double val){

     return;

     val = 3;    //return must be the last statement to execute

}

&nbsp;

void setNumber2(double val){

     if(val < 0)

          return;   //return is the last statement to be executed

     else

          val++;

}

In this scenario, the return statement is not the last statement, but it will be the last statement to execute when the parameter val is less than zero.

3.4.  Create an overloaded method

Overloaded methods are methods with the same name, defined In the same class but with different argument lists.

For example the System.out.println() accepts different types of parameters:

int intVal = 10;

boolean boolVal = false;

String name = "eJava";

System.out.println(intVal);   //prints an integer

System.out.println(boolVal);  //prints a boolean

System.out.println(name); // prints a string

 

3.4.1.    Argument list

The argument lists of an overloaded method can differ in terms of any of these options:

  • Change in the number of parameters that are accepted
  • Change in the types of parameters that are accepted
  • Change in the positions of the parameters that are accepted (based on parameter type, not variable names)

 

double calcAverage(int marks1, double marks2) {

     return (marks1 + marks2)/2.0;

}

double calcAverage(int marks1, int marks2, int marks3) {

     return (marks1 + marks2 + marks3)/3.0;

}

 

In the previous example the methods differ in the number of parameters.

 

class MyClass {

      double calcAverage(double marks1, int marks2) {

            return (marks1 + marks2)/2.0;

      }

     double calcAverage(int marks1, double marks2) {

            return (marks1 + marks2)/2.0;

      }

      public static void main(String args[]) {

            MyClass myClass = new MyClass();

            myClass.calcAverage(2, 3);    // compiler can’t determine method to use

     }

}
 

Because int can be passed to a variable type of double, the values 2 and 3 can be passed to both methods, in this scenario the compilation fails.

3.4.2.    Return type

Methods can’t be defined as overloaded if they only differ in their return types.

3.4.3.    Access modifier

Methods can’t be defined as overloaded if they only differ in their access modifiers.

3.5. Constructors of a class

Constructors are methods that create and return an object of the class in which they are defined. They have the same name of the class where they are defined and they don’t specify a return type, not even void.

3.5.1.    User defined constructors

If the author of the class defines a constructor it is known as user defined constructor. It can be used to assign default values to the variables of the class. If a return type is specified, Java will treat it as another method and not as a constructor.

class Employee {

     void Employee() { //return type specified, not a constructor

           System.out.println("not a Constructor ");

     }

}

class Office {

     public static void main(String args[]) {

           Employee emp = new Employee();

          emp.Employee();// calling the Employee method with void return type

     }
}

 

3.5.1.1. Initializer block

It is a block defined in a class that is not a part of any method. It gets executed for every object that is created for a class.

   
class example {

     {

           System.out.println("Initializer Block");

     }

}

 

3.5.2.    Default constructor

In the absence of a user defined constructor, Java inserts a default constructor; it doesn’t accept method arguments and assigns default values to all the instance variables.

3.5.3.    Overloaded constructors

Overloaded constructors can be defined in the same way as overloaded methods. Overloaded constructors can be called within other constructors by using the keyword this.

 

   
class Employee {

     String name;

     int age;

     Employee() {   //no arg constructor

         this(null, 0); //invoking the other constructor

     }

     Employee(String newName, int newAge) {   //constructor with 2 arguments

           name = newName;

           age = newAge;

     }

}

Constructors cannot be called from any other method that is not a constructor of the class.

 

3.6.  Accessing object fields

 

3.6.1.    What is an object field?

It is another name for an instance variable defined in a class.

3.6.2.    Read and write object fields

To access an object field of a class you can use the set method or use the variable name.

   
obj.name = "Selvan";//as long as access modifier of the variable name is not private

obj.setName("Harry");

 

3.6.3.    Calling methods on objects

Java uses the dot notation to execute a method on a reference variable. When calling a method, the exact number of parameters must be passed on it, literal values and variables are also acceptable when invoking a method.

   
Employee e1 = new Employee();

String anotherVal = "Harry";

e1.setName("Hanna");

e1.setName(anotherVal);

Values returned from a method are also accepted.

   
e2.setName(e1.getName());

 

3.7. Apply encapsulation principles to a class

 

3.7.1.    Need for encapsulation

Sometimes when a class is defined, some parts of it must be hidden to other classes to prevent unexpected behavior or security problems.

3.7.2.    Apply encapsulation

Encapsulation is the concept of defining variables and methods together in a class. The private members of a class are used to hide the internal information to other classes.

 
class example {

     private double num1;

}

 

3.8.  Passing objects and primitives to methods

 

3.8.1.    Passing primitives to methods

It is okay to define a method parameter with the same name as an instance variable or object field. Within a method, a method parameter takes precedence over an object field.

 
class Employee {

     int age;

     void modifyVal(int age) {

           age= age+ 1;

           System.out.println(age);

     }

}

In the previous example, in order to reference the instance variable age, the keyword this must be used before.

3.8.2.    Passing object references to methods

There are two main cases:

  • When a method reassigns the object reference passed to it to another variable
  • When a method modifies the state of the object reference passed to it

 

3.8.2.1.Methods reassign the object references passed to them

 

In the following example, since the object references are passed to other variables, the state of the objects remain intact.

   
class Person {

     private String name;

     Person(String newName) {

          name = newName;

}

     public String getName() {

          return name;

     }

     public void setName(String val) {

          name = val;

     }

}

class Test {

     public static void swap(Person p1, Person p2) {

          Person temp = p1;

          p1 = p2;

          p2 = temp;

     }

     public static void main(String args[]) {

          Person person1 = new Person("John");

          Person person2 = new Person("Paul");

          System.out.println(person1.getName()

          + ":" + person2.getName());      //prints: John : Paul

          swap(person1, person2);

          System.out.println(person1.getName()

          + ":" + person2.getName());   //prints: John : Paul

     }

}

 

3.8.2.2. Methods modify the state of the object references passed to them

In the following example, the method modifies the value of both objects person1 and p1:

  
class Test {

     public static void resetValueOfMemberVariable(Person p1) {

          p1.setName("Rodrigue");

     }

     public static void main(String args[]) {

          Person person1 = new Person("John");

          System.out.println(person1.getName());   //prints John

          resetValueOfMemberVariable(person1);  //changes the name

          System.out.println(person1.getName());  //Prints Rodrigue

     }

}

This entry is the third part of of a series on Java Basics, for further reading:
Java Basics I
Java Basics II

Learn How to Hack an App Video Series

Our friends at Arxan,  a company that specializes in mobile payment security and application protection, have shared a list of videos on how applications are hacked.

The first step in defending against mobile application attacks is to see just how easy it is for a hacker to tamper with an application’s code. The “How to Hack an App” video series includes a handful of short clips (1-2 minutes long), each demonstrating how to perform an attack with the use of readily available tools.

  • iTunes Code Encryption Bypass

      • See how easy it is for hackers to bypass iOS encryption to progress a mobile app attack. (Watch Video)
  • Android APK Reverse Engineering

    • Watch how hackers can easily reverse engineer binary code (the executable) back to source code — which is primed for code tampering.  (Watch Video)
  • Algorithm Decompilation and Analysis

    • See how “Hopper” is leveraged to initiate a static, springboard attack for counterfeiting and stealing information.  (Watch Video)
  • Baksmali Code Modification

    • Learn how hackers can easily crack open and disassemble (Baksmali) mobile code.  (Watch Video)
  • Reverse Engineering String Analysis

    • Watch how hackers use strings analysis as a core element for reverse engineering.  (Watch Video)
  • Swizzle with Code Substitution

    • Learn how hackers leverage infected code to attack critical class methods of an application to intercept API calls and execute unauthorized code, leaving no trace with the code reverting back to original form. (Watch Video)
  • Understanding application internal structures and methods via Class Dumps

    • Learn how hackers use this widely available tool to analyze the behavior of an app as a form of reverse engineering and as a springboard to method swizzling.  (Watch Video)

Java Basics II

2.     Working With Java data types

2.1. Primitive Variables

Simplest data type in a programming language
. In Java there are eight primitive data types:

  • char
  • boolean
  • byte
  • short
  • int
  • long
  • float
  • double

2.1.1.    Boolean

Boolean variables can only store one of two values: true or false.

boolean answer =  false;

In this case, the variable answer is assigned a fixed value with a literal (false). A literal is a fixed value that doesn’t need calculations to be assigned to any variable. true and false are the boolean literals.

2.1.2.    Numeric

There are two subcategories for numeric variables: integers and decimals.

2.1.2.1.           Integers

When the value can be counted in whole numbers, it is an integer. They can be stored in different data types:

  • byte
  • int
  • short
  • long

The difference between those types is the range of values they can support:

  • byte –128 to 127, inclusive
  • short –32,768 to 32,767, inclusive
  • int –2,147,483,648 to 2,147,483,647, inclusive
  • long –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, inclusive

For designation of an integer literal value as a long value, the suffix L or l must be added to the literal:

long bigNumber = 584677658897L;

Integer variables can be defined as binary, decimal, octal or hexadecimal numbers. In order to specify the number system, a prefix must be used:

  • decimal use no prefix: int value = 267;
  • octal use the prefix 0: int octVal = 0413;
  • hexadecimal use the prefix 0x or 0X: int hexVal = 0x10B;
  • binary use the prefix 0b or 0B : int binVal = 0b100001011;

Java version 7 allows the use of underscores to help group individual digits or letters of literal values:

long baseDecimal = 100_267_760;

long octVal = 04_13;

long hexVal = 0x10_BA_75;

long binVal = 0b1_0000_10_11;

Underscores cannot be placed at the start or the end of a literal value, cannot be placed right after prefixes for binary and hexadecimal values (0b, 0B, 0x and 0X) but it can be placed right after the prefix for octal values (0). Underscores cannot be placed prior to a long suffix (l or L), finally, they cannot be placed in positions where a string of digits is expected

int i = Integer.parseInt(“3_14”);  //invalid use of underscore

2.1.2.2.           Float and Double

When expecting decimal numbers in Java float and double primitive data types can be used. Float has smaller range than double and requires less space. Capture To initialize a decimal literal value as a float value, the suffix F or f must be used because the default type of a decimal literal in java is double.

float average = 17.925F;

After Java version 7, underscores can be used with floating-point literal values following these rules:

  • You can’t place an underscore prior to a D, d, F, or f suffix (these suffixes are used to mark a floating-point literal as double or float).
  • You can’t place an underscore adjacent to a decimal point.

2.1.3.    Character

A char can store a single character from all the existing scripts and languages. To assign a value to a char variable, single quotes must be used instead of double quotes, otherwise the code will fail to compile.

char v1 = ‘v’;

Java stores char data as a positive integer, therefore it is acceptable to assign an integer to a char.

char a1 = 97;   // a assigned to a1

2.1.3.1.           Casting

Casting is used to forcefully convert data to another data type and must be used between compatible data types, when casting a bigger value to a smaller data type the compiler chops the extra bits that does not fit into the smaller variable. Negative integer numbers can be casted into a char as follows:

char a2 = (char) -97;  //successfully compiled

2.2.  Identifiers

Identifiers are names of packages, classes, interfaces, methods, and variables.

2.2.1.    Valid and Invalid Identifiers

Rules to define valid and invalid identifiers: Identifiers

2.2.1.1.         Java reserved words and keywords:

Words that cannot be used as an identifier name: reserved_words

2.3.  Object Reference Variables

An Object Reference is a memory address that points to a memory area where an object’s data is located.

Class1 refVal = new Class1(); //refVal is the name of the object reference variable

In the previous line, a reference variable refVal of type Class1 is created and an object is assigned to it. The literal value of reference variables is null, it can also be assigned explicitly:

Class1 refVal = null;

2.3.1.    Object reference variables and primitive variables

The main difference between these variables is that primitive variables store the values and reference variables store the memory address of the object they refer to.

2.4.  Operators

Some of the most important Java operators: Java_Operators

2.4.1.    Assignment Operators

The most frequently used operator is the = and it is used to initialize variables with values and to reassign new values to them. The +=, -=, *=, and /=operators are short forms of addition, subtraction, multiplication and division with assignment and work as follows: a -= b is equal to a = a – b a += b is equal to a = a + b a *= b is equal to a = a * b a /= b is equal to a = a / b Multiple values can be assigned in the same line of code as follows:

int a = 7, b = 10, c = 8;

a = b = c; // here a = 8 because the assignment starts from right to left.

2.4.2.    Arithmetic Operators

Arithmetic operators in Java: Arithmetic_Operators

2.4.2.1.           ++ And – (Unary increment and decrement operators)

Used to increment or decrement the value of a single variable by 1. Can be used in prefix or postfix notation:

int a = 10;

++a;   // a = 11

int b = 10;

b++;  //b = 11

When a unary operator is used in a expression, its placement with respect to its operand decides whether its value will increment or decrement before the evaluation of the expression or after the evaluation of the expression.

int a = 20;

int b = 10;

int c = a - ++b;

System.out.println(c);    // c = 9

System.out.println(b);   // b = 11

 

int a = 20;

int b = 10;

int c = a - b++;

System.out.println(c);  // c = 10

System.out.println(b);  // b = 11

int a = 10;

a = a++ + a + a-- - a-- + ++a;

System.out.println(a); //a = 32(a = 10 + 11 + 11 - 10 + 10)evaluates from left to right

2.4.3.    Relational Operators

Relational operators are used to check a condition. The result of the relational operator is always a Boolean value. Usually subdivided in two categories:

  • Comparing greater (>, >=) and lesser values (<, <=)
  • Comparing values for equality (==) and nonequality (!=)

The operators (>, >=) and (<, <=) work with all types of numbers, char and floating point variables that can be added and subtracted.

int a = 10;

int b = 15;

System.out.println(a >=  b);  //prints false

The operators (==) and (!=) can be used to compare all types of primitives: char, byte, short, int, long, float, double, and boolean. != returns true if the values compared are not equal and false otherwise. For the same set of values if == returns true, != will return false. These operators cannot be used to compare incomparable types, for example comparing an int with a boolean will fail to compile.

2.4.4.    Logical Operators

These Operators are used to evaluate one or more expressions and should return a boolean value.

  • And (&&) operator in Java returns true when both conditions are true.
  • Or (||) operator in Java returns true when at least one condition is true.
  • Not (!) operator reverses the outcome of a Boolean value.
int x = 1;

int y = 5;

System.out.println(x == y); //prints false

System.out.println(x != y); //prints true

boolean b1 = false;

System.out.println(b1 == true);  //prints false

System.out.println(b1 != true);  //prints true

System.out.println(b1 == false); //prints true

System.out.println(b1 != false); //prints false

2.4.5.    Operator Precedence

The next list illustrates the precedence of operators in Java, the operators on top have the highest precedence and operators within the same group are evaluated from left to right. Operator Precedence

This entry is the second part of  of a series on Java Basics, for further reading:
Java Basics I
Java Basics III

Java Basics

1.1   The structure of a Java class and source code file

1.1.1       Structure of a Java class

A class can define multiple components for example:

  • Package statement
  • Import statement
  • Comments
  • Class declarations and definitions
  • Variables
  • Methods
  • Constructors

1.1.1.1       Package Statement

All Java classes are part of a package; if a class is not defined in a named package it becomes part of a default package, which doesn´t have a name. If a class includes a package statement, it must be the first statement in the class definition (it cannot appear within a class declaration or after the class declaration) and if present, it must appear exactly once in a class:

package certification;
//should be the first statement in a class

class Course{
}

1.1.1.2 Import Statement

Classes and interfaces from the same package can use each other without prefixing the package name. But to use a class or interface from another package, the import statement can be used:

package University;
import certification.ExamQuestion;
// import must be placed after the package

class AnnualExam{
     examQuestion eq;
}

The import statement follows the package but precedes the class declaration.

1.1.1.3 Comments

The comments in Java code can be placed at multiple places in a class. To place multiline comments, start with /* and end with */ . End-of-line comments start with // and are placed at the end of a line of code. Comments can be placed before the package statement.

/**
* @author JRamirez // first name initial + last name End-of-line within a multiline
* @version 0.0.2
*
* Class to store the details of a monument
*/
package uni; // package uni End-of-line comment

class Monument {
     int startYear;
}

1.1.1.4 Class Declaration

Components of a class declaration:

  • Access modifiers
  • Nonaccess modifiers
  • Class name
  • Name of the base class, if the class is extending another class
  • All implemented interfaces, if the class is implementing any interfaces
  • Class body (class fields, methods, constructors), included within a pair of curly

braces, {}

Example:

public final class Runner extends Person implements Athlete {}

1.1.1.5 Compulsory and optional elements of a class:

Compulsory

  • Keyword class
  • Name of the class
  • Class body, marked by the opening and closing curly braces, {}

Optional

  • Keyword class Access modifier, such as public
  • Nonaccess modifier, such as final
  • Keyword extends together with the name of the base class
  • Keyword implements together with the name of the interfaces being implemented

1.1.1.6 Class Definition

The use of a class is to specify the behavior and properties of an object using methods and variables. It is a design from which an object can be created.

1.1.2       Structure and components of a Java source code file

A  Java  source code  file  is  used  to  define  classes  and  interfaces.  All your Java code should be defined in Java source code files (text files whose names end with .java)

1.1.2.1   Definition of interfaces in a Java source code file

An interface is a grouping of related methods and constants, but the methods in an

interface cannot define any implementation.

interface Controls {
     void changeChannel(int channelNumber);
     void increaseVolume();
     void decreaseVolume();
}

1.1.2.2 Definition of single and multiple classes in a single java source code file

A single class or interface can be defined in a single Java source code or multiple classes and interfaces can be within the same source code. The classes and interfaces can be defined in any order of occurrence in a Java source code file. If a public class or interface is defined, its name should match the name of the Java source code file.

1.1.2.3  Application of package and import statements in Java source code files

When an import or package statement is used within a java source code file, it applies to all classes and interfaces defined in that code.

1.2 Executable Java applications

1.2.1    Executable Java classes versus nonexecutable Java clases

An executable Java class is a class which, when handed over to the Java Virtual Machine, starts its execution at a particular point in the class in the main method. A nonexecutable class doesn’t have it. The programmer designates an executable class from all of the files of an application.

1.2.2  Main method

The first requirement in creating an executable Java application is to create a class with  a  method  whose  signature  (name  and  method  arguments)  match  the main method.

public class HelloExam {
         public static void main(String args[]) {
         System.out.println("Hello exam");
    }
}

This main method should comply with the following rules:

  • The method must be marked as a public method.
  • The method must be marked as a static method.
  • The name of the method must be main.
  • The return type of this method must be void.
  • The method must accept a method argument of a String array or a variable argument of type String

The keywords public and static can be interchanged:

public static void main(String[] args)

static public void main(String[] args)

1.3       Java Packages

1.3.1       The need for packages

Packages are used to group classes and interfaces, they also provide protection and namespace management. Subpackages can also be created within the packages.

1.3.2       Defining classes in a package using the package statement

//The first statement in a class or interface must be the package statement:

package certification;

class ExamQuestion {

     //..code

}

Rules about packages:

  • Per Java naming conventions, package names should all be in lowercase.
  • The package and subpackage names are separated using a dot (.).
  • Package names follow the rules defined for valid identifiers in Java.
  • For packaged classes and interfaces, the package statement is the first statement in a Java source file (a .java file). The exception is that comments can appear before or after a package statement.
  • There can be a maximum of one package statement per Java source code file (.java file).
  • All the classes and interfaces defined in a Java source code file will be defined in the same package. There is no way to package classes and interfaces defined within the same Java source code file in different packages.

1.3.2.1       Directory Structure and Package Hierarchy

The hierarchy of the packaged classes and interfaces should match the hierarchy of the directories in which those classes are defined.

1.3.3       Using simple names with import statements

For using classes and interfaces in other classes of your code, there are two options, using the fully qualified name or using the import statement with a simple name of the class or package.

import1


package office;

 class Cubicle {

     home.LivingRoom livingRoom;

}

package office;

import home.LivingRoom;

class Cubicle {

     LivingRoom livingRoom;

}

1.3.4       Using packaged classes without using the import statement

By using its fully qualified name, a class or interface can be used without an import statement.


class AnnualExam {

     certification.ExamQuestion eq;

}

This is often used when there are multiple classes and interfaces with the same name, because the import statement cannot be used in that case.


class AnnualExam {

     java.util.Date date1;

     java.sql.Date date2;

}

1.3.5       Importing a single or all members of a package

By using an asterisk, all the public classes, members and interfaces of a package can be imported at once.


import certification.*;

 class AnnualExam {

     ExamQuestion eq;

     MultipleChoice mc;

}

Importing a class in Java doesn’t add to the size of the file.

1.3.6       Importing Recursively

By using an asterisk, classes from a subpackage are not imported, only classes from the main package.

1.3.7       Default Package Import

If no explicit package is defined for classes or interfaces, they are imported in the default package automatically in all the classes and interfaces in the same directory.


class Person {

     // code

}

class Office {

     Person p;

}

A class from a default package can’t be used in any named packaged class.

1.3.8 Static Imports

To import an individual static member of a class or all its static members, the import static statement must be used.

package certification;

public class ExamQuestion {

     static public int marks;

     public static void print() {

          System.out.println(100);

     }

}
package university;

import static certification.ExamQuestion.marks;

class AnnualExam {

     AnnualExam() {

           marks = 20;

      }

}

//Importing all of the static members:

package university;

import static certification.ExamQuestion.*;

class AnnualExam {

     AnnualExam() {

          marks = 20;

          print();

     }

}

1.4       Java Access Modifiers

1.4.1       Access Modifiers

Access modifiers control the accessibility of a class or interface and its members, by other classes and interfaces.

They can be applied to classes, interfaces, and their members (instance and class variables and methods). Local variables and method parameters can’t be defined using access modifiers.

Java defines four access modifiers:

  • public(least restrictive)
  • protected
  • default
  • private(most restrictive)

1.4.3       Public Access Modifier

Classes and interfaces defined using the public access  modifier  are  accessible  across  all  packages,  from  derived  to  unrelated classes.

1.4.4       Protected Access Modifier

Classes and interfaces defined using the protected access modifier are accessible to classes and interfaces in the same package and all derived classes even in separate packages. They cannot be accessed by unrelated classes in other packages.

1.4.5       Default Access (package access)

Classes and interfaces defined without any explicit access modifier are defined with package accessibility (default accessibility). They can only be accessed by classes and interfaces defined in the same package.

1.4.6       Private Access Modifier

The members of a class defined using the private access modifier are accessible only to themselves. Private members are not accessible outside the class they are defined.

1.5       Nonaccess Modifiers

1.5.1       Abstract Modifier

When added to the definition of a class, interface, or method, the abstract modifier changes  its  default  behavior.

1.5.1.1       Abstract Class

When  the abstract keyword  is  prefixed  to  the  definition  of  a  concrete  class,  it changes it to an abstract class. An abstract class can’t be instantiated. An abstract class can be defined without any abstract methods but a concrete class cannot define an abstract method.

1.5.1.2       Abstract Interface

An interface is an abstract entity by default. The Java compiler automatically adds the keyword abstract to the definition of an interface.

1.5.1.3       Abstract Method

An abstract method doesn’t have  a  body.  Usually, an abstract method is implemented by a derived class.

1.5.1.4       Abstract Variables

No type of variable can be defined as abstract.

1.5.2       Final Modifier

The keyword final changes the default behavior of a class, variable, or method.

1.5.2.1       Final Class

A class defined final cannot be extended by other classes.

1.5.2.2       Final Interface

No interface can be marked as final.

1.5.2.3       Final Variable

A final variable can only be assigned a value once.

1.5.2.4       Final Method

A final method defined in a base class cannot be overridden in a derived class.

1.5.3       Static Modifier

Can be applied to the definitions of variables, methods,  classes,  and  interfaces.

1.5.3.1       Static Variables

They are common to all instances of a class and are not unique. They are shared by all the objects of the class. Static variables may be accessed even when no instances of a class have been created.

1.5.3.2       Static Methods

Static methods aren’t associated with objects and can’t use any of the instance variables of a class. They can be used to use or manipulate static variables of a class.

Nonprivate static variables and methods can be inherited by derived classes and can be redefined within the derived class.

1.5.3.3       What can a static method access?

Non-static variables and methods can access static variables and methods. Static methods and variables cannot access the instance methods of a class.

 

 

 

This entry is the first part of of a series on Java Basics, for further reading:
Java Basics II
Java Basics III

JSApps 101: AngularJS In A Nutshell

Introduction

Moving on with the topic, in the previous part of this series, we discussed about that interesting new tendency to let the browser do all the user interface heavy-lifting on the client-side, since it is such a good guy. Of course, this involves a LOT of JavaScript going on, since it is the only language the browser understands besides HTML.

We all know how complex and crazy things can get when you involve JavaScript in the picture. The language is usually seen as over-complicated, it used to be hard to debug, learning curve is steep as hell and it can get confusing quickly; also, there used to be a lack of tools and IDEs with strong support for its development just sums up for bad reputation.

However, fear not! After this article, you will have a solid base on how you can turn the fiendish JavaScript you have known for years from a simple DOM traversal helper to a whole reliable application development framework with the aid of AngularJS; man, now THAT’S a catchy name.

What In The World Is AngularJS?

AngularJS is a JavaScript library that allows you to implement the Model-view-controller pattern (in some sort of way) at a client-side level (dude, the browser). Why is this? Because you have two options in life:

  • Option A    You implement a +1000 lines JavaScript source file with a bunch of code that not only is in charge of handling manipulation of the HTML structure and creation of UI components, but also handles all of the data validation and display logic of it, all of this while your fellow teammates start hating the guts out of you.
  • Option B    You be a good developer, who cares about separation of concerns, and split all those tasks in several components where each is in charge of a single thing; those written in separate files for your code maintainability’s sake, while making a lot of friends in the process.

In the good old days, option A was “kind” of affordable (heavy quotations), since JavaScript was used for simple things like adding and removing elements from the HTML structure, changing colors and such. But when we talk about implementing a client application only using JavaScript, option A starts struggling. Mainly because we are not only moving HTML elements around, animating stuff and other user interface tasks; but also performing data validation, error handling and server communications in the client-side.

Of course, option B is the way to go. Since there is a ton of things going on in the browser, we need a way to create components that handle each task separately. This is known as the Separation of Concerns principle, or SOC; which states that your code has to be split in several parts, handling a single task each, orchestrated in order to achieve a common good. And this is where AngularJS shines. It allows you to:

  • Organize your client-side code in a Model-view-controller fashion, so you have separate components where each handles a different task in the logic stack: from user input to server data posting (Don’t worry, we’ll get on this later on.)
  • Live template processing and data-binding; more specifically: munch a template, bind it to specific data coming from the server or anywhere else and then produce a valid HTML piece that can be displayed in the browser.
  • Creation of re-usable user interface components.
  • Implementation of advanced patterns, like dependency injection; which is tied to…
  • Ability to implement unit tests for the JavaScript code.

Client-side Model-View-Whatever

We all know Model-View-Controller (MVC from now on) was conceived for a good reason: Roles and responsibilities matters. It was designed as a practical way to separate all of the front-end logic into three interconnected parts, so code having to do with how data is displayed is clearly separated from the code that validates, stores and retrieves that data. Also, it was thought with unit testing in mind. MVC Flow Now, MVC is commonly used server-side; think of ASP.NET MVC or Spring MVC, where you have a class representing the “controller”, which fetches data into “models” and then binds them to a template producing a “view” in the form of an HTML document, which is returned to the browser for display on the user screen. Remember, each time we talk about MVC, we are generally referring to the Presentation Layer of an application.

Now, why go crazy and MVC-fy my JavaScript code? Well, because what’s trendy right now are dynamic web interfaces where pretty much everything is asynchronous, little post-backs are done to the server unless really necessary and you have complex UI components like pop-ups, multi-level grids and others living on the screen (think of Facebook, for example). The only way to do this is delegate the browser (through JavaScript) with the user-interface composition, interaction between all of the components and lastly fetching and posting data back and forth from the server. You really, really NEED a way to achieve law and order so the client-side code does not become an uncontrollable mess.

OK, enough talk already. Let’s dive into how to implement a simple application using AngularJS.

Hello, Angular

Consider the classic “To-do List” example. We want a screen that displays a list of items to be completed; also we need to show a mini-form that allows us to enter and add new items to the list. Here is how it should look: To-do List UI So, in order to get this done, we need to complete some steps:

  • Create the HTML document which will be representing our view.
  • Include the AngularJS library in the HTML document so we can start creating controllers that will handle behavior of the user interface.
  • Create and include a JavaScript file where we are going to create our application object (wait for it) and define some controllers.
  • Add scope (almost there…) variables and functions that will be bound to the view through special AngularJS HTML attributes.

Basic View Markup

Let’s start this in a natural way: let’s create the user interface first. We will create a file called todolist.html and we will add the following HTML to it:
ANGJS SNIP1
Now, nothing fancy right there; we just included the AngularJS library at line 8 and another file at line 9, which we will create in a moment. However, just notice the structure of the document: We have an UL element which will represent our list of to-do items and then a couple input controls so we can add new items to the list. It does not have any information on it for now, but eventually it will… And it will be awesome.

Let’s leave this code as it is for now, let’s move to the app.js file which has all the fun going on.

Adding Logic: The Controller

Just by looking at the previous HTML document, you will realize that there are two things we need regarding to view state data:

  • An array to store the to-do items to be displayed in the UL element at line 13.
  • A function to add new items when I click the Add button at line 15.

Simple, right? Well, let’s create a new file called app.js and add the following code; I’ll explain it later:

ANGJS SNIP2

First things first: let’s take a look at line 1. Before we start building controllers that handle UI logic, we need to create what is known as an AngularJS application module; this is done by calling the angular.module() function and passing it the module name, which returns the created module. This object will later be used as a container where you will store all of the controllers belonging to this particular JS App.

The variable angular is available after we included the AngularJS library in our HTML document at line 8.

After we create the application object, we can start creating controllers; being done in line 3 through the controller() function, which is now callable from the application module we created in line 1. This function takes two arguments: the name of the controller and a callback function that will be responsible of initializing the controller and which will be called each time a controller is instantiated by AngularJS. AngularJS also passes a special variable to that function called $scope; everything that is added to the $scope variable during controller initialization, will be accessible to the view for data binding; better said: it represents what the view can see.

The rest of the lines are quite self-explanatory:

  • Lines 7 to 11 adds a pre-initialized array of to-do items to the scope, that will be used as storage for new items. It represents the items that will be displayed in the empty UL element we have right now.
  • Line 13 declares a variable that will hold the description of new items to be added after the Add button is clicked.
  • Lines 17 to 21 define a function that will add new items to the to-do items array; this should be called each time the Add button is clicked.

Binding The View

Now that we have AngularJS, the application module and the to-do list controller, we are ready to start binding HTML elements in the view to the scope. But before that, we need to change our <html> tag a little and add some special AngularJS attributes:

ANGJS SNIP3

Notice the ng-app attribute we added to the <html> tag; this is your first contact with one of the several directives that are part of the AngularJS data binding framework.

Directives are simply HTML element markers that are to be processed by the data binding engine. What does ng-app do? Well, it tells AngularJS which application module it should use for this HTML document; you might notice we specified ToDoListApp, which is the one we created in out app.js file at line 1.

After we associate our HTML document with the ToDoListApp, second step is to specify a controller for our view; this is done through the ng-controller directive. The ng-controller directive assigns a controller to a section of the HTML document; in other words, this is how we tell Angular where a view starts and when it ends.

Anyways, modify the <body> tag so it looks like this:

SNIP4

Same with the ng-app directive, the previous code tells AngularJS that everything inside the <body> tag will be governed by the ToDoListController, which we created in our app.js file at line 3.

Now we are ready to start binding elements to members added to the $scope variable during the ToDoListController controller initialization.

The ng-repeat Directive

Let’s start with the empty UL list element. In this case we want to create a new child LI element per item that is contained in the to-do items array. Let’s use the ng-repeat directive for this matter; add the following code inside the UL tags:

ANGJS SNIP5

OK, hold on tight. The ng-repeat directive will repeat an element per item in an array used as data source; the quoted value represents the iterator expression, which defines the array to be iterated and an alias used to refer the current item being iterated.

In this case, we specified that it should repeat the LI element for all of the items in the items array defined in the $scope variable from line 7 through 11 in the app.js file.

Lastly, inside the LI tags we define an Angular template, which is an expression enclosed in double curly braces that will be compiled dynamically during run-time. In this case, the template is extracting a member named desc from each item and is going to display its value inside the LI tags being repeated.

Go ahead, save your files and open todolist.html in your preferred browser; you will see how the list gets filled. Awesome stuff, huh?

The ng-model Directive

Next in our list is the ng-model directive, which is used to bind the value of an input element, a text box, text area, option list, etc.; to a variable of the $scope. But before I give you more talk, change the input element at line 15:

ANGJS SNIP6

Binding the value of an element means that each time the value of the input element changes, the variable specified in the ng-model directive will change with that value.

AngularJS enables two-way binding by default, meaning that if the value of the variable the input element is bound to changes, the change will be reflected in the input element on screen. This is the true magic of AngularJS: You can change the value of elements displayed on screen just by modifying values of the $scope variable; no need of selectors, no need to access the DOM from JavaScript, no need of extra code.

In this case, the input element has been bound to the newItemDescription variable of the $scope, defined at line 13 of the app.js file. Each time the value of the input element changes, the variable at the scope will be updated and viceversa.

The ng-click Directive

What if I want to do something when I click that? For that, AngularJS provides a bunch of event handler directives. These directives can be used to invoke functions defined on the $scope each time the user performs an action over an element.

The only one we are going to use for this example is the ng-click, which handles the user click on a button or input element; the expression it takes is basically the code to be executed on each click. In our case, we will modify the button element at line 15 and add the following directive:

ANGJS SNIP7

If you look closely, we are telling AngularJS to call the addItem function defined in the $scope. If you see the code of that function from line 17 to 21, you will see that it adds a new item to the to-do list array, based on the value of the newItemDescription variable.

If you save your files and open todolist.html, you will see how the list is automatically updated each time you enter a new description in the text box and click on Add.

Your HTML document is dynamic and alive. How cool is that?

What Kind Of Sorcery Is This!?

OK, I must tell you that all of this does not happen through magic. AngularJS is what’s called an unobtrusive library; which means that everything happens automatically as soon as the library finishes loading.

At the very beginning, when the HTML document finished loading, AngularJS crawls through HTML document structure looking for ng-app directives which tells it that something has to be done there. After all of the directives have been found, the marked elements are processed separately: elements are bound to controllers and templates are compiled.

The $scope variable lifetime is automatically handled by AngularJS, each time something happens on-screen, it is notified and performs anything that has to be done to ensure the controller and view are synced; from updating values in the $scope bound to a particular element to refreshing an element or template. This is done through the implementation of some sort of the observable pattern that allows AngularJS to react to changes on elements and the $scope itself.

Conclusion

Woah! That was a bunch of stuff to digest. Hopefully, you will make sense out of it with some practice. Of course those three directives are not everything that there is on AngularJS; for a complete list on all of the possible directives you can use out-of-the-box, take a look here.

Have in mind that you can also extend the library with custom directives, but that is an advanced topic we might cover in a future article.

AngularJS is not everything there is about JS Apps, this was a very basic introduction and I want you to have knowledge you can use in real life, so we will be learning how to build more complex JS Apps in my next article. Topics to be covered will be:

  • Creating custom Angular directives.
  • Complex user interfaces (windows, redirection and data validation.)
  • RequireJS for on-demand asynchronous JavaScript files loading.

Hope that sounds exciting enough for you. Stay tuned! 😀

Source Code

Further Reading

JSApps 101: Introduction To JavaScript Applications

Introduction

So, JavaScript… Again! After some months away from this blog, I am back with a new series of articles related to the incredible, magical and mysterious world of JavaScript. More specifically, JavaScript applications. Have you ever heard of AngularJS, Backbone, Knockout JS, LESS and such things? Read on, this might interest you.

We have used, at some point of our Internet life, some awesome websites, such as Facebook, Github, Spotify, and others; where everything is asynchronous, the user interface is super-responsive and couldn’t be closer to a desktop application in matters of functionality, all of this right in our browser. Less that some people imagine is that these sites owe their slickness mainly to our good old friend in battle: JavaScript; oh so many developers underestimate JavaScript. This article series will dive you into the basis of how these kind of powerful JavaScript applications are built and over what technologies and frameworks, so let’s move forward into some basic concepts.

Server-side v.s. Client-side

So, what in the world is a JavaScript application anyways? Well, as you might know, the traditional way a web application works is that you have a set of specialized frameworks and tools (name it ASP.NET, PHP, Spring Framework) running server-side; when someone requests a page from the server, it responds with an HTML document, usually resulting of the parsing of a server-side template (a PHP, ASPX or the alike) and then bound to data coming from the database. Those templates being processed by the server usually contain special syntax and directives that instructs the server’s templating engine how to bind data to it and produce a valid HTML document; some might recall these as the dreaded “server tags.”

Standard Server Request/Response

 

Some server-side technologies like ASP.NET use “controls” or helpers that assist in the rendering of complex user interface components into HTML like grids, forms and charts bound to dynamic data coming from the database. Each time these components need to be refreshed, they do it through asynchronous AJAX requests or a full-page refresh (known as a server post-back, which all users love, or not). While these are handy for speed-building of web solutions, is not as efficient as pure-JavaScript graphical components.

ASP.NET WebControls

Often, JavaScript is used to manipulate the structure of the resulting HTML document, get the value of a field, and other simple tasks dynamically on the browser (better known as “the client side”) without the need of refreshing the page. But as popularity of JavaScript arise (let’s thank jQuery for that), it is being delegated with more and more complex stuff like rendering templates into HTML, so it is done client-side and not server-side; binding of server data, validation of user input and controlling page flow. This being said, a JavaScript application is basically a “client” that runs on the browser, thanks to the leverage of technologies such as JavaScript, HTML5 and CSS3. All of the UI logic is controlled client-side, right there in the browser.

Structure of a JavaScript App

Before moving on, it is true that this requires a paradigm shift if you have been working on traditional web applications for a while, specially if you have never used a Model-View-Controller approach. If you have never heard of, or used Model-View-Controller, I’m afraid there is some reading to be done before continuing. But hey! You can start here, or else you can continue reading this incredibly sexy article.

As mentioned before, a JavaScript application, or JS App (patent pending), usually follows an MVC approach. It is composed of several “views”, which are usually HTML documents or templates; “controllers” that handles validation, logic flow and communications with the server; and “models” that contains the data to be displayed and bind on the views. As you might notice, is a pretty similar model to server-side technologies like ASP.NET MVC and Spring MVC, just that the entire presentation layer is being moved to the browser, specifically into JavaScript components. We’ll analyze advantages of this later on.

With all the presentation logic being handled by the browser, where does the data we see on the UI coming from? It comes from the server; that is the real use we have for it. The controller at the browser is the one responsible for this channel of communication; it retrieves data from the server each time the user pages through a data grid and sends data to it whenever the user needs to create or edit information. JS Apps work in a similar way to smartphone apps, in which a client runs on the phone locally and it uses data coming from a remote server. In fact, there are specialized build tools, like PhoneGap, that creates applications to be installed on a smartphone from HTML/JS/CSS3 sources.

JS App Structure

Pros & Cons

While JS Apps goes far off any conventional use of a browser, it offers several advantages:

  • Rendering of pages and templates is done by the browser in the client computer, taking advantage of the client computer’s processing power and leaving less workload on the server.
  • Better user interface responsiveness, since all calls to the server are asynchronously and JavaScript UI components are usually lightweight.
  • Completely decoupled from the server logic.
  • Less calls to the server, since it is only accessed to get data and not pages in every possible display state it might have.
  • High separation of concerns, since the server ONLY handles business logic and not UI-related validation and such.
  • Easy unit testing of the user interface and UI logic.

Also, it might represent some disadvantages:

  • Lots, lots and LOTS of JavaScript to be written; we all know it can be a pain to maintain if not properly done.
  • The learning curve is quite step, since most people is used to jQuery and DOM manipulation but not to JavaScript controllers, models and pseudo-classes; let alone advanced concepts like JavaScript dependency injection.
  • Data incoming to the server needs to be double-checked in order to prevent bad information sent by tampered JavaScript components.

Sounds Kind of Interesting, Now What?

OK, now that you might get the picture of what a JS App might look like and its advantages, so the next step would be to analyze the technologies and frameworks you could use, getting your hands dirty along the way so you can start developing this kind of applications.

In the following articles we will move into learning JavaScript libraries like AngularJS, for client-side Model-View-Controller; RequireJS, a library that allows asynchronous loading of JavaScript files on-demand; usage of Twitter Bootstrap, to build nice HTML5-compliant user interfaces; and ultimately how to structure your server application as a solid data provider for your JavaScript application.

So, stay tuned for more articles! 😀

 

6 Days with Windows Phone

Disclaimer: What follows is my personal opinion, it does not reflect Informatech’s position necessarily. Though I’ve tried to be as unbiased as possible, it will undoubtedly reflect my views.

A friend upgrades to a Lumia 920 and a Lumia 900 is left orphaned.

With a Galaxy Nexus experiment going on since Oct 2012, and waiting for Apple’s comeback iOS 7 (plus whatever they introduce later this year), I dive in for a week to see how the Windows Phone 7.8 experience stacks up.

Clarifications

I hail from a background of Apple devices, at least for a couple of years now (I had Nokia smartphones before). I’ve been exploring Android, if anything because as a developer it’s unforgivable not to have any experience in it, but customizability is not something that drives my purchases.

Beyond specific OS choices, I believe in finished, polished products. I dislike having to hack or otherwise mod my devices. Yep, that includes spending hours tweaking and configuring.

I like my stuff to just work, with minimal fuss. Things can be technologically interesting, but in a device I want a product. That said, let’s delve in.

The Experience

2013-06-10 10.54.522013-06-10 10.55.03

What do I usually do in a smartphone (that will thus dictate the experience on Windows Phone)? Pretty much WhatsApp, Facebook, push Gmail, push Google Contacts, camera, and Dropbox auto photo uploads. Yes, other things matter, but that’s what realistically I use most of the time, and will be the scope of this review.

So let’s not waste too much time discussing setup (which is generally polished), suffice it to say that of the above:

  • WhatsApp and Facebook were installed from the Marketplace.
  • Camera is good, but there is no official Dropbox support. I routed around this by enabling SkyDrive auto uploads, so no biggie.
  • When setting up the Google account, we hit our first snag. Because Google discontinued ActiveSync, the only straightforward choice is IMAP setup just for email, no calendar or contacts. Fortunately you can add Gmail as an Exchange server manually through the end of July. This worked OK, but the contact import was kinda crappy (ie. contacts with multiple numbers, just had the first imported).

Once everything was working, it took me about a day to get used to the concept of Live Tiles. That is the driver of the Windows Phone UI, where you’ll launch apps, get notifications, and see periodic content changes of relevant content. The idea is novel and elegantly implemented, and after months on Android, it made me feel that special care had been taken in the consistency and polish of the interface. Both were very much welcome.

In full day-to-day usage, the UI shines, though where I felt the most joy was in the touch keyboard. It is absolutely a pleasure to use (no gestures or swipes, straight taps), and by far it’s the best of any smartphone that I’ve used.

The camera was another pleasant surprise. The capture and photo browser were excellent, behold:

WP_000006

The multitasking also requires a bit of getting used to, as a long press of the back key will allow you to get an open app list, however it will not let you kill any. You have to jump in, and continually press back until you exit.

To finish off the “stock” functionality, the People hub was generally useful (even though the Google contacts were indeed not wholly sync’d). It gave quick access to recent contacts, and integrated well with social networks.

Even though Facebook is integrated in, the way to properly see your Newsfeed is through the standalone app. Which sadly is not developed by FB, and is quite honestly sub par to similar offerings on iOS and Android.

WhatsApp was a similar story, the implementation is not up to par with the other platforms, and more annoyingly it activated the music controls and gobbled battery. As a workaround, you have to download a separate app that kills the music controls, and run it periodically. The app also seemed to implode under heavily used group chats.

Even with the mediocrity of third-party apps, I can honestly say the OS is pleasant to use, and the tiles are colorful and attractive. So rounding out:

Pros

  • Superb interface, extremely polished.
  • Quite simply the best touch keyboard I’ve ever used, on any smartphone.
  • Integration between social networks and contacts is almost seamless.
  • Excellent camera.
  • Lumia hardware is very capable and attractive.
  • Integration with Microsoft services is predictably good.

Cons

  • Synchronization with Google services is poor (especially now that ActiveSync was retired).
  • App selection and most importantly, quality, is low, low, low. Years behind iOS and Android.
  • WhatsApp drains the battery, and requires “Stop the Music” to kill it every once in a while.
  • Multitasking does not allow you close the application from the app list (WP 7.8?)
  • Lack of a centralized notification area is confusing.

Conclusion

If you’re a Hotmail user, and you live your life in Exchange and Microsoft Office, Windows Phone is a natural fit. The Lumia hardware is capable and attractive, the UI is very polished, and if you can live with the poor app selection and quality, you’ll enjoy it.

However if you use Google services, and have gotten used to the abundance of other app stores, the UI may not compensate the tradeoffs for functionality you would have to give up. In the future this may change, but at present it’s too much to take.

Overview Of The Task Parallel Library (TPL)

Introduction

Remember those times when we needed to spawn a separate thread in order to execute long-running operations without locking the application execution until the operation execution completes? Well, time to rejoice; those days are long gone. Starting by its version 4.5, the Microsoft.NET Framework delivers a new library that introduces the concept of “tasks”. This library is known as the Task Parallel Library; or TPL.

Tasks v.s. Threads

In the good (annoying) old days we frequently had the need to spawn a separate thread to query the database without locking the main application thread so we could show a loading message to the user and wait for the query to finish execution and then process results. This is a common scenario in desktop and mobile applications. Even though there are several ways to spawn background threads (async delegates, background workers and such), in the most basic and rudimentary fashion, things went a little something like this:

User user = null;

// Create background thread that will get the user from the repository.
Thread findUserThread = new Thread(() =>
{
    user = DataContext.Users.FindByName("luis.aguilar");
});

// Start background thread execution.
findUserThread.Start();

Console.WriteLine("Loading user..");

// Block current thread until background thread finishes assigning a
// value to the "user" variable.
findUserThread.Join();

// At this point the "user" variable contains the user instance loaded
// from the repository.
Console.WriteLine("User loaded. Name is " + user.Name);

Once again, this code is effective, it does what it has to do: Load a user from a repository and show the loaded user’s name on console. However, this code sacrifices succinctness completely in order to initialize, run and join the background thread that loads the user asynchronously.

The Task Parallel Library introduces the concept of “tasks”. Tasks are basically operations to be run asynchronously, just like what we just did using “thread notation”. This means that we no longer speak in terms of threads, but tasks instead; which lets us execute asynchronous operations by writing very little amount of code (which also is a lot easier to understand and read). Now, things have changed for good like this:

Console.WriteLine("Loading user..");

// Create and start the task that will get the user from the repository.
var findUserTask = Task.Factory.StartNew(() => DataContext.Users.FindByName("luis.aguilar"));

// The task Result property hold the result of the async operation. If
// the task has not finished, it will block the current thread until it does.
// Pretty much like the Thread.Join() method.
var user = findUserTask.Result;

Console.WriteLine("User loaded. Name is " + user.Name);

A lot better, huh? Of course it is. Now we have the result of the async operation strongly typed. Pretty much like using async delegates but without all the boilerplate code required to create delegates; which is possible thanks to the power of C# lambda expressions and built-in delegates (Func, Action, Predicate, etc.)

Tasks have a property called Result. This property contains the value returned by the lambda expression we passed to the StartNew() method. What happens when we try to access this property while the task is still running? Well, the execution of the calling method is halted until the task finishes. This behavior is similar to Thread.Join() (line 16 of the first code example).

Tasks Continuations

OK, we now have knowledge of how all this thing about tasks goes. But, let’s assume you don’t want to block the calling thread execution until the task finishes, but have it call another task after it finishes that will do something with the result later on. For such scenario, we have task continuations.

The Task Parallel Library allows us to chain tasks together so they are executed one after another. Even better, code to achieve this is completely fluent and verbose.

Console.WriteLine("Loading user..");

// Create tasks to be executed in fluent manner.
Task.Factory
    .StartNew<User>(() => DataContext.Users.FindByName("luis.aguilar")) // First task.
    .ContinueWith(previousTask =>
    {
        // This will execute after the first task finishes. First task's result
        // is passed as the first argument of this lambda expression.
        var user = previousTask.Result;

        Console.WriteLine("User loaded. Name is " + user.Name);
    });

// Tasks will start running asynchronously. You can do more things here...

As verbose as it gets, you can read the previous code like “Start new task to find a user by name and continue by printing the user name on console”. Is important to notice that the first parameter of the ContinueWith() method is the previously executed task which allows us to access its return value through its Result property.

Async And Await

The Task Parallel Library means so much for the Microsoft.NET Framework that new keywords were added to all its languages specifications to deal with asynchronous tasks. These new keywords are async and await.

The async keyword is a method modifier that specifies that it is to be run in parallel with the caller method. Then we have the await keyword, which tells the runtime to wait for a task result before assigning it to a local variable, in the case of tasks which return values; or simply wait for the task to finish, in the case of those with no return value.

Here is how it works:

// 1. Awaiting For Tasks With Result:
async void LoadAndPrintUserNameAsync()
{
    // Create, start and wait for the task to finish; then assign the result to a local variable.
    var user = await Task.Factory.StartNew<User>(() => DataContext.Users.FindByName("luis.aguilar"));

    // At this point we can use the loaded user.
    Console.WriteLine("User loaded. Name is " + user.Name);
}

// 2. Awaiting For Task With No Result:
async void PrintRandomMessage()
{
    // Create, start and wait for the task to finish.
    await Task.Factory.StartNew(() => Console.WriteLine("Not doing anything really."));
}

// 3. Usage:
void RunTasks()
{
    // Load user and print its name.
    LoadAndPrintUserNameAsync();

    // Do something else.
    PrintRandomMessage();
}

As you can see, asynchronous methods are now marked with a neat async modifier. As I mentioned before, that means they are going to run asynchronously; better said: in a separate thread. Is important to clarify that asynchronous methods can contain multiple child tasks inside them which are going to run in any order, but by marking the method as asynchronous means that when it is called in traditional fashion, the runtime will implicitly wrap this method contents in a task object.

For example, writing this:

var loadAndPrintUserNameTask = LoadAndPrintUserAsync();

.. is equivalent to writing this:

var loadAndPrintUserNameTask = new Task(LoadAndPrintUserAsync);

Remember the task was created, but it has not been started yet. You need to call the Start() method in order to do so.

Now, we can also create awaitable methods. This special kind of methods are callable using the await keyword.

async Task LoadUserAsync()
{
    // Create, start and wait for the task to finish; then assign the result to a local variable.
    var user = await Task.Factory.StartNew<User>(() => DataContext.Users.FindByName("luis.aguilar"));

    // Return the loaded user. The runtime converts this to a Task<User> automagically.
    return user;
}

All awaitable methods specify a task as its return type. Now, there are things we need to discuss in detail here. This method’s signature specifies that it has a return value of type Task<User> but it is actually returning the loaded user instance instead (line 7). What is this? Well, this method can return two types of values depending of the calling scenario.

First scenario would be when it is called in a traditional fashion. In this case it returns the actual task instance ready to be executed.

Task loadUserTask = LoadUserAsync();

// The previous code is equivalent to:
Task loadUserTask = new Task<User>(() => LoadUserAsync().Result);

Second scenario would be when it is called using await. In this case it starts the task, waits for it to finish and gets the result, which then gets assigned to the specified local variable.

User user = await LoadUserAsync();

// The previous code is equivalent to:
User user = LoadUserAsync().Result;

See? Personally it is the first time I see a method that can return two types of value depending on how it is called. Even though is quite interesting such thing exists. By the way, is important to remember that any method which at any point awaits for an asynchronous method by using the await keyword needs to be marked as async.

Conclusion

This surely means something for the whole framework. Looks like Microsoft has taken care of parallel programming on its latest framework release. Desktop and mobile application developers will surely love this new feature which reduces significantly boilerplate code and increases code verbosity. We can all feel happy about our beloved framework moving forward the right way once again.

That’s all for now, folks. Stay tuned! 😉

Further Reading

Unit Testing 101: Inversion Of Control

Introduction

Inversion Of Control is one of the most common and widely used techniques for handling class dependencies in software development and could easily be the most important practice in unit testing. Basically, it determines if your code is unit-testable or not. Not just that, but it can also help improve significantly your overall software structure and design. But what is it all about? It is really that important? Hopefully we’ll clear those out on the following lines.

Identifying Class Dependencies

As we mentioned before,  Inversion Of Control is a technique used to handle class dependencies effectively; but, What exactly is a dependency? In real life, for instance, a car needs an engine in order to function; without it, it probably won’t work at all. In programming it is the same thing; when a class needs another one in order to function properly, it has a dependency on it. This is called a class dependency or coupling.

Let’s look at the following code example:

public class UserManager
{
    private Md5PasswordHasher passwordHasher;

    public UserManager()
    {
        this.passwordHasher = new Md5PasswordHasher();
    }

    public void ResetPassword(string userName, string password)
    {
        // Get the user from the database
        User user = DataContext.Users.GetByName(userName);

        string hashedPassword = this.passwordHasher.Hash(password);

        // Set the user new password
        user.Password = hashedPassword;

        // Save the user back to the database.
        DataContext.Users.Update(user);
        DataContext.Commit();
    }

    // More methods...
}

public class Md5PasswordHasher
{
    public string Hash(string plainTextPassword)
    {
        // Hash password using an encryption algorithm...
    }
}

The previous code describes two classes, UserManager and PasswordHasher. We can see how UserManager class initializes a new instance of the PasswordHasher class on its constructor and keeps it as a class-level variable so all methods in the class can use it (line 3). The method we are going to focus on is the ResetPassword method. As you might have already noticed, the line 15 is highlighted. This line makes use of the PasswordHasher instance, hence, marking a strong class dependency between UserManager and PasswordHasher.

Don’t Call Us, We’ll Call You

When a class creates instances of its dependencies, it knows what implementation of that dependency is using and probably how it works. The class is the one controlling its own behavior. By using inversion of control, anyone using that class can specify the concrete implementation of each of the dependencies used by it; this time the class user is the one partially controlling the class behavior (or how it behaves on the parts where it uses those provided dependencies).

Anyways, all of this is quite confusing. Let’s look at an example:

public class UserManager
{
    private IPasswordHasher passwordHasher;

    public UserManager(IPasswordHasher passwordHasher)
    {
        this.passwordHasher = passwordHasher;
    }

    public void ResetPassword(string userName, string password)
    {
        // Get the user from the database
        User user = DataContext.Users.GetByName(userName);

        string hashedPassword = this.passwordHasher.Hash(password);

        // Set the user new password
        user.Password = hashedPassword;

        // Save the user back to the database.
        DataContext.Users.Update(user);
        DataContext.Commit();
    }

    // More methods...
}

public interface IPasswordHasher
{
    string Hash(string plainTextPassword);
}

public class Md5PasswordHasher : IPasswordHasher
{
    public string Hash(string plainTextPassword)
    {
        // Hash password using an encryption algorithm...
    }
}

Inversion of Control is usually implemented by applying a design pattern called the Strategy Pattern (as defined in The Gang Of Four book). This pattern consists on abstracting concrete component and algorithm implementations from the rest of the classes by exposing only an interface they can use; thus making implementations interchangeable at runtime and encapsulate how these implementations work since any class using them should not care about how they work.

The Strategy Pattern

So, in order to achieve this, we need to sort some things out:

  • Abstract an interface from the Md5PasswordHasher class, IPasswordHasher; so anyone can write custom implementations of password hashers (line 28-31).
  • Mark the Md5PasswordHasherclass as an implementation of the IPasswordHasher interface (line 33).
  • Change the type of the password hasher used by UserManager to IPasswordHasher (line 3).
  • Add a new constructor parameter of type IPasswordHasher interface (line 5), which is the instance the UserManager class will use to hash its passwords. This way we delegate the creation of dependencies to the user of the class and allows the user to provide any implementation it wants, allowing it to control how the password is going to be hashed.

This is the very essence of inversion of control: Minimize class coupling. The user of the UserManager class has now control over how passwords are hashed. Password hashing control has been inverted from the class to the user. Here is an example on how we can specify the only dependency of the UserManager class:

IPasswordHasher md5PasswordHasher = new Md5PasswordHasher();
UserManager userManager = new UserManager(md5PasswordHasher);

userManager.ResetPassword("luis.aguilar", "12345");

So, Why is this useful? Well, we can go crazy and create our own hasher implementation to be used by the UserManager class:

// Plain text password hasher:
public class PlainTextPasswordHasher : IPasswordHasher
{
    public string Hash(string plainTextPassword)
    {
        // Let's disable password hashing by returning
        // the plain text password.
        return plainTextPassword;
    }
}

// Usage:
IPasswordHasher plainTextPasswordHasher = new PlainTextPasswordHasher();
UserManager userManager = new UserManager(plainTextPasswordHasher);

// Resulting password will be: 12345.
userManager.ResetPassword("luis.aguilar", "12345");

Conclusion

So, this concludes our article on Inversion of Control. Hopefully with a little more practice, you will be able to start applying this to your code. Of course, the  biggest benefit of this technique is related to unit testing. So, What does it has to do with unit testing? Well, we’re going to see this when we get into type mocking. So, stay tuned! 😉

Further Reading

Unit Testing 101: Basics

Introduction

We all know unit testing is an essential part of the development cycle. Actually, unit tests code is as important as the actual application code (Yeap, you read that right); this is something we should never forget. That’s why we are going to look at some important (introductory) concepts relating to composing proper testing code.

I will be using NUnit as my testing library. The package comes with the framework libraries and a set of test runner clients. You can download it at their site’s download section.

Unit Test Structure

Unit tests are usually grouped in test fixtures. Basically, a test fixture is a group of unit tests targeted to verify a single application feature. Let’s illustrate this in code:

using NUnit.Framework;

namespace AppDemo.Tests
{
    [TestFixture(Category = "User Authentication")]
    public class WhenUserIsBeingAuthenticated
    {
        [Test]
        public void ShouldReturnTrueIfValidationIsSuccessful()
        {
            // TODO: Implement test code.
        }

        [Test]
        public void ShouldReturnFalseIfUsernameOrPasswordIsNull()
        {
            // TODO: Implement test code.
        }
    }
}

We can now picture how a test fixture looks in code. In this case, the test fixture is a regular class filled out with test methods. As you might have noticed, the class name describes the state of the feature being tested: “When the user is being authenticated”. Each particular test method seeks to verify a required result on a specific condition: “Should return true if validation is successful”.

Running Tests

Once you have your fixture ready to go, is now time to run all tests on it and see results. I will be using the NUnit GUI Runner which looks for all classes in the assembly marked with the [TestFixture] attribute and then calls each method on them marked with the [Test] attribute. Is important to remember that all tests must be in a separate class library. First reason is because it is a good practice, you should not be mixing application code with test code; and second because the NUnit test runner can only load DLL files.

So, first thing to do is to build the project so we have a DLL containing all our tests. Once we have a DLL file with our test fixture classes on it, fire up the NUnit test runner (NUnit.exe) and load the file on it.

NUnit Test Runner

At this point everything is quite intuitive. You can hit the “Run” button and see how all tests pass or rebuild the project on Visual Studio and see how the test runner auto-updates with new changes. Cool, huh?

Arrange, Act and Assert

Test methods are usually composed of three common phases: Arrange, act and assert. Or “triple-A” if you like.

  • Arrange: At the very beginning of the method, you need to setup the test scenario. This includes expected test results for comparison with actual results, instances of the components to be tested and type mocking.
  • Act: After arrangement is done, we now have to actually perform the actions that will produce the actual test results. For instance, call the Validate method on the UserAuthenticator class which performs the actual user validation.
  • Assert: The assertion phase verifies that actual tests results match what we are expecting.

Is a good practice to provide comments delimiting each phase:

[Test]
public void ShouldReturnTrueValidationIsSuccessful()
{
    // Arrange
    var expectedResult = true;
    var userAuthenticator = new UserAuthenticator();

    // Act
    var actualResult = userAuthenticator.Validate("luis.aguilar", "1234");

    // Assert
    Assert.That(actualResult, Is.EqualTo(expectedResult), message = "Authentication failed though it should have succeeded.");
}

As you might see, these three phases are executed in order. Is a good practice to initialize variables with expected results at Arrange phase to make the Assert phase more readable. Also, for the sake of readability, I am using the Assert.That syntax of NUnit so assertions are more verbose.

Tests Before Implementation

Even though unit testing is good for all development methodologies, I’m an avid supporter of the Test-Driven-Development (TDD) methodology. As the name implies, TDD is all about writing all tests BEFORE you implement actual application code. That way, your code will meet acceptance criteria right from inception. Basically, application infrastructure design is driven by tests. Now we think on user requirements rather than UML diagrams and classes.

For instance, you should write all the previous sample tests before implementing the UserAuthenticator class. That way that particular class will be born satisfying user requirements so we don’t have to  change its code later on, which helps save lots of time (and money, managers love to hear that) and improves code efficiency and design greatly.

Conclusion

Okay, hopefully this served out as a brief introduction to the exciting world of unit testing. Of course, there’s a lot more on this topic. In next articles we are going to look at concepts like inversion of control, type mocking and more things related to TDD. Is going to be lots of fun!

Stay tuned! 😉