RichardWarburton / java-8-lambdas-exercises

Exercises and Answers for Java 8 Lambdas book

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A point of confusion

Nuclear-Liu opened this issue · comments

Hi !

I am reading your book.
I am a little confused about the writing here.

src/main/java/com/insightfullogic/java8/examples/chapter1/Album.java

public Album(String name, List<Track> tracks, List<Artist> musicians) {
    Objects.requireNonNull(name);
    Objects.requireNonNull(tracks);
    Objects.requireNonNull(musicians);      
    this.name = name;
    this.tracks = new ArrayList<>(tracks);
    this.musicians = new ArrayList<>(musicians);
}

Is it correct to write like this:

public Album(String name, List&lt;Track&gt; tracks, List&lt;Artist&gt; musicians) {
    Objects.requireNonNull(name);
    Objects.requireNonNull(tracks);
    Objects.requireNonNull(musicians);      
    this.name = name;
    this.tracks = tracks;
    this.musicians = musicians;
}

or

public Album(String name, List&lt;Track&gt; tracks, List&lt;Artist&gt; musicians) {
    this.name = Objects.requireNonNull(name);
    this.tracks = Objects.requireNonNull(tracks);
    this.musicians = Objects.requireNonNull(musicians); 
}

In my opinion, the first way is more safe.
Validate then Set.
With the second way, we will have a problem if the second or third param is null however the first parameter still is changed.

Thank you very much for your answers

Hi, thanks for your question. So in the case of those choices there's no difference in safety really 99% of the time. In both cases an exception would be thrown if one of the fields is null and since the exception is being thrown from the object constructor then the object wouldn't be created. It doesn't really matter if another field has been initialised first as the object will be live past it's constructor.

There is one exception to that reasoning and that is if a reference to the newly created object is handed out in the constructor before validation is complete. For example if the first line of the constructor was AlbumStore.register(this);. In this case a reference to the object can leak before construction is complete and then whether or not the field was instantiated matters.