Yakov Fain's Blog

My notes about everything in IT

What’s the difference between abstract classes and interfaces?

with one comment

Probably the most popular question during Java technical interviews is “What’s the difference between abstract classes and interfaces”.  In my own three year old book I’ve offered the following answer:

“An abstract class may contain code in method bodies, which is not allowed in an interface.With abstract classes you have to inherit your class from the abstract one because Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.”

But starting from Java 8 this answer is wrong. This is how I’d answered it now:

Both abstract classes  and interfaces allow you to implement common static methods while leaving the implementation of some methods to other classes. Abstract classes can also have instance-specific methods and they enforce vertical inheritance hierarchy.  Interfaces can’t have instance methods, but they don’t enforce any class hierarchy, so your class can extend any other class while implementing multiple interfaces.

So abstract classes and interfaces have subtle differences now, which are good to recognize anyway. You can find more details on this subject in the draft of Chapter 5 of my upcoming Java for Kids book.

Written by Yakov Fain

August 18, 2014 at 4:56 pm

Posted in java

JavaFX Event handling and Property Binding

with 6 comments

Some time ago I blogged that Java Swing should be deprecated and replaced with JavaFX. In this blog I’ll show a piece of JavaFX namely event handlers and binding. I’ve created a simple Sign In window with a GridPane layout (it’s JavaFX equivalent of Swing’s GridBagLayout). I’m not going to spend much time on the GridPane itself, but will show you a basic event handling and a binding.

In JavaFX an event object is represented by the instance of the class javafx.event.Event. There are different ways of handling events. Depending on how you structured your application you can handle events either in Java or in FXML. In this blog I’ll do everything in Java, where you can process events using one of the following techniques:

1. Create an instance of an anonymous class overriding its handle() callback method. Pass it to the the event handler for a specific event.

2. Use lambda expressions.

3. Use Java method references introduced in Java 8.

The Sign In window, will have the buttons Sign In, Cancel, and the hyperlink Forgot password. Each of these controls will use different way of handling click event. The Sign In window will look as follows:

f1807

The event handler for the button Sign In will be implemented using an anonymous inner class. The event handler for the Cancel button will be implemented using a lambda expression. I’ll implement the click handler for the hyperlink Forgot password using a method reference. The code of the class GridPaneSampleEvents is shown next (see the section marked as event handlers).

public class GridPaneSampleEvents extends Application {

    public void start(Stage primaryStage) {
        
        Label userIdLbl = new Label("User ID:");
        TextField userIdTxt = new TextField();
        Label userPwdLbl = new Label("Password:");
        PasswordField userPwdTxt = new PasswordField();
        Button signInBtn = new Button ("Sign In");
        Button cancelBtn = new Button ("Cancel");
        Hyperlink forgotPwdLink = new Hyperlink("Forgot password");

        GridPane root = new GridPane();
        root.setVgap(20);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);
        
        // Using static methods for setting node constraints 
        GridPane.setConstraints(userIdLbl, 0, 0);
        GridPane.setConstraints(userIdTxt, 1, 0);
        GridPane.setConstraints(userPwdLbl, 0, 1);
        GridPane.setConstraints(userPwdTxt, 1, 1);
        GridPane.setConstraints(signInBtn, 0, 2);
        //Cancel button: span 1, right aligned
        GridPane.setConstraints(cancelBtn, 1,2, 1, 1, HPos.RIGHT,
                                                      VPos.CENTER);
        GridPane.setConstraints(forgotPwdLink, 0, 3,2,1);

        root.getChildren().addAll(userIdLbl, userIdTxt, userPwdLbl, 
                     userPwdTxt,signInBtn, cancelBtn, forgotPwdLink);
            
        // event handlers
        //1. Anonymous class 
        signInBtn.setOnAction(new EventHandler(){
            public void handle(ActionEvent evt){
              System.out.println(
                      "Anonymous class handler. Sign in clicked.");   
            }
        });
        
        // lambda expression
        cancelBtn.setOnAction(evt -> 
            System.out.println("Lambda handler. Cancel clicked.")
        );
        
        // method reference
        forgotPwdLink.setOnAction(this::forgotPwdHandler);
        
