en ru de
Victor Kropp

No prefix, please!

For many years developers have been adding prefixes to instance fields: my, m, _ and whatever else. I’ve seen many coding style guides requiring one of these prefixes. But nowadays it looks like a rudiment of a previous century.

Like ill-famed Hungarian notation they are used to give programmer a hint on some properties of entity. With powerful IDEs, it is not necessary anymore. You can have much more powerful hints and easily navigate code to discover much more.

Modern software development practices almost eliminate situations, where the confusion between instance fields and methods parameters can arise. If your objects are immutable, then you don’t have setters and only deal with parameters in the constructor. Here C++ has a nice syntax for fields initializers:

class Point {
  private:
    const int x, y;
  public:
    Point(int x, int y) : x(x), y(y) {}
};

Note also, that you can declare methods with the same as fields. And again there is no confusion! No, actually, you can’t.

Kotlin went further and completely eliminated getters and setters and merged them with fields and constructor parameters into a single entity.

class Point(public val x: Int, public val y: Int)

Similarly, properties are implemented in Objective-C. And in C# many people prefer properties to fields because in most cases one can leave them auto-implemented while retaining an ability to assign getter and setter different access rights.

So the last case where confusion may arise is a method that has a parameter with the same name as a field, but it is neither a setter nor the constructor or there is similarly named variable. This sounds suspicious. Probably some fields or variables must be renamed to better reflect their purpose.

And there is one more aid in this situation: color coding. I’ve been using it for quite some time already in IntelliJ IDEA 2016.3 and am absolutely impressed. I used to use highlight usages on a variable to see data flow in a method. Now it is immediately visible at a glance. And you’ll never mix up different variables anymore.

Don’t add prefixes to fields names! They are unnecessary.

programmingnaming

Subscribe to all blog posts via RSS, follow me @kropp and join my Telegram channel.