Sunday, December 30, 2007

Java Links - Collection of Useful Java links

Many a times colleagues & friends who want to learn java were asking me to provide some good links to go through to start with. I compiled some set of useful links. I hope that this will be useful to all the people who want to know about Java.
In Java world, the difficulty isn't to find good API but is to use it well. Moreover, the Java API is too large to memorize all. That's why, the internet links are important. You name any task there will be minimum more than 10 ways of accomplishing in Java, that's the strength of Java. But irony is that's fastly becoming weakness as well compared to RoR & .NET at least in developing web applications. Having lot many options is not always good :-)
Each technology (Desktop, Enterprise, Content Management, Web applications...) is so big that each has enormous amount of information to learn. Here I have included the links that are generic in nature useful for starters.

Resources from creator of Java - I always maintained that Java API (JavaDoc & Java source code) is "the best" resource, Most of us don't realize this.
Java 6 - Programmer Guide
Java 1.5 API Specification
Sun Tutorials
Technical Articles from sun based on category

Most Java books are written by people who couldn't get a job as a programmer, since programming pays more than book writing. Most of the time they are outdates & comes with bad examples. This is especially true for free books, but I guess these books (Especailly first 2) deserves reading.

eBooks - Free
Java Language Specification - James Gosling- Father of Java It's like Ritchie book in C,
Thinking in Java - Bruce Eckel One of the best writer, Has also written books like Thinking in C++ along with other Java books. Now a days he is putting efforts behind Adobe Flex, RIAs
Object-Oriented System Development - Dennis de Champeaux, Douglas
Mastering Enterprise JavaBeans 3.0 - Ed Roman, EJB3.0 is definately not as bad as earlier versions.
Processing XML with Java - Elliotte Rusty Harold, I think we should avoid XML as much as possible, if required Groovy provides better alternative compared to Java
The J2EE Architect's Handbook - Ashmore - Don;t carried awayby the asserions
Servlets and JavaServer Pages: The J2EE Technology Web Tier - Falkner and Jones
Java Design patterns - James W. Cooper - Examples are provided in Swing
Well written set of Java Series books from Sun.

Good Java Websites
Sun's Java Site - Official java resources
Java practices - Supereb Collection of Java practices
The Server Side - Interesting discussion but usually consists lot of marketting literature, So
don't believe what ever people say there.
IBM's developerWorks- Wealth of Java information - IBM has made huge java investment in developing literature of building large scale applications.But they are quite slow in supporting new stuff like weblogic guys.
Weblogic - dev2dev - #1 in providing enterprise software
Spring - Lightweight framework providers ,
JBoss - First popular open source application server, Now Gavin King author of HIbernate, Seam works for JBoss
The essential Java language library - The resources you need like you need air
JavaRanch - Good old Java certification site - But you are forced to see all sort stupid questions & answers, If you not interested in certification no need to go here.
O'Reilly's onJava - O'Reilly books are generally good
Good Applet resources
Kick Java
Java open Source Collection - My #1 site for looking into java open source options. All kudos to creators of this site.

Java Tech magazines
Infoq - My favorite, If I start a magazine it is going to be like this (BTW I am planning to launch one)
Net Beans magazine - Good place for all NetBean lovers
Parleys - Belgium based site with lots of quality presentation on various interesting Java areas
JavaWorld IDG's online magazine for Java language and programming professionals--featuring news, views, tips, tools, technologies, and more. But I guess these days we are not getting much content here
Java Report Online Online segments of Java Report, featuring Java Tutor, products and services listing, articles, jobs and more.
About java An in-depth collection of news, tips, articles, and tutorials.
Javaposse News,Interviews about java.
Java Skyline - Magazine for Server Java developers
Java Developer Journal - Self proclaimed #1 magazine, with lot of ads.
Java Jazz Up -free online magazine on Java Technology
DevX - Java zone - Very good articles, again lots of ad
java blogs - A java blog aggregator.

learntechnology.net (EJB, JMS, Ajax, iBatis, Struts, Wicket, ...)
The Java Memory Model (lot of ressources ...)
Free Java EE (J2EE) Training Online

Some interesting DB related links
Design Patterns - Nice explanation design patterns

