Showing posts with label General. Show all posts
Showing posts with label General. Show all posts

Sunday, September 13, 2009

Elements of Java Coding Styles

Java Coding Styles: Here are some of the tricks which I felt useful for java developers & I have been using them a lot. Again these are personal preferences, consider what you like & disdain if you don't. By end of the day the software professional is all about getting "good working software, quickly and at low cost" that can sustain for longer time & solves the business problem at hand (with YAGNI caveat). I want to keep updating this whenever I see interesting ones.

Prefer smaller methods
They look beautiful, easy to understand/reuse/change & test.

'As I did 20 years ago, I still fervently believe that the only way to make software secure, reliable, and fast is to make it small.' - Andrew Tanenbaum

Dr. Venkat gives wonderful explanation on - how to convince your fellow developer to write short methods?

Use JUnit test cases; assert statements and method/variable names as documentation, writing comments in JavaDoc are obsolete and useless many a times.

The purpose of the assert statement is to give you a way to catch program errors early, using assertions to state things you know (or think you know) about your program can improve readability & are great in serving as comments, they are intended to be cheap to write, just drop them into your code any time you think of them. They are great tool of communication for a programmer & can get rid of dumb English stuff in the code with // & /** */.

"There is nothing as useless as doing efficiently, which should not be done at all." - Peter Drucker.

I hate to hear someone telling me to add javadoc comments especially for private methods. The method name variable name should be wise enough to reveal the intent. Fluent interface & design pattern can help a lot in naming variables, methods & class names. Over the years my variable & function names have become more verbose. It's so much easier to understand code from years ago when it reads like a sentence.

Big caveat with respect to assertions,

Assertions should be used to specify things that to be true at various points in your program for providing the documentation & definitely NOT for error checking and any active code. Assertions are disabled ("turned off") by default. Assertions were introduced in Java1.4 & can be turned on with -enableassertions (or -ea) flag on the java command line.

& for JavaDoc,

Code that isn't fully documented is unfinished and potentially useless. Javadoc comments on methods and classes should normally indicate what the method or class

It was necessary document the type of keys and values in a Map, as well as the Map's purpose, but now with Java5 Generics that is also not required. Prior to Generics I always used to code List/*String*/ = new ArrayList();

Some Java 5 features are smart; Look for smarter new libraries that exploit these features well

Use basic infrastructure libraries like Google Collections (I prefer this over apache collections), sl4j, Guice etc… as much as possible. We will learn to appreciate the value of Java-5 new features by looking into the source code of these libraries, Old coding styles have to be abandoned in favor new features.

Commenting the code with "if(false)"

In many a times we want to use different implementation for testing & commenting out code temporarily. If the method is very long it's painful to comment out the whole block. Let us say we have method like this.

public void sendMail(){

if(true) return;

// Lot of code for adding to database to event

...

// Transforming text with XSL etc...

....

}

if(true) return; -> This line has the same impact as the commenting out the whole stuff :)

Use double brace initialization (For non-performance intensive code), If possible use Google Collections in all the cases.

As swing programmer I have been using these quite long time. I have seen quite number of experienced java programmers aren't aware this. This really useful while testing. It's concise, requires less typing & more readable but comes with cost. Google Collections provide better same feature without any performance cost.

Map map = new HashMap() {{ 
    put(1, "one");     
    put(2, "two");    
    put(3, "three");     
    put(4, "four");     
    put(5, "five"); 
}};

Use protected & final where ever possible

Using final does not make much sense from performance point of view as modern JVM is intelligent enough to make use them efficiently, but still I feel they have lot of value in making the intent clear & in multi threading simple with im-mutable state.

Usage of "private" is over-rated & I think it's better to have it has protected making setting the code simpler.

Person p = new Person(){{

age=30; name="Suresh";

}}

where age & name are protected variables.

More & more you start using inner classes, you will get frustrate with java for lack of "closures" & will eventually move to Groovy or Scala (Like me :-))

