Pure Java Cookbook.pdf

download Pure Java Cookbook.pdf

of 61

Transcript of Pure Java Cookbook.pdf

  • 8/8/2019 Pure Java Cookbook.pdf

    1/61

    Sun Microsystems, Inc.901 San Antonio RoadPalo Alto, California 94303 USA

    100% Pure Java

    CookbookGuidelines for achieving the

    100% Pure Java Standard

    Revision 4.0

  • 8/8/2019 Pure Java Cookbook.pdf

    2/61

    Copyrights

    2000Sun Microsystems, Inc. All rights reserved.901 San Antonio Road, Palo Alto, California 94043, U.S.A.

    This product and related documentat ion are protected by copyright and dist r ibuted under licensesrestricting its use, copying, distribution, and decompilation. No part of this product or relateddocumentation may be reproduced in any form by any means without pr ior writ ten authorization ofSunand its licensors, ifany.

    Restricted Rights Legend

    Use, dup lication, or disclosure by the United States Government is subject to the restrictions set forth inDFARS 252.227-7013 (c)(1)(ii) and FAR 52.227-19.

    The product descr ibed in this manual may be protected by one or more U.S. patents, foreign patents, orpend ing applications.

    Trademarks

    Sun, the Sun logo, Sun Microsystems, Java, Java Compatible, 100%Pure Java, JavaStar, JavaPureCheck,JavaBeans, Java 2D, Solaris,Write Once, Run Anywh ere,JDK, Java Development Kit Standard Edition,

    JDBC, JavaSpin, HotJava, The Network Is The Computer, and JavaStation are trademarks or registeredtrademarks of Sun Microsystems,Inc.in the U.S. and certain other countries.UN IXis a registeredtrademark in the United States and other countr ies, exclusively l icensed through X/ Open Company, Ltd.All other product names mentioned herein are the trademarks oftheir respect ive owners .

    Netscape and Netscape Navigator are trademarks ofN etscape Communicat ions Corporat ion in theUnited States and other countries.

    THISPUBLICATION ISPROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHEREXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OFMERCHAN TABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NO N-INFRINGEMENT.

    THISPUBLICATION COULD INCLUDE TECHN ICAL INACCURACIES OR TYPOGRAPHICALERRORS. CHAN GESARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESECHAN GES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUNMICROSYSTEMS, INC. MAY MAKEIMPROVEMENTS AND/ OR CHAN GESIN THE PRODUCT(S)AND/ OR THE PROGRAM(S) DESCRIBED IN THISPUBLICATION ATAN Y TIME.

    Revisi on History4/ 97 - 1.0 First release

    5/ 97 - 1.1 Minor updates

    4/ 98 - 2.0 Added certification instructions for beans

    Introduced new feature based dynamic testing requirements

    Dropped code coverage requirements

    Added instructions for recertification

    4/ 99 - 2.1 Added certification instructions for servlets

    Added guidelines for certificat ion under 1.2 runtime environments

    Updated recertification requirements

    Added guidelines for certifying hybrid programs

    Added FAQ

    10/ 99 - 3.0 Reorganized and updated

    3/ 00 - 3.1 Reorganized and updated

    10/ 00 - 4.0 For merly 100% Pu re Java Cer tification Gu id e, rew ritten to rem ove th e cer tification

    process and branding program.

  • 8/8/2019 Pure Java Cookbook.pdf

    3/61

    Revision Date: 10/00 i

    Table of Contents

    Introduction

    The 100% Pure Java Stand ard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 1

    Abou t th is Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 1

    Con ten ts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 2

    100% Pure Java Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 3

    Online Inform ation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 3

    What is th e 100% Pure Java Stand ard ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 4

    Pu rp ose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 4

    API Con stra ints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 4

    Com mon Behav ior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 4

    Should I Comp ly With The Pur ity Standard ?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 5

    The Suggested Comp liance Evaluation Cr iteria? Checklist . . . . . . . . . . . . . . . . . 1 - 5

    Understanding Portability

    & Purity

    Stand ard s for Portability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 1

    The Pu rpose of the Pu rity Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 1Which Java API? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 2

    Understanding Purity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 2

    Pu rity is Not Goodness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 3

    Por tability vs. Pu rity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 3

    Rules of Pu rity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 4

    The Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 5

  • 8/8/2019 Pure Java Cookbook.pdf

    4/61

    ii 100% Pure Java Cookbook

    Guidel ines for Developing Pure Programs

    How to Develop a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 1

    Use of Native Cod e. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 3

    Use ofexec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 4Failure to Use th e Portability Featu res of Java Core API . . . . . . . . . . . . . . . . . . . . . . 3 - 4

    Reflection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 4

    Direct Use of AWT Peer Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 4

    Misu se of System .exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 5

    Use of H ard-Coded File Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 5

    JDBC Driver Load ing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 7

    Line Term inat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 8

    Unp ortable Com mand -Line Program s. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 9

    Com mand Line Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 9

    Internationalizat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 9

    Unicode Rend ering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 9

    File I/ O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 10

    GUI Elem ent Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 10

    GUI Fon ts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 10

    GUI Ap pearance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 10

    The Paint Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 11

    Mixed Event Mod els . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 12

    Use of Dep recated Meth ods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 12

    The Object.hashCode an d Object.equals Method s . . . . . . . . . 3 - 12Installation Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 13

    Hostnam e Form at . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 13

    Pluggable Look and Feel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 14

    Mixing Classes Com piled on Different Versions of the Java Platform . . . . . . . . . 3 - 15

    Por tability Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 16

    Security Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 16

    Cop ing with Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 17

    Explanations of Purity Problems and Variances

    Explanations of Pu rity Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 1

    Report In form ation Categor ies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 1

    Explana tions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 2

    Warn ings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 2

    Possible H ard coded Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 2Mixing the 1.0 and 1.1 Event Mod els . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 2

    Dynam ically Loaded Classes:. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 2

    Object is Compiled for a Previous (Java Developm ent Kit) release . . . . . . . . . . 4 - 3

    Unsu pp orted Pluggable Look and Feel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 3

    Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 4

    Constant Strings w ith OS-Specific Syntax Used in I/ O Class Constructors . . . 4 - 4

    Peer Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 4

  • 8/8/2019 Pure Java Cookbook.pdf

    5/61

    Revision Date: 10/00 iii

    Use of Native Cod e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 4

    Use ofjava.lang.Runtime.exec. . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 4Injection into Core Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 4

    Undefined Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 4

    Undocumented Internal sun.* Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 4

    Variances. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 5

    Types of Variances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 5

    The Variances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 5

    Varian ces for Program Invocat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 5

    Variances for Programs Con taining N ative Cod e . . . . . . . . . . . . . . . . . . . . . . . . 4 - 7

    Miscellaneou s Variances. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 9

    Available Java Platforms

    Platforms for Java App lications and Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .A - 1

    Available Platforms for Java Application Environmen t Version 1.0.2 . . . . . . . . . .A - 2

    Available Platforms for Java Ap plication Environmen t 1.1 . . . . . . . . . . . . . . . . . . .A - 3

    Available Platforms for Java Ap plication Environmen t 1.2 . . . . . . . . . . . . . . . . . . .A - 4

    Frequently Asked Questions for Purity

    Frequ ent ly Asked Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B - 1

  • 8/8/2019 Pure Java Cookbook.pdf

    6/61

    iv 100% Pure Java Cookbook

  • 8/8/2019 Pure Java Cookbook.pdf

    7/61

    Revision Date: 10/00 1 - 1

    Introduction 1

    The 100% PureJava Standard

    The 100% Pure Java Standard is part of Sun Microsys tems in it ia tive to

    promote the development of portable applicat ions, applets , beans, class

    librar ies, and servlets writ ten using the Java Programming language.

    Compliance to the s tandard cons is ts of code analysis and tes ting the program

    on multiple Java Applicat ion Environment.

    This cookbook will ass is t you in the process of unders tanding the guide lines

    fo r wr it ing por table code. The st eps descr ibed in t his gu ide a re designed t o

    ensu re t ha t your code is por table and that it will m eet your cust om er sexpectat ions of a 100% Pure Java program.

    About this Guide

    This gu ide cover s a ll o f the basic t hings t ha t you shou ld know about t he 100%

    Pure Java Standard.

    This document serves as:

    Developers Style Guide: for developers using the Java programming

    language who want to maximize the portability of their programs. It explains

    the imp ortant d ifference between merely wr iting p rograms u sing the Java

    programming language, and writ ing effect ive and portable programs that will

    indeed r un on Java Comp atible platform or device.

    Programming Manual for Purity: for programm ers. It presents the rules for

    compliance with 100% Pure Java standard. It also provides pract ical hints and

  • 8/8/2019 Pure Java Cookbook.pdf

    8/61

    1 - 2 100% Pure Java Cookbook

    Introduction

    advice for maximizing portabili ty of programs, and offers workarounds for the

    most common p ortability pitfalls encoun tered wh en wr iting software.

    Th is docum en t can help you :

    Gain purity expertise: deve lopers can benefit from the collect ive experience

    ofSuns development team. This guide contains information and ideas to help

    developers achieve the maximum portability with their programs. This guide

    describes the p rinciples for pur ity, along with h ints for portability.

    Contents

    This gu ide has t wo purposes: it set s out t he r u les fo r ach iev ing t he 100% Pur e

    Java st andard , and it p resen ts advice and exam ples t o a id t he developm en t o f

    fu lly portable software. It defines the s teps you must take to cert ify a program.

    It a lso defines what cr it er ia applies to 100% Pure Java programs and, equallyimportant, what does not.

    Chapter 1, "Introduction"

    gives bas ic defin it ions tha t descr ibe the vocabulary of pur ity. This chapter is

    important for everyone.

    Chapter 2, "Understanding Portability & Purity"

    descr ibes t he v ir tues o f pu rity. The 100% Pur e Java st andar d is not designed

    for a ll programs; th is chapter will help de termine if fo llowing the pur ity

    s tandard is appropria te for you.

    Chapter 3,"Guidel ines for Developing Pure Programs"

    descr ibes t he r ules and gu idelines t ha t a p rogr am m er m ust know in order t o

    develop a 100% Pure Java program.

    Chapter 4, "Explanations of Purity Problems and Variances"

    descr ibes the pi tfalls that programmers frequent ly encounter while t rying to

    modify their programs for pur ity. This chapter will g ive Suns perscr ibed

    solu t ions to these pit fa lls . Some pit fa lls wi ll require bending pur ity ru les to

    some degree.

    The Appendices also give helpful information descr ibing:

    Appendix A, "Available Java Platforms"

    descr ibes the suppor ted architectures, OS types, JAE versions that a pure java

    p rogr am shou ld r un on.

  • 8/8/2019 Pure Java Cookbook.pdf

    9/61

    Revision Date: 10/00 1 - 3

    About this Guide

    Appendix B, "Frequently Asked Questions for Purity"

    descr ibes common ques tions that people have rela ting to the ru les of pur ity,

    how to in te rpret resu lt s from JavaPureCheck software, etc..

    100% Pure Java Definitions

    Java Compatible : A b ran d th at is associated w ith th e JA E. Th is br an d

    descr ibes tha t a given version of the Java language compile r, Vir tua l Machine

    (VM), and Java Class Libraries (Application Program Interfaces, or APIs) have

    passed Suns conformance tests.

    100% Pure Java : A t er m used t o descr ibe p rogr am s t ha t fo llow Suns pu rit y

    sta nd ard . Th is term d escr ib es th at a p rogr am th at r un s on top of a Jav aCompatib le pla tform has passed the requirements set forth in th is document ..

    Java Application Environment (or JAE): A specific version of the Java

    language compiler, Vir tual Machine (VM), and Java Class Librar ies

    (Application Program Interfaces, or APIs) define the JAE. The Java 2 Platform,

    St andar d Ed it ion is an example o f a JAE.

    Java Compatible Platform (or Platform): A specific combination of computer

    hardware (or architecture), operat ing system, and version of a suppor ted JAE.

    Program: In t he cont ext o f t his docum en t, a p rogr am is a self-cont ained set o f

    classes . A program can be a applica tion , an apple t, a class library, a servle t, a

    b ean , or m ore th an on e of th ese.

    OnlineInformation

    For online information about Sun Microsys tems and some of their programs,

    go t o these sit es:

    Sun Microsystems Main Web Site

    http://www.sun.com

    Java Developer News & Information

    http://industry.java.sun.com/

  • 8/8/2019 Pure Java Cookbook.pdf

    10/61

    1 - 4 100% Pure Java Cookbook

    Introduction

    What is the 100% PureJava Standard?

    The 100% Pur e Java st andard is t he se t o f gu idelines t ha t a p rogr am m er can

    follow to assure a reasonable sense of portab ility. Customers can be assured

    tha t the program relies only on the documented and specified Java pla tform, so

    that it will r un on any compu ter host ing a Java Com pat ib le app lica tion

    environm en t. The end r esu lt is t ha t you r p rogr am deliver s on t he p romise o f

    Write Once, Run Anywhere.

    Programmers can inspect the program for compliance to the s tandards defined

    in t his gu ide, using the p rocedures and test t oo ls p rovided by Sun .

    The steps descr ibed in th is gu ide a re necessa ry to ensu re t ha t your p rogr am is

    portable and that it wi ll meet your cus tomers expectat ions of a product

    meeting the 100% Pure Java s tandard .

    Purpose

    The purpose o f t he 100% Pure Java st andar d is t o p rovide r ea sonable and

    economic assurance that a program will run on any Java Compat ible platform.

    Sun addre sse s t hese goa ls by defin ing the doma in where purit y is ana lyzed :

    API Constraints the part s of the Java Class Library tha t a re defined as usable

    in a pure manner.

    Common Behavior The behavior that you r prog ram exhibits on different Java

    Compatible platforms.

    API CONSTRAINTS

    API Const ra in ts descr ibe the ru les tha t Sun has chosen regarding how you call

    methods defined in the Java Class Library. Only Java Compatib le pla tform

    APIs can be referenced , and m ust be used in a por table m anner.

    For more information about API const ra in t s , see "Rules of Purity" in Chapter

    2, an d Chapter 3, "Guidelines for Developing Pure Programs".

    COMMON BEHAVIOR

    An im por tant pa rt o f t he 100% Pur e Java st andar d is t o obser ve t ha t a p rogr ambehaves with funct ional commonali ty independent of the platform upon which

    it is run . This means (in pr incip le ) tha t each product feature is demonst rable on

    any Java Compat ible platform. While platforms may exhibit cosmetic user

    interface and look and feel differences or have limitations in underlying

    hardware, operating system, or browser funct ionali ty, all product features

  • 8/8/2019 Pure Java Cookbook.pdf

    11/61

    Revision Date: 10/00 1 - 5

    Should I Comply With The Purity Standard?

    should s till funct ion in every suppor ted Java environment. Common

    behavior does not mean ident ical behavior, but functional behavior

    conformant with the underlying platform.

    For more information about portability, see Chapter 2, "Understanding

    Portability & Purity".

    Should I Comply With ThePurity Standard?

    Befo re decid ing whet her t o m od ify your p rogr am for pu rity, r ead t he r est o f

    th is document , and the JavaPureCheck users guide .

    The Suggested ComplianceEvaluation Criteria?Checklist

    D ep en d in g on th e d esig n d eta ils of y ou r p rog ram it m ig ht b e m ore or less

    advisable to t ry to comply wit h t he standa rd . Review t he Table 1 - 1 to see how

    your program stacks up to the recommended cr it er ia .

    Evaluate each Program Character is tic quest ion and the evaluat ion statement

    that follows it , then check Yes, for Advisable, No for Not Advisable, or

    M aybe if you a re not su re .

  • 8/8/2019 Pure Java Cookbook.pdf

    12/61

    1 - 6 100% Pure Java Cookbook

    Introduction

    Table 1-1: Suggested Compliance Evaluation Criteria

    Program Characteristic Yes No Maybe

    Is platform portability an important differentiator for my program?

    A single code base can significantly reduce maintenance costs if you plan to support your

    program on several hardware platforms. If your product is an applet, servlet, or

    development library/bean, then you might want to market your code as usable in many/all

    Java environments.

    Can my program comply with the purity standard?

    Use the JavaPureCheck tool to see if there are existing portability problems. Its free, and

    takes only a few minutes to run. If problems exist, determine whether they can be fixed or

    worked around. See Chapter 3, "Guidelines for Developing Pure Programs" for moreinformation.

    What if my program cant comply with the purity standard?Impure programs are not necessarily bad programs. In some cases, it isnt possible to

    achieve certain functionality without making direct calls to the operating system or using

    native code (e.g. using platform-specific devices). Identifying portability problems in your

    program will, however, make it much easier to port to other hardware platforms. The

    JavaPureCheck tool provides an excellent means to find potential portability issues in your

    program.

    Is complying with the standard worth my effort?

    A competent engineer should need 3-4 full days (without distractions) to prepare a typical

    program for for purity compliance. Your time may vary, depending on the nature of your

    program.

    Another valuable benefit you might realize is that the process of testing and checking your

    program with the JavaPureCheck tool might expose bugs or problems in your code.

    Naturally, it is always best to find these problems and fix them before your

    customers find them.

  • 8/8/2019 Pure Java Cookbook.pdf

    13/61

    Revision Date: 10/00 2 - 1

    Understanding Portability& Purity 2

    Standards for Portability

    Th e id ea l of th e 100% Pu re Ja va sta nd ard is to a ssu re th at th e en d u ser h as a

    seamless and pain less experience running a given Java program on any

    conforming Java pla tform. Ident ica l behavior is not the s tandard; a portab le

    program might behave differently on different plat forms, but still exhibit the

    same feature set .

    Fo r some progr am s, por tability is not a p roper ty o f t he p rogr am , bu t o f t he

    program's input . As an example , cons ider a program tha t parses and in te rpret s

    Java programming language statements. This program will necessar ily behaveunpor tably when g iven an unpor table p rogr am to in ter p ret . As long as t he

    portability problem is not in tr insic to the program, the program cannot be

    considered compliant with the 100% Pure Java s tandard . The software' s

    deve loper mus t be the fina l authority on the program's correct behavior.

    Simila rly, the appearance of the program (if it has a GUI) is the responsib ility

    o f t he developer. The st andar d fo r pu rity is t ha t t he p rogr am disp lay

    essent ially the same elements on all plat forms, not that those elements have the

    same appearance.

    The Purposeof the Purity StandardThe purpose o f t he purit y standa rd is t o p rovide rea sonable and economic

    assurance tha t the 100% Pure Java program design guide lines have been

    followed, and tha t the program will run on any Java Compatib le pla tform. The

    p rocess is n ot in ten d ed to be im m un e to su bv ersion , b ut is in ten d ed to b e a

    chance fo r you t o p rovide ev idence o f the por tabilit y o f your p roduct in a

    uniform and consistent way.

  • 8/8/2019 Pure Java Cookbook.pdf

    14/61

    2 - 2 100% Pure Java Cookbook

    Understanding Portability & Purity

    Which JavaAPI?

    Sun Microsys tems recommends wr it ing to the 1.1 or la te r versions of the Java

    API.

    The Java technology web s ite has helpfu l information about making the

    transi tion between v1.0 and v1.1.

    For information, go to:

    http://java.sun.com/products/jdk/1.1/compatible

    Unless your circumstances prohibit you from moving away from version 1.0, i t

    is a good idea t o do so . You will gain por tabilit y benefit s a long wit h ext ra

    features. In particular, the conformance requirements for 1.1 and later Java

    p la tfo rm ver sions a re m uch m or e str ingen t t han those t ha t wer e in p lace fo r

    the 1.0 version; you can thus expect a greater uniformity between pla tforms

    implementing 1.1 and la te r versions than among 1.0 pla tforms.

    By wr it ing to the 1.0 in ter faces, you achieve backward compat ib ility with old

    installations. By writ ing to the 1.1 or later interfaces, you take advantage of the

    recen t im provem en ts and prepar e fo r t he fu tu re. The choice depends on your

    circumstances. Programs wri tten to any version are eligible for cert ification.

    The enhancements made to the Java 2 Pla tform, Standard Edit ion, v 1.2 API are

    quite compelling for many developers. Choosing th is version of the Java

    pla tform (or la te r) is recommended for a ll deve lopers who need the s ta te of the

    a rt API suppor t found in t his ver sion.

    Understanding Purity

    The Java platform promises streamlined software development and delivery. It

    saves developers t ime and it saves their companies the expense of mult ip le

    ports and tradi tional dist ribut ion methods. Unlike programming systems that

    t ie deve lopers to a s ingle hardware pla tform, the Java pla tform bridges many

    var ie ties of hardware and sys tem software wi th a common language , opening

    up new market s rather than limit ing market oppor tunit ies.

    This portab ility brings new freedom to developers, who can now deliver

    so lu tions fo r a wide var iet y o f har dware, wit hout the expense and delay o f port ing and qualifica tion. It a lso brings new freedom to users, who can choose

    to change hardware pla tforms to bes t meet their needs, while preserving the ir

    investment ins software.

  • 8/8/2019 Pure Java Cookbook.pdf

    15/61

    Revision Date: 10/00 2 - 3

    Understanding Purity

    Yet the inherent portabil ity of the Java platform alone does not ensure seamless

    operat ion for every program. A number of pit fa lls can adverse ly affect the

    por tability o f p rogr am s, and developer s need t o know what they a re and how

    t o work a round t hem . That is why Sun has developed gu idelines fo r wr it ing

    100% Pure Java code.

    A p u re p rogr am is d efin ed a s on e th at relies on ly on th e d ocu m en ted an d

    specified Java platform. By focusing on this design criter ion now, developers

    can reduce the ir exposure to portability r isks in the fu ture .

    Purity is Not Goodness

    N ot a ll g ood p rog ra ms are p u re; n ot a ll p u re p rog ra ms a re g ood .

    It is en tir ely possib le to use the Java p rogr am m ing language t o wr it e a

    program that depends on platform-specific capabi lit ies, defines native

    m et hods, and v io la tes a ll t he r ules fo r pu rit y. Just because a p rogr am is not

    p u re d oes n ot m ean it is p oor qu ality or bad in an y w ay; th e p rogram m ay in

    fact m eet th e n eed s of its u ser s in w ays n ot p ossible to a ch iev e in a p u re

    m an ner. A n p rogr am ca n b e g ood w ith ou t bein g p u re.

    Likewise, the m easu rem en ts m ade to ascer ta in t he purit y o f a p rogr am are

    in tent ionally blind to the user s requirements. A program can be comple te ly

    pu re and st ill be qu it e unsu it ed to t he user s requ ir em en ts even be qu ite

    buggy. The purit y p rocess a ttem pts t o find out if the p rogr am will behave t he

    sam e on a ll Java Com pat ib le p la tfo rm s, not if it will behave we ll on a ll

    p la tfo rm s. An progr am can be pure wit hout being good .

    Purit y is in tended t o be a m easu re o f only one of the m any char act er ist ics

    r equ ir ed o f a p rogr am . Alt hough it is not a per fect m easu re o f por tabilit y, it is

    nonetheless a usefu l measure. Experience has shown that performing pur ity

    assessment will de tect some common portability problems. In tha t way,

    checking the pur ity of programs does result in bet te r portab ility of programs.

    Portability vs. Purity

    There is a critical distinctionand connectionbetween portabili ty and purity.

    M ost people t hink o f a por table p rogr am as one t ha t p roduces t he same r esu lt s

    on any pla tform. This is actually a very imprecise defin it ion .

  • 8/8/2019 Pure Java Cookbook.pdf

    16/61

    2 - 4 100% Pure Java Cookbook

    Understanding Portability & Purity

    For example, consider this program:

    Figure 2 - 1: Example Code Pure Example (class ShowOS)

    M ost people would say that t his is a por table p rogr am , even t hough it

    produces different results on different plat forms. Compare it to this program:

    Figure 2 - 2: Example Code Impure Example (class BadOS)

    The d iffer ence between t hese two progr am s is not in t he use o f t he Java

    platform; formally, they are very nearly identical. The difference is in the

    funct ionali ty they implement. The second example contains an OS platform

    dependency that is im p lem en ted in to t he p rogr am in a por table way.

    Rules of Purity

    A 100% Pu re Ja va p rog ram is on e th at d ep en d s on ly on th e Jav a p latfor m, a s

    defined in this documentat ion . It is rela tively easy to de termine if a program

    confo rm s to t he design cr it er ia deta iled in t his m anual. If it does, it is defined

    as pure.

    class ShowOS {public static void main (String[] args) {

    try {

    String osName = System.getProperty("os.name");System.out.println(osName);

    } catch (RuntimeException re) {System.err.println(Problem: " + re);

    }}

    }

    class BadOS

    public static void main(String[] args) {

    try {

    String osName = System.getProperty("os.name");

    if (osName.equals("Solaris")) {

    throw new RuntimeException();

    }

    System.out.println(osName);

    } catch (RuntimeException re) {

    System.err.println("Problem: "+ re);

    }

    }

    }

  • 8/8/2019 Pure Java Cookbook.pdf

    17/61

    Revision Date: 10/00 2 - 5

    Rules of Purity

    Purity is measured a t the bot tom (pla tform) edge of the program, rather than a t

    th e top (u ser ) ed ge. Exp er ien ce h as sh ow n u s th at if a p rogr am h as been

    designed acco rd ing to t hese st andar ds, in o ther words, is pu re, it is a good

    predictor of portab ility; a pure program should not be accidenta lly unportable .

    The pla tform edge is defined by the ca lls to the Java API (Applica tion Program

    Interfaces) that the program makes. In this discussion, we will often refer to the

    Java core API . The core API is the set of documented classes (typica lly

    under t he java an d javax packages) that Sun designates as public classes .

    This document set s out the ru les and pr incip les for pur ity, a long with hin t s and

    t ips for the more general goa l of portab ility.

    TheRules

    A pure p rogr am shou ld :

    1. Use no native methods.

    2. Depend only on the Java core Application Programmer Interfaces .

    3. Rely on no hardwired platform-specific constants.

    4. Follow any applicable API protocols.

    RULE 1: USE NO N ATIVE METHODS.

    The fir st and fo rem ost r ule o f pu rit y is to avo id t he usage o f nat ive m ethods.

    Attempt ing to in troduce native code in to a program result s in the sacr ifice of

    most of the benefits of the Java programming language: security, plat form

    independence, garbage collect ion, and easy class loading over the network.

    For users, the secur ity issues of software that includes na tive methods are

    subs tantia l. There is no assurance tha t the code is v irus-free ; moreover, if a

    na tive method has a poin te r overrun or a tt empts to access protected memory, it

    can crash the Java vir tua l machine, poss ib ly corrupting and certain ly

    in ter rup ting the user s work .

    The only exception to this ru le is in a lt ernat ive implementat ions of s tandard

    interfaces. Several of the Java core APIs function as standardized interfaces to

    specific external functionality; examples are the JDBC database access

    interface and the JSA cryptography interface. These are circumscribed

    interfaces, well-defined and with precise specifications, designed to facili tate

    free subs titu tion of the user s chosen implementa tion. Due to this

    subst itutability, a program can include native code implementations of these

  • 8/8/2019 Pure Java Cookbook.pdf

    18/61

    2 - 6 100% Pure Java Cookbook

    Understanding Portability & Purity

    in te rfaces, as long as it a lso includes a t leas t one pure implementat ion . The

    other implementa tions may be made available to users as an installa tion or

    runtime opt ion.

    RULE 2: DEPEND ONLY ON THE JAVA CORE APPLICATION

    PROGRAMMER INTERFACES .

    The Java core APIs form a s tandard foundat ion for components , apple ts and

    applications; i t is the essent ial framework for program development. 100%

    Pure Java programs must depend only on classes and in te rfaces documented in

    the Java core API specification.

    Th is m eans, in det ail, t ha t a 100% Pur e Java p rogr am m ust be a complet e

    program, wi thout dependencies on external libraries or in ter faces tha t a re not

    par t of the Java core API specificat ion.

    The Java core APIs provide the bas ic language , u t ility, I/ O, network, GUI, and

    applet services; vendors who have l icensed this Java technology from Sun have

    contracted to include them in any Java pla tform they deploy.

    The specificat ions for all Java APIs are freely accessible on the World Wide Web

    at ht tp:/ / java.sun.com.

    INCOMPLETE PROGRAMS ARE IMPURE

    To be cert ified as a program meet ing the 100% Pure Java cert ification standard,

    mus t be self-conta ined; it mus t include a ll required classes aside from the core

    API. An incomplete p rogr am is unpor table, because it will not r un on a Javaplatform implementation that lacks the special classes required by the

    program.

    DON T DEPEND ON THE INTERNALS OF ANY PARTICULAR IMPLEMENTATION

    Any implementa tion of the Java core APIs will include classes and packages

    tha t a re not part of the documented API in te rface . Por table programs must not

    depend on these undocumented classes , because they might vary among

    diffe rent Java pla tform implementa tions. This is t rue even if the classes in

    ques tion are undocumented part s of the reference Java pla tform

    implementa tion from Sun Microsys tems. Those in te rfaces are not part of the

    Java p la tfo rm defin ition, and t hey a re not checked by t he Java t est s fo rcompat ib ilit y, so t hey m ight be absen t o r m ight behave in subt ly and

    dangerously different ways on different Java platform implementat ions. They

    a re not docum en ted because t hey a re not in tended fo r clien t use.

  • 8/8/2019 Pure Java Cookbook.pdf

    19/61

    Revision Date: 10/00 2 - 7

    Rules of Purity

    O ne su btle w ay th at a p rogr am m igh t d ep en d on a cla ss is b y d efin in g classes

    in to t he packages t ha t a re pa rt o f the co re APIs o r a specific im p lem en ta tion.

    Defining a class within an exist ing core package is called inject ing a class into

    a core package. This breaks protect ion boundaries that the core implementors

    a re en tit led t o coun t on .

    Another subt le dependency on implementat ion deta ils is d irect use of the AWT

    component peer interfaces defined in classes in the java.awt.peer package.

    These in te rfaces are documented as being for use by AWT implementors; a

    portab le program uses the AWT rather than implementing it .

    USING RUNTIME.EXEC

    Using Runtime.exec is generally not acceptable as pure. Cer ta in features of

    the Java programming language defin it ion give the programmer access to

    hardware-specific code; native method definit ion (see Rule 3, No Hardwired

    Platform-Specific Constants), and some methods in the class

    java.lang.Runtime. This hardware access is very usefu l for wr it ing

    programs tha t in te rface to legacy sys tems, but such in te rface programs are by

    defin it ion not compliant to the 100% Pure Java s tandard .

    Th e u se of th e Runtime.exec m et hod is only a llowed if it s a t t he r equest o f

    the user of the program. For example , a command interpreter that executed

    p rogr am s nam ed in t he user s inpu t could be pure. Ano ther example is the

    invoca tion of an external program with a specific funct ion, such as a Web

    browse r, a s long as the user has cont ro l o f wh ich b rowser is invoked .

    The exact cr it er ia fo r use o f t he Runtime.exec method are :

    The invoca tion m ust be a d ir ect resu lt o f a specific user action; t he usermus t know theyre execut ing a separa te program.

    Th e u ser m u st b e ab le to ch oose, by con fig ur ation or a s p ar t of th einvocation act ion, which program is executed.

    A fa ilu re o f t he Runtime.exec method, especia lly one caused by theabsence of the reques ted program, must be handled cleanly.

    U se of th e Runtime.exec method is p la tform neut ra l. No pla tformspecific funct iona lity documented by your product can be made

    exclusively available to users of any particular hardware/ OS platform.

    Examples of the correct use of Runtime.exec are:

    Invoca tion of a Java compile r, with the name of the compile r specified as auser-settable Property.

    Execu tion o f a comm and the user t yped in (a shell ).

    Invoca tion of a browser, configured as part of the installa tion of thep rog ram, when t he user p resses a Help bu tton.

  • 8/8/2019 Pure Java Cookbook.pdf

    20/61

    2 - 8 100% Pure Java Cookbook

    Understanding Portability & Purity

    see Chapter 4, "Explanations of Purity Problems and Variances" for additional

    information.

    DUMMY CLASSES

    The use of stubs or dummy classes to hide references to external classes is

    prohib it ed in pure programs. For example , it is considered chea ting if you

    include a class in your program tha t can be subs titu ted (e .g ., v ia classpath

    manipula tion) with another more funct iona l and poss ib ly impure class .

    RULE 3: RELY ON NO HARDWIRED PLATFORM-SPECIFIC

    CONSTANTS.

    This rule prevents programs from using platform-specific constants (such as

    os.name, os.arch, or os.version) to determine funct ion that your program

    p rov id es. It is n ot p u re to for a p rog ra m to p rov id e on e set of ser vices for on epla tform, and a diffe rent set of services on another p la tform.

    This does not mean that all uses of platform-specific constants are prohibited.

    For example , t es ting for and working around pla tform bugs is encouraged, as

    long as the so lu tion t o the bugs does not p rovide ext ra fea tu res fo r a g iven

    platform.

    The java.io.File cla ss can be used in an unpor table way, by const ruct ing

    Fi les using a platform-specific path constant . Similar ly, input and output

    s treams can be used unportably, with hard-coded and hardware-specific line

    termination characters. Fortunately, it is easy to avoid these sources of

    unportabili ty, because the Java core APIs provide portable alternatives.

    RULE 4: FOLLOW ANY APPLICABLE API PROTOCOLS

    Ther e a re cer ta in m ethods in t he co re API that m ust be ca lled o r im p lem en ted

    in a cer ta in pat ter n. By fa iling to fo llow these pat ter ns, it is possib le t o wr it e a

    program that is syntact ically correct , but which will be highly non-portable.

    For example:

    An AWTimplementation isallowed to invalidate a Graphics object after a call to

    a Components update method returns.A Component that retains a reference to

    the Graphics object may h app en to w ork on one imp lementation, but is notportable.

    The JavaBeans component p rotocol and p atterns, wh ich mu st be followed in

    order to make a portable bean, are described in the JavaBeans documentation.

    A class that overrides the java.lang.Object equals method must also override the

    java.lang.Object.hashCode method, to p reserve the invariant that equal

    Objects have the same hashCode.

    The 1.1 JDKintroduced a new AWT event model;a program should not mix the

  • 8/8/2019 Pure Java Cookbook.pdf

    21/61

  • 8/8/2019 Pure Java Cookbook.pdf

    22/61

    2 - 10 100% Pure Java Cookbook

    Understanding Portability & Purity

  • 8/8/2019 Pure Java Cookbook.pdf

    23/61

    Revision Date: 10/00 3 - 1

    Guidelines for Developing PurePrograms 3

    How to Develop a Program

    This sect ion ident ifies common problems encountered in program

    programming for portabil ity, and offers solut ions or workarounds.

    This is information about portability, not specifically about purity; some of

    these portability problems are de tected in the pur ity checking process and

    some are not . Simila rly, some of these pit fa lls a re specific to given methods of

    classes , while other pi tfalls are stated with principles instead of remedies.

    1. Pitfall:Thread Scheduling

    Explanation: Thread scheduling may differ on different plat forms. If you rely

    on pr io rit ies o r luck to p reven t two th reads fr om accessing t he same object a t

    the same t im e, your p rogr am is not por table.

  • 8/8/2019 Pure Java Cookbook.pdf

    24/61

    3 - 2 100% Pure Java Cookbook

    Guidelines for Developing Pure Programs

    For example , this program is not portab le :

    class Counter implements Runnable {

    static long val = 0;

    public void run() {

    val += 1;

    }

    public static void main(String[] args){

    try {

    Thread t1 = new Thread(new Counter());

    t1.setPriority(1);

    Thread t2 = new Thread(new Counter());

    t2.setPriority(2);

    t1.start();

    t2.start();

    t1.join();

    t2.join();

    System.out.println(val);

    } catch (Exception e) {

    e.printStackTrace();

    }

    }

    }

    Figure 3 - 1: Example of an Unportable Program

    This program might not pr in t 2 on all p la tforms , even bar ring errors, because

    the two threads are not synchronized .

    Unfo rt unately, t his is a deep problem , and t here is no qu ick check fo r it s

    presence nor easy fix to prevent it occur ring .

    Workaround: One sim p le, if d r ast ic, answer is t o m ake a ll m ethods

    synchronized. This may make some synchronization errors show up as obvious

    deadlocks rather than as silent data corrupt ion. Unfortunately, there are

    examples of thread content ion tha t wi ll not be de tected . For example , the

    JavaPureCheck Tool will not detect the problem in the example Counter class,

    because the content ion in the example is in fie ld access rather than method

    access.

  • 8/8/2019 Pure Java Cookbook.pdf

    25/61

    Revision Date: 10/00 3 - 3

    How to Develop a Program

    Solution: Adopt a discipl ine of multithreaded application programming, as

    descr ibed in several textbooks. One that is specifically wri tten for developers

    us ing the Java programming language is Concurrent Application Programming

    in Java, Second Edition, by Doug Lea, Addison-Wesley 1999,

    ISBN 0-201-69581-2.

    2. Pitfall:Useof Native Code

    Explanation: Calling native funct ions is inherently not portable. In rare

    instances however, it may seem necessary to include native methods to de liver

    access t o a syst em r esour ce t ha t is not suppor ted by t he Java t echnology APIs

    or to boost performance of a part icu la r program.

    Solutions:

    Define a simple protocol to give that service, then w rite your 100% Pure Java

    prog ram as a client of that protocol.

    Rewrite the native method u sing the Java programming language.

    It m ay seem th at y ou cou ld con fin e th e n ativ e m eth od s to on e cla ss a nd

    provide an implementation of that class for every Java platform. However, this

    solu t ion in fact only complica tes matter s, because the number of Java

    pla tforms is not fixed , but is ever-increasing; and some Java pla tforms , such as

    the JavaStat ion workstat ion, have no ability to execute native program code.

    There is no 100% Pure Java program workaround for na tive code. Even though

    it is possib le t ha t a p rogr am wit h nat ive m et hods can be m ade por table (by

    wr iting a cla ss o r m et hod with t he Java p rogr am m ing language to ser ve as a

    fa llback for the na tive code), such a program cannot be cert ified as pure

    because we know no pr incip led way t o show that t he nat ive-code and Java

    language versions of such a program actually implement the same funct ionally.

    If the two versions do, in fact , implement the same funct ionality, the program

    withou t t he native code is an equally capable 100% Pure Java p rogr am . That

    program is the one you can measure pur ity aga inst , and class ify as a 100% Pure

    Java program.

    Note: The Java Native Method Interface is not a way to make native code

    platform-independent; it is a way to make it easy to port native code. Thenative code still must be recompiled for each different hardware, and that

    recompilation will be difficult or impossible if the target hardware does not

    provide the library or the capabilities required by the native method.

  • 8/8/2019 Pure Java Cookbook.pdf

    26/61

    3 - 4 100% Pure Java Cookbook

    Guidelines for Developing Pure Programs

    3. Pitfall:Useofexec

    Explanation: The java.lang.Runtime.exec method is not generally

    por table ; not a ll p la tfo rm s have progr am s t ha t can be r un, and not a ll

    p la tfo rm s have the notion o f st andar d inpu t o r st andard out pu t. A hard -cod ed p rog ram n am e w ill n ot b e p or ta ble; th ere is n o p rog ram th at h as th e

    same nam e on a ll Java p la tfo rm s.

    Solution: Dont use this method except under the res tr ict ions de ta iled in

    Using Runtime.exec in Chapter 2.

    4. Pitfall:Failureto Use the Portability Features of Java CoreAPI

    Explanation: It is unpor table to hard-code text d isp lay s izes, co lors , layout

    management details, etc.

    Solution: The sys tem propert ies in general a re very usefu l for portab ility; use

    them whenever applicable . The AWT abs tract s the de ta ils of coping with the

    pla tform 's window sys tem. Use tha t abs tract ion to the fu llest . For example :

    Use a LayoutManager rather than hard-coding component sizes or positions

    Use the various getSize methods

    Use the desktop colors available in java.awt.SystemColor.

    5. Pitfall: Reflection

    Explanation: The reflect ion facilit ies of JDK 1.1 and later versions of the Java

    pla tform are an immense ly powerfu l addit ion to the language; they a lso makeit h ard er to p red ict w h at a p rogr am w ill d o. Method.invoke can be u sed to

    invoke any method, including ones that present portability problems.

    Solution: Be ca refu l. Any use o f Method.invoke to s ta rt another program

    must fo llow the same requirements as Runtime.exec detailed in Using

    Runtime.exe in Chapter 2.

    6. Pitfall:Direct Use of AW T Peer Classes

    Explanation: Por table programs, tha t use rather than implement the AWT

    interfaces, should not use the AWT peer classes direct ly. The protocol for

    interact ion with the peer classes is plat form specific.

    Solution: Stay on t he clien t side o f t he AWT.

  • 8/8/2019 Pure Java Cookbook.pdf

    27/61

    Revision Date: 10/00 3 - 5

    How to Develop a Program

    7. Pitfall: Misuseof System.exit

    Explanation: The System.exit method forces termina tion of a ll threads in

    the Java vir tua l machine. This is dras tic. It might, for example , dest roy a ll

    windows crea ted by t he in ter p ret er wit hou t g iv ing t he user a chance t o reco rd

    or even read the ir content s.

    Solution: Programs should usually termina te by s topping a ll non-daemon

    t hreads; in the sim p lest ca se o f a comm and-line p rogr am , th is is a s ea sy as

    return ing from the main method. System.exit shou ld be reser ved fo r a

    ca ta str oph ic er ro r exit , o r fo r ca ses when a progr am is in tended fo r use as a

    u tilit y in a comm and scr ip t t ha t m ay depend on the p rog rams exit code.

    8. Pitfall: Use of Hard-Coded FilePaths

    Explanation: Hard-coded filenames may present portabili ty problems. Hard-

    coded paths (with directory names jo ined to filenames) certain ly do.

    Solution: The m ost por table way to constr uct a File fo r a file in a d ir ect or y is

    to u se th e File(File,String) const ruct or to bu ild up t he pat h. Other

    portable solut ions are to use the system properties to get the local file separator

    and st ar ting d irecto ry, o r t o use a file d ia log t o ask t he use r fo r a filenam e.

    Note: The concept of an absolute path is somewhat system dependent; for

    example, UN IX absolute paths all start with /, while Windows absolute

    paths may s tart with any l etter. For this reason, the use of an absolute path

    that is not derived from user input or from a system property is unportable.

    Her e is t he code fo r a u tilit y cla ss that m ight m ake it m or e conven ien t t o

    construct portable pathnames:

    package util;

    import java.io.File;

    import java.util.StringTokenizer;

    /** A utility class to make it easier to use

    * java.io.File in a portable way.

    */

    public class FileUtil {

    /** Create a new pathname by gluing together

    * a series of names.

    * If initial base is null, works from

    * current directory.

    */

    public static File fromDir(File bse,

  • 8/8/2019 Pure Java Cookbook.pdf

    28/61

    3 - 6 100% Pure Java Cookbook

    Guidelines for Developing Pure Programs

    String[] path) {

    File val = bse;

    int i = 0;

    if (val == null && path.length > 0) {val = new File(path[i++]);

    }

    for ( ; i < path.length; i++) {

    val = new File(val, path[i]);

    }

    return val;

    }

    public static File fromHere(String[] path) {

    return fromDir(null, path);

    }

    private static File fromProp(String propName) {

    String pd = System.getProperty(propName);

    return new File(pd);

    }

    /** A File for system property "user.dir".

    */

    public static File userDir() {

    return fromProp("user.dir");

    }

    /** A File for system property "java.home".

    */

    public static File javaHome() {

    return fromProp("java.home");

    }

    /** A File for system property "user.home".

    */

    public static File userHome() {

    return fromProp("user.home");

    }

    /** Split first argument, using second arg* as separator char.

    * Convenient for creating a portable pathname.

    */

    public static String[] split(String p,

    String sep) {

    StringTokenizer st =

    new StringTokenizer(p, sep);

    String[] val = new String[st.countTokens()];

  • 8/8/2019 Pure Java Cookbook.pdf

    29/61

    Revision Date: 10/00 3 - 7

    How to Develop a Program

    for (int i = 0; i < val.length; i++) {

    val[i] = st.nextToken();

    }

    return val;

    }

    }

    9. Pitfall: JDBCDriver Loading

    Explanation: The JDBC interface, defined by the java.sql package, provides

    for flexibility in loading the actual JDBC driver code. This flexibil ity allows for

    subs titu tion of diffe rent JDBC dr ivers without changes to the programs code.

    This flexibility is provided by the DriverManager class, which selects among

    the available JDBC drivers during connect ion establishment . Drivers can be

    m ade ava ilable to t he Driver Manager in two ways:

    They can be named in the jdbc.drivers system p roperty

    They can be explicitly loaded by use of the java.lang.Class.forName

    method.

    This becomes a portabili ty issue because JDBC drivers, par ticular ly those that

    include nat ive code , m ight be less por table t han t he p rogr am s t ha t uses them .

    If you code a specific JDBC dr iver nam e in to your p rogr am , your p rogr am is

    only as portable as that dr iver. To be pure, your program must be cert ified wi th

    a portable driver.

    Solution: In o rder t o m axim ize t he por tability o f your JDBC progr am , we

    recommend that you make the exact JDBC dr iver name configurable . You can

    do th is eit her by r ely ing on t he jdbc.drivers system proper ty, o r by using a

    property file (or some other configura tion mechanism) to provide the name of

    t he JDBC dr iver cla ss t ha t will be loaded wit h t he Class.forName method.

    It is a lso poss ib le to load a select ion of dr ivers, rely ing on the DriverManager

    select ion mechanism to find an appropria te dr iver when the database

    connect ion is made.

  • 8/8/2019 Pure Java Cookbook.pdf

    30/61

    3 - 8 100% Pure Java Cookbook

    Guidelines for Developing Pure Programs

    If you chose to use th is approach , consider the fo llowing guide lines :

    Drivers are tried in the order they w ere registered, so earlier drivers will have

    priority over later ones, with dr ivers listed in jdbc.drivers having h ighest

    priority. A driver that includes native code will fail to load on any platform other than the

    one for which it was written; therefore, your program must cope gracefully with

    the ensuing ClassNotFoundException,

    A driver with native code mustnot regis ter i tself with theDriverManager until

    it knows that it has successfully loaded .

    A driver with native code is not governed by the security sandbox, and presents

    a p otential security hazard .

    In addit ion , rely ing on Class.forName to r un t he st at ic sect ion o f t he d r iver

    (which typically creates a driver instance and registers it ) causes portabili ty

    problems. The workaround is to expl icit ly create and register an instance of the

    driver class , like this :

    DriverManager.register(

    Class.forName("MyDriver").newInstance());

    Since t he sta tic sect ion m ay r un , and m ay reg ist er t he cla ss, th is can resu lt in

    dupl icate instances and dupl icate regis trations; however, according to the

    JDBC team this should not crea te a problem.

    10. Pitfall: Line Termination

    Explanation: Different plat forms have different convent ions for line

    ter m inat ion in a t ext file. Th is is a comm on inst ance o f the gener al p roblem of

    representing text.

    Different machines have different internal representat ions of text. The Java

    platform uses Unicode internally, which is an international s tandards-based

    so lu tion t o t he p roblem ; but we st ill need t o get t ext to and from files.

    The Java 1.1 (and la ter ) API has t he java.io.Reader an d java.io.Writer

    classes to handle that kind of character-set conversion. However, the problem

    can arise even when reading and wr it ing pla in ASCII files, because the ASCII

    standard isn 't specific about the l ine termination character. Some machines use

    "\n", som e u se "\r", som e u se th e seq uen ce "\r\n". Th e p or ta ble w ay to d ea l

    w ith th is, so y ou 'll w rite files th at th e u ser ca n rea d, is to u se th e "println"m eth od s to w rite a lin e of text, or to p ut th e lin e m arker at th e en d of a lin e.

    You m ay also u se th e line.separator sys tem property (us ing the System

    propert ies may be problemat ic for apple ts that can not access the System for

    security reasons).

    Solution: For inpu t, r at her t han wr it ing the code your self t o look fo r t he

    various line-termination sequences, it 's best and easiest to use the readLine

    method from the java.io.BufferedReader class to fe tch a comple te line of

  • 8/8/2019 Pure Java Cookbook.pdf

    31/61

    Revision Date: 10/00 3 - 9

    How to Develop a Program

    text. The other readLine m et hods a re a lso usefu l, bu t t he one in

    BufferedReader gives you code set t ransla tion as well. Likewise, for output ,

    use writeLine or println funct ion to output lines of text .

    11. Pitfall: UnportableCommand-Line Programs

    Explanation: Command-line programs tha t use System.in, System.out,

    or System.err might be less than perfect ly portable , because not a ll Java

    p la tfo rm s have t he concep t o f st andard inpu t o r ou tpu t st reams.

    Solution: Consider using a GUI, a t lea st a s an a lt er na tive some p la tfo rm s

    don't have a comm and line.

    12. Pitfall: Command Line Processing

    Explanation: The Java pla tform leaves command line process ing up to the

    programmer. However, the syntax and conventions are quite d iffe rent on the

    different platforms.

    Solution: The m ost por table answer is not to use the comm and line, bu t t ha t's

    n o g ood for b atch p rog ra ms th at n eed to be d riv en from a scrip t. U se th e

    widely unders tood POSIX convention (options indica ted with a dash) when

    process ing command line options . Provide , a t leas t as an a lternat ive, a GUI, or

    read opt ions from properties files (and document the properties).

    13. Pitfall: InternationalizationExplanation: Comput ing is a worldwide phenomenon. Par ticu la rly if your

    p rog ra m is a n a pp let, it is h ig hly lik ely to be r un in a n en viron men t w ith a

    different native language than yours .

    Advice: Use the internationalization and localization features of JDK 1.1software and later Java platform versions. Complete documentat ion is

    included in the JDK software, and is a lso ava ilable a t:

    http://java.sun.com/products/jdk/1.1/docs/guide/intl

    an d

    http://java.sun.com/products/jdk/1.2/docs/guide/intl

    14. Pitfall: UnicodeRendering

    Explanation: Not a ll p la tforms can render a ll Unicode character s.

  • 8/8/2019 Pure Java Cookbook.pdf

    32/61

    3 - 10 100% Pure Java Cookbook

    Guidelines for Developing Pure Programs

    Workaround: For the default t ext of messages , buttons, labe ls, and menus , use

    only ASCII. Of course, it is a ll r ight to use non-ASCII in loca lizat ion resources

    and in t ext obt ained fr om the user.

    15. Pitfall: FileI/O

    Explanation: The JDK 1.0 inpu t and out pu t cla sses a re not por table t o

    hardware architectures with non-ASCII native file formats.

    Solution: Use t he reader & wr it er cla sses found in t he JDK 1.1 so ftwa re and

    la te r versions of the Java pla tform.

    16. Pitfall: GUI Element Size

    Explanation: The exact s ize of the AWT elements will d iffe r from pla tform to

    p latfor m, a s w ill th e siz e of th e screen an d th e d efau lt a nd m axim u m siz e of awindow. Any hard-coded posit ions or s izes wi ll run afoul of these var ia tions.

    Solution: Use a layout manager.

    17. Pitfall: GUI Fonts

    Explanation: The s ize and availability of fonts var ies from display to disp lay

    (even on the same hardware pla tform, depending on installa tion).

    Solution: Dont hard-code text s izes; let text elements assume their natural s ize

    in a layou t, and use the Font Metr ics m ethods t o find t he act ua l d isp layed size

    o f a st ring on a Canvas. When set ting a nondefau lt font , be su re t o im p lem en ta fa llback in t he ca tch b lock . When cr ea ting a font m enu , get t he font nam es

    from the java.awt.Toolkit.getFontList m et hod r at her t han using a

    hardwired font l is t.

    When updating a program from 1.0 to 1.1 or la te r versions of the Java pla tform,

    be su re t o updat e t he font nam es as descr ibed in t he docum en ta tion fo r t he

    java.awt.Toolkit.getFontList method:

    Times Roman becomes Serif

    Helvetica becomes Sans-serif

    Courier becomes Monospaced

    18. Pitfall: GUI Appearance

    Explanation: The size o f the screen and the num ber o f ava ilable co lo rs m ay

    change from platform to platform, or even user-to-user or day-to-day. This can

    make a disp lay illegib le (for example , b lack text on a dark blue background), or

    can h ide bu tt ons if t hey d isp lay o ff t he screen .

  • 8/8/2019 Pure Java Cookbook.pdf

    33/61

    Revision Date: 10/00 3 - 11

    How to Develop a Program

    Solution: It m ay be necessa ry t o ad just font size o r defau lt window size

    according to screen resolu t ion, which may be obtained by:

    Toolkit tk = java.awt.Toolkit.getDefaultToolkit();

    int dpi = tk.getScreenResolution();

    Applets a re p robably sa fest t o use t he default font , a s it m ay have been

    cus tomized by the user according to the ir personal preferences.

    Fo r an applica tion, you m ay wish t o g ive t he user an opt ion o r cont ro l t o select

    among several appearances, so they can choose one tha t su it s their d isp lay and

    mood.

    If wr it ing to t he JDK 1.1 so ftwa re o r la ter in te rface, you can m ake your co lo rs

    har monize wit h t he user s desk top by using the co lo rs from t he

    java.awt.SystemColor class.

    If you choose to use your own color scheme instead , beware that d isp lays vary

    great ly in the color d isp layed for a part icu la r RGB trip le . Your programs

    appea rance will be m or e por table if you use nam ed co lo r field s from

    java.awt.Color rather than numeric colors.

    19. Pitfall: The Paint Protocol

    Explanation: The AWT Component.paint an d Component.update methods

    take a Graphics object as a parameter. This object should not be retained ,

    because it m ight be a t ransien t object valid only dur ing t he pain t; an AWT

    implementat ion is free to dest roy that Graphics object a fter the pa in t methodreturns, which makes it poin tless (and dangerous) to retain the object .

    Solution: Do not r eta in t he pa in t Graphics object . In gener al, it is not sa fe to

    pa in t ou tside a ca ll t o update() (or paint(), wh ich is ca lled by t he default

    Component.update()). If you do need a long-lived Graphics object , you

    sh ou ld crea te a n ew on e from th e a rgu m en t v alu e, b ut be w ar ned th at th is

    might fa il on some pla tforms:

    Graphics myGraphics = null; // retained

    void paint(Graphics g) {

    if (myGraphics == null) {myGraphics = g.create();

    }

    // painting code goes here

    }

  • 8/8/2019 Pure Java Cookbook.pdf

    34/61

    3 - 12 100% Pure Java Cookbook

    Guidelines for Developing Pure Programs

    20. Pitfall: Mixed Event Models

    Explanation: The JDK 1.1 software (and la te r) AWT uses a diffe rent event

    model from the previous AWT. Programs wr it ten to the 1.0.2 event model will

    w or k on a 1.1 or later p la tfor m v er sion , bu t m ixin g th e tw o ev en t m od els inone program will a lmost certain ly not work .

    Solution: Stick t o one even t m odel per p rogr am . Dont tr y t o conver t a

    p rog ram g rad u ally from th e old ev en t m od el to th e n ew ; d o it a ll a t on ce.

    21. Pitfall: Use of Deprecated Methods

    Explanation: Cer ta in m et hods fr om the Java co re APIs have been m arked as

    depreca ted . While these methods work in the cur rent release, they are s la ted

    fo r rem oval a t some poin t.

    Advice: When you work on code (class , method, or fie ld) tha t uses depreca ted

    m eth od s, it is p rob ab ly a g ood id ea to u p d ate th e cod e for th e rep la cem en t as

    suggest ed in the API docum en ta tion. Th is will a lso g ive you a head sta rt on

    future work.

    22. Pitfall: TheObject.hashCode andObject.equals

    Methods

    Explanation: The Object.hashCode m eth od retu rn s a n u mber w h ich is

    effect ively random. The number is also implementat ion- and instance-

    dependent. This has several consequences:

    The order of iteration for elements in a Hashtable will be unpredictable, and

    will generally differ from on e program invocation to the next.

    A class that overr idesObject.equalsmust also overrideObject.hashCode.

    It is safe, if inefficient, if the hashCode method returns the same value for

    unequalobjects. It isu nsafe if the hashCodemethod returns different values for

    two objects that are, in fact, equal.

    Solution: If a repeatable (although unpredictable) order of enumeration over

    the elem en ts in a Hashtable is im por tant t o your p rogr am , t hen any object

    u sed as a key in the Hashtable should have a class-specific hashCode

    m et hod which ret ur ns a value compu ted from da ta field s o f t he object .

    If any of your cla sse s defines an equals m et hod , it m ust a lso define a

    hashCode m et hod , such that fo r any t wo object s a,b of that class ,

    a.equals(b) implies that a.hashCode() == b.hashCode(). N ote th at

    hashCode shou ld not depend on any m utable p roper ty. If an object s

    hashCode value changes , tha t object is very likely to become unfindable .

  • 8/8/2019 Pure Java Cookbook.pdf

    35/61

    Revision Date: 10/00 3 - 13

    How to Develop a Program

    23. Pitfall: Installation Issues

    Explanation: Ther e a re a ser ies o f p roblem s t ha t can a rise when inst alling on

    various platforms, due to limitations or restr ict ions on filenames. This might

    in te rfe re with the convent ion that the Java vir tua l machine uses to loca te

    r equ ir ed cla ss files, wh ich depends on a sim p le m app ing fr om cla ss nam e t o

    filename.

    The problem s m ight occu r when inst alling, or when a tt em pting t o r un t he

    installed program.

    The problematic restrictions are:

    File name length: This is particularly a pr oblem w ith inner classes, wh ich are

    represen ted as class files with concatenated names.

    Case distinctions:Some platforms ignore case when comparing filenames.Ifyouhave two classes or a class and a package whose names differ only by case,

    your p rogram w ill not be portable to those platforms.

    Imperfect Unicode Support: Class names may contain Unicode characters that

    are not u sable as filenames on all platforms.

    Special Filenames: Some platforms assign special meaning to certain filenames,

    such as LPT or con. These filenames cannot be u sed as p art of a package

    nam e for classes that are to be installed a s files on those systems.

    Workarounds: Package your classes in to a .jar a rch ive, wh ich is pa rt o f the

    JDK, s ta rt ing wi th version 1.1. This wi ll work around the problems of long

    cla ss nam es and of ca se d ist inct ions. It m ight not work a round the p roblem of

    non-ASCII class names.

    If you a re wr iting fo r t he JDK 1.0 p la tfo rm , a .zip file is a possible alternative.

    Solution: Either rename your packages and classes , or use a .jar or .zip file.

    24. Pitfall: Hostname Format

    Explanation: The fo rm a t o f t he st ring r et ur ned by t he

    java.net.InetAddress.getHostName m et hod depends on t he hardware

    pla tform. In some cases, it will be a fu lly-qualified domain name; in others, it

    w ill on ly be th e h ost p ar t of th at n am e.

    Workaround: In m ost ca ses, t his p roblem , wh ich is a ca se o f under-

    specification, will pose no pract ical problem, because the unqualified name and

    the ful ly-quali fied name can be used for identification and connect ion within a

    d om ain . In cases w h ere th e n am e m u st b e exp or ted to d ista nt h osts, it m ay be

    b est to g iv e th e IP n u mb er in ad d ition to th e h ost n am e. Th e IP n u mb er is

    available from the getAddress method.

  • 8/8/2019 Pure Java Cookbook.pdf

    36/61

    3 - 14 100% Pure Java Cookbook

    Guidelines for Developing Pure Programs

    25. Pitfall: PluggableLook and Feel

    Explanation: The Pluggable Look and Feel (PLAF) architecture built in to the

    Swing classes of the Java 2 Standard Edit ion and the Java Foundat ion Classes

    s tandard extension for JDK 1.1 software a llows windows, d ia logs and otherGUI components to take on a dis tinct ive visual identity ca lled a LookAndFeel.

    No t a ll PLAFs a re ava ilable on ever y p la tfo rm and some m ay only be

    suppor ted on the operat ing sys tem the PLAF emula tes. Por table programs

    shou ld ensu re that a PLAF is bot h suppor ted and ava ilable t o t he under ly ing

    Java pla tform before it is set .

    Note: The Java platform Look and Feel is the default LookAndFeel and is

    always available. It will be used if the requested PLAF is not available or

    unsupported.

    Advice: For method:

    javax.swing.UIManager.setLookAndFeel(javax.swing.LookAnd

    Feel)

    M ake su re t ha t t he specified PLAF cla ss is suppor ted on t he active Java

    pla tform by us ing LookAndFeel.isNativeLookAndFeel() or u se th e

    current PLAF class from method UIManager.getLookAndFeel().

    For method:

    javax.swing.UIManager.setLookAndFeel(java.lang.String)

    Use UIManager.getSystemLookAndFeelClassName() or

    UIManager.getCrossPlatformLookAndFeelClassName() to ensure that

    the PLAF class is suppor ted .

    Alternatively, you can call UIManager.getInstalledLookAndFeels()

    This returns a LookAndFeelInfo object . This object can be quer ied to

    determine which PLAFs are available to the current ly act ive Java platform.

    You m ust be ca refu l when designing a user in ter face based upon a pa rticu la r

    PLAF since your user in ter face m ight be compromised if you r p rogr am is r un

    on a p la tfo rm wher e that PLAF is unavailable. To be sa fe, check your user

    in ter face wit h t he Java p la tfo rm Look and Feel un less you a re cer ta in the

    targeted PLAF will always be available.

    Obviously, the most portab le PLAF is the default Java Pla tform Look and Feel.

  • 8/8/2019 Pure Java Cookbook.pdf

    37/61

    Revision Date: 10/00 3 - 15

    How to Develop a Program

    26. Pitfall: M ixing Classes Compiled on Different Versions of the Java

    Platform

    Explanation: Classes are compiled against a part icu la r API set defined by the

    Java pla tform version . A program compiled on one major version (i.e ., 1.0, 1.1,

    1.2, e tc.) of the Java pla tform might not run on ear lie r versions because the

    program might targe t APIs tha t do not exis t in ear lie r versions .

    Mixing classes compiled against different major versions of the Java platform is

    generally not recommended because , in some rare s ituat ions, bug fixes or

    subtle incompatibili ties between the versions may cause portabili ty problems.

    Note: When the JavaPureCheck tool is used to check a program using the 1.2

    API system model, it will generate a warning when the program references a

    method from JD K 1.1 softw are that has been removed in the 1.2 API. The 1.2virtual machine will properly resolve this reference if the superclass

    contains a method w ith the s ame sig nature. How ever, the JavaPureCheck

    tool does not resolve these references to the superclass, and it generates a

    warning to flag the u se o f a class compiled on an earlier Java platform

    version.

    Sometim es you m ight be fo rced t o include a lib ra ry o r .jar of class files

    compiled against JDK1.1 software with a program that is compiled against 1.2.

    In this case , the warnings are unavoidable .

    Advice: If possible, compile all class files against the same Java platform

    ver sion on which you p lan t o r un your p rogr am . For sit ua tions where you

    must make use of classes tha t were compiled against ear lie r versions of the

    Java platform, check the relevant compatibili ty page for the Java development

    kit:

    http://java.sun.com/products/jdk/1.1/compatibility.html

    http://java.sun.com/products/jdk/1.2/compatibility.html

    If you have difficu lty with a 3rd party class library, contact the vendor and ask

    to have a library compiled for your targe t Java pla tform version .

    Note: Compiling you r classes w ith the -target 1.1 compile r flag on

    version 1.2 only affects the class file f ormat; it does not change the version ofthe JDK software APIs that the compiler compiles against.

  • 8/8/2019 Pure Java Cookbook.pdf

    38/61

    3 - 16 100% Pure Java Cookbook

    Guidelines for Developing Pure Programs

    Portability Hints

    This sect ion presents general hints for writ ing portable code.

    1. Hint: Writing PortableApplets

    Writ ing portable apple ts is somewhat harder than wr it ing portable programs.

    An apple t is , formally, a class tha t extends java.applet.Applet. In

    actuali ty, an applet's portability situation includes the Web page the applet

    loads fr om , t he o ther cla sses the applet u ses, t he HTM L that loads t he applet ,

    and the secur ity manager and Apple tContext of the user 's browser.

    One subt le , poss ib le problem in the HTML tag is t ha t t he cont en ts

    o f t he applet m ar kup m ust fo llow these r ules:

    elements come before the alternate contents

    alternate contents are text elements, such as the contents ofa paragraph (the

    tag). This means that you cannot u se

    tags in the alternate contents!

    Apple ts wi ll a lmost certain ly have to run under cont ro l of a secur ity manager.

    However, there is no s tandard profile for secur ity managers. The user can

    inst ruct the ir secur ity manager to deny any combina tion of access . The bes t

    t act ic is to make sure tha t your apple t handles any secur ity exception

    gracefully.

    Similar ly, the Java technology API specifications do not specify required

    content types or protocols . The MIME types image/jpeg an d image/gif

    a re p robably sa fe, a s a re t he http:, file:, and ftp: protocols . Again, handle

    any errors gracefully.

    In the Java 1.0 technology API, the specifica tion of the AppletContext/

    Applet protocol was not very precise. As a consequence, different browsers

    ca ll the apple ts enter & leave methods a t d iffe rent t imes. The protocol

    specifica tion is much more precise in the Java 1.1 software and la te r API, so

    this problem wi ll d isappear in t ime. Meanwhile , beware tha t an apple t tha t

    behaves polit ely on one browser m ay hog r esour ces on ano ther, wh ile a

    diffe rent apple t may funct ion normally on one browser but s ta ll on another.

    2. Hint: Security ExceptionsIf y ou r p rogr am w ill r un u n der con trol of a SecurityManager for

    example , if it 's an apple t it might encounter a SecurityException. Th is is

    an unchecked excep tion, so it m ay be t hrown wit hout being decla red .

  • 8/8/2019 Pure Java Cookbook.pdf

    39/61

    Revision Date: 10/00 3 - 17

    Portability Hints

    Depending on the part icu la r SecurityManager, the user can rest rict any

    access to protected resources a tt empted by the program. Therefore , it wi ll

    g rea tly enhance t he por tabilit y o f your p rogr am if you ca tch any

    SecurityException an d rep or t th e situ ation to th e u ser in a p olite m an ner.

    3. Hint: Coping with Bugs

    There are bugs in some Java pla tform implementa tions . To be most portab le , it

    is cour teous t o work a round t hose bugs. It is help fu l to consu lt t he known bug

    lists ava ilable from Sun and from some browser m aker s. Bugs a re harder t o

    cope wit h than fea tu res, because t hey a re less well defined and less well

    designed.

    Workarounds: In some cases, a program will have to include diffe rent code for

    different plat forms. Workarounds are expensive, both to code and to test. Theyare, unfortunately, inescapable in some circumstances.

    In general, you can act ivate a workaround either proact ively by branching on

    system properties, such as java.class.version an d os.name, or reactively

    by put ting the workaround in an exception handler. The choice depends on the

    character of the workaround. If the s tructure of the program or of long-lived

    data structures is affected, it s probably best to be proact ive. If the workaround

    has rela tively loca l e ffect , a react ive fa llback may be eas iest to code and

    understand. When possible, the react ive fallback will probably perform bet ter

    when the fa llback is not taken , because the cost of estab lishing an exception

    handler is quite low.

    A preem ptive fa llback is requ ired if t he nor m al code pa th would cause

    irreversible changes before the problem is detected.

    Heres an example of a preemptive workaround:

    class Preemptive {

    private boolean hasFooBug() {

    String java_name =

    System.getProperty(java.maker);

    return java_name.equals(KnownBad);

    }

    void something() {if (hasFooBug()) {

    workaround();

    } else {

    // normal code path

  • 8/8/2019 Pure Java Cookbook.pdf

    40/61

    3 - 18 100% Pure Java Cookbook

    Guidelines for Developing Pure Programs

    }

    }

    }

    Figure 3 - 1: class Preemptive

    And here is an exam ple o f a react ive workar ound :

    class Reactive {

    void something() {

    try {

    // normal code path

    } catch (Exception e) {

    workaround();

    }

    }

    }

    Figure 3 - 2: class Reactive

  • 8/8/2019 Pure Java Cookbook.pdf

    41/61

    Revision Date: 10/00 4 - 1

    Explanations of Purity Problemsand V ariances 4

    Explanations of Purity Problems

    For a de ta iled HTML-generated lis t of the pur ity problems, use the fo llowing

    comm and line to r un t he JavaPureCheck t oo l t o gener at e a r epor t:

    java JavaPureCheck -d -h

    where is: jdk102, jdk11 or jdk12

    In this usage, the JavaPureCheck tool crea tes an html descr ip t ion file of the

    sys tem model JavaPureCheck loads for a given JDK version ..

    Report Information Categories

    The report categorizes reports into three categories:

    Pure: No portability problems. The class file is a pu re Java class.

    Warning:Possible portability problem. You must provide an explanation for all

    warnings.

    Error: An unequivocal portability problem. An error must be granted a variance

    by Sun. The only acceptable explanation for su ch an err or is a reference to a

    variance num ber granted by Sun.

  • 8/8/2019 Pure Java Cookbook.pdf

    42/61

    4 - 2 100% Pure Java Cookbook

    Explanations of Purity Problems and Variances

    Explanations

    You should provide explanat ions for a ll warnings and errors ident ified on the

    JavaPureCheck tool report . An explanat ion must descr ibe why the reported

    problem does not, in fact , impede portability. Below is a lis t of typical problems

    reported by the JavaPureCheck tool, the reason they were flagged, and an

    ind ica tion o f how t o hand le them :

    Note: See the documentation included with the JavaPureCheck tool and the

    information below for complete coverage of all warnings and errors.

    Warnings

    Warning: PossibleHardcoded PathThe JavaPureCheck tool checks the str ing constants in your applicat ion,

    looking for any that resemble hardcoded file pathnames. The JavaPureCheck

    tool a tt empts to resolve any suspicious s tr ings by determining how they are

    used . If a susp icious str ing (one that looks like a har dcoded pa th ) is used in

    an I/ O class const ructor, this is reported as an error. If the JavaPureCheck

    t oo l cannot deter m ine how a susp icious st ring is used , it repor ts a warn ing.

    If the s tr ing identified in the JavaPureCheck tool report is not a hardcoded

    pa th , you shou ld supp ly an exp lana tion t ha t descr ibes how the st ring is

    used . St rings used as URLs, for example , a re acceptable .

    Warning: Mixing the1.0 and 1.1 Event Models

    This is likely to be a applica tion programming error that will impair

    portability.

    Possib le explanat ions for th is warning would have to show reasonable need

    for mixing event models .

    Warning: Dynamically Loaded Classes:

    U se of java.lang.Class.forName

    U se of java.lang.ClassLoader.defineClass U se of java.lang.ClassLoader.resolveClass

    U se of java.lang.ClassLoader.findSystemClass

    Classes that are dynamically loaded might contain portability bugs.

  • 8/8/2019 Pure Java Cookbook.pdf

    43/61

    Revision Date: 10/00 4 - 3

    Explanations of Purity Problems

    To expla in an acceptable use of these methods , you should lis t a ll the classes

    that could be dynamica lly loaded such that you can det er mine t ha t t hose

    classes are part of the systembeing checked for compliance. All classes

    should be checked for pur ity.

    If your applica tion does dynamic loading of arb it ra ry classes , you should

    p rovide a descr ip tion o f how t he nam es o f those cla sses a re det er m ined .

    Warning: Object is Compiled for a Previous (Java Development Kit)

    release

    This warn ing appea rs when your cla ss files a re compiled on one ver sion o f

    the Java p la tfo rm , and have dependencies on m et hods t ha t no longer exist

    when t est ed on a la ter system m odel by t he JavaPureCheck t oo l.

    Even though the Java vir tua l machine will handle these s ituat ions by

    deferr ing execut ion of a missing method to its superclass , mixing classes

    compiled against different versions of the Java platform is discouraged

    because, in rare situations, bug fixes or subt le incompatibilit ies between the

    versions might cause portability problems. See Mixing Classes Compiled on

    Different Versions of the Java Platform for more information.

    Explanations for these warnings should descr ibe why all applicat ion classes

    are not compiled against the same Java pla tform version (e .g ., your

    applica tion might require the use of 3rd party libraries which were compiled

    against a previous JDK version).

    Warning: Unsupported PluggableLook and Feel

    The Swing cla sses in t he Java 2 SDK and t he JFC st andard ext ension fo r JDK

    1.1 software define a pluggable look and feel a rchitecture tha t may cause

    portability problems when an unsupported or unavailable LookAndFeel is

    hard-coded into your application.

    Explanat ions for this warning should show tha t the proper a llowances for

    unavailable and / o r unsuppor ted LookAndFeel have been m ade in your

    application.

  • 8/8/2019 Pure Java Cookbook.pdf

    44/61

    4 - 4 100% Pure Java Cookbook

    Explanations of Purity Problems and Variances

    Errors

    Error: Constant Strings with OS-Specific Syntax Used in I/O Class

    Constructors

    Use of str ings including OS-specific constants, such as hardcoded line

    termination characters or device names, are not portable.

    Error: Peer Use

    The AWT peer classes are not in tended for direct use by Java applica tions .

    Error: Useof Native Code

    Native method definition U se of java.lang.Runtime.load

    U se of java.lang.Runtime.loadLibrary

    100% Pure Java programs cannot depend on native code.

    Error: Useofjava.lang.Runtime.exec.

    Execut ion of an external applicat ion is not plat form independent , except

    under the circumstances de ta iled in the sect ions of this chapter that deal with

    Variance Numbers 1, 5, and 17.

    Error: Injection into CoreLibrary

    100% Pure Java applica tions may not insert classes in to the Java core library

    (e.g . packages whose nam es st ar t wit h java, javax, or omg).

    Error: Undefined Reference

    An incomplete applicat ion (i.e ., an applicat ion with depende