Java Reference
In-Depth Information
Use a leading or trailing underscore (_) when dealing with attributes.
In this case, at the value in B in the previous example, we'd have int
_value . We would also place the underscore at D . Doing so avoids all
collisions at the cost of readability.
1
Precede all attributes with this . For that solution, at D , we'd have
this.value = getFromTable(tableName) , yielding the desired result.
This approach has the advantage of reducing the number of collisions
with little effect on readability.
2
Limit the access of all member attributes to the accessors. In this case,
at D we'd have setValue(getFromTable(tableName)) with no con-
flict. This has the advantage of hiding the implementation of all
attributes, at the cost of real estate.
3
Finally, we could prohibit conflicting names. This method results in
code with better readability, but it is error prone.
4
In order of preference, I like options 2, 1, 3, and 4, though I have seen each
employed successfully. Table 9.3 lists the coding conventions for preventing
collisions.
The best policy for any standard is flexibility. For attribute scope, we might
decide to choose option 4 and revise the policy if bugs created by the collision
Table 9.3 Here are coding conventions for preventing collisions between attribute names and
local variables. These types of errors are usually obscure and can be difficult to trace. They are
preventable, at a cost.
Scope Rule
Example (Declare, Use)
Pros
Cons
Leading or trailing _
for all attributes.
Public int _value;
_value = 0;
Prevents
collisions.
Hinders readability with
clutter.
Precede all attribute
references with
this .
// no change in declaration
this.value = 0
Prevents
collisions.
Hinders readability by
taking up space.
Access attributes
solely through acces-
sors.
// no change in declaration
setValue(0)
Prevents
collisions.
Isolates
attributes.
Hinders readability by
taking up space.
Disallow attribute
names in the method
body.
// no change in declaration
// no change in use
Most
readable
alternative.
Allows collisions and
human error.
Search WWH ::




Custom Search