I think these are important areas that any Java Programmer must be familar witth.
1. Java Programming
2. Java Collections -> Look at the apache commons as well as Google collections, You will understand both power & shortcomings of Java collections.
3. Java threading Model -> There is going to be lot of investment in coming years as the API that exploit the multiple CPU power are going to be important. Scala/Erlang is also important scripting languages to follow.
4. Understand the servlet model. You can look into source of Wicket or Tapestry pure object oriented component models for developing web applications. My Swing way of developing complex web applications is going to be popular in coming days. (WingS, ZK, Echo, GWT, JSeam)
5. Scripting/DSL is bringing lot of cahnges in development (Groovy looks to be the best bet for Java programmers), So it's also better to focus on Groovy support in Spring, Grails & Seam

Monday, December 10, 2007

Effective Java & Practical Java - The grand-old two books that are suggested for java basics.
I thought it might be helpful for Java programmers to glance through rule list as most of the recommendations here still have relevance.


Effective Java -Joshua Bloch
Creating and Destroying Objects
1: Consider providing static factory methods instead of constructors

Not always the best, Now a days Dependency Injection is better than factories for low coupling
We have 3 ways of instantiating a class,
1. Using 'new' operator
2. Using java reflection Class.forName("myClass")
3. Using clone() bitwise copying
4. Using Serialization (java.io.Serializable)
All have their own use-cases of use.
2: Enforce the singleton property with a private constructor
Over use of Singleton are regarded as bad practice because of increased usage multiple VMs & clustering. We have Singleton Detector (Google code) to find singletons and global state in the Java code that we produce to help us refactor them. This tool which analyzes Java bytecode and detects the use of Singletons.
Item 3: Enforce noninstantiability with a private constructor
Spring does this with abstract class (StringUtils) & static methods- I really likes this idea compared to private constructor.
4: Avoid creating objects
This also needs to be done based on requirement, With modren JVM's it's not so costly as you may think of, You can avoid re-instantiating heavy objects
like SimpleDateFormat in for loops etc... by caching them as private static final member variable. We should avoid creating duplicate objects
5: Eliminate obsolete object references
Google collection APIs should help us for better use of Java collections
6: Avoid finalizers
Why this was invented in the first place, there is no need of finalizers
Methods Common to All Objects
7: Obey the general contract when overriding equals
8: Always override hashCode when you override equals
Now IDE like NetBeans 6 provide the option to automatically do this.
9: Always override toString
This can come handy while analzing the logs, Again with modren debuggers we hardly need toString()
10: Override clone judiciously
Ideally Cloneable should be having clone() method instead of being a marker interface , I am still not convinced on the importance of Marker interfaces
(Serializable, Remote etc...)
11: Consider implementing Comparable
Yes sorting may be required @ any point of time & these days it's better put more work on JVM than the Database
Classes and Interfaces
12: Minimize the accessibility of classes and members
Make all members private, Give me explanation if you think otherwise
13: Favor immutability
I don;t think it's valid with modren JVM's there is no need to make inline (making final) the code, JVM takes care it automatically
14: Favor composition over inheritance
non intrusive model better compared to intrusive model, POJO's better compared to EJB (not the JEE version of course :-))
15: Design and document for inheritance or else prohibit it
Spring is a wonderful example of this principle& struts the worst offender
16: Prefer interfaces to abstract classes
Spring is a wonderful example of this principle& struts the worst offender
17: Use interfaces only to define types
18: Favor static member classes over nonstatic
I guess this is debatable
Substitutes for C Constructs
I am not sure how many people are really interested in converting C programs to Java now a days
19: Replace structures with classes
20: Replace unions with class hierarchies
21: Replace enum constructs with classes
Now we have enum type in Java 5
22: Replace function pointers with classes and interfaces
Methods
23: Check parameters for validity
Throw IllegalArguemtException for any errors & don;t throw checked Exception.
24: Make defensive copies when needed
25: Design method signatures carefully
26: Use overloading judiciously
I say don;t use it.
27: Return zero-length arrays, not nulls
Good point, For objects use Null Object pattern
28: Write doc comments for all exposed API elements
General Programming
29: Minimize the scope of local variables
30: Know and use the libraries
Don;t use any library blindly, Look into the code.
31: Avoid float and double if exact answers
are required
32: Avoid strings where other types are more appropriate
Again debatable point, I have seen people arguing String for even 'id' value, With the popularity of scripting languages I guess over-use of String not an offence as long as it simplifies coding
33: Beware the performance of string concatenation
There is one myth involved with this, Now if you use '+' operator for concatenation, it is better compared to StringBuffer & the Compiler(JDK1.5)
automatically does this for you by using non -synchrized StringBuilder classes.
So use '+' freely, Use StringBuffer if you need synchronization which is rare anyway.

