No no-argument constructor. No default constructor found



Similar documents
Java Application Developer Certificate Program Competencies

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Java EE Web Development Course Program

Fundamentals of Java Programming

CS 111 Classes I 1. Software Organization View to this point:

Jonathan Worthington Scarborough Linux User Group

Creating Java EE Applications and Servlets with IntelliJ IDEA

2. Follow the installation directions and install the server on ccc

Monitoring Java enviroment / applications

Glossary of Object Oriented Terms

Chapter 1 Fundamentals of Java Programming

Java Interview Questions and Answers

Course Number: IAC-SOFT-WDAD Web Design and Application Development

IBM WebSphere Server Administration

CS506 Web Design and Development Solved Online Quiz No. 01

Penetration from application down to OS

Android Application Development Course Program

Web Development in Java

Official Android Coding Style Conventions

Java 2 Web Developer Certification Study Guide Natalie Levi

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Aspects of using Hibernate with CaptainCasa Enterprise Client

Exception Handling In Web Development DevelopIntelligence LLC

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014

Specialized Programme on Web Application Development using Open Source Tools

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

WebSphere Server Administration Course

WebSphere Performance Monitoring & Tuning For Webtop Version 5.3 on WebSphere 5.1.x

B M C S O F T W A R E, I N C. BASIC BEST PRACTICES. Ross Cochran Principal SW Consultant

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

Real-world Java 4 beginners. Dima, Superfish github.com/dimafrid

Manual. Programmer's Guide for Java API

Explain the relationship between a class and an object. Which is general and which is specific?

Building Web Applications, Servlets, JSP and JDBC

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Building a Multi-Threaded Web Server

The V8 JavaScript Engine

Session Tracking Customized Java EE Training:

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Implementing the Shop with EJB

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Chapter 5 Names, Bindings, Type Checking, and Scopes

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Specialized Programme on Web Application Development using Open Source Tools

Web development... the server side (of the force)

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Tuning WebSphere Application Server ND 7.0. Royal Cyber Inc.

SW5706 Application deployment problems

Moving from CS 61A Scheme to CS 61B Java

Data Flow Static Code Analysis Best Practices

Core Java+ J2EE+Struts+Hibernate+Spring

Getting Started with the Internet Communications Engine

The end. Carl Nettelblad

Kotlin for Android Developers

Computer Programming I

Visual Basic. murach's TRAINING & REFERENCE

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

Restraining Execution Environments

Software Construction

Symbol Tables. Introduction

Testing and Inspecting to Ensure High Quality

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

Objectif. Participant. Prérequis. Remarque. Programme. C# 3.0 Programming in the.net Framework. 1. Introduction to the.

The first time through running an Ad Hoc query or Stored Procedure, SQL Server will go through each of the following steps.

Japan Communication India Skill Development Center

Servlets. Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun

2.8. Session management

Performance Monitoring API for Java Enterprise Applications

How to create/avoid memory leak in Java and.net? Venkat Subramaniam

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Debugging Java Applications

Japan Communication India Skill Development Center

Source Code Security Analysis Tool Functional Specification Version 1.0

Computing Concepts with Java Essentials

Monitoring, Tracing, Debugging (Under Construction)

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Curriculum Map. Discipline: Computer Science Course: C++

Creating a Simple, Multithreaded Chat System with Java

7.1 Our Current Model

When an exception occur a message which explains its cause is received. PL/SQL Exception message consists of three parts.

CSE 530A Database Management Systems. Introduction. Washington University Fall 2013

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Using DOTS as Apache Derby System Test

Top 10 reasons your ecommerce site will fail during peak periods

D06 PROGRAMMING with JAVA

INTEGRATING MICROSOFT DYNAMICS CRM WITH SIMEGO DS3

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Handling PL/SQL Errors

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

Java SE 7 Programming

An introduction to web programming with Java

Java Programming Language

Transcription:

