Type Embedded in Name (Including Hungarian)


Type Embedded in Name (Including Hungarian)

Symptoms

  • Names are compound words, consisting of a word plus the type of the argument(s). For example, a method addCourse(Course c) .

  • Names are in Hungarian notation, where the type of an object is encoded into the name; e.g., iCount as an integer member variable.

  • Variable names reflect their type rather than their purpose or role.

How It Got This Way

The type may be added in the name of communication. For example, schedule.addCourse(course) might be regarded as more readable than schedule.add(course) . (I don't think it is, but some do.)

The embedded type name represents duplication: Both the argument and the name mention the same type. The embedded name can create unnecessary troubles later on. For example, suppose we introduce a parent class for Course to cover both courses and series of courses. Now, all the places that refer to addCourse() have a name that's not quite appropriate. We either change the name at every call site or live with a poor name. Finally, by naming things for the operation alone, we make it easier to see duplication and recognize new abstractions.

Hungarian notation is often introduced as part of a coding standard. In pointer-based languages (like C), it was useful to know that **ppc is in fact a character, but in object-oriented languages it overcouples a name to its type.

Some programmers or teams use a convention where a prefix indicates that something is a member variable ( _count or m_count ) or that something is a constant ( ALL_UPPER_CASE ). Again, this adds friction as we change whether something is a local variable, a member, and so on. Aren't there times when we need to know which is which? Sure ”and if it's not easy to tell, then it may be a sign that a class is too big. (The idea that these conventions are problematic is not universally agreed to; even the code in Fowler's Refactoring uses _member variables .)

What to Do

  • Rename Method (or field or constant) to a name that communicates intent without being so tied to a type.

Payoff

Improves communication. May make it easier to spot duplication.

Contraindications

Rarely, you might have a class that wants to do the same sort of operation to two different but related types. For example, we might have a Graph class with addPoint() and addLink() methods . If the abstract behavior for the two cases is the same, it may be appropriate to overload the method name ( add() ).

Sometimes you're using a coding standard that uses typographical conventions to distinguish different classes of variables. You may then value the team's readability of code above the flexibility of untyped names, and follow those conventions.



Refactoring Workbook
Refactoring Workbook
ISBN: 0321109295
EAN: 2147483647
Year: 2003
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net