Java Reference
In-Depth Information
Safe Java Programming
Programming languages are sometimes described as being type safe —however, this
term is used rather loosely by working programmers. There are a number of differ‐
ent viewpoints and definitions when discussing type safety, not all of which are
mutually compatible. The most useful view for our purposes is that type safety is the
property of a programming language that prevents the type of data being incorrectly
identified at runtime. This should be thought of as a sliding scale—it is more helpful
to think of languages as being more (or less) type safe than each other, rather than a
simple binary property of safe / unsafe.
In Java, the static nature of the type system helps prevent a large class of possible
errors, by producing compilation errors if, for example, the programmer attempts
to assign an incompatible value to a variable. However, Java is not perfectly type
safe, as we can perform a cast between any two reference types—this will fail at run‐
time with a ClassCastException if the value is not compatible.
In this topic, we prefer to think of safety as inseparable from the broader topic of
correctness. This means that we should think in terms of programs, rather than lan‐
guages. This emphasizes the point that safe code is not guaranteed by any widely
used language, and instead considerable programmer effort (and adherence to rig‐
orous coding discipline) must be employed if the end result is to be truly safe and
correct.
We approach our view of safe programs by working with the state model abstraction
as shown in Figure 5-1 . A safe program is one in which:
O n
• All objects start off in a legal state after creation
• Externally accessible methods transition objects between legal states
• Externally accessible methods must not return with object in an inconsistent
state
• Externally accessible methods must reset object to a legal state before throwing
In this context, “externally accessible” means public , package-private, or pro
tected . This defines a reasonable model for safety of programs, and as it is bound
up with defining our abstract types in such a way that their methods ensure consis‐
tency of state, it's reasonable to refer to a program satisfying these requirements as a
“safe program,” regardless of the language in which such a program is implemented.
Private methods do not have to start or end with object in a
legal state, as they cannot be called by an external piece of
code.
Search WWH ::




Custom Search