Every software developer deals with bugs. The really tough bugs aren t detected by the compiler. Nasty bugs manifest themselves only when executed at runtime. Here is a list of the top ten difficult and common Java bugs compiled by the Intertech team. Even though these bugs are specific to Java, most of them would apply to just about any object-oriented language. Knowing and avoiding these can reduce hours spent testing and debugging applications. 1. No no-argument constructor. Java provides a no-argument constructor to each class by default (a.k.a. the default constructor). However, as soon as you add your own constructor, the compiler no longer includes the default/no-argument constructor in your class. Compilers detect direct calls to use a non-existent no-argument constructor. However, a nasty bug comes to life when you use popular frameworks like Spring or Hibernate that rely on the existence of a no-argument constructor to create instances of your classes. Since these frameworks often rely on reflection rather than a direct call to the no-argument constructor, compilers are not able to detect the potential issue. Instead, you encounter a runtime exception when executing code that involves the class without the no-argument constructor and the framework (as shown in this example with Spring below). org.springframework.beans.factory.beancreationexception: Error creating bean with name 'contact1' defined in file [C:\student\workspace\ContactManagement\test-beans.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.beaninstantiationexception: Could not instantiate bean class [com.intertech.domain.contact]: No default constructor found; nested exception is java.lang.nosuchmethodexception: com.intertech.domain.contact.<init>()

2. == versus equals( ). In Java, there are two forms of equal with objects. The == operator checks to see if two object references point to the same object in memory (in heap). The equals( ) method, can and often does operate differently than the == operator. For example, when using equals( ) with String objects, Java is checking that the objects contain the same sequence of characters. Using the wrong form of equal in conditionals can result in a bug that does not manifest itself in any immediate exception. Usually, this type of bug is detected only after carefully stepping through the code when getting unexpected application results. String x = "a test"; String y = new String("a test"); System.out.println(x==y); //prints false System.out.println(x.equals(y)); //prints true 3. JDBC is 1-based. When you learn Java, you quickly commit to memory the fact that Java is a zero-based indexing language. For example, to get the first element from an array or collection, you ask to get the item at the index of zero. The JDBC API, however, is one-based. Setting statement parameters, getting resulting column data by index, etc. all start at index 1. Depending on the situation, code that uses the wrong index (one that is zero-based) may throw an SQL Exception at runtime or create a hidden data issue caught only by exploring the data in the database and code more closely. 4. NullPointerExceptions. Unfortunately, Java compilers can sometimes warn us but not protect us from uninitialized variables, instance variables and the like. Trying to perform operations on a property, for example, that has not been initialized and points to null results in the most infamous and common runtime exception: NullPointerException. Contact c = new Contact(); //results in a null pointer exception if getfirstname returns null String name = c.getfirstname().tolowercase(); 5. Empty Catch Blocks. Bugs are tough enough to track down without hiding exceptions that are occasionally thrown by code. Developers can be lazy and when roughing out a piece of code, some leave the catch block of try/catch code empty. An I ll-get-that-later mentality can end up masking a bug for a very long time. At the very least, log the exception in the catch block. While 2

developing, if you must leave the exception handling coding for another day, consider having the catch block throw an unchecked exception. This will at least cause problems to manifest themselves at the point of origin. 6. Shadowing Attributes. Local variables (variables declared inside of methods) can have the same name as instance or class variables. Often, this is done to help highlight how a method parameter (and local variable) is going to be used to set the value of an instance or class variable (see below). We call this shadowing attributes. However, mistakes in forgetting the this keyword, or forgetting that the local variable shares the name of an instance or class variable can escape compiler detection and cause all sorts of issues at runtime (from NullPointerExceptions to hidden data issues). //good shadowing public void setfirstname(string firstname) { this.firstname = firstname; // Hidden problem. Now the firstname is never set. public void setfirstname(string firstname) { firstname = firstname; 7. Same Name, Different Package. At the airport baggage claim, you ll often find a sign that reads, Many bags look alike. The connotation is that you should check the bag you pick out to make sure it is really yours before you leave the baggage claim area. The same can be said of classes and interfaces. Many classes/interfaces have the same name. Sometimes they even perform many of the same operations (especially in the case of different versions of a framework org.hibernate.session and org.hibernate.classic.session is a perfect example). When you pick the wrong class or interface, the problems may not be caught until runtime. Because the classes may serve the same or similar roles, the runtime exceptions that occur might even mislead you to believe the issue is somewhere else. Always review package import statements, especially when using IDEs that may automatically add them to your code. 3

8. Memory Leaks. Yes, you can have memory leaks in Java even though Java has automatic garbage collection. In order for the garbage collection to work, it must be able to identify an object as garbage. If you create a long-standing reference to an object, it will not get collected as garbage despite the fact that the object is no longer used. In the extreme, consider the small piece of code below. Message objects are collected for as long as message are coming in, which might be forever. However, the Message objects are probably not used after work with that message is complete. The messages never get removed from the currentmessages hash and therefore never avail themselves for garbage collection. How long will it take for the machine running this code to run out of memory? The answer depends, but no machine can hold objects forever and ever. HashSet currentmessages = new HashSet(); while (moremessages()){ Message message = getnextmessage(); currentmessages.add(message.getid(), message); //do work with message Memory leaks can hide themselves for months or minutes depending on the runtime environment. In a server loaded with memory, it may take months for a memory leak like the one shown to manifest. In a Java ME device where memory is limited, an OutOfMemoryError is likely seen much sooner. Watch object references closely and remember to dereference an object when you are done with it. Tools, such as JProbe, can also help profile your applications and help identify memory leaks before they become a problem in production environments. 9. Concurrent Access to Shared Data. Developers often test their code by running their code and acting as a single user. It is tough, but absolutely critical, to simulate multiple, simultaneous users when testing code. Data comes in many forms. Data can be persisted to a relational database. Data can also be held in memory in the form of instance variables. No matter the data type or location, make sure all data is protected from multiple users hitting it simultaneously. Concurrent data access issues hardly ever result in exceptions thrown, but almost always end up corrupting data a far worse problem. As a small example, consider the Java servlet below. Because Web containers only create a single instance of each servlet, and run many user threads through the 4

same instance, the name instance variable here is open to concurrent updates. Testing this application as a single user will never highlight this potentially grave error. Even when there are hundreds of users, a problem with the code may not be seen or seen rarely. Concurrent access of shared data must be examined as part of the application design. It requires an understanding of what is shared and how to protect it given the type and location of the data. public class NonConcurrentServlet extends HttpServlet { String name; public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getwriter(); response.setcontenttype("text/html"); username = request.getparameter("name"); out.println("<html><body>"); out.println("<h1>hello, "+name+"</h1>"); out.println("</body></html>"); 10. ClassCastExceptions. Polymorphism is a core principal in object-oriented programming languages like Java. It allows code to be very flexible. Interfaces, for example, establish a contract that can be implemented by many classes. In many situations, the compiler prevents us from creating references to the wrong type of object. However, cast operations (whether implicit or explicit) can create situations that allow the compiler to believe that you have appropriately typed references to objects when you really have not. When the JVM hits an unexpected object type, it throws the dreaded runtime ClassCastException. These types of runtime exceptions can be more prevalent when using frameworks like Spring, Hibernate, etc. where Java code is at the mercy of XML or other configuration that dictates the type of object actually created. FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("spring-beans.xml"); // is the salescontacts bean really going to be a ContactList?? ContactList list = (ContactList) context.getbean("salescontacts"); 5

If you are a new or experienced Java developer, keep this list handy and run through it as you get close to shipping your code for integration testing or production use. Make sure you have taken your best shot at eliminating those nasty bugs that may only appear after your code is getting run extensively. Need some help with understanding these issues and how to be a better developer? Take a look at Intertech s curriculum. Give us a chance to improve your bug-eyes. If you have been doing Java for some time and might even be in the Guru category, how does our list stack up? Feel free to comment and leave us your thoughts on what needs to be added/removed from the list. 6