Monday, June 13, 2011

Better Faster Lighter Java

The section is designed to help you make the most effective use of the Java™ programming language and its fundamental libraries, java.lang, java.util, and, to a lesser extent, java.util.concurrent and java.io. It discusses other libraries from time to time, but it does not cover graphical user interface programming, enterprise APIs, or mobile devices. Section consists of 9 items, each of which conveys one rule. The rules capture practices generally held to be beneficial by the best and most experienced programmers. Many new features were added to the platform in Java 5. Most of the items here try to cover these features in some way.
  1. Minimize the scope of local variablesBy minimizing the scope of local variables, you increase the readability and maintainability of your code and reduce the likelihood of error. The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used. Declaring a local variable prematurely can cause its scope not only to extend too early, but also to end too late. The scope of a local variable extends from the point where it is declared to the end of the enclosing block. If a variable is declared outside of the block in which it is used, it remains visible after the program exits that block. If a variable is used accidentally before or after its region of intended use, the consequences can be disastrous. Nearly every local variable declaration should contain an initializer. If you don’t yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do.
    // Preferred idiom for iterating over a collection
    for (Element e : c) {
    doSomething(e);
    }
    Here is another loop idiom that minimizes the scope of local variables:
    for (int i = 0, n = expensiveComputation(); i < n; i++)
    {
    doSomething(i);
    }
    A final technique to minimize the scope of local variables is to keep methods small and focused. If you combine two activities in the same method, local variables relevant to one activity may be in the scope of the code performing the other activity. To prevent this from happening, simply separate the method into two: one for each activity.
  2. Know and use the librariesDon’t reinvent the wheel. If you need to do something that seems like it should be reasonably common, there may already be a class in the libraries that does what you want. If there is, use it; if you don’t know, check. Generally speaking, library code is likely to be better than code that you’d write and is likely to improve over time. Advantages of using library are:- Firstly by using a standard library, you take advantage of the knowledge of the experts who wrote it and the experience of those who used it before you. A second advantage of using the libraries is that you don’t have to waste your time writing ad hoc solutions to problems that are only marginally related to your work. Third advantage of using standard libraries is that their performance tends to improve over time, with no effort on your part. Because many people use them and because they’re used in industry-standard benchmarks also. Many of the Java platform libraries have been rewritten over the years, sometimes repeatedly, resulting in dramatic performance improvements. A final advantage of using the standard libraries is that you place your code in the mainstream. Such code is more easily readable, maintainable, and reusable by the multitude of developers.

  3. Prefer primitive types to boxed primitivesJava has a two-part type system, consisting of primitives, such as int, double, and boolean, and reference types, such as String and List. Every primitive type has a boxed primitives corresponding to it, like int, double, and boolean are Integer, Double, and Boolean. To summarize, use primitives in preference to boxed primitives whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw a NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.
  4. Avoid strings where other types are more appropriateStrings are designed to represent text, and they do a fine job of it. Because strings are so common and so well supported by the language, there is a natural tendency to use strings for purposes other than those for which they were designed. This item discusses a few things that you shouldn’t do with strings.
    • Strings are poor substitutes for other value types.
    • Strings are poor substitutes for enum types.
    • Strings are poor substitutes for aggregate types.
    • Strings are poor substitutes for capabilities.
    To summarize, avoid the natural tendency to represent objects as strings when better data types exist or can be written. Used inappropriately, strings are more cumbersome, less flexible, slower, and more error-prone than other types. Types for which strings are commonly misused include primitive types, enums, and aggregate types.
  5. Beware the performance of string concatenationThe string concatenation operator (+) is a convenient way to combine a few strings into one. It is fine for generating a single line of output or for constructing the string representation of a small, fixed-size object, but it does not scale. Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It is an unfortunate consequence of the fact that strings are immutable. When two strings are concatenated, the contents of both are copied.
    // Inappropriate use of string concatenation - Performs horribly!
    public String statement() {
    String result = "";
    for (int i = 0; i < numItems(); i++)
    result += lineForItem(i);
    // String concatenation return result;
    }
    This method performs abysmally if the number of items is large. To achieve acceptable performance, use a StringBuilder in place of a String to store the statement under construction. The StringBuilder class, added in release 1.5, is an unsynchronized replacement for StringBuffer, which is now obsolete. The difference in performance is dramatic.
  6. Use loggingWhile building an application or doing debugging to trace out the control flow to rectify a bug always use standard logging libraries. Below are wrong and right way do keep control over logging.
    WRONG
    public void bar() {
    try {
    //doSomething()
    }
    catch (JMSException e) {
    System.out.println("exception occurred"); e.printStackTrace();
    }
    finally {
    System.out.println("cleaning up");
    }
    }
    RIGHT
    public void bar() {
    try {
    // ...
    }
    catch (JMSException e) {
    logger.log(Level.WARNING, "JMS Problem", e);
    } finally {
    logger.info("cleaning-up");
    }
    }

    Wrap complex logging expressions into conditions
    if (logger.isDebugEnabled()) {
    logger.debug("Message: " + object.calculateSomething() + ", count=" + cnt);
    }
  7. Code Formatting and stylingThere are 2 standard plugins available for Eclipse PMD and CheckStyle which comes to rescue
    • CheckStyle
      • http://checkstyle.sourceforge.net/index.html
      • Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard.
      • Checkstyle will help you during your programming by checking your coding style i.e braces, naming etc. Simple things but very numerous!
      • Checkstyle is highly configurable and can be made to support almost any coding standard.
      • Historically it's main functionality has been to check code layout issues
      • Checkstyle is most useful if you integrate it in your build process or your development environment.
    • PMD
      • http://pmd.sourceforge.net/
      • PMD scans Java source code and looks for potential problems like:
        • Possible bugs - empty try/catch/finally/switch statements
        • Dead code - unused local variables, parameters and private methods
        • Suboptimal code - wasteful String/StringBuffer usage
        • Overcomplicated expressions - unnecessary if statements, for loops that could be while loops Duplicate code - copied/pasted code means copied/pasted bugs
      • PMD is also able to point out questionable coding practices and its output is generally more relevant and useful.
      • PMD will help you by checking more complicate rules like during the design of your classes, or for more special problems like implementing correctly the clone function. Simply, PMD will check your programming style
      • PMD to find problematic code areas and next refactoring targets
    Checkstyle and PMD both are good at checking coding standards and are easy to extend. But PMD has additional rules to check for cyclomatic complexity,Npath complexity,etc which allows you write healthy code.
  8. Adhere to generally accepted naming conventions
    The Java platform has a well-established set of naming conventions, many of which are contained in The Java Language Specification. Loosely speaking, naming conventions fall into two categories: typographical and grammatical. There are only a handful of typographical naming conventions, covering packages, classes, interfaces, methods, fields, and type variables. You should rarely violate them and never without a very good reason. If an API violates these conventions, it may be difficult to use. If an implementation violates them, it may be difficult to maintain. In both cases, violations have the potential to confuse and irritate other programmers who work with the code and can cause faulty assumptions that lead to errors.

