Why I love Angular 2.x

I always felt the need for a proper JavaScript (or client-side) framework. While searching, I came across various solutions like jQuery, AngularJS 1.x, Apache Cordova and PhoneGap. All of them had few things in common: they do not have built-in types and they do not support compile-time check. With the developing fame of AngularJS 1.x, I investigated it with desire that it may offer something better. Honestly speaking: I did not appreciate Angular JS (1.0) much because of its steep learning curve. To me, it involved more of a JavaScript or jQuery-like syntaxes. Inability to perform compile-time checks, no strong type cast features, no object-oriented programming style, as well as time-consuming learning… these were the reasons for me not to invest my energy in learning AngularJS (1.x).

Here is an AngularJS 1.x example to illustrate:

var myApp = angular 
.module("myModule", [])
.controller("productController", function($scope) {
 var prods = { name: "Prod1", quantity: 1 };
 $scope.products = prods;
});

My simple observations from the above code is:

  • There are attributes/properties declred as var (a typical JavaScript style). No way to distinguish between and String, Number or Boolean. Everything is just ‘var’- The above code is hard to read, there are functions-inside-functions; thuse giving an impression of a boiler-plate code
  • There is no concept of object oriented programming here

When it comes to OOP, AngularJS 1.x is somehow strange (same as JavaScript) in comparison with other object oriented languages (like Java or C#). Looking at some of the sample codes/projects/tutorials in Angular1.x, I felt like “Hmmm …. this does not seem the right way to define a class”. One basic example is here: http://zbic.in/2015/08/01/OOP-in-AngularJS-within-minutes-1-Defining-a-class.html. With Typescript support in Angular2, we can define class in a more OOP way.

Now another example from jQuery

jQeury_example

[Source: https://www.tutorialspoint.com/jquery/jquery-overview.htm]

This kind of code is really fragile and hard to maintain: one single quote in the wrong place and we will still have a valid JavaScript string that will look completely broken ONLY when rendered by the browser. This is the type of code that we don’t want to have to write ourselves: it’s really brittle.

A proper explanation is here: http://blog.angular-university.io/why-angular-angular-vs-jquery-a-beginner-friendly-explanation-on-the-advantages-of-angular-and-mvc/

My venture about Angular2.x

The best thing about Angular2.x (and above) is that it provides more choice for languages. I can use any of the language from ES5, ES6, TypeScript etc. For me, I choose TypeScript.

Angular 2’s TypeScript offers:

  • Static typing
  • Compile time error checking (e.g. type checking)
  • Object-oriented programming
  • Classes (with inheritence, extension, constructors)
  • Lamdba/Fat Arrow functions (this is nice! I find it quite interesting as it has quite similarities with JDK 8 Lambda expressions)

Good things about compile time type checking are that,

  1. It helps me to write code in a bugfree way because it can prevent bugs at compile time and I don’t need to wait until my code is finished and it fails during runtime
  2. It improves readability of the code by clarifying intentions. (A String means text, a Number means numeric; unlike Angular1.x where a var can be either text or number).

What are the built-in types in Angular2.x?

The build-in types in Angular2.x that I mostly use are:

  • String (e.g. “Hello World”, “John”)
  • Number (e.g. 1, 5.00)
  • Boolean (e.g. true, false)
  • Array (e.g. name: String[])
  • Enums (enum Role {Superuser, Administrator, Guest})
  • Void (no return type is expected)

OOP features with Typescript and Angular2.x

Coming from a Object-Oriented background with Java Skills, I find the following code (after this section) is just elegant. Because,

  • The code (below) is neatly isolated (rather than old-style JavaScript/JQuery way); subsequently making it more justifiable and readable.
  • Class is defined and annotated with a component (a component object is imported above). The Class has properties, methods, and constructors.
  • From the Array, it is clear to to understand that ‘prods’ is an array of type Product; and not just some arbitrary ‘var’ type
  • Another important aspect of object oriented programming is inheritance. From the code (below), we can see that a class receives behavior from its parent class. Then we can override, modify those behaviors in the new child class.

Let’s see the code.

The same code (which was written above in Angular1.x), when re-written in Angular2, becomes like this:

import { Component } from '@angular/core';

@Component({
 selector: 'prodsdata',
 template: '<h3>{{prods.name}}</h3>'
})
export class ProductComponent {
 prods : Product[];
 constructor() {
 this.prods = [new Product('Prod1', 1)];
 }
}

 

Last but not the least:

One of the advantage of Angular is the Dependency Injection feature (with TypeScript style). With the use of @Injector, the hard-coded ‘new‘ operator is replaced within classes. With DI, the client object does not need to be aware of how instances are created; DI feature let’s us configure how objects are created and supplied to the client component.

Let’s see some codes (again 🙂 ) 

With two simple steps, DI can be achieved. First a class is decorated or annotated with @Injectable annotation

@Injectable()
export class UserService {
 getUsers(): User[];
}

Next, the class is registered with providers in the @NgModule. In this way, the class will be available for injection anywhere in the application. We can also configure this class in providers of @Component but in this case it will be available to that component only, and not to any other components in the project.

@NgModule({
 providers: [UserService],
 ... //Other stuff like declarations, imports, bootstrap etc
})

export class AppModule { 
....
}

This class is now ready to be injected by its dependent classes. E.G.

@Component({
....
})

export class UserManageComponent { 
  constructor(private userService: UserService) { 
 }
}

To conclude

There are quite a number of reasons to love Anguar2.x (and NOT Angular 1.x… spaghetti !). In short: Object-Oriented programming style (with DI feature), compile time error checking, consistent coding patterns, mobile support with NativeScript, rich documentation and community support are all I can think of.

Java Generics: An Example

Here are two questions that I found in https://docs.oracle.com/javase/tutorial/java/generics:

Q1. Write a generic method to count the number of elements in a collection that have a specific property (for example, odd integers, even numbers, prime numbers, palindromes .. etc etc etc).

Q2. Write a generic method to exchange the positions of two different elements in an array.

Combinedly I have tried to solve these two as follows:

For Q1


Step 1:

An interface called SomeSpecialNumber is created:

SomeSpecialNumbe.java

public interface SomeSpecialNumber<T> {
public boolean match(T t);
}

The idea behind using this interface is such that we can implement it in our customized classes way ie. every special type of class (PrimeNumber class or EvenNumber class) that implements the ‘SomeSpecialNumber’ class, will be responsible for its own implementation of the match method.

Step 2:

Two implementation classes are created: PrimeNumber and EvenNumber

PrimeNumber.java

public class PrimeNumber implements SomeSpecialNumber<Integer> {

@Override
public boolean match(Integer t) {
for (int i = 2; i < t; ++i) {
if (t % i == 0) {
return false;
}
}
return true;
}
}

 

EvenNumber.java

public class EvenNumber implements SomeSpecialNumber<Integer> {

@Override
public boolean match(Integer t) {
return (t % 2 == 0);
}
}

As can be seen, the above two classes have their own way of implementing the ‘match’ method to count the prime numbers or even numbers.

Step 3:

A class called Algorithm is created to act as an intermediary or facade class to perform the count based on the supplied class as parameter

Algorithm.java

import java.util.List;

public class Algorithm {

public <T> int count(List<T> list, SomeSpecialNumber<T> s) {
int count = 0;
for (T type : list) {
if (s.match(type)) {
++count;
}
}
return count;
}
}

Step 4:

To test, let’s write a simple class as follows:

Test.java

public class Test {

public static void main(String[] args) {
Test tq = new Test();
tq.testSpecificElement();
}

public void testSpecificElement() {
List<Integer> list = Arrays.asList(1, 4, 5, 7, 8, 9, 13, 11);
PrimeNumber pn = new PrimeNumber();
EvenNumber en = new EvenNumber();
Algorithm a = new Algorithm();
System.out.println(” Count of prime numbers: ” + a.count(list, pn));
System.out.println(” Count of even numbers: ” + a.count(list, en));
}

}

 

After compiling/running Test.java, the following output is shown:

Result:

Count of prime numbers: 5
Count of even numbers: 2

For Q2


For the next part (swap), I simply added another method within the Test class, as follows:

private static <T> void swap(T[] a, int i, int j)  {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}

 

To test it, the following block of code is added within the main method:

public static void main(String[] args) {
Test  tq = new Test();
Integer[] a = { 11, 22, 33, 44, 55 };
System.out.println(“Initial value: ” + a[0] + “, ” + a[3]);
swap(a, 0, 3);
System.out.println(“After swap value: ” + a[0] + “, ” + a[3]);
}

The Output:

Initial value: 11, 44
After swap value: 44, 11

 

Lambda expressions: Any thoughts?

JDK8.0 has introduced Lambda expression. According to official docs from Oracle “Lambda Expressions, a new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.

While developing a client socket app, I first viewed the following code in one of the tutorials online. (URL: http://www.hascode.com/2014/11/creating-different-websocket-chat-clients-in-java/)

clientEndPoint.addMessageHandler(responseString -> {
System.out.println(jsonMessageToString(responseString, roomName));
});

My initial thought was “Okay. So they put it on the next line since there is not enough space“. That’s how the online sample codes are usually shown in many tutorials/blogs/publications, when a continuation of a block of code does not fit it one line, the newline is indicated with the use of arrow symbol like this ->. And that’s it!!!

Surprise! Surprise! Surprise! This symbol is the lambda notation.

Lets’ see a few examples:

Example 1:

Old style when using Runnable

Runnable r1 = new Runnable(){
@Override
public void run(){
System.out.println(“Hello world one!”);
}
};

JDK 8.0 Lambda Style Runnable

Runnable r2 = () -> System.out.println(“Hello world two!”);

Example 2:

Old style with Collections


Collections.sort(personList, new Comparator<Person>(){
public int compare(Person p1, Person p2){
return p1.getSurName().compareTo(p2.getSurName());
}
});

JDK 8.0 Lambda Style Collections

Collections.sort(personList, (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName()));

Example 3:

Old style with Listener

button.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent ae){
System.out.println(“Click Detected by Anon Class”);
}
});