Use Null Object Pattern & throw IllegalArguementException wherever applicable

The Null Object provides intelligent do nothing behaviour that helps to avoid problems with Null references (NPEs) & so called "A billion dollar irreversible mistake"

Prefer Unchecked Exception over Checked Exception

90% of time Unchecked Exception makes more sense than the Checked Exception. This is one of the most significant attribute of successful libraries like Spring & Hibernate. Use Checked Exception for recoverable errors (Business Exception) & Unchecked for remaining stuff.

Understand Soft, Weak and Phantom references in Java

WeakReference is a reference which doesn't have enough force to prevent Garbage Collector(GC) deleting object - Useful for caching

Soft Reference behaves like weak references, except when GC determines object is softly reachable & can be used to avoid OutOfMemoryError.

Phantom references are enqueued when objects are deleted from memory and get()method always returns null to prevent resurrecting object. So phantom references are good for determining exactly when object is deleted from memory.

__________________

Interesting quotes from Rock star programmers that I collected.

"Write lots of code. Have fun with it!" — Joshua Bloch

"Learn to use your tools. And I don't mean just enough to get by. I mean really learn how to use your tools." — Tor Norbye

"Don't use line numbers. Don't put your entire application in one method." — Chet Haase

"Don't be overwhelmed by the language or the platform." — Raghavan Srinivas (In the same line Neal Ford says "When you were hired by your current employer, you may think it's because of your winning personality, your dazzling smile, or your encyclopedic knowledge of Java. But it's not. You were hired for your ability to sit and concentrate for long periods of time to solve problems")

"Millions of people have been employed because someone at Sun Microsystems invented Java." - Masood Mortazavi. Master it & you will never regret for that

"There will always be opportunities for great engineers, but as I said earlier, I think the number of these opportunities will shrink as other, less technical personnel play larger roles in the software-development process, using more productive, higher-level tools and frameworks than we have used in the past." - Ben Galbraith

"Google makes finding information easier than ever, but nothing beats interacting with an expert."- Ben Galbraith. So always associate with people from whom you think you can learn.

From Pragmatic Thinking & Learning

There is no expertise without experience.It takes something on the order of ten years/ 10,000 hours
of practice to be expert in a field Deliberate, thoughtful practice is what makes the difference—not
just going through the motions.Practice doesn't make perfect, but it does make permanent:
neuroplasticity will cause your brain to re-wire itself according to what you do.You may not become
what you dream, or what you aspire to be, but you will become what you do.Unfortunately there is no substitute for hard work.

References:

http://java.sun.com/developer/technicalArticles/Interviews/studentdevs/index.html?intcmp=2225

http://www.agiledeveloper.com/blog/PermaLink.aspx?guid=8a745e85-2a34-4d9c-8c25-ca371530e281 - How to convince your fellow developer to write short methods?

http://weblog.raganwald.com/2007/04/rails-style-creators-in-java-or-how-i.html - Rails style initializers

http://www.refactory.org/s/double_brace_initialisation/view/latest

http://c2.com/cgi/wiki?DoubleBraceInitialization

http://bwinterberg.blogspot.com/2009/09/introduction-to-google-collections.html

http://thestrangeloop.com/sessions/ghost-virtual-machine-reference-references

http://juixe.com/techknow/index.php/2009/11/18/favorite-programming-quotes-2009/

http://www.readwriteweb.com/archives/top_10_software_engineer_traits.php



Sunday, July 13, 2008

Bio-Rhythmic Cycles - I got curious about bio-rhythmic cycles & wanted to try out the the results on my life.

For those who don't know what bio rhythmic cycles are, here is explanation:

The theory of biorhythms claims that one's life is affected by rhythmic biological cycles, and seeks to make predictions regarding these cycles and the personal ease of carrying out tasks related to the cycles. These inherent rhythms are said to control or initiate various biological processes and are classically composed of three cyclic rhythms that are said to govern human behavior and demonstrate innate periodicity in natural physiological change: the physical, the emotional, and the intellectual (or mental) cycles. Others claim there are additional rhythms, some of which may be combinations of the three primary cycles. Some proponents think that biorhythms may be potentially related to bioelectricity and its interactions in the body