Agile Software/Web Development

Agile software development is a group of software development methodologies based on iterative and incremental development, where requirements and solutions evolve through collaboration between self-organizing, cross-functional teams. In fact it is a framework that promotes development iterations throughout the life-cycle of a project. It minimizes risk by developing software in short amounts of time. Developments accomplished in one unit of time (generally up to four weeks) is called an iteration. Each iteration is a project with analysis, design, coding, testing and also documentation All the required functionality may not be covered in one iteration for releasing the project. But it will be covered in multiple iterations. The idea is to have a defect free release available at the end of each iteration.
Being agile is critical if you are to succeed in today‟s competitive world. More and more people are achieving greater productivity and success by applying agile methodology to their work. Organizations of all sizes are achieving greater success by adopting the Agile Method, replacing rigid and inflexible processes with our dynamic and iterative approach.
The Agile Manifesto introduced the term in 2001. Agile Manifesto reads, in its entirety, as follows:
We are uncovering better ways of developing software by doing it and helping others do it. Through this work we have come to value:
  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change over following a plan
That is, while there is value in the items on the right, we value the items on the left more.

Twelve principles underlie the Agile Manifesto, including:
  • Customer satisfaction by rapid delivery of useful software
  • Welcome changing requirements, even late in development
  • Working software is delivered frequently (weeks rather than months)
  • Working software is the principal measure of progress
  • Sustainable development, able to maintain a constant pace
  • Close, daily co-operation between business people and developers
  • Face-to-face conversation is the best form of communication (co-location)
  • Projects are built around motivated individuals, who should be trusted
  • Continuous attention to technical excellence and good design
  • Simplicity
  • Self-organizing teams
  • Regular adaptation to changing circumstances
