Thursday, December 24, 2015

Java - Coding - Java 8 new features - Aggregate Operation


Concept:
  1. Stream - A stream is a sequence of elements. Unlike a collection, it is not a data structure that stores elements. Instead, a stream carries values from a source through a pipeline
  2. Intermediate operation - an intermediate operation produce a new stream
  3. Terminal operation - produces a non-stream result. Can be a collection, primitive value or no value at all
  4. Pipeline - a sequence of aggregate operations. 
    1. Components in a pipeline
      1. A source or stream
      2. Zero or more intermediate operation
      3. A terminal operation
  5. Reduction function - the terminal operations returning one value combining the content of a stream.
    1. Raw reduction functions are provided by JDK to have custom implementation. Example-4 and 5 elaborates that
  6. Parallelism in Stream - stream execution can be done in parallel. the Java runtime partitions the stream into multiple substreams. Aggregate operations iterate over and process these substreams in parallel and then combine the results. Method to use '.parallelStream(...)'.


Example-1: basic operations on a stream.  

1
2
3
4
5
int[] values = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
System.out.println("Any match of element value 3. "+ (Arrays.stream(values).anyMatch(each -> each==3) ? "FOUND": "NOT FOUND"));
System.out.println("All element between 1 and 15. "+ Arrays.stream(values).allMatch(each -> each > 0 && each <15));
//Show how many elements, average and sum of elements
System.out.print(Arrays.stream(values).count()+" elements, where SUM= "+Arrays.stream(values).sum()+" AVERAGE="+Arrays.stream(values).average().getAsDouble());
Full source code below.

Explanation - Arrays.stream(...) converts any array to a stream than any pipeline operation can be used. anyMatch, allMatch methods are passed lambda expression. count, sum, average, max, min methods don't take any input parameter or expression and are terminal operations. Terminal operations return OptionalInt/OptionalDouble/etc. if returns a value. max method returns OptionalInt and getAsInt method is used to fetch the value. average method returns OptionalDouble and getAsDouble is used to fetch the value.

Example-2: filter out value elements and show the values.

1
2
3
//Filter out odd value elements and print the even values.
System.out.print("Even value elements are= ");
Arrays.stream(values).filter(each -> each %2 == 0).forEach(each -> System.out.print(each+", "));
Full source code below

Explanation - first operation in the pipeline is filter which takes a lambda expression. When the lambda expression is executed, it returns true if element value is a even number and that even value is passed to the next operation which is forEach. forEach operation is passed with another lambda expression which executes a regular statement, in this case it prints the value from stream to console. Filter method returns a stream as input for forEach and the stream type is IntStream.

Example-3: use aggregate operation on collection and map to a value.