I wrote a sample application in swing, which basically takes the date of birth as input & generate the charts.


Here is the sample screenshot, I used JFreecharts & some Date manipulating APIs to create above application. BTW is there any way I can show applet in this blog? Please let me know.

The results were interesting, Most of the events in my life had some kind of correlation with the above graph & explanation:

Physical cycle - 23 days; coordination strength well-being

Emotional cycle - 28 days; creativity sensitivity mood perception awareness

Intellectual cycle - 33 days; alertness analytical functioning logical analysis memory or recall communication

I also tried correlate our god Sachin's best innings with these cycles & surprisingly, cycle behaviour used to match with his best time :-)

Anyway I will try out with some other important figures before coming to conclusion these cycles have any impact or it's just a humbug. BTW, I am little skeptical about all astrology stuff.

So I am planning to develop a RESTful sample as well sample mobile application accepting date of birth & generating the charts possibly using Google charts instead of Jfreecharts

Monday, February 11, 2008

2008 - Programming Technologies to look for:
Comet Programming:
a web server sends data to a web browser (client) asynchronously without any need for the client to explicitly request it, So it's a server side AJAX (supported in Tomcat6). This is great feature & opens up lot of possibilities with server side events. It's like RMI's Callbackinterface where client can listen to events from UnicastRemoteObject.It has great potential where it's not advisable for client to poll . Servlet2.5/Tomcat6 will support Comet programming & I am sure all the frameworks will start laveraging the same. But I am little skeptical about the popularity of this; although the statements from several authors are exciting.

Web Technology Frameworks:
I tried out some samples with component frameworks. Since I have been working swing programming model, it was so easy to write Listener anonymous classes. I wrote samples with GWT, wings & Echo.I did more work with wingS as they were using YUI library as backbone.
I also followed Wicket & Tapestry very closely. I am yet to work with real project to really appreciate the necessity of having to define HTML & Java artifacts for each page. zk framework,JSF & many other frameworks compete for this space. Wicket is my favorite component oriented framework although I am not sure it's scalability capabilities. As tapestry claims to work well with highly scalable sites, there is neither such explicit asserstions or sample sites avaiable for Wicket to prove that it's possible to create highly scalable sites, anyway I am excited to work with new Wicket release that will get released in coming months leveraging JDK1.5 features. Although personally I love swing programming model,my guess is page-centric MVC is going to be mainstream web programming model in 2008 as well. RoR, Grails are offering great productivity gains in this space. Grails1.0 got released in Feb 1'st week & I believe that 2008 will be Grails year as for as page centric web sites development is concerned & it's going to be Wicket year for developing complex web applications.

Closures & DSLs with dynamic languages:
Last year there was lot of discussion on aspect oriented programming & dependency injection. Dynamic lanaguages have brought lot changes to the programming parctices with Groovy & Ruby leading the way.It was difficult to commit to any of these two languages (Groovy & Ruby (JRuby) ) , Although Groovy looks to be easiest to select for Java programmer I was little skeptical as Sun choose to invest over Ruby/JRuby over Groovy & Thoughtworks , a technically intelligent company invested in Ruby. But after trying out few samples I am convinced that Groovy is the best way for dynamic programming for Java programmers. Closures, DSLs & weak typing languages are simply unstoppable on JVM. I bought Groovy In Action book.

Closures:-> As a swing programmer, I have been using anonymous classes a lot. Spring's JDBCTemplate... & other template wrappers were huge hits for me. Not only closures will help solving resource handling( File, Database, User Interfaces, transactions (open<>close)), they also help better thinking (recurse & iterative). Joel explained them well here. The main point I guess with closures is that we can assign a variable to a method & use just like any object & you can pass on these parameter to a other methods as explained superbly here.
I used to wonder about the reason for final variable only accessibility in anonymous classes. I found explanation here, where Guy Stele says java should not allocate any memory in heap without "new" call & allowing non-final variables violates this. He also says dynamic class loading ,reflection already violates this principle. Anyway it's clear that anonymous classes are not equal to closures. Paul Graham argued brilliantly for closures saying succinctness is power long back. Paul's concern over java for not providing power & Joel concern of java being simple, I guess are now solved with dynamic languages.With James Gosling asserting that it was resource/time constraint that prevented Closure inclusion in original JDK, closures are likely to reach java mainstream this year.

Some useful links on this topic:
Review of Groovy/Grails books from Matt Raible
Higher Order Functions with Groovy - GINA book doesn't cover this topic
Closures samples
Some closure theory
Closure proposals from Bob lee (Guice creator) & Josh Bloch where they argue removal of new keyword to support closures.
comparison of different closure proposals:
Closure Debate from IBM
Language comparison:
A closure sample in Groovy

Some how Fluent interfaces were not familiar or popular in Java world. Standard Java bean definition is not really good way to define & populate objects. Martin Fowler defined them as back as Dec 05. Although fluent interface & builder pattern cannot be implemented in java easily my guess it's happening mainly because of Java Bean spec (which are well used by frameworks(ex.hibernate) & tools (IDEs)), we can also write java code like,
new Person("test","test").email("praveenm").firstName("Praveen").lastName("Manvi"); instead of calling set method on each variable. Many JDK standard classes like StringBuffer, ProcessBuilder already using this. I guess more & more APIs will start using fluent interfaces like JAXB2 commons.I am also planning to write a plug-in in netbeans/eclipse to extract fluent interfaces from existing classes. Venkat provides a very neat explanation about the necessity & usage of DSLs & XML limitations to be used as full fledged DSL.
Cloud Computing, Grid computing, Virtualization might reach masses this year.
OSGI - OSGi is going to change the deployment and run time model for enterprise apps.(Although I am not able fully appreciate/understand the value even after going through literature, The immedeate advanatage I see as of now as a Swing programmer that I can run may java apps with single JVM which is painful now), Although Oracle, Bea (Oracle?), IBM & more importantly Spring showing lot of interest & excitement, Sun doesn't seem to be that excited
So exciting days ahead...

Tuesday, January 01, 2008

Best Java Minds:
One of the best way to learn any technology is to follow the best minds. Here I have collected the set of authors & their blogs who have made(and making) huge contribution to the Java.
It's interesting to see their activities in coming days

James Gosling - Father of Java
Rod Johnson - Author of Spring Framework. Finally, provided promising solution to the lunacy of EJB that triggered new EJB3/Java EE to evolve. It looks like now Rod wants to be actively part of next javaEE spec.
Gavin King - Father of Hibernate. Saved lot of time of writing and maintaining hand written SQL in java & telling world that transparent persistence a good thing & is huge advantage, which some reason TopLink/entity beans failed confirm
Clinton Begin & his team - Creators of superb SQL Data mapper framework iBatis - Making working SQL easy even for legacy DBMS where selling 'hibernate' to paranoid DBAs is a difficult task. It has also influenced JDBC4 to evolve.
Bruno Lowagie - Author of iText (iText is an open source Java library for PDF generation and manipulation & regarded as one of the best library)
Gregor Kiczales - AspectJ Author, Showing cross cutting concerns could be handled in a intelligent/non intrusive way.
Ceki - Log4j. The de-facto standard for Java Logging.
Doug Cutting - Lucene. Developed the de-facto full-text search engine for Java.
James Duncan Davidson - Ant and Tomcat.
Joe Walnes - XStream and SiteMesh. Top class framework for handling XML & web templates.
OpenSymphony -Copmany behind great frameworks like SiteMesh, Quartz, Webwork, Xwork
Erik Thauvin - Java pointers - A Java Crawler Great Collection of links, although he has stopped now adding anymore links citing the time it takes to come up with valid links, but still it's good to visit his old collections. I am planning to start this again in 2008