Characteristics
There are many specific agile development methods. Most promote development, teamwork, collaboration, and process adaptability throughout the life-cycle of the project.
Agile methods break tasks into small increments with minimal planning, and do not directly involve long-term planning. Iterations are short time frames that typically last from one to four weeks. Each iteration involves a team working through a full software development cycle including planning, requirements analysis, design, coding, unit testing, and acceptance testing when a working product is demonstrated to stakeholders.
Team composition in an agile project is usually cross-functional and self-organizing without consideration for any existing corporate hierarchy or the corporate roles of team members. Team members normally take responsibility for tasks that deliver the functionality iteration requires.
Agile methods emphasize face-to-face communication over written documents when the team is all in the same location. Most agile teams work in a single open office, which facilitates such communication
No matter what development disciplines are required, each agile team will contain a customer representative. This person is appointed by stakeholders to act on their behalf and makes a personal commitment to being available for developers to answer mid-iteration problem-domain questions.
Most agile implementations use a routine and formal daily face-to-face communication among team members.
Agile development emphasizes working software as the primary measure of progress.

Industry Analysis – Software Developments of 2010

With the end of 2010, it is time to summarize the most significant developments in 2010 in the software development community. It is difficult to judge the importance of events in spaces one is not familiar with, so I tend to favor areas that I do know and am able to make some educated conclusions about their significance.
Thus below are the top major events occurred in the industry.

Java EE 6
Java EE 6 was technically finalized in late 2009, but 2010 has been its year of implementation and adoption. There has been significant enthusiasm for Java EE 6. The question is whether Java EE 6 can lure even more developers away from the Spring Framework and other common alternatives.

.NET Framework 4 and Visual Studio 2010
Roughly 2 1/2 years after the release of .NET 3.5 and Visual Studio 2008, .NET 4 and Visual Studio 2010 were released in April of 2010. .NET Framework 4 offers numerous new features including support for covariance and contra variance for generics, simpler property syntax in VB.NET, optional method parameters in C#, late/dynamic binding in C#, security improvements, improved ability to measure performance diagnostics, background garbage collection as a replacement for concurrent garbage collection, code contracts, and built-in Tuple support.

Oracle/Google Dispute over Android
For those of us who identify ourselves as members of the Java community, this Oracle lawsuit over Android and Java is a big deal because one of the attractive aspects of Android development is the ability to use language syntax we are familiar with to develop applications for mobile devices that run on the Android platform.

The Rise of HTML5
Web developers have been frustrated with HTML/CSS/DOM/JavaScript behavior across major web browsers (particularly the most popular web browser) for years. Developers doubt to some extent regarding adoption of HTML5 at a level that would make it truly viable. Although it's certainly "not there yet," HTML5 finally seems to be gaining the traction it needs among the major browsers and among web developers and authors to be worth paying attention to. In particular, market-leading browsers Google Chrome, Firefox 4 (beta), and Microsoft Internet Explorer 9 (beta) have or are advertised to have significant greater HTML5 support. As important as it is that the desktop web browsers provide consistent HTML5 support to make it more attractive to use, it seems that the mobile device arena is already pushing HTML5 features heavily. Many of the HTML5 features, such as the web forms features, are more useful and more interesting on mobile device browsers, more granular HTML forms controls are truly appreciable.

Cloud Computing
Some developers still have some lingering doubts about cloud computing as a long-term widely applicable concept. Others still question whether it's something a majority of developers will ever really need to deal with as-is, but at this point it's obvious that at least some significant portion of developers will and already are dealing with development for the cloud. With all the major vendors want a piece of the action, there are at least short-term gains associated with that action. IBM, Oracle, and Microsoft have all expressed commitment to cloud computing. Although it's normal for vendors to chase anything new because it's easier to sell products and services for new rather than for familiar. That type of sales pressure often leads to acceptance.