Arguments to constructors were once prefixed with 'arg' or 'init' or 'the' to ensure they were different from member variables.  There was no consistency between projects.

public class Product
{
    private int id;
    private String name;
    private String desc;

    public Product(int theId, String theName, String theDesc)
    {
        id = theId;
        name = theName;
        desc = theDesc;
    }
:     

Over time a recommended way to pass parameters to constructors and setters has emerged:

Tip: When referring to member variables in constructors and setters only, use a prefix of 'this.' in all cases.  Do not use 'this.' to refer to member variables in other methods because the 'this.' is implied.

An example is below.

public class Product
{
    private int id;
    private String name;
    private String desc;

    public Product(int id, String name, String desc)
    {
        this.id = id;
        this.name = name;
        this.desc = desc;
    }     
     
    public void setId(int id)
    {
        this.id = id;
    }
:

    

Parameters to methods are local variables like any other, and have a scope in which they are valid, which is the duration of the method call.  As with other variables, use true names for parameters.

In the following example the developer has given lazy names to method parameters that makes them difficult to understand without javadoc.

public String getNice(String n, int c)
{
    if (c == 1)
        return “Welcome “ + n + “, there is 1 item in your cart”;
    else
        return “Welcome “ + n + “, there are “ + c
             + “ items in your cart”;
}

With poor names like these they may as well have used other meaningless words like param1 and param2.

The code is much easier to understand if the parameters are given true names.

public String getWelcomeMessage(String userName,  
                                int cartItemCount)
{
    if (cartItemCount == 1)
    {
        return “Welcome “ + userName  
             + “, there is 1 item in your cart”;
    }
    else
    {
        return “Welcome “ + userName  
             + “, there are “ + cartItemCount  
             + “ items in your cart”;
    }
}

Parameter names too should be qualified with information that identifies what the parameters represent:

public void logRequest(HttpServletRequest requestParam)
{
    String parameter = request.getParameter(“userId”);
    :
}

It is obvious when a function is passed a parameter in the method signature that the passed value is a parameter, so the above naming adds little value.  Name it what it really is – there is no need to add the redundant 'parameter' word.  The code would be better written as:

public void logRequest(HttpServletRequest request)
{
    String userId = request.getParameter(“userId”);
    :
}
blog comments powered by Disqus