Collected Java Practices
javapractices.com offers concise presentations of Java practices, tasks, and designs, illustrated with syntax-highlighted code examples. The code examples are available for download. See below for user comments on the site.

The only permissible judgement in polite society is that no judgement is permissible.
- Our Culture, What's Left of It, Theodore Dalrymple

Servlets and JSPs
A Web App Framework - WEB4J Always maintain HttpSessions
Application scope is multi-threaded Beware multilingual submit buttons
Beware of common hacks Beware of custom cookies
Beware of doubly escaped ampersands Beware of URL rewriting
Choose form validation style carefully Consider Controllers for redirects
Do not synchronize doGet, doPost Emit flexible URLs
Escape special characters Forward versus redirect
JSPs should contain only presentation logic Loss of data during restart
Manage sessions closely Measure web app performance
Minimize site response time Parse parameters into domain objects
Pre-populate forms Prefer JSTL tags
Prefer UTF-8 in all layers Prevent self-linking
Refactor large Controllers Repel invalid requests
Reuse login page for errors Send trouble-ticket emails
Serve binary content Session-scope objects often Serializable
Struts seems mediocre Try alternatives to ResourceBundle
Understand details of FORM tags Use Cascading Style Sheets
Use extensions for fine-grained security Use Model-View-Controller framework
Use templates to standardize layout Validate email addresses
Validate generated HTML Web usability guidelines
Wrap file upload requests
Swing
A Swing App - StocksMonitor Actions
Align menu items Change theme
Consider JGoodies Forms for layouts Don't bury dialogs
Don't subclass JDialog or JFrame Filter table rows
Indicate table sort Input dialogs
Layout Managers Look and Feel guidelines
Minimal Swing application Observers and listeners
Preferences dialogs Provide an uncaught exception handler
Render table cells Sort table rows
Splash screen Standardized dialogs
Swing in general Swing threads
Swing utility tasks Timers
Using JavaHelp Using preferences
Verify input with Model Objects Verify input with regular expressions
Exceptions
Avoid @throws in javadoc Avoid empty catch blocks
Be specific in throws clause Beware of unknown root causes
Checked versus unchecked exceptions Exception translation
Exceptions and control flow Finally and catch
Javadoc all exceptions Pass all pertinent data to exceptions
Stack trace as String Use template for repeated try-catch
Input-Output
Always close streams Buffering usually appropriate
Console input Reading and writing Serializable objects
Reading and writing text files
Databases
Business identifiers as String Connection pools
Consider data layer tools Consider using standard SQL
Consider wrapper classes for optional data Data access objects
Data exception wrapping Data is king
Do not perform database tasks in code Encapsulate connections
Keep SQL out of code Prefer PreparedStatement
Read-write locks Reduce database code duplication
Remember the basics of database design Simplify database operations
Try pseudo-persistence for mock ups Use template for transactions
Collections
Choosing the right Collection Encapsulate collections
Iterate without an index Prefer Collections over older classes
Two ways of using Iterator Use for-each liberally
Use interface references to Collections Use standard Collections
Overriding Object Methods
Avoid clone Implementing compareTo
Implementing equals Implementing hashCode
Implementing toString Never rely on finalize
Common Tasks
Arrays as String Clipboard copy and paste
Compare and sort Strings Copy an array
Determine if Strings are equal Examine bytecode
Fetch web page and header Generate random numbers
Get database connection Get size of object in memory
Internationalization Logging messages
Measure application performance Modernize old code
Parse text Pattern-match lines of a file
Recovering resources Recursive file listing
Replace a substring Representing money
Send an email Time execution speed
Common Design Patterns
Abstract Factory Command objects
Factory methods Immutable objects
Lazy initialization Model Objects
Private constructor Singleton
Template method Type-Safe Enumerations
Common Practices
Avoid basic style errors Avoid raw types
Beware of instanceof operator Class for constants
Construct classes from the outside in Do not break portability
Don't declare local variables before use Fields should usually be private
Interface for constants Know the core libraries
Minimize ripple effects Naming conventions
Output parameters Separate public and private members
String concatenation does not scale Uncommon classes need explicit imports
Use @Override liberally Use final liberally
Use javadoc liberally Use static imports rarely
Use System.exit with care Validate method arguments
Inheritance
Consider composition instead of subclassing Designing for subclassing
Overridable methods need special care Remember styles of inheritance
More Common Practices
Avoid null if possible Beware of DecimalFormat
Beware of floating point numbers Clarifying method
Coding conventions Compile regular expressions once
Conditional compile Consider code generators
Consider immutable forms for dates Defensive copying
Design by Contract Extra space in argument list
Generating unique IDs Include 'from', exclude 'to'
Multiple return statements Overloading can be tricky
Package by feature, not layer Passwords never in clear text
Quote dynamic text when logging Return result
Self-encapsulate fields Test using main method
Use a fake system clock Use a testing framework (JUnit)
Use Ant for build scripts Use boxing with care
Use enums to restrict arguments Use zero-length arrays instead of null
Validate state with class invariants Validation belongs in a Model Object
Assertions
Assert is for private arguments only Assert use cases
Assertions in general Force enabling of assertions
Constructors
Avoid JavaBeans style of construction Beware of mistaken field redeclares
Construct Object using class name Constructors in general
Constructors shouldn't call overridables Copy constructors
Initializing fields to 0-false-null is redundant
Serialization
Implementing Serializable Serialization and subclassing
Some classes need readResolve
Threads
Avoid ThreadGroup Data integrity first, liveness second
Document thread safety Launch thread is just another user thread
Objects communicating across threads Remember the types of locking
Stop threads through cooperation Synchronize access to mutable fields
Synchronized is implementation detail Thread priorities are not portable
Use Timer to schedule periodic tasks
User Comments
"I just wanted to take a second to say that this site is really useful. It's not all that often that I come across a site that has some good design information without a bunch of boring fluff. It reminds me of reading Effective Java, which I would consider to be one of the best books I've ever picked up."
"I love this site. It's one of the best laid out and most useful sites that I've ever used. Thank you very much."
"First I have to say, what a great site. We were thinking about starting something similar inside the company, but what better news than to hear that someone has done it for us. Keep up the great work."
"I do think this site is excellent. Keep it up."
"Awesome for a beginner like me!"
"A Great Site!!! I refer to it often. I really enjoy your common sense and straight forward, flexible approach to these issues. Thanks!"
"Thanks for a great site, it really stands out from the crowd. Keep up the good work!"
© 2009 Hirondelle Systems | Source Code | Contact | License | Quotes | RSS
Individual classes can be used under this BSD License - Last updated on June 28, 2009.
Over 140,000 unique IPs last month - Built with WEB4J.
- In Memoriam : Bill Dirani -