        // Show the window
        Scene scene = new Scene(root,250,200);
        primaryStage.setScene(scene);
        primaryStage.show();

    }
    
    private void forgotPwdHandler(ActionEvent evt){
        System.out.println(
              "Method reference handler. Forgot password clicked");
    }

    public static void main(String[] args) {
        launch(args);
    }
}

If you run this program, and click on Sign In, Cancel, and Forgot password, the console output will show the following:

Anonymous class handler. Sign in clicked.
Lambda handler. Cancel clicked.
Method reference handler. Forgot password clicked

While each of the event handlers works the same, I prefer the lambda expression version as it’s concise and is easy to read. Each of the JavaFX GUI controls has a set of setOnXXX() methods (e.g. setOnAction(), setOnMouseMoved() et al) that should be called for the events you’re interested in handling.

Properties and Binding

While Java developers casually use the words properties referring to class attributes, JavaFX properties are more than just class attributes. JavaFX defines an interface javafx.beans.property.Property, which has a very useful functionality allowing to bind the GUI components (the view) with properties of the Java classes (the model) and automate notifications of the GUI components when the value in the model change or visa versa.

Imagine that you’re developing a financial application that receives notification from the server about the stock price changes. When a Java object receives the new price, you need to modify the content of the corresponding GUI component. With JavaFX you can simply bind a property price of a Java class to the property of, say Label component. No more coding required. As soon as the price value changes, the Label will be automatically updated. JavaFX properties greatly simplify the process of synchronization of the data and the GUI.

Existing implementations of the Property interface serve as wrappers to Java attributes adding the change notification functionality. The interface Property declares the following methods: bind(), unbind(), bindBidirectional() , unbindBidirctional(), and isBound(). Can you bind any value to a JavaFX property? No – the value has to be of an ObservableValue type.

JavaFx property classes are located in the package javafx.beans.property. For each property type there are two classes: read-only and read-write ones. For example, if you need a String property, use either SimpleStringProperty or ReadOnlyStringWrapper. Both of these implement StringProperty interface. Similarly named classes exist for other data types and some collections too.

Let’s modify the GridPaneSampleEvents class. I will place an additional Label components at the bottom of the Sign In window. It’ll display the messages about the events as the user clicks on the buttons and the hyperlink. Initially this label will not have any text:

Label messageLbl = new Label();

JavaFX properties are observables. Hence we can add a listener (observer) to the property to be notified when the property value changes. But it’s much easier to simply use property in a binding expressions. I’ll bind this label to the string property, and as soon as the value of this property changes, the label component messageLbl will display this value.

private StringProperty message = new SimpleStringProperty();
messageLbl.textProperty().bind(message);

The class GridePaneSampleEvents was just printing messages on the system console when the user clicked on the buttons or the hyperlink. The new class GridPaneSampleBinding will modify our property message instead, for example:

cancelBtn.setOnAction(evt -> message.set(“Cancel clicked.”));

The click on the cancelBtn changes the value of the the message property, which was bound to the label’s text – the GUI will change automatically! This is how our Sign In window will look like after pressing the Cancel button.

f1808

The complete code of the GridPaneSampleBinding class is shown next.

public class GridPaneSampleBinding extends Application {

    //Declaring a JavaFX property
    private StringProperty message = new SimpleStringProperty();
    
    public void start(Stage primaryStage) {
        
        Label userIdLbl = new Label("User ID:");
        TextField userIdTxt = new TextField();
        Label userPwdLbl = new Label("Password:");
        PasswordField userPwdTxt = new PasswordField();
        Button signInBtn = new Button ("Sign In");
        Button cancelBtn = new Button ("Cancel");
        Hyperlink forgotPwdLink = new Hyperlink("Forgot password");
        
        // A label to display messages using binding
        Label messageLbl = new Label();
        // binding the StringProperty to a GUI component
        messageLbl.textProperty().bind(message);
        
        GridPane root = new GridPane();
        root.setVgap(20);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);
        
        // Using static methods for setting node constraints 
        GridPane.setConstraints(userIdLbl, 0, 0);
        GridPane.setConstraints(userIdTxt, 1, 0);
        GridPane.setConstraints(userPwdLbl, 0, 1);
        GridPane.setConstraints(userPwdTxt, 1, 1);
        GridPane.setConstraints(signInBtn, 0, 2);
        
