Home > Software engineering >  How to avoid calling this.field for every field in a java class
How to avoid calling this.field for every field in a java class

Time:04-22

Is there a way to avoid calling this.field for every field in a class ?

public class Test {
    private String name;
    private String email;

    public Test(String name, String email) {
        // I want to avoid this
        this.name = name;
        this.email = email;
    }

    public Test(Test test) {
        // Something like this would be perfect, setting both name and email to test
        this(test);
    }
}

CodePudding user response:

The use of this is only required in cases of name collisions, to resolve the ambiguity.

Some programmers like me prefer using the this. prefix routinely, whereas other use only where necessary.

See Answer by Wasserman for an example of how to avoid naming collision.

Use the IDE, Luke

Your IDE will generate constructors, accessors (getters/setters), equals & hashCode, toString, and so on. So you need not type this.; let the machine do the typing.

Use custom settings to control whether you want the IDE to include or omit this. prefixes.

record

You may be interested in using the records feature, new in Java 16 . A record is a brief way to write a class whose main purpose is to communicate data transparently and immutably.

With a record, by default, the compiler implicitly writes the constructor, getters, equals & hashCode, and toString. The implicitly created constructor populates each and every member field on your behalf. You write none of that code.

Here is your entire example class when written as a record. No this required. All your member fields are automatically assigned.

public record Test ( String name , String email ) {}

Be cautious in using records. The reason for their invention was not writing less code. The reason was to provide an explicit mechanism for transmitting immutable data transparently, a “nominal tuple” in academic-speak. Less boilerplate coding is merely a nice side-effect. I highly recommend reading JEP 395 for more explanation.


Tip: You can combine the two points of this Answer. Ask your IDE to generate a full-blown class by starting with a record.

  1. Write a record with all your member fields listed in the parentheses.
  2. Invoke your IDE to convert from a record to a class.

Voilà, you have a complete class with constructor, accessors, equals & hashCode, and toString all written out with an absolute minimum of typing by you.

CodePudding user response:

Sorry, the only way to avoid this is to have different names for your constructor parameters and for your class fields.

    public Test(String _name, String _email) {
        // I want to avoid this
        name = _name;
        email = _email;
    }

That said, you might have better luck using Java 16 's record syntax.

CodePudding user response:

As suggested, using records is the easiest way:

public record Test (String name, String email) {
}

That's all you need. What you then get:

  • A constructor that takes all arguments, in the same order as the field list
  • A method for each field. This does not start with get. In this case, the methods are name() and email().
  • equals, hashCode and toString implementations that use all fields.

There is no need for a copy constructor, because every field is automatically final.


If you want, you can add extra constructors. However, they must delegate to the automatically generated constructor, because that's the one that sets the fields. Adding additional utility methods is also fine.

And if needed, you can add validation to the generated constructor. There's special syntax that allows you to omit all the field names:

public record Test (String name, String email) {
    public Test {
        Objects.requireNonNull(name);
        Objects.requireNonNull(email);
    }
}

The assignments are done for you, there's no need to type those either.

CodePudding user response:

You need this.x everytime, if there are 2 or more variables, which are called x and you want to call the attribute variable x. The this keyword is used, to point on an attribute variable of the created instance (object) of the class.

There could be an attribute, that is called x, and a local variable which is called x too.

  • Related