Source code

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestAggregateOperation {

 private static List<Course> courses = new ArrayList<Course>();
 static{
  courses.add(new Course("Basic math", 89, Course.Type.Math));
  courses.add(new Course("English", 75, Course.Type.Literature));
  courses.add(new Course("Geomatry I", 82, Course.Type.Geomatry));
  courses.add(new Course("Advance math", 92, Course.Type.Math));
  courses.add(new Course("Basic science", 89, Course.Type.Science)); 
  courses.add(new Course("Physics", 78, Course.Type.Science));
  courses.add(new Course("Chemistry", 77, Course.Type.Science));
 }
 public static void main(String[] args) {
  new TestAggregateOperation().example1_2();
  new TestAggregateOperation().example3();
  new TestAggregateOperation().example4();
  new TestAggregateOperation().example5();
 }

 private void example1_2() {
  int[] values = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
  
  System.out.println("Any match of element value 3. "+ (Arrays.stream(values).anyMatch(each -> each==3) ? "FOUND": "NOT FOUND"));
  System.out.println("All element between 1 and 15. "+ Arrays.stream(values).allMatch(each -> each > 0 && each <15));
  //Show how many elements, average and sum of elements
  System.out.print(Arrays.stream(values).count()+" elements, where SUM= "+Arrays.stream(values).sum()+" AVERAGE="+Arrays.stream(values).average().getAsDouble());
  //Show min and max value
  System.out.println(" MAX= "+Arrays.stream(values).max().getAsInt()+" MIN= "+Arrays.stream(values).min().getAsInt());
  //Filter out odd value elements and print the even values.
  System.out.print("Even value elements are= ");
  Arrays.stream(values).filter(each -> each %2 == 0).forEach(each -> System.out.print(each+", "));
  System.out.println("");
 }
 
 public void example3(){
  //Find Math courses and get total and average
  double total = courses
   .stream()
   .filter(each -> each.getCourseType()== Course.Type.Math)
   .mapToDouble(each -> each.getMark())
   .sum();
  double average = courses
   .stream()
   .filter(each -> each.getCourseType()== Course.Type.Math)
   .mapToDouble(each -> each.getMark())
   .average().getAsDouble();
  System.out.println("Total mark ("+total+") and average ("+average+") on math courses");
  
  //Print all courses mark along with name and type
  System.out.println("Courses");
  courses.stream().forEach(each -> System.out.println("Course ("+each.getName()+"), Type ("+each.getCourseType()+"), Mark ("+each.getMark()+")"));
 }
 
 public void example4(){
  System.out.println("Total= "+courses.stream().mapToDouble(each -> each.getMark()).sum());
  System.out.println("Total using reduce= "+courses.stream().mapToDouble(each -> each.getMark()).reduce(0.0, (a,b)-> a + b));
 }
 
 public void example5(){
  CalculateAverage avg = courses.stream().mapToDouble(each -> each.getMark())
    .collect(CalculateAverage::new, CalculateAverage::accept, CalculateAverage::combine);
  System.out.println("Average using collect= "+ avg.average()); 
 }
}

class Course{
 enum Type{Science, Math, Geomatry, Literature};
 private String name;
 private double mark;
 private Type courseType;
 
