Latest Entries »

Saturday, July 24, 2010

When does it make sense to choose an abstract class over an interface?

In Java, under what circumstances would you use abstract classes instead of interfaces? When you declare a method as abstract, can other nonabstract methods access it? In general, could you explain what abstract classes are and when you might use them?

Those are all excellent questions: the kind that everyone should ask as they begin to dig deeper into the Java language and object-oriented programming in general

Yes, other nonabstract methods can access a method that you declare as abstract.
But first, let's look at when to use normal class definitions and when to use interfaces. Then I'll tackle abstract classes.
Class vs. interface

Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.

Interface vs. abstract class

Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.




Thanks to Tony Sintes

Friday, July 23, 2010

What is the difference between an application server and a Web server ?

Taking a big step back, a Web server serves pages for viewing in a Web browser, while an application server provides methods that client applications can call. A little more precisely, you can say that:

A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols.

Let's examine each in more detail.

The Web server
A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScript’s, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser.

Understand that a Web server's delegation model is fairly simple. When a request comes into the Web server, the Web server simply passes the request to the program best able to handle it. The Web server doesn't provide any functionality beyond simply providing an environment in which the server-side program can execute and pass back the generated responses. The server-side program usually provides for itself such functions as transaction processing, database connectivity, and messaging.

While a Web server may not itself support transactions or database connection pooling, it may employ various strategies for fault tolerance and scalability such as load balancing, caching, and clustering—features oftentimes erroneously assigned as features reserved only for application servers.

The application server
As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on an object (or a function in the procedural world).

Such application server clients can include GUIs (graphical user interface) running on a PC, a Web server, or even other application servers. The information traveling back and forth between an application server and its client is not restricted to simple display markup. Instead, the information is program logic. Since the logic takes the form of data and method calls and not static HTML, the client can employ the exposed business logic however it wants.

In most cases, the server exposes this business logic through a component API, such as the EJB (Enterprise JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers. Moreover, the application server manages its own resources. Such gate-keeping duties include security, transaction processing, resource-pooling, and messaging. Like a Web server, an application server may also employ various scalability and fault-tolerance techniques.
An example

As an example, consider an online store that provides real-time pricing and availability information. Most likely, the site will provide a form with which you can choose a product. When you submit your query, the site performs a lookup and returns the results embedded within an HTML page. The site may implement this functionality in numerous ways. I'll show you one scenario that doesn't use an application server and another that does. Seeing how these scenarios differ will help you to see the application server's function.

Scenario 1: Web server without an application server
In the first scenario, a Web server alone provides the online store's functionality. The Web server takes your request, then passes it to a server-side program able to handle the request. The server-side program looks up the pricing information from a database or a flat file. Once retrieved, the server-side program uses the information to formulate the HTML response, then the Web server sends it back to your Web browser.

To summarize, a Web server simply processes HTTP requests by responding with HTML pages.

Scenario 2: Web server with an application server
Scenario 2 resembles Scenario 1 in that the Web server still delegates the response generation to a script. However, you can now put the business logic for the pricing lookup onto an application server. With that change, instead of the script knowing how to look up the data and formulate a response, the script can simply call the application server's lookup service. The script can then use the service's result when the script generates its HTML response.

In this scenario, the application server serves the business logic for looking up a product's pricing information. That functionality doesn't say anything about display or how the client must use the information. Instead, the client and application server send data back and forth. When a client calls the application server's lookup service, the service simply looks up the information and returns it to the client.

By separating the pricing logic from the HTML response-generating code, the pricing logic becomes far more reusable between applications. A second client, such as a cash register, could also call the same service as a clerk checks out a customer. In contrast, in Scenario 1 the pricing lookup service is not reusable because the information is embedded within the HTML page. To summarize, in Scenario 2's model, the Web server handles HTTP requests by replying with an HTML page while the application server serves application logic by processing pricing and availability requests.

Caveats
Recently, XML Web services have blurred the line between application servers and Web servers. By passing an XML payload to a Web server, the Web server can now process the data and respond much as application servers have in the past.

Additionally, most application servers also contain a Web server, meaning you can consider a Web server a subset of an application server. While application servers contain Web server functionality, developers rarely deploy application servers in that capacity. Instead, when needed, they often deploy standalone Web servers in tandem with application servers. Such a separation of functionality aids performance (simple Web requests won't impact application server performance), deployment configuration (dedicated Web servers, clustering, and so on), and allows for best-of-breed product selection.



Thanks to Tony Sintes

Thursday, June 24, 2010

Maven install:install-file (Access is denied)

Sometimes silly mistakes will build more frustration and this is the same happened to me while installing an artifact from the command prompt (cmd)

Initially I was driven into the error

C:\Sravan.Modugula>mvn install:install-file -Dfile=C:\lib
-DgroupId=org.portletfaces -DartifactId=portletfaces-bridge-impl -Dversion=2.0
.0.ALPHA4 -Dpackaging=jar -DgeneratePom=true
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'install'.
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO] task-segment: [install:install-file] (aggregator-style)
[INFO] ------------------------------------------------------------------------
[INFO] [install:install-file {execution: default-cli}]
[INFO] Installing D:\lib to C:\repository\org\portletfaces\portletfaces-bridge-i
mpl\2.0.0.ALPHA4\portletfaces-bridge-impl-2.0.0.ALPHA4.jar
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error installing artifact 'org.portletfaces:portletfaces-bridge-impl:jar'
: Error installing artifact: D:\lib (Access is denied)

[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Thu Sep 23 18:31:03 IST 2010

After reading some expert opinions and several irrelevant blogs I came to a conclusion that I haven’t specified the complete path @ -Dfile. We must specify the complete path including jar file name.

-Dfile=D:\lib\portletfaces-bridge-impl-2.0.0.ALPHA4.jar

Here is the working command

mvn install:install-file -Dfile=D:\lib\portletfaces-bridge-impl-2.0.0.ALPHA4.jar -DgroupId=org.portletfaces -DartifactId=portletfaces-bridge-impl -Dversion=2.0.0.ALPHA4 -Dpackaging=jar -DgeneratePom=true

I hope this information will help few readers.

Wednesday, June 23, 2010

Manually installing missing artifacts

We declare all the repositories and the dependencies in the pom.xml, if any dependencies are missing from the repository you will get the exception like

Missing:
----------
1) org.portletfaces:portletfaces-bridge-impl:jar:2.0.0.ALPHA4

Try downloading the file manually from the project website.

Then, install it using the command:
mvn install:install-file -DgroupId=org.portletfaces -DartifactId=portletfaces-bridge-impl -Dversion=2.0.0.ALPHA4 -Dpackaging=jar -Dfile=/path/to/file

Alternatively, if you host your own repository you can deploy the file there:

mvn deploy:deploy-file -DgroupId=org.portletfaces -DartifactId=portletface
s-bridge-impl -Dversion=2.0.0.ALPHA4 -Dpackaging=jar -Dfile=/path/to/file -Durl=
[url] -DrepositoryId=[id]

Path to dependency:
1) test.jsf2:jsf2:war:0.0.1-SNAPSHOT
2) org.portletfaces:portletfaces-bridge-impl:jar:2.0.0.ALPHA4

