Interview Questions On Java,Java EE

Enter your email address:

Add to Technorati Favorites
Google PageRank Checker
Showing posts with label Java Coding Standards. Show all posts
Showing posts with label Java Coding Standards. Show all posts

Monday, August 4, 2008

All Posts On Java Coding Standards

As most of my readers demanded, here is this post summarizes series of posts that I did on Java coding standards,best practices and guidelines. This is a quick reference for all readers who are looking for a consolidated information in a single post as the direct reference for same will be found on my main page.
Here we go:

Naming Conventions
Exception Handling,Logging and JUnits
Best Practices
Continue reading...

Java Coding Standards: Best Practices

This is my last post in series of Java coding standards posts. It focuses on best practices or dos and don'ts while coding. I am sure these good practices once observed while writing code will make your Java code consistent and in most cases bugs free. If you make these practices a habit, it ensures better code quality,less rework and robustness of one's application.

Here goes the list:

·Put each class in a separate file (except where a private class is used exclusively by one class only and also when using inner classes and anonymous classes).

·Use relative path with respect to the location of the execution directory.

·No Compiler warnings / Exceptions should be allowed in the final source code.

·Declare all class variables in one place (at the top of the class).

·Initialize the class/instance variables in default constructor or with declaration.

· Initialize all local variables where they are declared.

·Put declaration only at the beginning of the blocks. Don't wait to declare the variables to until where they are first used (one exception is indexes to loops).

·Avoid using an object to access a class (static) variable or method. Use a class name instead.

·Numerical constants (literals) should not be coded directly, except for –1, 0 and 1, which can appear in a for loop as counter values.

·Avoid assigning several variables to the same value in a single statement. It is hard to read.

·Do not use embedded assignments in an attempt to improve run-time performance. It is the job of the compiler. Example:
d = ( a = b + c) + f; //Avoid
Should be written as
a = b + c;
d = a + f;

· Generally prefer long to int, and double to float. But use int for compatibility with standard Java constructs and classes.

·Minimize direct internal access to instance variables inside methods. Use protected access and update methods instead.

·Prefer declaring arrays as Type[] arrayName rather than Type arrayName[].

·Ensure that non-private statics have sensible values even if no instances are ever created. Use static initializers if necessary.

·Define return types as void unless they return results that are not accessible otherwise

·Avoid hard coding. If hard coding is inevitable due to functionality, give proper comments.

· Constants specific to a class/module should be part of interfaces related to that domain. All constants must relate to some domain specific grouping. If at all possible the interfaces that define globals should be located with the classes which they would operate on.

·Variables for local use should not be declared global.

·Method Names, variable names, class names should be meaningful.
Give proper names for methods, variables, class names focusing on
Maintainability, Readability.

·Variables should be named in such a way that it conveys the actual usage of thevariable.

·All get methods should return a value.

·All set methods should accept values.

·Vector, Array position specific code should not be present.

·Similar methods/parts of code in different classes should be refactored.

·Code inside a method should exactly serve the purpose.
For example, a method written for validation should not do any focus/tab setting.

·The method/variable should be declared as private if it isn't used outside the current class.

·Avoid NullPointerException by checking the input parameters for null in a method and throwing an IllegalArgumentException with the appropriate message.

·If the code in the constructor is too large, logical parts should be separated out into methods.

·If a particular piece of logic is repeated in a class, make a private static method and move that logic in that. If the logic is shared across different classes, then it should be moved in some utility class.

·Make use of appropriate data structure Collection – unordered objects, List – ordered objects, Set – unique objects, HashMap – unordered key- value pairs, LinkedHashMap – ordered key-value pairs.

·Use inline comments for all complex calculations or business logics.

·Check for unnecessary code like System.out.printlns in the code.

·Avoid using Strings in double quoted form. Declare a local private static final constant variable for that.

·Use a Iterator class for iterating a Collection, List or Set instead of using a for( ; ; ) loop. This would make the code more consistent.

·Implementation should be based on proper abstraction. Use Interfaces and abstract classes for hiding the implementation from the client code.

·Try and identify the immutable attributes of your classes and make them final member variables assigned in the constructor. This can prevent some coding errors.

·Always override hashCode method when you override equals. Failure to do so will result in violation of the general contract for Object.hashCode which will prevent your class from functioning properly with conjunction with all hash-based collections, including HashMap, HashSet and HashTable

·Return zero-length arrays instead of nulls. Can prevent null pointer exceptions or complicated if (results == null) tests.

·Try to avoid returning null from methods. Consider the NULL Object pattern as a replacement for returning Null. E.g create a static final constant class instance to represent an empty/null object. E.g Within the Employee interface public static final Employee NULL = new Employee(); So now the calling client code can test for if (Employee.NULL == result). Leads to clearer code and removes some potential for null pointer issues.