 public Course(String name, double mark, Type courseType){
  this.name = name;
  this.mark = mark;
  this.courseType = courseType;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public double getMark() {
  return mark;
 }
 public void setMark(double mark) {
  this.mark = mark;
 }
 public Type getCourseType() {
  return courseType;
 }
 public void setCourseType(Type courseType) {
  this.courseType = courseType;
 }
}

class CalculateAverage implements DoubleConsumer{
 int total = 0;
 int count = 0;
 public double average(){
  return count > 0 ? total/count : 0.0;
 }
 @Override
 public void accept(double value){
  total += value;
  count++;  
 }
 public void combine(CalculateAverage other){
  total += other.total;
  count += other.count;
  
 }
}

Explanation - Course class is created to represent a course which has mark and course type attributes. Course type is an enum. In example3 method 5 Course instance are created. To find total and average on Math courses, filter is used with lambda expression to short out Math courses and passes to mapToDouble as stream of Course element. This mapToDouble maps each Course element to a double value which is the mark of the Course instance and passes to sum/average as another stream (DoubleStream). sum/average performs as terminal operation and returns OptionalDouble and getAsDouble method fetches the value.

Usage of Stream.reduce function
This method can be used to work on custom reduction functions which not provided in the API. For example - median. 

Arguments of Stream.reduce - 
  • identity - represents both initial value of reduction function and default value if no elements in the stream
  • accumulator - this is a function which takes two parameters, partial value of reduction and next element of stream. Returns a new partial result
Example-04: Stream.reduce to find total marks obtained.


1
2
System.out.println("Total= "+courses.stream().mapToDouble(each -> each.getMark()).sum());
System.out.println("Total using reduce= "+courses.stream().mapToDouble(each -> each.getMark()).reduce(0.0, (a,b)-> a + b));
Full source code above.

Usage of Stream.collect function
Stream.reduce is not a good choice when dealing with complex object or collection. Because every time accumulator function processes an element in reduce method, will create a new collection including that element. In such situation, it's better to use Stream.collect.

Example-05 - average using new data type.

1
2
3
CalculateAverage avg = courses.stream().mapToDouble(each -> each.getMark())
  .collect(CalculateAverage::new, CalculateAverage::accept, CalculateAverage::combine);
System.out.println("Average using collect= "+ avg.average());
Full source code above.

Explanation - 
  • New data type CalculateAverage is created to store total of elements and count of elements
  • Stream.collect method is used
  • Signature of Stream.collect-
    • supplier - factory function, creates a new instance
    • accumulator - incorporates stream element to container (CalculateAverage)
    • combiner - combines two resulting containers and merges 
  • accumulator and combiner don't return any value
  • 'method reference' is passed in supplier/accumulator/combiner which a new feature of JDK 8. Lambda expression could be used

Tuesday, November 3, 2015

AngularJS - Best practices

Introduction:
This a quick guide for myself to check/review what pattern/style/standard should be followed during AngularJS application development. Please check the resources section for the links where the gurus have explained elaborately the reason behind each item in this post. Once someone gets the head around the explanations or becomes more advanced developer, this post will serve as a quick cheat sheet for a refresher and reference. Added a facts section which would help going through the practices to understand better.

Some quick facts:
  1. All services (value, factory, service) in AngularJS are Singleton 
  2. Service services are instantiated with the new keyword, need to use this for public methods and variables
  3. Factory services expose it's members (variable, function) using return{} defined in it
Practices grouped by component:

ComponentPractices to follow
Module1 - 11
ControllerModule + (12, 13, 15, 16, 17, 18)
ServiceModule + (14, 19)
DirectiveModule + (20, 21, 22, 23, 24, 25)
RouterModule + (18)


Best practices items:
  1. Create separate file for each controller/service/router/directiveReason: code separation, better testability of code, developers work on independently without being affected by others
  2. File name should follow - ..js
  3. Test file should use spec suffix. ..spec.js
  4. Application Structure should follow LIFT(Locate, Identify, Flat, Try to be DRY) Principle.
    1. Locating our code is easy 
    2. Identify code at a glance 
    3. Flat structure as long as we can 
    4. Try to stay DRY (Don’t Repeat Yourself) or T-DRY
  5. Use unique naming conventions for modules and with separators for sub-modules
    Reason: help avoid module name collisions
  6. Put any member variables in any module on top
    Reasonhelps identify instantly what members are defined and used in the implementation flow
  7. Use named functions instead of passing an anonymous function in as a callback. May ideal to use on major functions
    Reasoneasy to debug, reduces the amount of nested callback code, increases code readability
  8. Declare any function in any module at the bottom. JavaScript anyway hoists the function definition at the top during execution
    Reason: helps separate the implementation detail from the flow and increases readability
  9. Use functional declaration over functional expression (declare and assign to a var)
    Reason: removes the concern over using a function before it is defined. Code organization (moving a block of code up or down) won't break anything
  10. Use IIFE scoping. Ideal solution should be creating build task to wrap the concatenated files inside an IIFE. IIFE - Immediately Invoked Function Expression.
    Reason:to avoid polluting the global scope with custom function declarations
  11. Consider manual annotation for dependency injection
    Reason: to make the code safe of minification
  12. Use the 'controller as' syntax over the classic $scope. Need to follow below steps for that - 
    1. Use 'controller as' in view (HTML). Like - 'MyController as ctl'
    2. Refer any members using the controller reference. Like - 'ctl.aValue'
    3. In controller, use a capture variable and associate members to the capture variable. Like - 'var vm = this; vm.aValue = 'A Value';'

      Reason
      avoids any reference issues, gives way to write code on contextual manner, easier to read
  13. Put bindable variables on top
    Reasonhelps identify instantly which members of the controller can be bound and used in the View
  14. Put member variables on top
    Reasonhelps identify instantly which members can be called and must be unit tested
  15. Defer logic in a controller by delegating to services and factoriesReason: Controller would be slimmer where implementation is hidden. Allows logic to be reused by multiple modules (specially by other controllers) and easier for unit testing
  16. Use one controller per view. If any logic needs to be reused, better to move it to a factory/service and use it from each separate controller
    Reason: Controller will be slimmer, writing unit test will be simpler
  17. Should use prototype to extend a controller and Object.create to create new object
  18. When a controller must be paired with a view and either component may be re-used by other controllers or views, define controllers along with their routes (check this)
  19. Use this for public methods and variables as services are instantiated with the new keyword
  20. Consider creating a directive for any DOM manipulation. If alternative ways can be used such as using CSS to set styles or the animation services, Angular templating, ngShow or ngHide, then use those instead.
    Reason: DOM manipulation can be difficult to test, debug
  21. Use unique and short directive prefix
    Reason: helps identify the directive's context and origin
  22. Use restrict E for standalone element represented by the directive
  23. Use restrict A when the directive is enhancing a DOM element's attribute
  24. Avoid ng- as these are reserved for Angular directives
  25. Directives normalization
    1. Prefer using the dash-delimited format (e.g. ng-bind for ngBind). To use an HTML validating tool, data-prefixed version can be used (e.g. data-ng-bind for ngBind).
    2. Prefer using directives via tag name and attributes over comment and class names.
      Reason: easier to determine what directives a given element matches
  26. Directive creation
    1. Prefer using the definition object over returning a function
    2. prefix own directive names
      Reason: to avoid any future collisions
    3. Unless template is very small, it's typically better to break it apart into its own HTML file and load it with the templateUrl option
  27. Directives should clean up after themselves. Use $element.on('$destroy', ...) or $scope.$on('$destroy', ...) to run a clean-up function when the directive is removed
  28. use controller when want to expose an API to other directives. Otherwise use link.
  29. Use angular wrapper services. Like $document, $window, $timeout, $interval etc. instead of using native.
    Reason: easily testable rather mocking native ones by yourself
Few Additional items: these items are more like personal preference. Though the Angular gurus (John Papa, Todd Motto) are more used to doing these or suggesting to do so.
  1. Consider separate line to inject dependencies rather in-line dependencies
    Reason: long list of dependencies makes it harder to read. Little confusing as last item in the array is a function rather string value
  2. Use ng-annotate for Gulp or Grunt and comment functions that need automated dependency injection using /* @ngInject */.
  3. Tool usage:
    1. Use Jasmine or Mocha for testing
    2. Use protractor for E2E (End to End) testing 
    3. Use karma for test runner
    4. Use Sinon for stubbing and spying
    5. Use headless browser like PhantomJS
    6. Use JSHint as code analyzer 



Resources:
1. https://github.com/johnpapa/angular-styleguide
2. https://github.com/toddmotto/angularjs-styleguide
3. http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
4. http://www.johnpapa.net/angular-function-declarations-function-expressions-and-readable-code/

Sunday, November 1, 2015

Tips - Blogger - Useful tips for organize and write post on Blogger


Introduction:
As I got more involved writing posts frequently, the need of advance features to facilitate it grew which basic blogger hasn't come up with yet. To name such features could be putting a table, inserting programming code etc. Target of this post is to list down such finding/techniques which are used somewhere in my blogs or about to or considering to use. Expect this as working in progress and growing numbers of items over the period.

Features:

1. How to put various type of programming code blocks in a post.
Found this beautiful link which can convert most of the well known programming language code to a formatted one which can be directly used in the Blogger post.

2. Add a JavaScript block on a blog.

Steps to follow:
1. Go to 'https://www.blogger.com/' and login
2. Click on 'More Options' dropdown icon left to 'View blog' button and select 'Layout'
3. Click on 'Add a Gadget' link at right side of the page that will show a popup
4. Click on 'HTML/JavaScript' link
5. On next page, provide a title and write your code in content. I have added a small code snippet to try it out to comply with seeing is believing term.

Script snippet

3. Add a JavaScript block on a post.

Steps to follow:
1. Copy above code snippet
2. Go to Post Edit screen
3. Click on 'HTML' button at top left blogger menu next to Compose button. 
4. Paste the code block (better to put at the beginning or at the end)
5. Save/Update the post and view

4. How to add a table in a post.


Table snippet

Steps to follow:
1. Copy above code snippet
2. Go to Post Edit screen
3. Click on 'HTML' button at top left blogger menu next to Compose button. 
4. Paste the code block
5. Save/Update the post and view

5. How to make a section collapsible.

Script snippet
1. Copy snippet-01 which is a javascript and follow feature-03 mentioned above. This JavaScript show or hide a element passed to the function as name.
2. Put a DIV around the section needs to be collapsible. '<div id="aID" style="display:block">'. Need to make sure ID value is unique across the section. I used DIV to define a section, any other HTML element can be used as long as ID and style values are provided. Valid values are 'display:block' and 'display:none'.
3. Use an anchor element to generate show/hide action like '<a href="javascript:void(0);" onClick="showHideADiv('aID')"></a>'.
4. Feature 4 & 5 above used exact same technique 



Resources:
1. http://hilite.me/

Saturday, October 24, 2015

Java - New features in Java 8 - default method

Introduction:
Java 8 introduces 'default' method declaration in interfaces. The idea behind this to make a change in the interface (adding new method signature) without affecting already implemented classes of the interface. This a nice thing to kept the old implementations intact still adding new features whoever needs it. See Example-01.


Notes:
1. Extend an interface with a default method 

