GOOGLE SEARCH

Sunday, May 19, 2013

Dependency Injection in Existing Java Code The idea of dependency injection (DI), aka dependency Inversion, is the way we decouple dependency relationships between objects. It is more of a concept than a framework and is not bound by any language barrier. We generally encounter unwanted dependencies in the event of creating objects or during object interaction. This leads to a tight coupling. Dependency injection in Java initially may seem a circumlocution of control flow, yet with increasing lines of code the application becomes more maintainable. For the sake of good design, sacrificing efficiency is acceptable to some extent. And the goal to easy maintenance is where major software engineering tricks apply. This article tries to give a a hint of DI in a sample code scenario and analyze its applicability. Dependency Injection in Java Applications DI can be a necessary phenomenon, especially when designing a large application where we want to immunize existing code base to change with the slightest change in the service logic (business logic). DI separates business logic from object creation and allows us to select from among various implementation of dependency at run time through configuration files. This pattern is particularly useful for locating components or locating and instantiating software services. High cohesion of the individual modules and low coupling is an important trait of a good software design. DI can suitably implement this trait and leverage good software design principles. There are basically three ways to implement DI: constructor injection, setter injection, and interface injection. The choice of one can be arbitrary with each having its own pros and cons. Also one may use a combination of all three types. However, to maintain consistency and readability of the code, adhering to one type throughout the project is highly recommended. Dependency Injection and Java Application Design In our hypothetical payroll system, suppose we have three types of Employees: Salaried, Commissioned, and Hourly. The system should have a provision to add/remove other types of employee as well. Each type of employee has its own payment method, which is calculated according to some predefined norms. For example, an hourly employee's payment is calculated according to the rate of pay per hour multiplied by the number of hours worked. So starting from scratch we have four classes as follows: Design 1: Simple Design Four classes Four classes Observe that the class PayrollApplication is tied to the three objects by the following code: SalariedEmployee e1 = new SalariedEmployee(); e1.payment(); CommissionedEmployee e2 = new CommissionedEmployee(); e2.payment() HourlyEmployee e3 = new HourlyEmployee(); e3.payment() The code in the PayrollApplication class above is completely tied with the different employee classes. If another type of employee object incorporated tomorrow, it has to be hard coded in the PayrollApplication class to reflect the changes. This may demand a major revamp of the existing code, which is not acceptable and definitely not a good design. To rectify the problem to some extent we can reduce this dependency with the help of polymorphism. The idea of implementing polymorphism here is to use an abstract class as the parent class in order to execute the methods of its child class. Then at runtime supply different children of the parent class. As a result the method of the child class gets executed instead. This idea gives the following class diagram. Design 2: Using Polymorphism Using Polymorphism Using Polymorphism Now the PayrollApplication class has the following code. Employee e = new SalariedEmployee(); e.payment(); Employee e = new CommissionedEmployee(); e.payment(); Employee e = new HourlyEmployee(); e.payment(); This may seem alright but still the employee classes are tied with the above code. Also it is a case of partial polymorphism because object instantiations are hard coded in the application class. A better method would be to have a function where objects are injected in such a manner that the function is unaware or does not care what type of employee object is passed as an argument. public void createEmployee(Employee employee) { employee.payment(); } Now the PayrollApplication class does not need to know the type of employee supplied to the function createEmployee(). We are almost there to achieve inversion of control and have apparently removed the dependency of the object in the PayrollApplication class. The Application class is independent of the type of employee object supplied and can call its own payment method according to the object supplied. But the problem here is that somebody somewhere in the application has to inject the right object in the createEmployee() method. Somewhere the Employee object of SalariedEmployee or HourlyEmployee or CommissionedEmployee is created such as: Employee emp = new SalariedEmployee() and then only the object is supplied as an argument to createEmployee(emp). Thus we are still tied and somehow not dependency free. To solve this problem comes the notion of a container that can supply objects that we require without bothering about its instantiation, destruction and its life cycle management. That's hard work developing such a container every time when working on a project. Fortunately, there are a number of frameworks available to make your life easier. Some of these frameworks, though not limited to these, are: Spring: It is a large framework that offers more than just dependency injection (DI) PicoContainer: Small framework particularly focused on dependency injection Xwork: a command pattern framework but also effectively leverages Dependency Injection. It is generally used in association with Webwork Guice: It is a lightweight framework improvised to use annotation to configure Java objects. Autumnframework: This dependency injection framework for C++ supports constructor and setter injection of POCO (Plain old C++ objects) objects. Here we shall focus on the Spring framework for our design and use a very simple coding pattern that can get this application up and running. Container for the Contain Spring is basically a container of beans in much the same way Tomcat is the container of servlets. Tomcat creates the servlet objects, which are required to run. While deploying what we do is to configure all the servlet in an XML file. Tomcat reads the XML and identifies what servlets need to be instantiated and creates those servlets. Spring is also a container not of servlets but of beans; pretty much any POJO can be contained in the container. All these are managed by the spring and handles complete responsibility of instantiation of object, life cycle of the object and destruction of the objects. The interaction of the object with Spring container can be depicted as: Spring Framework Spring Framework Putting it Together in Spring Employee.java Abstract class incorporating the basic properties of the employee. Sub-classes extending this must define the payment() method according to the rules applicable as per the type of employee. The reason for declaring the payment() method as an abstract is - it simply does not make sense to provide an implementation of this method in this class. We cannot calculate the earnings for a general employee - we first must know the specific Employee type to determine appropriate payment calculation. package org.payroll; publicabstractclass Employee { private String firstName; private String lastName; private String ssn; public Employee(){ } //Getter and Setter methods ... publicabstractdouble payment(); } SalariedEmployee.java This class is a subclass of Employee and defines the abstract payment() method of its parent class. It assumes the payment is weekly/monthly. package org.payroll; publicclass SalariedEmployee extends Employee { privatedoublesalary; public SalariedEmployee(){ } @Override publicdouble payment() { return getSalary(); } //Getter and Setter methods ... } HourlyEmployee.java This class is a subclass of Employee and defines the abstract payment() method of its parent class. Here the payment method also calculates overtime jobs and adds the extra earnings to the final payment. package org.payroll; publicclass HourlyEmployee extends Employee { privatedoublewage; privatedoublehours; @Override publicdouble payment() { if (this.getHours() returnthis.getWage() * this.getHours(); else return 40 * this.getWage() + (this.getHours() - 40) * this.getWage() * 1.5; } //Getter and Setter methods ... } CommissionEmployee.java This class retrieves the commission rate and gross sales respectively and calculates its payment accordingly. package org.payroll; publicclass CommissionEmployee extends Employee { privatedoublegrossSales; privatedoublecommissionRate; public CommissionEmployee() { } @Override publicdouble payment() { returnthis.getCommissionRate() * this.getGrossSales(); } //Getter and Setter methods ... } PayrollMain.java This is the main application class, which acts as an interface to retrieve/view employee information. This is the class where we can see the actual role of Spring DI. Spring container gets the necessary configuration information through ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); So whenever context.getBean()method is called Spring container supplies a reference of the appropriate bean instantiated within the container. package org.payroll; import java.util.ArrayList; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; publicclass PayrollMain{ publicstaticvoid main(String args[]) { List employees = new ArrayList<>(); ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); SalariedEmployee se = context.getBean(SalariedEmployee.class); se.setFirstName("Thor"); se.setLastName("Odinson"); se.setSsn("123-234-45"); se.setSalary(2000.00); CommissionEmployee ce = context.getBean(CommissionEmployee.class); ce.setFirstName("Jacques"); ce.setLastName("Duquesne"); ce.setSsn("345-67-890"); ce.setGrossSales(345); ce.setCommissionRate(0.56); HourlyEmployee he = context.getBean(HourlyEmployee.class); he.setFirstName("Bruce"); he.setLastName("Banner"); he.setSsn("567-78-678"); he.setHours(30); he.setWage(500); employees.add(se); employees.add(ce); employees.add(he); for(Employee e: employees){ System.out.printf("\nName: %s %s Payment: %.2f",e.getFirstName(), e.getLastName(), e.payment()); } } } spring.xml This configuration file is supplied to the ApplicationContext to acknowledge Spring container about the beans. Each bean is declared within the tag ... where id is the name given to the bean, which we could have used as... HourlyEmployee he = context.getBean("hourlyEmployee"); instead of... HourlyEmployee he = context.getBean(HourlyEmployee.class); Bean Scopes: Singleton Vs Prototype There are basically two types of bean scopes in Spring: Singleton and Prototype. Singleton is partially analogous to the singleton pattern in Java. Here once we initialize an ApplicationContext and pass to it the configuration file (spring.xml), it instantiates all the beans in the XML, one bean per bean definition. As it creates only one bean per spring container no matter how many calls are made to the getBean() method, the spring container returns only that particular instance. Here lies the difference between the singleton pattern in Java and Spring scoped singleton. Singleton pattern in Java ensures that there is only one instance overall but singleton in Spring refers one instance per spring container where a single JVM can run multiple such containers. Scope prototype on the other hand overrides the default behavior of ApplicationContext and does not instantiate beans until the getBean() method is called. Each call to getBean() method instantiates a new bean. Since there can be more than one employee per employee type, beans are scoped as prototype. xmlversion="1.0"encoding="UTF-8"?> DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> bean> bean> bean> bean> beans> Conclusion The concept of DI decouples objects dependency to a whole new level. Martin Fowler has a good article with some excellent insight on dependency injection. There are several ways to implement DI java. The choice of a particular technique is immaterial. DI leverages building pluggable service software that lives up to the Open-Closed principle. Building large enterprise applications with numerous fine grained services can benefit equally with DI implementation. www.developer.com

Is JavaFX 2 Enterprise Ready?

Is JavaFX 2 Enterprise Ready? JavaFX 2 is basically a front-end tool enabling developers to create and deploy rich internet applications (RIAs) that behave consistently across multiple platforms. Developing enterprise applications involves many people -- mash-up builders, programmers, graphic designers, media editors and many more. Today, applications are judged not only on their efficiency or user-friendliness but also on how they look and feel. Since clients nowadays are more designed than programmed, JavaFX rightly paved the path in giving RIAs a new look while leveraging the same old Java code. The features provided by JavaFX 2 are excellent, and it seems promising. But in order to be truly enterprise-ready it needs more than that. JavaFX 2 still has a long way to go in becoming a robust enterprise development tool. In this article, we'll evaluate JavaFX 2's enterprise readiness in five different areas: Features support Ease of Development Ease of deployment Documentation Overall impression JavaFX 2 Features API JavaFX 2 is fully integrated with the Java SE 7 runtime and comes as a bundled package of Java SDK + JavaFX. To work with JavaFX 2, developers can use their existing Java tools, such as IDEs, code re-factoring, debuggers, and profilers. Also, JavaFX 2 includes the familiar language features, such as generics, annotations and multi-threading. This cohesiveness means two things. First, it means JavaFX designers have an ambitious plan, and it is going to stay. We expect to see lot of development activity from its creators as well as the community in the coming days. Secondly, it means developers can now leverage and share existing Java APIs with JavaFX effortlessly and efficiently. Also, JavaFX APIs are designed to work with other JVM languages such as JRuby and Scala, keeping the option open to extensive development on other platforms as well. Graphics With its underlying hardware accelerated graphics pipeline called Prism coupled with its Glass windowing toolkit, JavaFX 2 can leverage modern GPUs for seamless and fast rendering of rich graphics. It can run on both hardware and software renderers, including 3-D. It supports DirectX 9 on Windows XP/Vista, DirectX 11 on Windows 7, OpenGL on Mac and Linux, and Java 2D when hardware acceleration is not supported. Graphics acceleration is very crucial because in a complex, heavily loaded enterprise application JavaFX 2's UI rendering can make or mar the application performance. RIA RIAs have gradually extended from computer to portable devices and TVs with many more devices yet to be seen. JavaFX can widen the market reach of an application by distributing RIAs easily across billions of devices. Applications developed in JavaFX 2 can extensively use the GStreamer multimedia framework media engine. They can also leverage a wide variety of built-in UI controls for form-based user input, charts, layout and advanced UI controls such as table, tree view, rich text editor and CSS3 skinning. JavaFX 2 also enables embedding HTML and JavaScript-based rendering on Webkit. Web Services Enterprise components generally communicate via Web resources. Web-based frameworks interact with enterprise components for rendering information. Sometimes these components are accessed from non-Web resources as well. Java supports SOAP through the javax.xml.soap package. Since JavaFX is build on top of Java2, it can leverage Java foundry for SOAP, REST-based Web services. Ease of Development with JavaFX 2 JavaFX Scene Builder is available for Windows, MacOS and Linux. This drag-and-drop visual design layout will immensely increase the productivity of the developers. The developer community has long sought a scene builder integrated with NetBeans or other popular Java IDE. The JavaFX Scene Builder separates application logic from UI layout via FXML and CSS. With this XML-based markup language for defining user interfaces JavaFX 2 provides a suitable alternative to developing UI programmatically in Java. FXML is easy to learn and intuitive for developers familiar with Web technologies or other markup-based UI technologies. JavaFX 2 controls can be easily integrated with Swing and work towards a combined UI design. However, integrating JavaFX 2 and Swing is not a very acceptable proposition because it results in code and design that do not look very good. Moreover, why does one GUI family need to hire controls from another? Does JavaFX 2 lack something? The answer is that Swing is more mature and has a lot more controls than JavaFX 2 at present, so integration may be an option. But with time, this integration will not be popular, I believe. JavaFX 2 coding can be started simply by importing jfxrt.jar as a library in any popular Java IDE. Deployment with JavaFX 2 In the past, frequent upgrades for JavaFX applications were troublesome affairs. However, the latest application packager released with JavaFX version 2.2 solved the problem to a great extent. This version allows developers to bundle JRE and JavaFX 2 runtime libraries as a package with the deployed application. This provides the end user with a traditional native installation process on Windows, MacOS and Linux. Igor Nekrestyanov and Nancy Hildebrandt have provided detailed information on building, packaging and deploying JavaFX application in the tutorial Deploying JavaFX Applications. JavaFX 2 Documentation As usual, JavaFX 2 has javadoc. Apart from that, there are several tutorials online, and its active community is growing. There is also an official site to JavaFX 2 how-to's. Overall Impression of JavaFX 2 Although it is still in its juvenile stage JavaFX 2 is progressing well and is sure to be a competent player in the arena very soon. JavaFX 2 can be easily integrated with the other frameworks such as Spring and Hibernate. (Check the article Integrate JavaFX, Hibernate and PostgreSQL with the MVC Pattern. So is JavaFX 2 enterprise ready? The answer would be yes, in view of all the features and current progress, but the issue of stability remains to be determined. It's true JavaFX 2 has yet to make a mark as an extensive business tool, especially in the enterprise arena. Jim Weaver's effort to put together a contest to challenge the best minds to bring out more from JavaFX developers is a commendable attempt to popularize JavaFX among mainstream developers. However, new learners expect a little more friendly environment to tingle their gray cells. To attract more enterprise developers, JavaFX would need the following features: Integration of Scene Builder with NetBeans and other popular Java IDE such as IntelliJ IDEA, Eclipse etc. More efficient deployment of JavaFX 2 from the IDE More built-in controls, especially for business specific enterprise applications Easy navigation and data source controls, especially for handling large data sets in enterprise applications. Conclusion Without a real world enterprise application to test, it is very difficult to judge the stability of JavaFX 2 as a front-end tool. Coping with huge and complex data is a challenge for even the most mature UI frameworks. This article will hopefully entice more and more developers to experiment with the technology and enable us to say JavaFX is enterprise ready without any doubt.www.developer.com