To resolve this issue you can manually add the required jar files to the local repository using the following command

mvn install:install-file -Dfile=D:\lib\portletfaces-bridge-impl-2.0.0.ALPHA4.jar -DgroupId=org.portletfaces -DartifactId=portletfaces-bridge-impl -Dversion=2.0.0.ALPHA4 -Dpackaging=jar -DgeneratePom=true

Wednesday, May 12, 2010

Unit testing with JUnit and EasyMock

Error while displaying content...

JUnit 4.x Quick Tutorial

How does JUnit work?


JUnit is a library packed in a jar file. Among other things it contains a tool (called test runner) to run your test files. It is not an automated testing tool: you still have to write your test files by hand. JUnit does give you some support so that you can write those test files more conveniently.

Suppose you have a class C that you want to test. We will write the tests in a new class; let’s call it Ctest. This Ctest is our test file. Actually, test class is a better name. We will typically group the tests in Ctest in a bunch of methods called test methods. You will see an example soon.

To actually test C we need to execute its test class Ctest. This is done by calling JUnit’s test runner tool; we pass the name Ctest to it. That’s all. JUnit will then execute Ctest for you.

JUnit will report how many of the test methods in Ctest succeed, and how many fail. The detail of each failure will be reported; this will be in the form of a print of Java’s stack trace leading to the location of the failure.

Locate it first

If you don’t have JUnit yet, you need to download it (from JUnit site). To use it you just need the jar file. A full download also contains its documentation.

Now locate where this jar file is; it is usually called:

junit-version-number.jar

To use JUnit you will need to add the full path to this jar to your class path. We will see examples latter.

A simple example

Let us consider the simple class below. This is the class that we want to test; but first let me explain a bit about what it is.

The class is called Subscription; an instance of it represents a subscription to something (e.g. newspaper, but it doesn’t really matter here). Each subscription has its total price, stored in the variable price. This price is in Euro-cent. It also has the length of the subscription, given in months.


















For example, new Subscription(1000,2) will create a new subscription of 1000 Euro-cent for the total period of 2 months.

By the way, the class has a number of bugs; e.g. pricePerMonth is supposed to return the price per month in euro. However it calculates the price in cent.

Let’s write a test

Let us write two simple tests to check if pricePerMonth correctly calculates the price per month:

1. If we have a subscription of 200 cent for a period of 2 month, its monthly price should be 1 euro, right?

2. The monthly price is supposed to be rounded up to the nearest cent. So, if we have a subscription of 200 cent for a period of 3 month, its monthly price should be 0:67 euro.

Of course we can write tests without JUnit; but this tutorial is about JUnit. So here is how we write them in JUnit.

Each of the tests above will be implemented as a test method; you then group your test methods in a test class. Usually you would group all the test methods that test a certain target class C is a test class called CTest, but you can also have multiple test classes if you want, and call them whatever you want.

Here is my test class implementing the above two tests:











The marker @Test is called an annotation in Java. When we later execute JUnit’s test runner it needs to know which methods in your test class are test methods (e.g. you may have several helper methods in your test class). The @Test is used to mark that a method is a test method.

In the first test (test_returnEuro) we first create a Subscription; we call it S. Then we want to check that S.pricePerMonth() will return the expected value of 1.0. The checking is done by the code:

assertTrue(S.pricePerMonth() == 1.0)

By the way, the annotation @Test and the method assertTrue are things exported by the JUnit library; so you need the imports as in the above code to use them.

Compiling and executing your test

Next we want to execute the above test class (SubscriptionTest). I’ll show how to do this from a console. If you use an IDE the steps are a bit different.

Open a console. You first need to compile the test class, and then you can execute it. The commands are (in Windows):

prompt> javac -cp .; SubscriptionTest.java

prompt> java -cp .; org.junit.runner.JUnitCore SubscriptionTest

(In e.g. Mac you probably have to use ':' instead of ';')

The first command will compile the test class. The second will execute JUnit’s test runner; we pass to it the name of your test class.

This is what you will get from JUnit; it reports that both tests fail. Notice also that it reports which lines exactly in your test class fail.

Time: 0,015
There were 2 failures:

1) test_returnsEuro(SubscriptionTest)
java.lang.AssertionError:
...
at SubscriptionTest.test_returns_Euro(SubscriptionTest.java:13)
...
2) test_roundUp(SubscriptionTest)
...
at SubscriptionTest.test_roundUp(SubscriptionTest.java:19)
...

Tests run: 2, Failures: 2

The next thing you want to do is to fix your Subscription class and then test it again. We keep fixing it until we get no more failures. You may in the mean time also want to add more tests to your test class.

Monday, March 29, 2010

The Quest for Excellence

Excellence should be the goal of every software engineer and programmer. We should seek to build good software that makes meaningful contributions to society. We should seek to constantly improve our talents and skills to be able to design better, program more effectively and become the best that we can. In our desire for excellence however, we should always consider at the cost of becoming better in our field and how it will effect our life.

There are many at the top of their fields, who are very successful in their careers but whose lives lack meaning and substance. We should not neglect family and friendships or compromise our health or our integrity to make it “to the top”. True success is the measure of one’s life, not just one’s career. It is better to be a good person and an average programmer than to be an exceptional programmer and a lousy person. It is however, better to be both.

Achieving the best of both your professional and personal life is hard, but trying to achieve your greatest potential in your career while failing in other areas in life is harder in the long run and very unsatisfying. The trick to achieving excellence in both is to make a balanced effort all around. This requires planning, preparation and keeping our priorities what they should be. It may mean turning down good opportunities in order to give time to more important things. It also means that we will have to give up what we want now, for what we want in the long run.

Acheiving excellence is a process, something we must constantly work on and improve. We must give the best of ourselves, day after day to the things that really matter. By so doing, we can live a more full life, satisfying and meaningful in all aspects.

Friday, March 26, 2010

Quality Code

No one writes perfect code. Programming is a process that takes a lot of planning, reviewing, and testing until an individual or team is satisfied that what they have produced is reasonably free of bugs and errors and works the way it should. However, despite our best efforts to produce quality code, customers will inevitably find ways to break it. They will find unexpected ways to use what we make, creating unexpected results.

The importance of writing good code depends on the type of system or program you are creating. For example, when programming a chess game, it is less important to eliminate bugs than when creating a program used to access someone’s bank account or deploy safety airbags in someone’s car. When we write code can cause financial problems, injury or even death, we better make sure that our code works reasonably well. This requires additional planning, revision and testing. Failure to do so can result in the loss of millions of dollars or even human lives.

Ultimately, the organization that sells the code should be responsible for its quality. If it is important that the product they sell be bug free, they should do additional testing to ensure quality. The only exception to this is when a programmer intentionally creates malicious code or leaves security flaws to later exploit the code for their own gain or to cause damage and harm. In such cases, both the organization and the programmer should be held responsible. Organizations should be responsible to hire good programmers, fire bad ones and create an environment in which quality is emphasized and good code is produced.

With that said, every programmer should take pride in their work and try to create as high-quality, bug-free code as possible. Additional planning in the design phase of a project and knowing your customer and how they will interact with what you are creating can help. Education, research, peer programming and using good programming techniques, data structures and algorithms will also lead to higher quality code. As always, the code produced should go through some sort of quality assurance, to make sure that it works reasonably well.

Making these extra efforts will not always guarantee that your code will be bug-free. It will however help it to perform better, have less bugs and cause less problems. Good code should be the goal of every programmer.