34: Refer to objects by their interfaces
Use Java 5 Generics
35: Prefer interfaces to reflection
Now java reflection performance has improved a lot.
Hibernate used CGLIB (byte code manipulation framework) against java reflection
Now I am sure Gavin King would have selected Reflection with modren JVMs.

36: Use native methods judiciously
I say don;t use it, It's better to re-write
37: Optimize judiciously
38: Adhere to generally accepted naming conventions
Follow the Sun rule, I also discussed in length about java coding conventions in one of my previous blog
8 Exceptions
39: Use exceptions only for exceptional conditions
40: Use checked exceptions for recoverable conditions and
run-time exceptions for programming errors
41: Avoid unnecessary use of checked exceptions
42: Favor the use of standard exceptions
43: Throw exceptions appropriate to the abstraction
44: Document all exceptions thrown by each method
I guess it's better to choose the long meaning names as nobody reads Javadocs these days.
45: Include failure-capture information in detail messages
46: Strive for failure atomicity
47: Don't ignore exceptions
here is ultimate explanation on Exception Handling
Wonderfully explained concept "Runtime=FaultException" & "Checked=Contigency" , a progmatic way of using Checked (extending Exception) & UnChecked (extending RuntimeException)
9 Threads
48: Synchronize access to shared mutable data
49: Avoid excessive synchronization
50: Never invoke wait outside a loop
51: Don't depend on the thread scheduler
52: Document thread safety
53: Avoid thread groups
10 Serialization
54: Implement Serializable judiciously
55: Consider using a custom serialized form
56: Write readObject methods defensively
57: Provide a readResolve method when necessary



Practical Java - Peter Haggar

General
Understand that parameters are passed by value, not by reference.
Use final for constant data and constant object references.
Understand that all non-static methods can be overridden by default.
Choose carefully between arrays and Vectors.
Prefer polymorphism to instanceof.
Use instanceof only when you must.
Set object references to null when they are no longer needed. Objects and Equality
Differentiate between reference and primitive types.
Differentiate between == and equals.
Do not rely on the default implementation of equals.
Implement the equals method judiciously.
Prefer getClass in equals method implementations.
Call super.equals of base classes.
Consider carefully instance of in equals method implementations.
Follow these rules when implementing an equals method. Exception handling
Know the mechanics of exception control flow.
Never ignore an exception.
Never hide an exception.
Consider the drawback to the throws clause.
Be specific and comprehensive with the throws clause.
Use finally to avoid resource leaks.
Do not return from a try block.
Place try/catch blocks outside of loops.
Do not use exceptions for control flow.
Do not use exceptions for every error condition.
Throw exceptions from constructors. -> This is very tedeous
Return objects to a valid state before throwing an exception. Performance
Focus initially on design, data structures, and algorithms.
Do not rely on compile-time code optimization.
Understand runtime code optimization.
Use StringBuffer, rather than String, for concatenation. -> Is incorrect statement with JDK5 onwards
Minimize the cost of object creation.
Guard against unused objects.
Minimize synchronization.
Use stack variables whenever possible.
Use static, final, and private methods to allow in lining.
Initialize instance variables only once.
Use primitive types for faster and smaller code.
Do not use an Enumeration or an Iterator to traverse a Vector.
Use System array copy for copying arrays.
Prefer an array to a Vector or ArrayList.
Reuse objects whenever possible.
Use lazy evaluation.
Optimize source code by hand.
Compile to native code. Multithreading
Understand that for instance methods, synchronized locks objects, not methods or code.
Distinguish between synchronized statics and synchronized instance methods.
Use private data with an accessor method instead of public or protected data.
Avoid unnecessary synchronization.
Use synchronized or volatile when accessing shared variables.
Lock all objects involved in a single operation.
Acquire multiple locks in a fixed, global order to avoid deadlock.
Prefer notifyAll to notify.
Use spin locks for wait and notifyAll.
Use wait and notifyAll instead of polling loops.
Do not reassign the object reference of a locked object.
Do not invoke the stop or suspend methods.
Terminate threads through thread cooperation. Classes and Interfaces
Use interfaces to support multiple inheritance.
Avoid method clashes in interfaces.
Use abstract classes when it makes sense to provide a partial implementation.
Differentiate between an interface, abstract class, and concrete class.
Define and implement immutable classes judiciously.
Use clone for immutable objects when passing or receiving object references to mutable objects.
Use inheritance or delegation to define immutable classes.
Call super.clone when implementing a clone method.
Do not rely on finalize methods for non-memory resource cleanup.
Use care when calling non-final methods from constructors.

Bookmark and Share