Friday, November 17, 2017

Programmers are Lazy and Proud of It - Lambda Expression to the Rescue

Programmers are lazy by nature just like any other field in STEM ( Science, Technology, Engineering, and Math).  Lazy is not a derogatory term in this case,it is the desire to find an easy way to do repetitive and mundane tasks.  Simplification is also the goal for engineers to help other engineers not to make common mistakes.  We can see that trend clearly in loop designs.

First we had while loop that requires Loop Control Variable ( LCV ) priming, boolean logic design, and update to LCV.

        java.util.ArrayList<Integer> me=new java.util.ArrayList<>();
        me.add(1);
        me.add(2);

        int count=0;                                                 //LCV priming
        while(count<me.size()){                             //boolean logic
            System.out.println(me.get(count));    

            count++;                                                  //update
        }


We had a problem since we had to keep track of these three components separately, so in a case of counter controlled loops, a simplified while loop was developed, called for loop.  It is a ternary operator using three arguments, all in one line, to simplify the while loop concept.

        for(int count=0;count<me.size();count++){
            System.out.println(me.get(count1));
        }


We still had problems with boolean logic and +/-1 mistakes processing data.  So, a simplified version of a for loop was developed, called advanced for loop.

        for(int i:me){
            System.out.println(i);
        }


Hiding the complexities and making things simple is an advanced concept, it is a form of oxymoron in geeks world. Thus, having an input, hiding the complexities of processing the input, and having the desired output is an aim for quicker program development with less logical errors or mistakes.  This hiding desire is not a digital age child, it is a mathematical theory and the base for lambda calculus.