  • Not mention the default method at all, which lets your extended interface inherit the default method
  • Re-declare the default method, which makes it abstract
  • Redefine the default method, which overrides it
2. Conflict with multiple interface - if a class uses multiple interfaces having same default method signature, the implementation class should explicitly specify which default method to use or define it's own one. Because the implementation class does not know which default method to use. See Example-02

Examples:

Example-01: Bird class inherits FlyInterface where the interface has a default implementation which Bird class is happy with rather than providing it's own implementation.

BehaviorInterface 
public interface BehaviorInterface {
public default void fly(){
System.out.println("Generic fly");
}
public default void sing(){
System.out.println("Generic sing");
}
public void swim();
}


Bird:
public class Bird implements BehaviorInterface{

public Bird(){
System.out.println("A bird is created");
}
@Override
public void swim(){
System.out.println("Swim by me");
}
@Override
public void sing(){
System.out.println("My own singing");
}
}

Test above implementation:
public class TestBird {
public static void main(String[] args){
Bird aBird = new Bird();
aBird.fly();
aBird.sing();
aBird.swim();
}

}
Output:
A bird is created
Generic fly
My own singing

Swim by me

Example-02: Two interface with same default method would throw compile time error 'Duplicate default methods named speed with the parameters () and () are inherited from the types SwimInterface and FlyInterface'.

FlyInterface
public interface FlyInterface {
public void fly();
public default void print(){
System.out.println("Print in FlyInterface");
}

}

SwimInterface
public interface SwimInterface {
public void swim();
public default void print(){
System.out.println("Print in SwimInterface");
}

}

NewBird
public class NewBird implements FlyInterface, SwimInterface {
public NewBird(){
System.out.println("A new bird is created");
}
@Override
public void swim() {
System.out.println("My swim implementation");
}
@Override
public void fly() {
System.out.println("My fly implementation");
}
@Override
public void print(){
System.out.println("I am forced to provide specific implementation");
FlyInterface.super.print();
SwimInterface.super.print();
}

}

Test above implementation 
public class TestNewBird {
public static void main(String[] args){
NewBird aBird = new NewBird();
aBird.fly();
aBird.swim();
aBird.print();
}

}

Output:
A new bird is created
My fly implementation
My swim implementation
I am forced to provide specific implementation
Print in FlyInterface

Print in SwimInterface

Resources:
1. https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
2. http://www.programcreek.com/2014/12/default-methods-in-java-8-and-multiple-inheritance/