Perl Best Practices [Electronic resources]

Damian Conway

نسخه متنی -صفحه : 317/ 47
نمايش فراداده

3.9. Ambiguous Names

Avoid using inherently ambiguous words in names .

It's not only abbreviations that can introduce ambiguities in your identifiers. Complete words often have two or more homonyms, in which case any name containing them will be inherently ambiguous.

One of the worst offenders in this respect is the word "last". A variable named $last_record might refer to the record that was most recently processed (in which case it should be called $prev_record), or it might refer to the ultimate record in a list (in which case it should be called $final_record).

The word "set" is another major stumbling block. A subroutine named get_set( ) might retrieve a collection of values (in which case, call it retrieve_collection( )), or it might test whether the "get" option has been enabled (in which case, call it get_is_enabled( )), or it might mediate both fetch and store operations of some value (in which case, call it fetch_or_store( )).

Other commonly used words to avoid include:

  • "left" (the direction

    vs what remains)

  • "right" (the other direction

    vs being correct

    vs . an entitlement)

  • "no" (the negative

    vs the abbreviation for number)

  • "abstract" (theoretical

    vs a précis

    vs to summarize)

  • "contract" (make smaller

    vs a legal agreement)

  • "record" (an extreme outcome

    vs a data aggregation

    vs to log)

  • "second" (the ordinal position

    vs the unit of time)

  • "close" (near

    vs to shut)

  • "bases" (more than one base

    vs more than one basis)

Any homograph can potentially cause difficulties if it has a distinct, non-programming-related sense that is relevant to your particular problem domain.

Keep in mind that it may not be immediately obvious to you that a given identifier is ambiguous. Indeed, the alternate interpretation might come to light only when someone else is (mis)reading your code, or when you are puzzling over theirs. If a particular identifier ever leads to this form of confusion, then it should be renamed immediately. However, in your initial coding it probably suffices just to avoid "last" and "set".