Lambda calculus (also written as λ-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. It is a universal model of computation that can be used to simulate any Turing machine and was first introduced by mathematician Alonzo Church in the 1930s as part of his research of the foundations of mathematics.
Lambda calculus consists of constructing lambda terms and performing reduction operations on them. In the simplest form of lambda calculus, terms are built using only the following rules:


The Lambda calculus is an abstract mathematical theory of computation, involving functions. The lambda calculus can be thought of as the theoretical foundation of functional programming. It is a Turing complete language; that is to say, any machine which can compute the lambda calculus can compute everything a Turing machine can (and vice versa).
The notation is based on function abstraction and application based on variable binding and substitution. If you have done same basic programming already, you might be familiar with lambda functions or anonymous functions already. They are featured in Haskell, Mathematica, Python and recent versions of C++ too. In this wiki, we will mostly stick to Haskell.


This concept of process hiding starts by understanding anonymous classes.  As you can see below, class can override methods without changing the original class permanently. 

class Perform{
    public int doubleIt(int i){
        return 2*i;
    }
}
public class HiddenProcess{
    public static void main(String args[]){
        Perform myNumber=new Perform() 
            {
                private String addedAttribute="My Added Message";
                public int doubleIt(int i){
                    return i+i;
                }
            }
;
       System.out.println(myNumber.doubleIt(3));
    }
}

The next concept we need to understand is interfaces.  Interfaces can not be instantiated without a class implementing the interface defined method headers.

interface MyWish{
    void complete(int a);  
}
class MyWishRealize implements MyWish{
    public void complete( int a){
        System.out.println(3);
    }

}
public class HiddenProcess{
    public static void main(String args[]){
        MyWishRealize wishOne=new MyWishRealize();
    }
}
So, we can override and implement methods in anonymous classes therefore we can override methods in classes implementing interfaces.

interface MyWish{
    void complete(int a);  
}
class MyWishRealize implements MyWish{
    public void complete( int a){
        System.out.println(3);
    }
}
public class HiddenProcess{
    public static void main(String args[]){
        MyWishRealize wishOne=new MyWishRealize(){
                public void complete(int a ){
                    System.out.println(3000);
                }
           };

        MyWishRealize wishTwo=new MyWishRealize(){
                public void complete(int a ){
                    System.out.println(6000);
                }
            };

    }
}


So, we can also implement an interface using an anonymous class, so we do not need to create an extra class just to implement the interface.

interface MyWish{
    void complete(int a);  
}
public class HiddenProcess{
    public static void main(String args[]){
        MyWish gift= new MyWish(){
                public void complete( int a){
                    System.out.println("Hello "+a);
                }
            };

    }
}

But the simplified structure can be even more simplified by lambda expression like this;
interface MyWish{
    void complete(int a);  
}
public class HiddenProcess{
    public static void main(String args[]){
        MyWish gift1=(i)->System.out.println("Hello "+i);
    }
}


Lambda Expression 

Prior to Java 1.8, if you looked at the API for ArrayList, you did not have a method to process the array with forEach mehod.

void
ensureCapacity(int minCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
E
get(int index)
Returns the element at the specified position in this list.
int
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Java 1.8 added that method to the available method's list to simplify processing the array.

void
ensureCapacity(int minCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
void
forEach(Consumer<? super E> action)
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
E
get(int index)
Returns the element at the specified position in this list.
int
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.


forEach method is based on the iterable interface and takes a consumer interface as its parameter.·         

forEach


public void forEach(Consumer<? super E> action)

Description copied from interface: Iterable

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller.

Specified by:

forEach in interface Iterable<E>

Parameters:

action - The action to be performed for each element


Iterable inerface's forEach method gives us the reference to the enhanced for loop and to the idea of simplifying its operation.·       

 forEach


default void forEach(Consumer<? super T> action)

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller.

Implementation Requirements:

The default implementation behaves as if:

 
     for (T t : this)
         action.accept(t);
 

Parameters:action - The action to be performed for each element

      Throws:NullPointerException - if the specified action is null

         Since:1.8

The Consumer interface has the method accept that takes any dataType object and performs the given operation on that dataType.  Since Consumer is an interface, a class needs to implement its method accept. 

java.util.function

Interface Consumer<T>

Type Parameters: 
      T - the type of the input to the operation

All Known Subinterfaces:Stream.Builder<T>

Functional Interface:This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

Modifier and Type
Method and Description
void
accept(T t)
Performs this operation on the given argument.



The following code demonstrates the implementation of Consumer interface. ( Note: For simple introduction to Java's Generics - read my article - http://intro2cs-java.blogspot.com/2017/03/generic-getting-started.html )

class implementConsumer<T> implements java.util.function.Consumer<T> {
 public void accept(T i){
     System.out.println(i);
    }

}
public class HiddenProcess{
    public static void main(String args[]){
        implementConsumer<String> value=new implementConsumer<>();
        value.accept("Hello");

    }
}


So, how can we do the same without using the extra class implementConsumer?  WE should use anonymous inner class to accomplish that for this interface. But we would need to create an implementation for each dataType and that would be very annoying.

public class HiddenProcess{
    public static void main(String args[]){
        java.util.function.Consumer<String> value=new java.util.function.Consumer<String>(){
                public void accept(String i){
                    System.out.println(i);
                }
            };

        value.accept("Hello");
    }
}


We would need to create an implementation for ArrayList for each dataType it is instantiated and that would annoy us as well.

public class HiddenProcess{
    public static void main(String args[]){
        java.util.ArrayList<Integer> me=new java.util.ArrayList<>();
        me.add(1);
        me.add(2);
        java.util.function.Consumer<java.util.ArrayList<Integer>> value=new       java.util.function.Consumer<java.util.ArrayList<Integer>>(){
                public void accept(java.util.ArrayList<Integer> i){
                   for(int val:i)
                    System.out.println(val);
                }
            };

        value.accept(me);
    }
}

At the end, we can simplify all this with our lambda expression that works for every dataType and the syntax is simplified to a single line of code.  Isn't that cool!!!

public class HiddenProcess{
    public static void main(String args[]){
        java.util.ArrayList<Integer> me=new java.util.ArrayList<>();
        me.add(1);
        me.add(2);
        me.forEach(i->System.out.println(i));
    }
}

Conclusion

Being lazy means innovation toward an advanced society, so be proud of it and keep innovating!

Package-private (no explicit modifier)

In recent courses, I was privileged to conduct, I noticed a disturbing trend of student skill degradation. These skill disappearance I trace back to the popularity of mobile devices and the wide use of YouTube videos that skip details.  Video lectures especially lectures by non-lecturers lead to a business venture driven by profit and the aim for keeping within current attention span of young adults create a skill gap that is very hard to reverse.

Mobil devices eliminate the cognitive process of thinking about file names, directory names, proper naming conventions, command line utility usage, utility help interpretation, and security right considerations essential for anyone interested to learn technology related fields like Computer Science. 

YouTube video and online courses aim to restrict video lengths to short precise videos that focus on how to perform a single task without explaining "why" the task is performed or "how" the task, to be performed, was researched by the presenter.

One of this trend I see in Object Oriented Programming (OOP) like Java is the aim to keep all source code in a single file for convenience of not handling multiple source files.  The aim of OOP in a learning environment is to lean problem solving by dividing the problem into specific objects that perform specific tasks for re-usability and sharing. 

In Java, source code can contain many classes, but classes are defined by class access modifiers and only one class can be a public class.  No modifier in class definition makes the class private to its package level, thus other packages can not instantiate those classes.  The compiled code will create a separate byte code file that can be shared, but other than the specified package would not be able to instantiate the class.

Like in the code below, the MyDefaultClass class has no access modifier, thus it is private to the package testing and no other package can instantiate it. This code is easy to talk about, easy to present in a single screen video tutorial, but it is damaging to skill development and to practice file management.  This example should be saved into two separate source files and MyDefaultClass should be made public so every package could instantiate the class in other application if needed.

package testing;

class MyDefaultClass{
    private String msg;
    public MyDefaultClass(String m){
        msg=new String(m);
    }
    public String getMsg(){
        return msg;
    }
}

public class Driver {
    public static void main(String[] args) {
        MyDefaultClass t=new MyDefaultClass("Hello");
        System.out.println("Hello World");
    }
}


As you can see below, we have one source code, but the compiled program produced two byte codes.  So, one of them can be shared.  In this case, MyDefaultClass cold be used in other applications since there is nothing indicating that it is tied to a package, as we'll see later.
 


In order to test this, we can create another package and see if we can instantiate the class in that package. (Note: This is another skill gap I see in courses, students are not taught and not driven to learn how to test concepts or theories. )

So, start a new package, in this case it is testAgain package and create a simple "Hello World" application in the package ( in this case, Driver ).  Now, just copy the MyDefaultClass.class from package testing to package testingAgain.

The source code, in this case, only has one single public class, so instantiating the class MyDefaultClass will happen from the bytecode directly ( if it will work )


 Adding the statement to instantiate the class MyDefaultClass will not work since the class is private to testing package.


 Now, let's create a separate source code for MyPublicClass in package testing. In this case, the class can be set to public, so regardless of the package, the class can be used in any program.


So, copy the MyPublicClass to testAgain package to test in that package.


Importing the class path and adding the statement to instantiate the class woks just fine since the class MyPublicClass access modifier is set to public this time.


Conclusion
Always seek to answer the "WHYs", in coding, in order to become a problem solver.  Video lectures are created for a quick lesson not as an educational resource, don't think that a quick video will be able to teach you what you need to know about the code, they are only a tool to help you overcome simple concept confusions. Videos will never replace search, reading, and critical thinking through collaboration. 


Appendix A - Access level modifiers
Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:
  • At the top level—public, or package-private (no explicit modifier).
  • At the member level—public, private, protected, or package-private (no explicit modifier).

Thursday, July 6, 2017

Exception - Can not Get any Simpler than This

Exception handling by custom exceptions is as easy as extending the Exception class. 


java.lang.Object
     java.lang.Throwable
         java.lang.Exception

Look at the API documentation to learn what you can do like what constructors are available and what methods you will have access to by extending this class.

Method Summary

  The most useful constructor for this purpose is the constructor that takes a string as its parameter since it will allow you to set a custom message for your custom exception class.  To get this message later, you will use the getMessage() method that is inherited from Throwable ( as seen above ).

To practice this concept, implement the following code and make modifications as you see it fit.  Create more exceptions and change the messages until it makes sense and you feel comfortable with this easy and useful object oriented concept.  Have fun!




public class HelloDriver{
    public static void main(String args[])throws MyException{  //the other is passed to JVM
         try{
             Hello msg=new Hello("Hello"," World");
             System.out.println(msg.getHello());         
         }
         catch(MyException2 e){                                        //one of the exceptions are handled here
             System.out.println("Zoltan: "+e.getMessage());
         }
    }
}

==============================================================

public class Hello extends World{
private String hello;

//because the parent constuctor with string parameter was called, the exception must be handled
//coming from the parent's constructor and also from this constructor
public Hello(String h, String w)throws MyException2,MyException{
    super(w);
    if(h.equals("He11o"))
       hello=h;
    else
        throw new MyException2();
}

public String getHello(){
    return hello+getWorld();
}
}

===============================================================

public class World{
private String world;

public World(String msg)throws MyException{   //pas the exception out of the constuctor
    if(msg.equals(" World"))
       world=msg;
    else
       throw new MyException();     //create exception if condition is met
}

public String getWorld(){
    return world;
}
}

===============================================================

public class MyException extends Exception
{
public MyException(){
    super("Your message was cool!!!");   //call the parent class Exception constructor with string parameter
}
}

================================================================

public class MyException2 extends Exception
{
public MyException2(){
    super("Your message was the coolest!!!"); //call the parent class Exception constructor with string parameter
}
}

Wednesday, June 28, 2017

Simple Inheritance






public class HelloWorld{
    public static void main(String args[]){
        Greet msg=new Greet();
        System.out.println(msg.getMessage());
        System.out.println(msg.getThankYou());
        msg.getMyMessage();
    }
}
public class Greet extends Message{
       private String msg=new String("Computer Science - ");
       public Greet(){
           super();
        }
    public String getMessage(){
        return msg+getWord();
    }
}

public class Message extends Goodbye implements Welcome {
       private String word;
       public Message(){
           System.out.println("Did you just call me?");
           word="Hello World";
        }
    public final String getWord(){   //try to override this in message
        return word;
    }
    public void greetMe(String m){
        System.out.println("Welcome to my application");
    }
    public String getThankYou() {
        return thanks;
    }
}
public abstract class Goodbye{
    protected String thanks="Thank you for visiting us";
    public abstract String getThankYou();
    public void getMyMessage(){
        System.out.println("This is from the abstract class");
    }
}

public interface Welcome{
    void greetMe(String m);
    //only default and public class modifier can be used
    //try to copy a method with body - fail
}