·Refer to objects by their interfaces if appropriate interface exists.

·Choose interfaces over abstract classes. If you know something is going to be a base class, your first choice should be to make it an interface, and only if you're forced to have method definitions or member variables should you change it to an abstract class. An interface talks about what the client wants to do, while a class tends to focus on (or allow) implementation details.

·First make it work, then make it fast. This is true even if you are certain that a piece of code is really important and that it will be a principal bottleneck in your system. Don't do it. Get the system going first with as simple a design as possible. Then if it isn't going fast enough, profile it. You'll almost always discover that "your" bottleneck isn't the problem. Save your time for the really important stuff.

·Watch for switch statements or chained if-else clauses. This is typically an indicator of type-check coding, which means that you are choosing what code to execute based on some kind of type information (the exact type may not be obvious at first). You can usually replace this kind of code with inheritance and polymorphism; a polymorphic method call will perform the type checking for you and allow for more reliable and easier extensibility. For Example-

interface IVehicle{
void drive(Car car);

class Car {
// These Car classes could as easily be interfaces, with no impact on the examples.
// members
class HondaCar extends Car {
// members

class BMWCar extends Car {
// members

Good Practice

class Car implements IVehicle {
public void drive(HondaCar car){
// handle standard drive
public void drive(BMWCar car){
// handle BMW car

Bad Practice

class Car implements IVehicle {
public void drive(Car car){

if(car instanceOf HondaCar )
// perform HondaCar logic

if(car instanceOf BMWCar)
// perform BMWCar logic


·From a design standpoint, look for and separate things that change from things that stay the same. That is, search for the elements in a system that you might want to change without forcing a redesign, then encapsulate those elements in classes.

·Keep scopes as small as possible so the visibility and lifetime of your objects are as small as possible.

·A class should only one reason to change. Attempt to keep your classes cohesive. E.g. to only do one thing and model one abstraction.

·Try to understand the Open-Closed principle when designing classes. Classes should be open for extension, but closed for modification. Basically, if you need to open up your classes to add new requirements / functions this is likely to indicate that you have not modeled the domain / abstractions correctly. Interfaces, Abstract base classes are all tools you can use to correctly model and abstract the domain requirements.

·Try to understand the Liskov substitution principle. Ok, nice name – good at the interviews. However, the underlying principle is sound. All subtypes must be substitutable for their base types. If you create subtypes you must ensure that if they are used in the same context as the base class that their behavior is predicable. E.g. in sub classing a type do not change its basic type behavior. Inherit because you are of that type not because you simply need some underlying common behavior.

·If there are no formalized code reviews try to discuss your design concepts and code with other team members. Even if they have the same / less experience than you. Sometimes the act of talking something out load can highlight good and bad elements in your code.
Continue reading...

Friday, July 25, 2008

Java Coding Standards:Exception Handling,Logging,JUnits

At enterprise level writing robust code is essential and test driven development technique is helping one in achieving that. So while you code your business components then writing JUnits in parallel is an essential exercise. This helps in checking all positive and negative scenarios which your code can get exposed to. While putting erroneous conditions, your code will behave erroneously,throwing relevant exceptions at right levels with messages making correct sense where and what went wrong. Besides correct exception handling,ensuring right way of logging errors,debug information and general information is significant from testing your code correctly.This post will focus on exception handling,logging and JUnits related coding standards.

In this post focus is writing/compiling standards required for Exception handling,logging and JUnits coding. I am sure these tips will give you some practical insight to achieve

Exception Handling
- Use runtime exception or extensions of this type. Checked exceptions should be avoided unless they make semantic sense for the interface/method. If not all clients of that component have to handle the checked exception even if there is nothing they can do without other than re throw it. These leads to a lot of messy try catch re throw code.
- Log all exceptions at the boundaries of the application. Exceptions should not be logged at every level they are caught and re-thrown. This can cause a lot of noise in the log files. Exceptions should be caught and logged at the boundaries of the application. E.g Middletier/service delegate level, webservice component level etc. The fact that a sub component throws an exception may not be a critical situation for the calling component. As such exceptions should be "bubbled" up to the top most layer of the application and logged just before the application loses programmatic control e.g to the application server or some other invocation framework (webservices, messaging systems etc).
-If rethrowing an exception ensure that the stack trace from the original exception is propagated to the new exception. E.g. converting from a checked to a runtime exception.

try {
} catch (RealException realException){
throw new RuntimeException(message,realException);

This section lists the practices, which should be followed while using Logging. Following these practices make bug fixing easy.

- Logger variable should always be declared as private static variable. For example
private static final Logger logger = Logger.getLogger(Main.class);
- Use the appropriate message level.
* INFO – For logging successful completion of a process.
* DEBUG – For logging the input and output parameters and understanding the behavior in detail.
* ERROR – For logging the failure messages from exceptions.
- Check whether the logging has been enabled for that severity. E.g

if (logger.isDebugEnabled()){
//log something;

- All Exception should be logged in the catch block with ERROR as the message level.

This section lists the practices, which should be followed for coding Junit test cases as well as execution of Junits.

- All classes should have a reasonable Junit coverage. To the extent possible all public methods in the class should have one or more corresponding Junit methods. E.g. one positive test method and another negative test method corresponding to a public method. This is just a thumb rule, the no of test methods could even be more. The only exceptions to this rule are getters and setters methods.
- How easy a class is to test depends on how good the underlying design is. Difficult classes to test, which have too many dependencies that need to be resolved or have poor interfaces, may need to be refactored accordingly.
- If the assertEquals () requires a comparison of two Objects, then make a customized assert<ObjectName>Equals() method which carries the assertEquals() on each property of the object with appropriate message.
- When writing a negative test case use the following convention:

fail(<appropriate message>);
catch(SpecificException ex){
// Successful condition

- For any bug reported during onsite or offshore system/unit testing, new unit test cases must be added Bottom line the test cases must be expanded to test the resolution to a given bug. So I would see at a minimum for each bug raised there should be a test case to replicate the conditions and validate the resolution.
Continue reading...

Monday, July 21, 2008

Java Coding Standards:Naming Conventions

While coding it is significant to stick to naming conventions of the language and Java is also no exception in that.The reason of this practice is to make your code look consistent and easy to comprehend.In most of the situations these conventions are set at organization level but some of them on a broader level are summarized under points given below:
-Capitals should not be used in the packages names.
-Automated unit test cases using frameworks like JUnit should be placed in a parallel package hierarchy in a separate source folder.
-Using the same package naming convention for them would cater to easy testability of complex protected methods

-Class name should be noun in mixed case, with the first letter upper case and the first letter of any subsequent words capitalized.
-If your class implements as design pattern then a the pattern as a suffix to the class name e.g <ClassName>Singleton, <ClassName>Decorator, <ClassName>Factory, <ClassName>Builder,<ClassName>Strategy.

-Method names should be verbs or verb phrases, with first letter in lower case and first letter of every subsequent word in uppercase. Underscore should not be used in method names. Some examples of conforming names are

-Variables should have names that are nouns, noun phrases, or abbreviations for nouns. Names of fields that are not final should have the first letter in lower case and first letter of the subsequent words in uppercase. Underscore should not be used in variable names. Some examples of conforming names are logger, logManager
-One –character local variable or parameter names should be avoided, except for temporary and looping variables, or where a variable holds an undistinguished value of a type.
-Variables should not have the same name as one in a super class.
-Collection classes, such as vectors and hashes should always be pluralized Member variables. E.g deviceNames, deviceNamesVector etc.
-All member variables should be prefixed with f. E.g. fMyMemberVariable. Use of the this.variable definition should be avoided for scope resolution between local and class level variables.

-The names of constants in interface types and final variables of class types should be a sequence of one or more words, acronyms, or abbreviations, all uppercase, with words separated by underscore "_" characters. All constants should public/private static final.
-Some examples of conforming names are

-Exceptions should follow the same naming conventions as those for naming classes; they must additionally be suffixed by the word Exception. For example, if more than one Exceptionvariable is in scope exception variables should be suffixed by Ex. Normal IDE behavior is to create an initial Exception variable in a try catch block as simply (e). This is acceptable. If more than one variable is required then these should be distinguished using the naming model defined below.

-The exception variables should be prefixed by some acronym. Commonly used ones are locEx for LocalizedException, sqlEx for SQLException, ioEx for IOException.

Test must be used in the name of the junit as suffix.
Class name: UserLogon
Junit Test Class name: UserLogonTest
Continue reading...

Friday, June 20, 2008

Java Coding Standards:Layout

In this post, some of the best practices of Layout used while coding in Java, has been enumerated. This helps better readability of code and hence better understanding for people who are going to maintain code.Some thumb rules which are nice to follow:

-Where possible the lines of code within a method should fit on one screen (1024 resolution). If not the method should be decomposed further in a logical manner.
-Files longer than 800 lines are cumbersome and should be avoided.
-Use an indentation level of one tab (4 spaces).Avoid lines longer than 120 characters, since they're not handled well by many terminals and tools.Spillover indentation for breaking up long lines.
-Give blank lines between major sections and blocks of code.
-Do put spaces around arithmetic binary operators such as +(plus).
-Do put spaces around assignment and conditional operators.
-Do put one space following commas and semicolons.
-Do put one space following keywords (if, while,for…..).
-Do put the return type of the function on the same line as the function name.
-Do not put space between unary and postfix operators and their operands, dot and the subscript.
-Do Not put spaces around parenthesis used in function invocations or declarations.
-The Tertiary Conditional Operator expression ? op1 : op2 should be avoided unless it makes the return expression more obvious / clearer. Ideally, explicit return values should be used.
-A return statement with a value should not use parenthesis unless they make the return value more obvious in some way.

return myDisk.size();
return (size>10 ? size : defaultSize);

-No Space between a method name and the parenthesis "(" starting its parameter list
Ideally, there should only be one return from method. Unless there is a real need for some fail fast logic. The exit path from a method should be clearly defined with only one return.
-Open brace "{" should appear at the end of the same line as the declaration statement.
Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{".
-Always use braces {} in if-else and loop statements, even though the statement is a single line.
Try-catch statements should be in the following format

catch (ExceptionClass e) {}

-Leave one blank line between methods between the local variables in a method and its first statement,before a block or single-line comment,between logical sections inside a method to improve readability.
-Leave one blank space after the commas in argument lists of the methods.

Have fun while coding. :-))
Continue reading...

Friday, May 23, 2008

Java Coding Standards:Documentation

A proper documentation of code ensures better maintainability and code management.Writing documentation may not be fun but it is necessary.The focus is practical tips, practices to be followed religiously while documenting code . When you are a beginner in coding world this seems to be a insignificant and time consuming exercise but as you grow in experience you know how important it is to follow such practices in code, so that relevance and meaning of each part of code become evident to anyone going through the code.
Some documentation tips that may make programmer fraternity happy:
  1. Documentation comment should not be more than 80 characters. If it is unavoidable, use paragraphs.
  2. Create comments for protected and public variables,methods and class.Give them meaningful names, if you do so then you may require less effort in description of your code.
  3. The first sentence of each documentation comment is a summary sentence (crisp and informative).It contains a concise but complete description of the API item.
  4. Why a method exists and what it does, this should be documented.Ask any programmer who has to maintain a code with real poor documentation. If you cannot document then do not code and forget about executing it.
  5. Use 3rd person (descriptive) instead of 2nd person (prescriptive) in the documentation comments.
  6. While describing a method or a class or an object created from the current class, describe it as given in example: Gets first name of the employee. Instead saying 'This method....'
  7. Never use JAVADOC style comments inside methods.
  8. All checked exceptions should be documented with the @throws tag.
  9. C++ style (// ..) comments should be used for briefly describing a particular statement (preferably place the comment at the end of the statement, in the same line).
  10. Take full advantage of JAVADOC and HTML tags to significantly improve the readability at HTML levels. Here are some of the HTML tags you can use –
  • <UL> This is a bulleted list<li>a bullet point</li></UL>
  • <CODE> …</CODE>- Anything that is Java code should be in code tags. E.g java keywords, package names, class names, method names
  • <B> - boldify
  • <i> - italicize
Each method comments should include

Purpose of the method
Examples of usage
@param based description of all input parameters
@return based description of the returned value
@throws based description of all the exceptions
@link or @see based reference to all the referred methods
Continue reading...

Saturday, May 17, 2008

Java Coding Standards : Layout

In professional Java programming world, it is essential that your developed code should follow some coding standards as per guidelines set by your organization or your client is technical enough to send you those details. A question arises why do I need such a practice, answer is very simple. To make life easy for those who are going to maintain or enhance your code. A better documented, neat-clean code with all programming standards and guidelines followed does not only enhance maintainability but also performance and robustness of your code. You may find these details to start with at Sun's website.The coding conventions set by Sun for Java recommends that others should ideally follow and no harm in transforming it to suit your organizational or clients' needs . It covers filenames, file organization, indentation, comments, declarations, statements, white space, naming conventions, programming practices and includes a code example.

The purpose of programming standards is to support the development of consistent and well-written applications. It helps developers to create a code base with a uniform presentation, which is understandable, reusable and maintainable. It also helps developers to avoid common pitfalls of Java that leads to robust, reliable and portable code.
In series of articles I will touch upon various aspects of Java coding standards,best practices and guidelines.

While writing Java classes it is quite important how you layout your code.It means how you structure and order constituents of your Java code.The order in which package,import statements and file header are placed:

- The first line of code represents 'package declaration'.
<blank line>
- The import list in sorted order
<blank line>
- The file header

It is important to have specific import statements rather with suffix '*'.Hence no "*"  in import statements.You must separate Sun classes and project specific classes.The order in which the parts of a class or interface declaration should appear in the java files is as below:

a. Class/interface documentation comment (/**...*/)
b. Class or interface statements
c. Class/interface implementation
           comment (/*...*/), if necessary
{This comment should contain any class-wide or interface-wide information  that wasn't appropriate for the class/interface documentation comment.}
d.Variables should always be defined before constructors and methods, irrespective of the order of variable declarations.

In next post, I will discuss about how we should document our code so that Javadoc utility will help build the documentation from code.

Continue reading...

Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker