Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefixing variables names to indicate their respective scope or origin?

In the companies I've been working, I've seen a lot the use of prefixes to indicate the scope or the origin of variables, for example m for classes members, i for methods intern variables and a (or p) for methods parameters:

public class User {

    private String mUserName;

    public String setUserName(final String aUserName) {
        final String iUserName = "Mr " + aUserName;
        mUserName = iUserName;
    }

}

What do you think about it? Is it recommended (or precisely not)? I found it quite ugly in a first phase, but the more I use it, the more I find it quite convenient when working on big methods for example.

Please note that I'm not talking about the Hungarian notation, where prefixes indicate the type rather than the scope.

like image 801
sp00m Avatar asked Nov 02 '22 20:11

sp00m


1 Answers

I've also worked in shops that had rigid prefix notation requirements, but after awhile this became a "smell" that the code had grown out-of-control and global variables were leaking from everywhere indicating poor code/review.

Java's "this." notation is the prefered way to reference a field, over a local. The use of "m" prefix for variables was popularized by that "Micro.." company as a branding gimmick (they even said "don't use that because we do").

The general rule I follow is to name the variable according to what it is used to store. The variable name is simply an alias. If it stores a user name, then userName is valid. If it is a list of user names, then userNames or userNameList is valid. However, I avoid including the "type" in the variable-name now, because the type changes quite often (shouldn't a collection of user names be a set, in practice? and so on...)

At the end of the day, if the variable name is useful to you to remember what the code was doing down the road, it is probably a good idea. Maintainability and Readability trump "perceived" efficiency and terse syntax, especially because modern compilers are rewriting your code according to macro usage patterns.

I hope this helps somewhat, and am happy to supply more details of any claims herein.

ps. I highly recommend the Elements of Java Style for these types of questions. I used to work with the authors and they are geniuses when it comes to style!

like image 139
jatal Avatar answered Nov 08 '22 08:11

jatal