JDK 8.0 Lambda Style Listener

testButton.addActionListener(e -> System.out.println(“Click Detected by Lambda Listner”));

Source URL:
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach1

And a lot more can be found in the official doc from Oracle. These are just a few.

My thoughts:
If you consider the above examples, it is pretty clear that the code is concise and readable. Question is: is it really understandable, especially for developers like us who have been involved in the old style Java coding for a long time? Who knows? May be, we will get used to it. When generics, auto-boxing etc. were introduced, we all panicked at first. But now can we think without those features?
I mean, who does coding like this anymore

<<
for(int i=0; i<personsList.size(); ++i) {
Person p = (Person)personList.get(i);
}
>>

What about the above solution?
Well, I contacted with the developer at hasCode.com. After a bit of investigation, I was able to convert the above code to old JDK7.0 style which is as follows:


clientEndPoint.addMessageHandler(new MyMessageHandler() {
@Override
public void handleMessage(String responseString) {
System.out.println(jsonMessageToString(responseString, roomName));
}
});

(Old is gold! )

The reason? Well truly speaking, JDK 8.0 is still at its pre-matured state. And I am not ready to use it (at least, for the moment)

JSF: Using DataTable with nested CommandLink or, CommandButton

Summery

This objective of this article is to present a common but somewhat tricky issue of JSF data table with nested commandLink or, commandButton.

 

