Collected Java Practices 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.

Science is the organized scepticism in the reliability of expert opinion.
- The Physics Teacher (Sep 1969), Richard Feynman

Servlets and JSPs
A Web App Framework - WEB4J Always maintain HttpSessions
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
Thread-safety in web apps 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
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
Input dialogs Launch other applications
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
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
Always close streams Buffering usually appropriate
Console input Copy a file
Reading and writing binary files Reading and writing Serializable objects
Reading and writing text files
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
Don't perform basic SQL tasks in code Encapsulate connections
Keep SQL out of code Prefer PreparedStatement
Reduce database code duplication Remember the basics of database design
Simplify database operations Try pseudo-persistence for mock ups
Use template for transactions
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
Command line operations 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 Implement code tables
Internationalization Logging messages
Measure application performance Modernize old code
Open file in native directory Parse text
Pattern-match lines of a file Read jar version information
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
Plugin Factory Private constructor
Singleton Template method
Type-Safe Enumerations Wrapper (Decorator)
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
Nest classes with care Output parameters
Separate public and private members String concatenation does not scale
Tag or marker interfaces Uncommon classes need explicit imports
Use @Override liberally Use final liberally
Use javadoc liberally Use static imports rarely
Use System.exit with care Use Version Control tools
Validate method arguments Wisdom, not rules
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 Byte Order Marks
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
Conventional name for return value Defensive copying
Design by Contract Don't use tab characters
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 Prefer empty items to null ones
Quote dynamic text when logging Self-encapsulate fields
Structs are occasionally useful Test using main method
Try alternatives to ResourceBundle Use a fake system clock
Use a testing framework (JUnit) Use Ant for build scripts
Use boxing with care Use enums to restrict arguments
Validate state with class invariants Validation belongs in a Model Object
Assert is for private arguments only Assert use cases
Assertions in general Force enabling of assertions
Avoid JavaBeans style of construction Beware of mistaken field redeclares
Construct Object using class name Constructors in general
Constructors shouldn't call overridables Constructors shouldn't start threads
Copy constructors Don't pass 'this' out of a constructor
Initializing fields to 0-false-null is redundant
Implementing Serializable Serialization and subclassing
Some classes need readResolve
Always shut down an ExecutorService Avoid ThreadGroup
Data integrity first Document thread safety
Dump thread information Handle InterruptedException
Launch thread is just another user thread Objects communicating across threads
Perform N tasks in parallel Prefer modern libraries for concurrency
Query host for the number of processors Read-write locks
Remember the types of intrinsic lock Schedule periodic tasks
Stop threads through cooperation Synchronize access to mutable fields
Synchronized is implementation detail Thread priorities are not portable
Use finally to unlock
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!"
© 2018 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -