Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the better constructor? Empty or using fields?

Tags:

java

class

I am currently taking an Android class and when I got the first assignment grade, I lost points due to using an empty constructor rather than using one with fields. The professor said using fields is better. Is he correct? If so, why?

Is this better?

Photos pic = new Photos(path, title, author, date);

public Photos(String url_path, String title, String author,
        String date_taken) {
    super();

    this.url_path = url_path;
    this.title = title;
    this.author = author;
    this.date_taken = date_taken;
} 

Or this? Or does it matter?

 Photos pic = new Photos();
 pic.setUrl_path(path);
 pic.setTitle(title);
 pic.setAuthor(author);
 pic.setDate_taken(date);

 public Photos() {
    super();

 }
like image 856
WeVie Avatar asked Dec 12 '22 03:12

WeVie


1 Answers

Neither is "better", they simply do different things. Which one is subjectively "better" depends on what you want to achieve with that class. Consider this code for example:

Photos pic = new Photos();
pic.setUrl_path(path);
pic.setTitle(title);
pic.setAuthor(author);
pic.setDate_taken(date);

Immediately following that first line, is the pic object in a valid state? Does having no values set result in a meaningfully and contextually complete Photos object? If the answer is "no" and if the fields being set are necessary in order to have a valid Photos object, then they should be required by the constructor.

That is, the job of the constructor is to ensure that only a valid instance is created. Never assume that consuming code will follow up with setters, it might not. The job of ensuring valid state of the object is a responsibility that should be encapsulated within the object.

On the other hand, if a parameterless constructor can create a valid instance of Photos then it's perfectly acceptable to have a parameterless constructor. You can have both, so consuming code has the option of which to use depending on the state is wishes to create:

public Photos() {
    // set default values
}

public Photos(String url_path, String title, String author, String date_taken) {
    // set supplied values
}

It all depends on what a valid state of a Photos object can be and what is required (or not required) in order to achieve that state.

like image 65
David Avatar answered Dec 28 '22 06:12

David