Details

As you might have already seen that it is not possible to use commandLink inside a datatable in JSF. It is possible however, if you write business logic in your getter method. But this is not recommended as because getter methods are invoked multiple times (according to JSF architecture). If you visit any of the following 3 articles, you will get an idea what I’m talking about: 

 

– JSF: DataTable and CommandLink

URL:

http://typo.ars-subtilior.com/articles/2007/02/07/jsf-datatable-and-commandlink

 

– JavaServer Faces – CommandLink inside a DataTable

URL: http://forums.sun.com/thread.jspa?threadID=5116147

 

– Avoid this common JSF mistake

URL: http://www.mojavelinux.com/blog/archives/2008/05/avoid_this_common_jsf_mistake/

 

The authors have proposed good solutions to this problem. Some mentioned about using a custom component, some suggested about using the SEAM framework. Well, if you are still using JSF without SEAM and do not want to write a custom component, then you can go through the steps that will be mentioned here.

 

What is the Solution then?

Well, the simple solution is to use Tomahawk’s preserveDataModel attribute to “true“. There is no problem using it. Does not matter how many times your getter method (in managed bean) is invoked, you will only have to keep in mind that you DO NOT write business logic in getter method.

Here is an example:

 

UI Layer: The XHTML page:

<rich:panel>

<a4j:commandButton value=”SEARCH” id=”searchBtnId” 

action=”#{propertyMgtBeanAction.processSearchAction}”/>

</rich:panel>


<t:dataTable id=”propertiesWithStatusListDataTblId” 

value=”#{propertyMgtBeanAction.listOfPropertyServices}” 

var=”prop”  rows=”10″

preserveDataModel=”true” 

binding=”#{propertyMgtBeanAction.propServiceData}”> 


<t:column>

<f:facet name=”header”>

<t:commandSortHeader columnName=”propertyId”>

<h : outputText value=”Property Id” />

</t:commandSortHeader>

</f:facet>

<t:commandLink id=”cmlId” action=”#{propertyMgtBeanAction.editOrViewProperty}”>

<h : outputText value=”#{prop.propertyVO.idpk}” />

</t:commandLink>

</t:column>

………

……

</t:dataTable>

 

 

Here, I bind with JSF UIData instead of the DataModel component i.e. binding=”{propertyMgtBeanAction.propServiceData}”, the value shows collection of objects which are populated from an outside method execution. i.e. the getListOfPropertyServices() method does not contain any business logic. It simply returns an ArrayList of populated objects and this population is done by submitting the “search” button which invokes the method processSearchAction() in the managed bean. (I could achieve the similar goal by using the DataTable in which case value attraubue would take a DataModel object instead of a collection object). The code follows:

 

UI Layer: The managed bean:

package com.ns.web.properties;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

…….

import com.sun.facelets.FaceletContext;


@Component(“propertyMgtBeanAction”)

@Scope(“request”)

public class PropertyMgtBeanAction {

private UIData mPropServiceData; 

private List<PropertyServiceVO> mListOfPropertyServices = new ArrayList<PropertyServiceVO>();


@Autowired

@Qualifier(“iServiceManager”)

private IServiceManager mIServiceManager;

public String processSearchAction() {

……..

mListOfPropertyServices = mIServiceManager.findPropertyWithServicesBySearchCriteria(

mRequestTypeCheckbox.getSelectedValues(), 

mServiceCheckbox.getSelectedValues(), 

mStatusCheckbox.getSelectedValues(), 

dateFrom, dateTo, mPageNumber, Constants.DEFAULT_LIST_SIZE);

… … … 

…..

return null;

}


public List<PropertyServiceVO> getListOfPropertyServices() {

return mListOfPropertyServices;

}


public String editOrViewProperty() {

PropertyServiceVO ps = (PropertyServiceVO)mPropServiceData.getRowData(); 

mPdtoForTermsAgreement = mIPropertyManager.getPropertyDTO(ps.getPropertyVO().getIdpk());

String status = mPdtoForTermsAgreement.getJobStatus();

String tmp = “”;

if (status.equals(Constants.JOB_STATUS_NEW) || status.equals(Constants.JOB_STATUS_PENDING)) {

tmp = Constants.TERMS_OF_AGREEMENT;

}

return tmp;

}

}

 

What I wanted to show here is: when the “search” button is pressed the corresponding processAction method is invoked, and the ArrayList (listOfPropertyServices) is populated (called from managed bean -> service layer bean -> DAO layer bean) and the value attribute in <t:dataTable> simply gets a populated list. 

 

Now about the commandlink inside DataTable: As because we have used preserveDataModel=”true”, so clicking on the commandLink inside the DataTable will invoke the editOrViewProperty() in the managed bean. If we try to click on the link by setting preserveDataModel=”false”, then this will NOT work. This would simply behave like a normal JSF feature where the “DataTable would modify the id of the CommandLink during renderering, but the CommandLink does not know that it was rendererd with a different id” (refer to http://typo.ars-subtilior.com/articles/2007/02/07/jsf-datatable-and-commandlink)

 

Now some people argue that they don’t find any problem or, they never see this as a JSF TRAP. I’m afraid that they are probably putting business logics in their managed bean getter methods. E.G. they could write something like this:

 

public List<PropertyServiceVO> getListOfPropertyServices() {

mListOfPropertyServices = mIServiceManager.findPropertyWithServicesBySearchCriteria(

mRequestTypeCheckbox.getSelectedValues(), 

mServiceCheckbox.getSelectedValues(), 

mStatusCheckbox.getSelectedValues(), 

dateFrom, dateTo, mPageNumber, Constants.DEFAULT_LIST_SIZE);

return mListOfPropertyServices;

}

 

This is NOT a recommended approach. And this will work, however.

If this is the case, you don’t need preserveDataModel. In fact, you don’t need to use tomahawk at all. You can make this work with any JSF implementation you like. But the problem is ALREADY KNOWN. You know how many times you are calling you getter method, hence how many times your business layer in invoked, and how many times your database is hit … Just for a simple population of Arraylist for a single method invokation?

 

The Business/Service layer: Where the actual business logic calculation is done. Although not much relevant, but the business layer code here shown here for your convenience. 

package com.ns.business.services;

import java.util.ArrayList;

….

….

@Service(“iServiceManager”)

@Transactional(isolation = Isolation.REPEATABLE_READ)

public class ServiceManagerImpl extends BaseManagerImpl implements IServiceManager {

protected final Log log = LogFactory.getLog(getClass());

 

@Autowired

@Qualifier(“iPropertyServiceDao”)

private IPropertyServiceDao mIPropertyServiceDao;


public List<PropertyServiceVO> findPropertyWithServicesBySearchCriteria(final Object[] pRegPurpose, 

final Object[] pServices, final Object[] pStatus, final Date pFromDate, final Date pToDate, 

final int pSelectedPageIndex, final int pNumberOfRowsPerPage) {


// Some business logic to populate variables

List<String> tmpRegPurpose = ….

List<Long> serviceIds = ….

List<String> tmpStatus = ….

mTotalNumberofRows = … 

mMaxPageNumber = …. 

// Call DAO to fetch the result

return mIPropertyServiceDao.findPropertyServicesBySearchCriteria(tmpRegPurpose, serviceIds, 

tmpStatus, pFromDate, pToDate, firstResult, pNumberOfRowsPerPage);

}

}

 

The DAO Layer: Not relevant, hence not shown here.