Java Swing isn't that bad because of these guys
Eugene Belyaev - Creator of IntelliJ IDEA. #1 IDE using just Swing.
Karsten Lentzsch - JGoodies. Superb contribution to java swing
Doug Lea - util.concurrent. Superb framework for parallel stuff. More important in Swing than anything else.
Romain Guy with amazing swing skills. Author of Filthy Rich clients
Ethan Nicholas Author of Yahoo SiteBuilder
Chet Haase - Co-Author of Filthy Rich clients
Jfreecharts - I was not able get the author details of this excellent framework

Gurus - Although they have not made any significant contributions to Java, but they have definitely has huge impact on the way software is created.
Martin Fowler - Probably the best writer who can be called as true technical Guru with amazing writing skills. Defining patterns samples...
Erich Gamma - JUnit, Design Patterns and Eclipse
Jack Shirazi - Java Performance. created website on performance tuning
Ward Cunningham and Kent Beck - Extreme Programming.
http://www.angelfire.com/tx4/cus/people/ - The list of language creators

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.

Tuesday, November 13, 2007

Some Architectural Notes:

"Practical Guide to Enterprise Architecture" book published by Prentce Hall has very readable contents. I enjoyed reading it. Here are some highlights

Architecture Is Business-Driven. This is the first and most important habit of an architect. All architectural undertakings should be done for the sole reason of solving business problems. Architecture planning is a continuous process that requires full alignment with business goals.

Communication Is King. Enterprise architecture must be communicated to all parties across all IT organizations and lines of business on an ongoing basis. This should include strategy, goals, and objectives. Its purpose is to increase awareness throughout an enterprise. It must also include a statement of shared values that are endorsed and supported by the executive team and incorporated into the IT governance model.

Unification Is Queen. For enterprise architecture to succeed, it must be unified across the enterprise. Success and failure of all forms of architecture depend upon the joint efforts of all business and IT areas, their support of the architecture, and consistent implementation.

The Frog Is a Prince. Support from the executive team is essential for the practice of architecture, but a successful architecture starts almost at a grass-roots level by seeking support from line managers and their direct reports where the sell is the hardest. Getting buy-in from the troops (Seek first to understand, then be understood) will shield the architecture from passive resistance.

K.I.S.S.: Keep Infrastructure Simple. Information technology assets and the elimination of the endless combinations of platforms that use disparate technologies are the main inhibitors of change and result in an inflexible architecture. A goal of sound enterprise architecture is the destruction of incompatible technologies. If infrastructure is kept simple and consistent, enterprise architecture can leverage existing skill sets, training, support, and services in a cost-effective and agile manner.

Agility Is Key. Sometimes the best solution for a particular business problem requires adoption of a technology and/or approaches that are not mainstream. Agile enterprise architecture will allow the modification of standards to support business requirements, and it will seek out alternate ways to integrate the technology with the current architectural model.
Crawl Before You Walk. Expectations should be managed. The best architecture for an enterprise is one that evolves versus one that is created. Each iteration of the architecture should build upon previous versions and provide an incremental improvement to the organization. Enterprise architecture should also focus initial efforts on near-term opportunities—what is within reach—that can provide immediate business benefit. Small but quick wins will help win allies from both the business and technology areas and will best demonstrate the value of agile enterprise architecture.









It's very important to capture & communicate business/technology drivers well in succinct manner to all the stake holders.Defining architecture satisfying all the stake holder is a very difficult task. Un-informed stake holders will have unrealistic architecture goals. CEO expects application to scale for decades, Manager wants no duplication efffort at any cost & expect that to come completely from architecture, Developers exepects libraries to ease out their coding & Designers expect check lists.