        //Cancel button: span 1, right aligned
        GridPane.setConstraints(cancelBtn, 1,2, 1, 1, 
                                      HPos.RIGHT, VPos.CENTER);
        GridPane.setConstraints(forgotPwdLink, 0, 3,2,1);
        
        // Message label: span 2
        GridPane.setConstraints(messageLbl, 0,4,2,1);

        root.getChildren().addAll(userIdLbl, userIdTxt, userPwdLbl,
          userPwdTxt,signInBtn, cancelBtn, forgotPwdLink, messageLbl);
        
        // event handlers
        //1. Anonymous class 
        signInBtn.setOnAction(new EventHandler(){
            public void handle(ActionEvent evt){
                  message.set("Sign in clicked.");   
            }
        });
        
        // lambda expression
        cancelBtn.setOnAction(evt -> 
           message.set("Cancel clicked.")
        );
        
        // method reference
        forgotPwdLink.setOnAction(this::forgotPwdHandler);
        
        // Show the window
        Scene scene = new Scene(root,250,220);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    private void forgotPwdHandler(ActionEvent evt){
        message.set("Forgot password clicked");
    }

    public static void main(String[] args) {
        launch(args);
    }
}

The binding can be bidirectional. If the value of the GUI component changes it can change the value of the underlying model (remember MVC?), and if the value of the model changes the GUI is updated too. If you want to stop binding at any time, use the method unbind().

That’s all folks for now.

Written by Yakov Fain

August 11, 2014 at 2:32 am

Posted in java

Why Java Applets should be banned

with 4 comments

During my training classes on Web development with Java I used to ask students this question, “Do you think it would be a smart move if Amazon.com would create their online store using Java Applets?” The right answer is “Yes, if their goal is to go out of business.”

While back in 1995 Java was introduced to the world with the help of Applets (remember that dancing Duke?) this technology was buried by Microsoft (remember that law suit between Sun and Microsoft back in 1998)?

Web applications written with Java Applets would require the user to have the Web browser supporting specific JRE required by the applet. If in the past I was joking that a truck driver from Alabama would not be able to install the proper JRE on his computer, now I have to admit that I ran into a serious issues with this as well. Here’s my story.

I need to run a Webinar for O’Reilly on Tuesday. This will be a second one. The first one was three months ago. When I was testing the software for presenters, I was told not to use Chrome browser, cause they use Web conference software from on24.com, which doesn’t support Chrome. Why? Because they use Java for the Web client. Fine. I started the Firefox, installed the Java plugin and was able to run the Webinar. Disclaimer: three months ago I was using Java 7 under MAC OS X.

Today I use Java 8. I decided to practice with On24 software for the upcoming seminar and got Java errors. Sent a stack trace to O’Reilly, they contacted On24, and I got an answer: uninstall Java 8 from your computer and install Java 7. On24 Webinar platform doesn’t support Java 8, which was released six months ago. WAT?

But I don’t want to uninstall/reinstall Java just to run a Web conference. It’s 2014 for crying out loud! As a matter of fact I have both Java 7 and 8 installed on my MAC OS 1.9.4. Can I just configure my MAC OS to use Java 7? In the past, MAC System Preferences would allow to select the Java version – not anymore. Found a script to run during the boot of my Macbook to make it use Java 1.7. Great, it worked, but only for applications – typing java -version in the Terminal window properly reported Java 7. Unfortunately Firefox uses its own Java plugin that still sees my Java 8, and the On24 applet still crashes. Firefox on MAC doesn’t offer installing older versions of the Java plugins for security reasons. Actually, replacing Java 8 JavaAppletPlugin.plugin from the Internet Plugins folder with the one from Java 7 will make Firefox happy, but the applet from On24 still doesn’t work properly.

I’m not a truck driver from Alabama, but I’m about to give up and will uninstall Java 8 just to run this Webinar. Hope this will help.

Amazon is not stupid. They would never develop a Web front end with Java applets. But On24.com should seriously consider modernizing their Web conferencing platform unless their goal is to go out of business.

Written by Yakov Fain

August 1, 2014 at 2:12 am

Posted in java, Web

Closures in Java With Lambdas

with 2 comments

While working on the second edition for my Java 24-hour Trainer book I’m re-writing some of the code samples to use lambda expressions. Today I was re-writing an example for wait/notify for the chapter on multi-threading. Beside illustrating the wait/notify, I used a closure in this example. Since Java closures are not well presented in the blogosphere, I decided to write a quick blog on the subject.

My goal was to write a program that starts a thread and waits for the notification from that thread until its execution is completed. When the main thread receives the notification from the second thread it continues processing.

In the traditional object oriented programming you’d create a class that implements Runnable with a constructor receiving an object to send notification to, for example:

class MarketNews implements Runnable throws InterruptedException{
    Object parent;
    
    MarketNews(Object whoToNotify){
        parent=whoToNotify;
    }

    public void run(){
       // Do something
       synchronized(parent){
           parent.notify();
       }
    }
}

Turning Runnable into a lambda expression and creating a thread is simple:

  Runnable mNews = () -> {
	// Do something
        // But who to notify????
  }; 
   
  Thread marketNews = new Thread(mNews, "Market News");
  marketNews.start();

But how to let the mNews know who to notify when this “Do something is done?” How to pass the reference to that parent thread? It’s not overly difficult if you understand the concept of closures and know that a method can return lambda expression.

In functional languages like JavaScript a closure is a nested function that knows the context where it was declared (I know, it’s fuzzy, just bear with me). In Java there is not nested function but you can return a lambda expression from a method:

private Runnable getMktNewsRunnable(){
   return () -> {//Do something};
}

Runnable mktNewsRunnable = getMktNewsRunnable();

After running the above code the variable mktNewsRunnable will store the text of the lambda expression that can be used for creating a thread:

new Thread(mktNewsRunnable, “Market News”).start();

But this version of lambda expression still doesn’t know who to notify. Let’s fix it:

private Runnable getMktNewsRunnable(Object whoToNotify){
   return () -> {
      // Do something
      // whoToNotify.notify();
   };
}

Runnable mktNewsRunnable = getMktNewsRunnable(this);

I’m using the fact that when the closure was created by the above return statement, it knew about the existence of the variable whoToNotify in the neighborhood! The rest is easy – just put the call to notify() into the synchronized block to make the Java compiler happy. Here’s the complete working example.

public class TestLambdaWaitNotify {

  private static Runnable getMktNewsRunnable(Object whoToNotify){
      
	return  () -> {
		 try{
	      for (int i=0; i<10;i++){
	       Thread.sleep (1000);  // sleep for 1 second
	       System.out.println( "The market is improving " + i);
	      } 
	      
	      synchronized(whoToNotify){
	          whoToNotify.notify(); // send notification to the calling thread	   
	       }
	    }catch(InterruptedException e ){
	       System.out.println(Thread.currentThread().getName() 
	                                        + e.toString());
	    }  
	};    
  }
	
	
  public static void main(String args[]){
    	
	 TestLambdaWaitNotify thisInstance = new TestLambdaWaitNotify();
	 
	 Runnable mktNewsRunnable = getMktNewsRunnable(thisInstance);
	 Thread marketNews = new Thread(mktNewsRunnable,"");
	 marketNews.start();
   
     
     synchronized (thisInstance) {
    	   try{
    		   thisInstance.wait(20000);  // wait for up to 20 sec
    	   } catch (InterruptedException e){ 
    		   e.printStackTrace();
    	   }
    	 }
     
        System.out.println( "The main method of TestLambdaWaitNotify is finished");
  }
}

The main thread will print the message “The main method of TestLambdaWaitNotify is finished” only after receiving the notification from Runnable or when 20 sec expires. Easy?

If you want to see how to write closures in JavaScript, I’ll be running a JavaScript Webinar for O’Reilly on Aug 5th.

Written by Yakov Fain

July 21, 2014 at 9:29 pm

Posted in java

Working on the second edition of Java Tutorial

with 2 comments

In 2011 Wiley (Wrox) published my book “Java Programming. 24-Hour Trainer“. To be honest, I don’t like the title because it misleads people as if this book promises that the reader can learn Java within 24 hours. But creators of this series (many titles were published under this umbrella) meant to say that this book was like your personal instructor; 24 hours a day. Whatever. It’s not my call.

But earlier this year I got a call from the publisher stating that they’re happy with the book sale numbers and want me to update the book and release the second edition reflecting the latest changes in the Java Language.

I agreed because with the latest release Java became more interested than ever. The magnitude of changes to the Java 8 language and APIs can be compared with Java 5 that was released back in 2004. It’s exciting to program in Java again.

In the second edition I’m replacing Java applets chapters with JavaFX . The Java EE part will reflect the latest Java EE edition. Of course, I’m adding the coverage of lambdas and Stream API. Re-writing and simplifying all examples and testing them in the freshly released Eclipse Luna IDE. GlassFish 4 is my server of choice for all Java EE 7 examples.

Those of you who used the first edition of my book or watched my Intro To Java video lessons may start using the fresh version of code examples, which I started publishing on Github. So far I’ve I’ve uploaded examples for lessons 1-10 and 13-17. If you haven’t worked with git, watch this video to get up to speed. I’d really appreciate your feedback on these code samples. The Table of Contents of the second edition is shown below.

1. Introducing Java
2. Integrated Development Environment
3. Object-Oriented Programming with Java
4. Class Methods and Constructors
5. Java Syntax: Bits and Pieces
6. Packages, Interfaces, and Encapsulation
7. Programming with Abstract Classes and Interfaces
8. GUI Basics with Swing
9. Event Handling in Swing GUI
10. Error Handling
11. GUI Basics with JavaFX
12. Developing a game with JavaFX
13. Collections
14. Generics
15. Lambda Expressions and Functional Programming
16. Working with I/O Streams
17.Java Serialization
18. Network Programming Basics
19. Introduction to Concurrency
20. The Stream API
21. Working with Databases Using JDBC
22. Rendering Table Data to GUI
23. Annotations and Reflection
24. Remote Method Invocation
25. Java EE 7 Overview
26. Programming with Servlets
27. JavaServer Pages
28. Web Applications with WebSockets
29. Java Messaging Service
30. Java Naming and Directory Interface
31. Enterprise JavaBeans
32. Java Persistence API
33. RESTful Web Services With JAX-RS
34. Introduction to Spring MVC Framework
35. Introduction to Spring Security
36.Build Automation with Gradle
37. Java Technical Interviews

Written by Yakov Fain

July 15, 2014 at 8:57 pm

Posted in java

Losing Polymorphism with Java Lambda Expressions

with 10 comments

Yesterday, I decided to re-write with lambdas one of the example I use while explaining polymorphism during my Java trainings. I realize that lambdas promote functional style of programming, while polymorphism is one of the crucial object-oriented features. Still, I decided to try mixing OOP and functional styles to see what happens.

The Task

The class Person has two descendants: Employee and Contractor. Also, there is an interface Payable that’s used to increase pay for workers.

public interface Payable {
   int INCREASE_CAP = 20;
   boolean increasePay(int percent);
}

Both Employee and Contract implement Payable, but the implementation of the increasePay() should be different. you can increase pay to the Employee by any percent, but the Contractor’s pay increase should stay under INCREASE_CAP.

The OOP version

Here’s the class Person:

public class Person {
	private String name;
	
	public Person(String name){
		this.name=name;
	}

	public String getName(){
		return "Person's name is " + name; 
	}
}

Here’s the Employee:

public class Employee extends Person  implements Payable{

   public Employee(String name){
     super(name);
    }
    public boolean increasePay(int percent) {
    System.out.println("Increasing salary by " + percent + "%. "+ getName()); 
    return true;
  }
}

Here’s the Contractor:

 public class Contractor extends Person implements Payable {
	
   public Contractor(String name){
 	super(name);
    }
   public boolean increasePay(int percent) {
	if(percent < Payable.INCREASE_CAP){
	  System.out.println("Increasing hourly rate by " + percent + 
                                      "%. "+ getName()); 
	  return true;
	} else {
	   System.out.println("Sorry, can't increase hourly rate by more than " + 
                       Payable.INCREASE_CAP + "%. "+ getName());
	   return false;
	}
  }
}

Here’s the code that will perform pay increase in a polymorphic way:

public class TestPayInceasePoly {

  public static void main(String[] args) {

     Payable workers[] = new Payable[3];
	workers[0] = new Employee("John");
	workers[1] = new Contractor("Mary");
	workers[2] = new Employee("Steve");		
	
        for (Payable p: workers){
	    p.increasePay(30);
	 }
  }
}

The output of this program looks like this:

Increasing salary by 30%. Person’s name is John
Sorry, can’t increase hourly rate by more than 20%. Person’s name is Mary
Increasing salary by 30%. Person’s name is Steve

Introducing Lambdas

Now I decided to experiment with lambdas. Namely, I wanted to pass a function as an argument to a method. I wanted to extract the increase pay logic from Employee and Contractor into lambda expressions and pass them to workers as argument to their methods.

I left the code of the Payable interface without any changes.

Here’s the new Person class that includes the method validatePayIncrease, which will take a lambda expression as a first argument (passing a function to a method):

public class Person {
	
	private String name;

	public Person (String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}
	
	public boolean validatePayIncrease(Payable increaseFunction, int percent) {
			 
         boolean isIncreaseValid= increaseFunction.increasePay(percent); 
         	 
         System.out.println( " Increasing pay for " + name + " is " + 
        	              (isIncreaseValid? "valid.": "not valid."));
		 return isIncreaseValid;
	}
}

The new version of Employee doesn’t implements Payable:

public class Employee extends Person{

  // some other code specific to Employee goes here

  public Employee(String name){
	  super(name);
  } 
}

The new version of Contractor doesn’t implements Payable either:

	  
public class Contractor extends Person{
    

  // some other code specific to Contractor goes here

    public Contractor(String name){
       super(name);
    }
}

Finally, the program that will increase the pay to all workers passing different lambda expressions to employees and contractors.

public class TestPayIncreaseLambda {
	
  public static void main(String[] args) {

        Person workers[] = new Person[3];
		workers[0] = new Employee("John");
		workers[1] = new Contractor("Mary");
		workers[2] = new Employee("Steve");		

	  // Lambda expression for increasing Employee's pay
	   Payable increaseRulesEmployee = (int percent) -> {
				return true;
	   };
	   
		// Lambda expression for increasing Contractor's pay	   
	    Payable increaseRulesContractor = (int percent) -> {
	    	if(percent > Payable.INCREASE_CAP){
	    		System.out.print(" Sorry, can't increase hourly rate by more than " + 
	    	             Payable.INCREASE_CAP + "%. "); 
				return false;
			} else {	
				return true;
			}
	   };	
	   
	   for (Person p: workers){
		   if (p instanceof Employee){
			   // Validate 30% increase for every worker
			   p.validatePayIncrease(increaseRulesEmployee, 30); 
		   } else if (p instanceof Contractor){
			   p.validatePayIncrease(increaseRulesContractor, 30);
		   }
	   }
  }

}

As you see, I’m passing one or the other lambda expression to the method validatePayIncrease. Running this program produces the following output:

Increasing pay for John is valid.
Sorry, can’t increase hourly rate by more than 20%.  Increasing pay for Mary is not valid.
Increasing pay for Steve is valid.

It works, but so far I like my OOP version better than the lambda’s one:

1. In the OOP version I’ve enforced a contract – both Employee and Contractor must implement Payable. In the lambda’s version it’s gone on the class level. On the plus side, the strong typing still exists in the lambda’s version –  the type of the valiastePayIncrease first argument is Payable.

2. In the OOP version I didn’t use type checking, but in the lambda’s version this ugly instanceof creeped in.

While it’s cool that I can pass the function to the object and execute it there, the price seems to be high. Let’s see if this code can be further improved.

Getting rid of the class hierarchy

Currently the code in Employee and Contractor is the same. If the only difference in their code is implementation of the validatePayIncrease method, we can remove the inheritance hierarchy and just add the property boolean workerStatus to the class Person to distinguish employees from contractors.

Let’s get rid of the classes Employee and Contractor and modify the Person. I’ll add the second argument to the constructor workerStatus.

public class Person {
	
	private String name;
	private char workerStatus;  // 'E' or 'C'

	public Person (String name, char workerStatus){
		this.name = name;
		this.workerStatus=workerStatus;
	}
	
	public String getName(){
		return name;
	}
	
	public char getWorkerStatus(){
		return workerStatus;
	}
	
	public boolean validatePayIncrease(Payable increaseFunction, int percent) {
			 
         boolean isIncreaseValid= increaseFunction.increasePay(percent); 
         	 
         System.out.println( " Increasing pay for " + name + " is " + 
        	              (isIncreaseValid? "valid.": "not valid."));
		 return isIncreaseValid;
	}
}

The code of the TestPayIncreaseLambda will become simpler now. We don’t need to store objects of different types in the array workers and can get rid of the instanceof:

public class TestPayIncreaseLambda {
	
  public static void main(String[] args) {

        Person workers[] = new Person[3];
		workers[0] = new Person("John", 'E');
		workers[1] = new Person("Mary", 'C');
		workers[2] = new Person("Steve", 'E');		

	  // Lambda expression for increasing Employee's pay
	   Payable increaseRulesEmployee = (int percent) -> {
				return true;
	   };
	   
		// Lambda expression for increasing Contractor's pay	   
	    Payable increaseRulesContractor = (int percent) -> {
	    	if(percent > Payable.INCREASE_CAP){
	    		System.out.print(" Sorry, can't increase hourly rate by more than " + 
	    	             Payable.INCREASE_CAP + "%. "); 
				return false;
			} else {	
				return true;
			}
	   };	
	   
	   for (Person p: workers){
		   if ('E'==p.getWorkerStatus()){
			   // Validate 30% increase for every worker
			   p.validatePayIncrease(increaseRulesEmployee, 30); 
		   } else if ('C'==p.getWorkerStatus()){
			   p.validatePayIncrease(increaseRulesContractor, 30);
		   }
	   }
  }
}

If a new type of a worker will be introduced (e.g. foreign workers), we’ll just need to add another lambda expression to the class TestPayIncreaseLambda that implements business rules for foreign workers.

The purists may not like the fact that I’m using hardcoded ‘E’ and ‘C’.You can add a couple of final variables EMPLOYEE and CONTRACTOR at the top of this class.

So what’s the verdict? Losing polymorphism may not be a bad thing. The code became simpler, we’ve removed two classes, but didn’t lose the type enforcement (the Payable interface). Software developers that use functional programming languages live without polymorphism and don’t miss it.

P.S. As a matter of fact you can lose the Payable interface too. This would require a different implementation of our lambda expressions with the help of the interfaces from the new package java.util.function. But this should be a topic of a separate blog. OK, here’s a hint: I did it using the BiFunction interface.

Written by Yakov Fain

July 11, 2014 at 3:52 pm

Posted in java

Be all you can be. Facebook.

with 4 comments

If there is one thing I hate about the Internet it’s the damaging effect that social networks like Facebook have on people’s minds.  Some of the younger minds are getting complete out of touch with the real world. They create their image to be seen online as super heros, bad boys, or even criminals. While in the real life, they could be  vulnerable teenagers or young adults  suffering from fear, anxieties, and lacking communication skills. But even 30-year old are losing their minds when get connected.

Yesterday I’ve heard the news on the radio, which is a good example of how far sick minded people can go on the Web. I’m talking about a virtual cannibal. He worked as a New York policeman till his wife found his online communication discussing preparing, cooking and eating his wife. She immediately packed her bags and ran away with their child.

Yesterday this virtual policeman cannibal was released from jail because he didn’t kill or eat anyone. IMO, the laws should be changed and such social-network-virtual-criminals should serve time in prisons for just presenting themselves as killers, robbers, rapers, et. al.

Mark Zuckerberg should buy out the US Army’s motto:

Be all you can be. Facebook.

 

 

Written by Yakov Fain

July 3, 2014 at 1:36 pm

Posted in life, Web

Follow

Get every new post delivered to your Inbox.

Join 142 other followers