You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 75 Next »

Generically typed code can be freely used with raw types when attempting to preserve compatibility between non-generic legacy code and newer generic code. Using raw types with generic code causes most Java compilers to issue "unchecked" warnings but still compile the code. When generic and non-generic types are used together correctly, these warnings can be ignored; at other times, these warnings can denote potentially unsafe operations.

According to the Java Language Specification [[JLS 2005]], §4.8 "Raw Types,"

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

If a parameterized type tries to access an object that is not of the parameterized type, heap pollution occurs. For instance, consider the code snippet below.

List l = new ArrayList();
List<String> ls = l; // Produces unchecked warning

It is insufficient to rely on unchecked warnings alone to detect violations of this rule. According to the JLS [[JLS 2005]], §4.12.2.1, "Heap Pollution,"

Note that this does not imply that heap pollution only occurs if an unchecked warning actually occurred. It is possible to run a program where some of the binaries were compiled by a compiler for an older version of the Java programming language, or by a compiler that allows the unchecked warnings to suppressed [sic]. This practice is unhealthy at best.

Extending legacy classes and generifying the overriding methods fails because this is disallowed by the Java Language Specification [[JLS 2005]].

Noncompliant Code Example

This noncompliant code example compiles although it produces an unchecked warning because the raw type of the List.add() method is used (the list parameter in the addToList() method) rather than the parameterized type.

class MixedTypes {
  private static void addToList(List list, Object obj) {
    list.add(obj); // unchecked warning
  }

  public static void main(String[] args) {
    List<String> list = new ArrayList<String> ();
    addToList(list, 1);
    System.out.println(list.get(0));
  }
}

When executed, this code produces an exception not because a List<String> receives an Integer but because the value returned by list.get(0) is an improper type. In other words, the code throws an exception some time after execution of the operation that actually caused the exception, complicating debugging.

Compliant Solution (Parameterized Collection)

This compliant solution enforces type safety by changing the addToList() function signature to enforce proper type checking. It also complies by adding a String rather than an Integer.

class Parameterized {
  private static void addToList(List<String> list, String str) {
    list.add(str);     // No warning generated
  }
  public static void main(String[] args) {
    List<String> list = new ArrayList<String> ();
    addToList(list, "1");
    System.out.println(list.get(0));
  }
}

The compiler does not allow insertion of an Object once list is parameterized. Likewise, addToList() cannot be called with an argument whose type produces a mismatch.

Compliant Solution (Legacy Code)

While the previous compliant solution eliminates use of raw collections, this could be infeasible when interoperating with legacy code.

Suppose that the addToList() method was legacy code that could not be changed. The following compliant solution creates a checked view of the list by using the Collections.checkedList() method. This method returns a wrapper collection that performs runtime type checking in its implementation of the add() method before delegating to the backend List<String>. The wrapper collection can be safely passed to the legacy addToList() method.

class MixedTypes {
  private static void addToList(List list, Object obj) {
    list.add(obj); // Unchecked warning
  }

  public static void main(String[] args) {
    List<String> list = new ArrayList<String> ();
    List<String> checkedList = Collections.checkedList(list, String.class);
    addToList(checkedList, 1);
    System.out.println(list.get(0));
  }
}

The compiler still issues the "unchecked warning," which may still be ignored. However, the code now fails precisely when it attempts to add the Integer to the list, consequently preventing the program from proceeding with invalid data.

Noncompliant Code Example

This noncompliant code example compiles and runs cleanly because it suppresses the unchecked warning produced by the raw List.add() method. The printOne() method intends to print the value one, either as an int or as a double depending on the type of the variable type.

class BadListAdder {
  @SuppressWarnings("unchecked")
  private static void addToList(List list, Object obj) {
    list.add(obj);     // Unchecked warning
  }

  private static <T> void printOne(T type) {
    if (!(type instanceof Integer || type instanceof Double)) {
      System.out.println("Cannot print in the supplied type");
    }
    List<T> list = new ArrayList<T>();
    addToList(list, 1);
    System.out.println(list.get(0));
  }

  public static void main(String[] args) {
    double d = 1;
    int i = 1;
    System.out.println(d);
    BadListAdder.printOne(d);
    System.out.println(i);
    BadListAdder.printOne(i);
  }
}

However, despite list being correctly parameterized, this method prints '1' and never '1.0' because the int value '1' is always added to list without being type checked. This code produces the following output:

1.0
1
1
1

Compliant Solution

This compliant solution generifies the addToList() method, which eliminates any possible type violations.

class GoodListAdder {
  private static <T> void addToList(List<T> list, T t) {
    list.add(t);     // No warning generated
  }

  private static <T> void printOne(T type) {
    if (type instanceof Integer) {
      List<Integer> list = new ArrayList<Integer>();
      addToList(list, 1);
      System.out.println(list.get(0));
    }
    else if (type instanceof Double) {
      List<Double> list = new ArrayList<Double>();

      // This will not compile if addToList(list, 1) is used
      addToList(list, 1.0);

      System.out.println(list.get(0));
    }
    else {
      System.out.println("Cannot print in the supplied type");
    }
  }

  public static void main(String[] args) {
    double d = 1;
    int i = 1;
    System.out.println(d);
    GoodListAdder.printOne(d);
    System.out.println(i);
    GoodListAdder.printOne(i);
  }
}

This code compiles cleanly and produces the correct output:

1.0
1.0
1
1

If the method addToList() is externally defined (such as in a library or as an upcall method) and cannot be changed, the same compliant method printOne() can be used, but no warnings result if addToList(1) is used instead of addToList(1.0). Great care must be taken to ensure type safety when generics are mixed with non-generic code.

Exceptions

OBJ14-EX0 Raw types must be used in class literals. For example, because List<Integer>.class is illegal, it is permissible to use the raw type List.class [[Bloch 2008]].

OBJ14-EX1 The instanceof operator cannot be used with generic types. It is permissible to mix generic and raw code in such cases [[Bloch 2008]].

if(o instanceof Set) { // Raw type
  Set<?> m = (Set<?>) o; // Wildcard type
  // ...
}

Risk Assessment

Mixing generic and non-generic code can produce unexpected results and exceptional conditions.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ14-J

low

probable

medium

P4

L3

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="35db2e7c-8ad2-4f5d-aa66-a80dbfa254ef"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. Bibliography#Bloch 08]]

Item 23: "Don't use raw types in new code"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ea21c4ce-a22e-4e87-9b83-1bc993dde0b2"><ac:plain-text-body><![CDATA[

[[Bloch 2007

AA. Bibliography#Bloch 07]]

Generics, 1. "Avoid Raw Types in New Code"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c8cf67e5-64ab-427d-9167-4904978aa932"><ac:plain-text-body><![CDATA[

[[Bloch 2005

AA. Bibliography#Bloch 05]]

Puzzle 88: Raw Deal

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e6966a9d-f8d6-46a4-8d5a-5a2f810a64ef"><ac:plain-text-body><![CDATA[

[[Darwin 2004

AA. Bibliography#Darwin 04]]

8.3 Avoid Casting by Using Generics

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6397bab7-7a46-41d4-be1a-db96b101defd"><ac:plain-text-body><![CDATA[

[[JavaGenerics 2004

AA. Bibliography#JavaGenerics 04]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="06e70eba-b8d7-4f8e-a420-dd13c42e4028"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[Chapter 5 "Conversions and Promotions"

http://java.sun.com/docs/books/jls/third_edition/html/conversions.html]

]]></ac:plain-text-body></ac:structured-macro>

 

§4.8 "Raw Types"

 

§5.1.9 "Unchecked Conversion"

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0d76dad2-5f5d-4981-bb54-c8e7356b34bc"><ac:plain-text-body><![CDATA[

[[Langer 2008

AA. Bibliography#Langer 08]]

Topic 3, "[Coping with Legacy

http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#Topic3]"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0cb3a975-1b20-4207-a7b4-fb3b1411e2d2"><ac:plain-text-body><![CDATA[

[[Naftalin 2006

AA. Bibliography#Naftalin 06]]

Chapter 8, "Effective Generics"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="809452d5-25fb-4efe-bea6-3cb55797fd57"><ac:plain-text-body><![CDATA[

[[Naftalin 2006b

AA. Bibliography#Naftalin 06b]]

"Principle of Indecent Exposure"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="859c4037-e8bb-40d1-81fb-21c3136dff12"><ac:plain-text-body><![CDATA[

[[Schildt 2007

AA. Bibliography#Schildt 07]]

"Create a checked collection"

]]></ac:plain-text-body></ac:structured-macro>


OBJ13-J. Preserve dependencies in subclasses when changing superclasses      04. Object Orientation (OBJ)      OBJ15-J. Write garbage-collection-friendly code

  • No labels