All the stake holders are correct in their own way on the expectation from architecture, but unfortunately Architecture cannot accomplish all the individual requierements & it's important to set the expectation clearly.

Architecture -> Is About Making Technology choices. In my openion this is the most important feature that will have huge impact on any projects. Application maintainence, Deveoper availability should be given as much importance as techincal excellence of the tools that we choose.
Architecture -> Is About understanding the context. All patterns/anti patterns work with aparticular context. If we miss out this context the patterns/anti pattern knowledge can have adverse impact on our judgements.
Architecture -> Is About understanding of problem space & strong connection with business. Respecting the domain experts & their openion is very important here.
Architecture -> Is not just about Reusable artifacts but flexible artifacts. There will be always better ways for implementiion techniques as time progresses. So "re-use" is overloaded word. So I guess flexibility is more important thatn reuse. Interfaces & Dependency Injection (Spring is excellent in serving this pupose & latest version gets you out of XML hell as well :-)) is more important as they give the power of changing the implementation with better means over the time without much pain.
Architecture -> Is about understanding varying scalability requirements, Every one don't require eBay or Amezon kind of requirements. I have personally executed 3 eBay projects as a lead & the rules of the game is totally different for those kind of applications.
Architecture -> Is About breaking rules.eBay doesn't rely on transactions. The data is heavily de-normalized, Most of the processing happens at the application tier. The asynchronous channels are heavily used. ThreadLocal's are used heavily. Scratch DB is preferred way to store the session data. Scaling happens @ the web-tier & EJB's doesn't even qualify as contenders & the XSL templates rule the presentation layer.These rules are definitely not suited all kinds of applications. It was very difficult for me to come out of hang-over of eBay code base.

Architecture -> Is about understanding the Return On Investment & ability to predict the future with political, local & legal aspects in the mind. Documenting patterns & anti-patterns in these areas will be invaluable as experience/historical knowledge holds the key.

Identifying the need of different stake folders & making sure that architecture artifact look relevant to all stake holders is important.So it is better to write different documents focusing on different stakeholders.It is important to keep the theme same in all artifacts. For Example,"System Architecture" document should capture the over-all technical decisions that were made along with explaining the rational & tried alternatives. This document should act as technical design review check list. It's important document non-functional or operational requirements as clearly as possible. Architecture goals and means (usually debating 2-3 options for achieving the same).Integration of various application modules (critical ones).
For any web based applications screens plays very important role & they capture the requirements in best manner. This exercise ideally should be part of requirements definition & this "System architecture" definition process should begin sometime during the middle of requirement definition. Unfortunately it's a tedious task define the screens manually& as of now there is no credible way to convert HTML directly into production by few tweaks (Frameworks like Tapestry & Wicket web frameworks certainly makes better compare to other approaches).
"Application Architecture" Should capture the different technical layers & their components. It also should capture the over-all application modules & their relationships. Integration is the most painful aspect development as it not only involves code integration it also requires to people also communicate & integrate. More emphasis should be given in declaring the interfaces & handshaking mechanisms between the teams & modules.

Conclusion:
Software Architecture is very challenging, I guess aspiring Architects need to focus get in touch with real developers & do active coding rather than relying on marketing literature available in Internet. The best brains sitting in ivory tower developing specification (Martin Fowler calls them Harvesting frameworks) really doesn't add much value compared to specification/frameworks that comes out as by-product of developing real time applications like Spring, Rails. (Non Harvesting frameworks). Unless Software Architects stop forming their opinions based marketing literature and blogs, they will be forced to be called as "White Elephants" of software industry.

Monday, December 18, 2006

Interviewing Tips

With the plenty of FAQ/Q&A available on Internet & books, most of the programmers are aware of nature of questions. If any one get selected by sheer power of raw memory, I guess that is unfair. Memory is also important but definitely not more important than the ability to assimilate just in time information to solve a particular problem.This is more important with the advent of Google Search & development methods.
So I think we should give 50-50 for both knowledge & analytical skills. We cannot undermine any of these two, both are equally important. With amount of APIs and available options we cannot afford to have good analytical person taking more than few months to learn & apply in 6-7 month duration projects.

Give a problem and see how the API design is done for that. Look out for class names, method names and handling alternate flows. Naming classes/methods and cache invalidation remains toughest part of the software creation. Probe on what difficult problem they have solved so far.

Q & A on factual details aren't useful & definitely not the best way to reject or consider.

Here some personal set of questions that I would like to consider while interviewing a person for technical lead position in my company. (Mainly in Java) All the professionals claiming developing web applications should be able to answer all these questions without any hesitation.

JSP/Servlet:
1. Difference b/w forward and re-direct & use cases for them
2. Difference b/w jsp include and include directive
I would expect senior guys to explain the actual implementation details by the container rather than just functional difference & usage scenario's.
3. Scope questions (session,request,application & page)
I expect senior guys to explain me terms like web clustering, session replication, load balancing, thread safety & it's implications on data stored in above scopes.
4. Explain the stateless nature of servlets,(It's life cycle, SingleThreadModel, web.xml entry requirements, ActionServlet implementation details if the candidate is aware of struts)
5. Filters, Listeners & their importnace.
6. Web framework(s) & their relative merits/de-merits. (Action Oriented Vs Component oriented) again from senior guys.

Core Java:
1. java.io.Serializable/Cloneable marker interfaces and their importance. Deep cloning Vs Shallow cloning.
Different ways of instantiating Objects & their overheads (new, Cloning, Serialize/De-serialize, reflection)
2. Collection API knowledge
Choosing a right collection is one of very important characterstic of good java programmer.
Practical usage of Map,Set,List from their experience. Performance related issues with them.
(Synchronized, Non synchronized)
A problem that involves string manipulation and usage of Collection APIs.A successful candidate should be able to produce code using proper APIs.
3. Exception Handling, Im-mutable nature of String
Any programmer who has coded in java should be easily able to tell about the difference/example for Checked Exception & Unchecked Exception. It will be interesting to debate on this issue with senior guys taking popular framework into consideration.

For Example reversing a given set of string with removing duplicates & sorting them alphabetically in case insensitive manner. Candidate should be able to pick up TreeSet, Comparator & String manipulation stuff.
Searching for a string in a file, It's important to see how the candidate write the code taking performance, Exception handling into consideration.

JDBC/Database:
1. Importance Normalization & join.
Difference between an inner join and an outer join
2. foreign key constraint? what can happen when you try to delete a parent record?
3. ResultSet, Template pattern, How to get column details from the table name?
4. A SQL query problem involving either outer or inner join with aggregate functions.
5. Dirty Reads/Phantom Reads. Selecting isolation levels .
6. Spring/Hibernate value addition
Spring Templates (For JDBC, Hibernate) I can't forgive a experienced person who is unaware of these APIs or he should be able to explain the home grown utility to reduce the # of lines of code in persistence layer
7. Lazy, Eager & Batch fetch strategies (With hibernate context if the candadate is hibernate aware)

Overall application architecture:
(These are must for architecture position)
1. Layering of application and their importance.
2. Technical benefits of EJB & how i tries to solve all these issues.
a. Security
b. Transactions
c. Distribution
d. Scalebility
Pragmetic aproach here should be appreciated rather than violent pro-against stand on EJB's.
3. Lightweight architectures
4. Design patterns & their benefits
You can pick up any pattern & discuss on the same, It's amzing to see people's answers when I ask difference b/w Singleton/class with all static methods & use get/set methods of javabeans :)
5. OOAD
Difference static binding Vs Dynamic binding typically discussion should start with questions like can we extend String class (with String being a final)
6. Knowledge of existing frameworks & shortcomings of those.
7. Asynchronus communication JMS, Thread, MDB

After this I have this matrix to measure the technical competence

