Guarded type promotion: eliminating redundant casts in Java

  • Authors:
  • Johnni Winther

  • Affiliations:
  • Aarhus University

  • Venue:
  • Proceedings of the 13th Workshop on Formal Techniques for Java-Like Programs
  • Year:
  • 2011

Quantified Score

Hi-index 0.00

Visualization

Abstract

In Java, explicit casts are ubiquitous since they bridge the gap between compile-time and runtime type safety. Since casts potentially throw a ClassCastException, many programmers use a defensive programming style of guarded casts. In this programming style casts are protected by a preceding conditional using the instanceof operator and thus the cast type is redundantly mentioned twice. We propose a new typing rule for Java called Guarded Type Promotion aimed at eliminating the need for the explicit casts when guarded. This new typing rule is backward compatible and has been fully implemented in a Java 6 compiler. Through our extensive testing of real-life code we show that guarded casts account for approximately one fourth of all casts and that Guarded Type Promotion can eliminate the need for 95 percent of these guarded casts.