Inicialización de campo de constructor de clase abreviada

I can't help but feel there is a shorthand method of writing something like this:

public abstract class MessageBase
{
    public String Destination, Sender = "", Uid = "";

    public MessageBase(String destination)
    {
        this.Destination = destination;
    }

    public MessageBase(String destination, String uid)
    {
        this.Destination = destination;
        this.Uid = uid;
    }
}

Is it possible to write this more "compactly"?

preguntado el 05 de mayo de 13 a las 12:05

this.Destination = destination; Solo necesita this when both attributes are the same case. Speaking of which, that attribute debemos be all lower case. Please learn common Convenciones de nomenclatura de Java (específicamente el caso utilizado para los nombres) para los nombres de clase, método y atributo y utilícelo de forma coherente. -

No. Also, it is atypical and confusing to begin member variables with a capital letter. -

I would write the { in the same line like the class/constructor/function. There you could save 3 lines. -

2 Respuestas

It is a good approach to nest constructors. Although it makes the code here only a bit shorter, it makes it mucho más más fácil de mantener.

public String destination;
public sender = "";
public uid = "";

public MessageBase(String destination){
    this.destination = destination;
}

public MessageBase(String destination, String uid){
    this(destination);
    this.uid= uid;
}

You should change the variable names to start with lower case letter.

I usually declare only one variable per line.

As @Jon Skeet have suggested, the constructor's chain can be reversed (less calls more). It is up to you what chain you want to use.

contestado el 05 de mayo de 13 a las 12:05

See my answer for an alternative approach, where the chaining goes de the single-parameter version a the multi-parameter version. - jon skeet

@Jon Skeet I've edited mine to add this option. What advantages do you find that way over mine? - Bob el Constructor

I explain that in my answer: it's . single place where all fields are specified, rather than trying to find it in multiple places, and it's obvious where the defaults are set. This is particularly important if you have several constructors, specifying different sets of fields. (Admittedly at that point you should consider redesigning the type anyway...) - jon skeet

@Jon Skeet I think your way is easier to understand, although finding defaults is harder I think (especially if its a global field declared somewhere else). I'll keep my answer for another opinion, and let OP decide. Thanx for your review! - Bob el Constructor

You should chain the constructors together: I regard it as a good idea to chain from a constructor with the menos parameters to one with todo especificado:

public abstract class MessageBase {
    private final String destination;
    private final String uid;
    private String sender;

    public MessageBase(String destination) {
        // Invoke the more parameterized constructor
        this(destination, "");
    }

    public MessageBase(String destination, String uid) {
        this.destination = destination;
        this.uid = uid;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    // etc
}

This way, all constructors end up going through a single "master" constructor, which is the only place which sets the fields. I find this easier to follow than the style of whoAmI's answer, where each constructor just sets some fields. It also makes it easier to see what the defaults are, as they're specified in the chaining constructor calls.

Also note that I've made the fields private as a matter of course (and named them according to Java naming conventions). I've also made the fields set in the constructor final - if you puede make your classes fully immutable, that's helpful when reasoning about them. For classes with many fields, you might want to consider using the builder pattern, where you set properties on a mutable builder, then build an immutable object from it.

contestado el 05 de mayo de 13 a las 12:05

I like your idea with the constructors. I don't believe I can make this class immutable as I am going to use a json library to convert it too and from json...for this reason aswell, I don't think I will use the builder pattern here. - Leopardo cazador

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.