Technology Ratings (1-5)
Core Java 3
Application/Framework 2
JDBC/DB 2

I will enter my rating (1 min & 5 Max), & it is more 5 in any he should be hired or can be considered for next round. If it is 3 in all the cases he can be considered.

In the same fashion non-technical competence can also be considered. But I don't want really want to consider this (May be as input for HR guys)

Criteria Ratings(1-5)
Previous Company/Projects 3
Academic Record/Stream 1
Attitude/Communication 2

For management position
1. Estimation techniques.
FP, WBS
2. Conflict solving ability
3. CMM levels & overall quality processes

Any thoughts on this??

Thursday, December 07, 2006

It is very important to articulate the expectations on attitudes and behaviour from new developer coming into software development team.
Here are the few points I tried to come up with...
I want to ask them to take oath on these principles

  • I will not resist learning new techonology to solve problems, but enjoy the chance to do so.
  • I will not blindly accept any technology or innovation but will always try new solutions, I will research & keep up on news about new solutions & never feel unconfortable to modify the source code that I am not familiar with.
  • I will not throw out the same working solution to a problem every time. I want have the good track record of introducing new ideas & technologies
  • I will try solutions without complaint or fear of failiure (& always own up the responsibilities to correct the same & never insist on using the same solution behind other's backs to management
  • I will never undermine the technology & always ready to accept good things coming from all the ways.


Tuesday, October 24, 2006

Java Framework Information Fatigue Syndrome

'We're often seeing a failure of concentration. We're seeing a loss of motivation, loss of morale. We're seeing greater irritability.'
-- Psychologist David Lewis
This was attributed to ammount of information that a person has to take in general these days & I guess same principle can be easily applied to Java space as well. There are so much of frameworks and patterns. I have seen this syndrome in many senior Java developers. It is becoming harder to cope this day after the day.

In today's competitive business world it is imperative that everyone delivers at a pace that has never been imposed upon in the past. User expectations risen sharply & there is growing trend of technical awareness & knowledge how technology can help to deliver products with shorter time to market impose an overwhelming challenge to business.

More often than not it is discovered that the programmers/designers requires technical assistance and guidance to be able to successfully deliver. It is also observed that strong technical people get caught in several non-technical (but important) aspects. This quickly results in shift of focus, diluting the drive towards technology & there is no time validate the information & the quality of web frameworks. There is so much of options to choose & there is no time to spend in learning.

Annual increase in the rate of change of information is moving at alarming speed. A modern java programmer after spending about 18 months to attempt to master JDK 1.4 >25,000 methods, now he must learn an additional 8,000 more methods for JDK 1.5 ( >30% increase) Now we have huge JEE stack with all the tons of web & persistence frameworks.

So forget about mastering all the stuff, it is nearly impossible to master all the technlogy stack with fighting ever ending project dead lines. Can we afford to neglect these trends? Not possible ! especially people in technical stream (Like me) & decided make living out of technical career, the situation is frightening.

So what's the way out?
There is no way we can get out of reading/learning new frameworks; We have to understand and appreciate the innovation to stay competetive. We have to spend quallity time in going through the code/innovation.

I think the best for us to follow the best brains. I consider Rod Johnoson & their ilk of Spring are the best bet. We have wasted enough time on EJB's & many JCP specs. JCP seems to be worried about only the technical excellence (Making generic very clever specs) but forgetting the developer life. Even big guys like IBM & BEA didn't help. It was Rod & his ilk who made our life simpler by making us to write lesser code & hence lesser bugs. So that we can spend more time with our family.

Even if people with same caiber like Gavin King (JBoss Seam), Geert Bevin(RIFE)... can innovate better, Spring team should be able to adapt these innovation without any hesitation. (By seeing there track record of DRY). So it is best for us to stick to them.

Final words,
The key to survival and indeed productivity is to have a firm grasp of fundamentals, and to be able to assimilate just-in-time information.
&
Blindly follow the Spring.
Bookmark and Share