Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 8. Good Citizenship > Static Methods

8.3. Static Methods

Static methods have one wonderful use: as a black-box, standalone, stateless method. The use of static methods of the Math class in Java illustrates good use. When you call the Math.sqrt() method, you don’t worry that a subsequent call might return the cube root instead of the square root because some state within the sqrt() method changed. Static methods work well when they are completely stateless. You get into trouble when you start mixing staticness and state.

Static Methods and Hawaii

For many years, I worked at a consulting and training company, and we taught a wide variety of Java topics. I got what was considered the Holy Grail of teaching gigs: two classes to two groups of developers in Hawaii. The schedule had me there two weeks (one week per class), three weeks back home, and then there again for the second set of classes for two weeks. And, of course, I was required to stay over the weekend, and as a good company man, I managed to persevere. It was a tough class, however, because all of the students came from a mainframe background. I remember one student who couldn’t quite grasp the concept of matching curly braces and thought that all compilation errors meant that you needed to add more curly braces at the end of the file. I would go to help this person and there would be a dozen close braces, all on one line.

Anyway, I struggled through and returned three weeks later for the second part of the class. I was greeted immediately by one of the students who proudly exclaimed, “While you were gone, we figured out Java!” I was shocked and wanted to see what kind of code they had been writing. Then she showed me. All the code looked pretty much like this:

public
						static Hashtable updateCustomer(
            Hashtable customerInfo, Hashtable newInfo) {
    customerInfo.put("name", newInfo.get("name");
    // . . .
}

They had achieved what I thought impossible: they had turned Java into a procedural language! With loose variable typing, no less. Needless to say, I spent the next weeks teaching them how not to use Java in this way.

This ancedote illustrates how the overuse of static methods indicates a procedural mindset. If you find yourself with lots of static methods, question the correctness of your abstractions.



  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint