Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Java Tip 11: Use references and save typing time!

With references, you can minimize keystrokes. Here's how

  • Print
  • Feedback
Here is a quick and easy hack to reduce the amount of typing involved in writing Java code.

References are a great way to simplify your code. It seems that people just coming to Java get frustrated by various "deficiencies" of the language because all they have really seen of it are the sample programs in a book or two.

It is common in sample code to use the the entire package.class.field naming style to access fields. For primitive types, just copy it to a local variable. For reference fields, why not use a local reference to the class instead? For example, rather than typing this all day long:

// ...
System.out.println (something);
System.out.println (or);
System.out.println (other);
// ...
System.out.println (yet);
System.out.println (still);
System.out.println (more);
System.out.println (stuff);
// ...


Why not just type:

public class SaveTyping
{
    private static final PrintStream o = System.out;
// ...
o.println (something);
o.println (or);
o.println (other);
// ...
o.println (yet);
o.println (still);
o.println (more);
o.println (stuff);
// ...
}


That's all there is to it.

Unfortunately, Java does not currently support method references (that is, "method pointers"), so you cannot shorten that part down any further. Well, OK, you could go totally wild and define your own local class, but that is a wee bit over the top in my book, so it is left as an exercise for the reader.

About the author

Subsisting on caffeine, sugar, and too little sleep, John D. Mitchell has been consulting for most of the last nine years, and developed PDA software in OO assembly language at Geoworks. He funds his Java addiction by writing compilers, Tcl/Tk, C++, and Java systems. He co-authored the hot new Java book Making Sense of Java and is currently developing a Java compiler.
  • Print
  • Feedback
What is Tech Briefcase?
TechBriefcase is a new, free service where IT Professionals can Search, Store and Share IT white papers and content like this. Learn more
Bookmark content
Speed up your research efforts with content across the web.
Search and Store
Find the white papers you need. Create folders for any topic.
View Anywhere
Open your briefcase on your iPhone, tablet or desktop. Share with colleagues.
Don't have an account yet?

Resources