How to reduce constructor overload code

In my one class, I have many such constructors.

public MyData(int position,String songName,String duration, boolean e) {

    //initialization of above variable like int, string,string and boolean

}

public MyData(String songName, String artistName, String duration,String downloadPath, String songSize, String albumName,String url,String trackId, boolean e) 
{
 //initialization of above variable like String,String,String,String,String,String,String,String and boolean

}

and a few more, as indicated above. Now the call time, I call this constructor only that I need data. but I don’t think my thread is good, so I need help to reduce my code and also create a good thread. If anyone has a good stream to achieve this, then please share.

Thanks in advance.

+1
source share
2 answers

Assuming you are effectively applying defaults, the usually best approach is to have one "full" constructor and force others to call it. For instance:

public Foo(String name)
{
    // Default the description to null
    this(name, null);
}

public Foo(String name, String description)
{
    this.name = name;
    this.description = description;
}

, "" - . , , - . , .

- " ", , - , . , . , , :

FooParameters parameters = new FooParameters()
    .setName("some name")
    .setDescription("some description");

// Either a constructor call at the end, or give FooParameters
// a build() or create() method
Foo foo = new Foo(parameters);

, , , - , , . Java ProcessBuilder, , , , , , : (

- , (build, create, start, ), . .

Java ,

Foo foo = new Foo.Builder().setName(...).setDescription(...).build();

, Foo.

+5

, , . , :

public class SongBuilder {
    private String artistName;
    private String songTitle;
    /* ... everything else ... */

    public SongBuilder setArtistName(String name) {
        this.artistName = name;
        return this;
    }
    public SongBuilder setSongTitle(String title) {
        this.songTitle = title;
        return this;
    }
    /* ... everything else ... */

    public Song create() {
         return new Song(artistName, songTitle, /* ... everything else ... */);
    }
}

Song, . Song,

 Song s = new SongBuilder().setSongTitle("Still Alive").setArtistName("GLaDOS").create();

, , set , . .

, , , . , n , 2 n , , .

, !

+3

All Articles