Why do we need to use the builder design pattern when we can do the same thing with setters? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!When would you use the Builder Pattern?On design patterns: When should I use the singleton?When would you use the Builder Pattern?What is the difference between Builder Design pattern and Factory Design pattern?Wrong ordering in generated table in jpaHow to deserialize a list using GSON or another JSON library in Java?org.springframework.orm.hibernate3.HibernateQueryException - HibernateTemplateOGNL setValue target is nullLombok javafx propertiesHibernate : Why FetchType.LAZY-annotated collection property eagerly loading?How to implement parcelable with my custom class containing Hashmap and SparseArray?
Is it possible for SQL statements to execute concurrently within a single session in SQL Server?
Did Krishna say in Bhagavad Gita "I am in every living being"
Why do we bend a book to keep it straight?
Denied boarding although I have proper visa and documentation. To whom should I make a complaint?
How fail-safe is nr as stop bytes?
Central Vacuuming: Is it worth it, and how does it compare to normal vacuuming?
Generate an RGB colour grid
Why is my ESD wriststrap failing with nitrile gloves on?
Converted a Scalar function to a TVF function for parallel execution-Still running in Serial mode
Find 108 by using 3,4,6
Performance gap between vector<bool> and array
Disembodied hand growing fangs
Illegal assignment from sObject to Id
What would you call this weird metallic apparatus that allows you to lift people?
Maximum summed subsequences with non-adjacent items
Did Deadpool rescue all of the X-Force?
Can the Great Weapon Master feat's damage bonus and accuracy penalty apply to attacks from the Spiritual Weapon spell?
What is the topology associated with the algebras for the ultrafilter monad?
What initially awakened the Balrog?
Question about debouncing - delay of state change
Localisation of Category
How to write the following sign?
Significance of Cersei's obsession with elephants?
Take 2! Is this homebrew Lady of Pain warlock patron balanced?
Why do we need to use the builder design pattern when we can do the same thing with setters?
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!When would you use the Builder Pattern?On design patterns: When should I use the singleton?When would you use the Builder Pattern?What is the difference between Builder Design pattern and Factory Design pattern?Wrong ordering in generated table in jpaHow to deserialize a list using GSON or another JSON library in Java?org.springframework.orm.hibernate3.HibernateQueryException - HibernateTemplateOGNL setValue target is nullLombok javafx propertiesHibernate : Why FetchType.LAZY-annotated collection property eagerly loading?How to implement parcelable with my custom class containing Hashmap and SparseArray?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
public class Employee
private String name;
private String address;
private int id;
public Employee()
// TODO Auto-generated constructor stub
@Override
public String toString()
return "Employee [name=" + name + ", address=" + address + ", id=" + id + "]";
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getAddress()
return address;
public void setAddress(String address)
this.address = address;
public int getId()
return id;
public void setId(int id)
this.id = id;
public class Main
public static void main(String[] args)
Employee e = new Employee();
e.setName("Priyanka");
Employee e1 = new Employee();
e1.setName("Rahul");
e1.setAddress("Delhi");
System.out.println("Value of e :"+ e);
System.out.println("Value of e1:"+ e1);
java design-patterns
add a comment |
public class Employee
private String name;
private String address;
private int id;
public Employee()
// TODO Auto-generated constructor stub
@Override
public String toString()
return "Employee [name=" + name + ", address=" + address + ", id=" + id + "]";
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getAddress()
return address;
public void setAddress(String address)
this.address = address;
public int getId()
return id;
public void setId(int id)
this.id = id;
public class Main
public static void main(String[] args)
Employee e = new Employee();
e.setName("Priyanka");
Employee e1 = new Employee();
e1.setName("Rahul");
e1.setAddress("Delhi");
System.out.println("Value of e :"+ e);
System.out.println("Value of e1:"+ e1);
java design-patterns
1
Possible duplicate of When would you use the Builder Pattern?
– jaco0646
3 hours ago
add a comment |
public class Employee
private String name;
private String address;
private int id;
public Employee()
// TODO Auto-generated constructor stub
@Override
public String toString()
return "Employee [name=" + name + ", address=" + address + ", id=" + id + "]";
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getAddress()
return address;
public void setAddress(String address)
this.address = address;
public int getId()
return id;
public void setId(int id)
this.id = id;
public class Main
public static void main(String[] args)
Employee e = new Employee();
e.setName("Priyanka");
Employee e1 = new Employee();
e1.setName("Rahul");
e1.setAddress("Delhi");
System.out.println("Value of e :"+ e);
System.out.println("Value of e1:"+ e1);
java design-patterns
public class Employee
private String name;
private String address;
private int id;
public Employee()
// TODO Auto-generated constructor stub
@Override
public String toString()
return "Employee [name=" + name + ", address=" + address + ", id=" + id + "]";
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getAddress()
return address;
public void setAddress(String address)
this.address = address;
public int getId()
return id;
public void setId(int id)
this.id = id;
public class Main
public static void main(String[] args)
Employee e = new Employee();
e.setName("Priyanka");
Employee e1 = new Employee();
e1.setName("Rahul");
e1.setAddress("Delhi");
System.out.println("Value of e :"+ e);
System.out.println("Value of e1:"+ e1);
java design-patterns
java design-patterns
edited 6 hours ago
Boann
37.5k1291123
37.5k1291123
asked 10 hours ago
Priyanka TanejaPriyanka Taneja
87119
87119
1
Possible duplicate of When would you use the Builder Pattern?
– jaco0646
3 hours ago
add a comment |
1
Possible duplicate of When would you use the Builder Pattern?
– jaco0646
3 hours ago
1
1
Possible duplicate of When would you use the Builder Pattern?
– jaco0646
3 hours ago
Possible duplicate of When would you use the Builder Pattern?
– jaco0646
3 hours ago
add a comment |
3 Answers
3
active
oldest
votes
The builder pattern can be useful to:
- apply some check on the data used to initialize the object. For example if you need a double check between variables
- create immutable objects. You can't change an object once initialized, so you can't use setters
- add readability of code.
- reduce the code used to initialize the object
- have the instance in a valid state. Using setters the object instance can be in a not valid state before all the setters are called.
Note on using the builder to create immutable objects.
When you work in a multithread environment an immutable object can be shared between threads without explicit synchronization. Because the object can't change during the time is not possible to have a race condition accessing and modifying it by two threads at the same time.
Also it makes it so you don't need a temp variable
– mackycheese21
4 hours ago
add a comment |
There is no need to use any pattern. You can even avoid setters with making the variables public. However,
the intent of the Builder design pattern is to separate the
construction of a complex object from its representation
Source: https://en.wikipedia.org/wiki/Builder_pattern
... and this is easier to use, as most Builder's methods return a reference tothis
to allow chaining of call. One could write:Employee jonSkeet = new Employee.Builder().withName("Jon").withLastname("Skeet").withSalary(1_000_000).build()
– spi
10 hours ago
@spi It makes code so much more easy to read and debug. Is this the only reason to use builder design pattern?
– Priyanka Taneja
10 hours ago
@PriyankaTaneja the only one no... You can also build several "Jon Skeet" just callingbuild()
several times. Again, this may seem a minor advantage, but these little things put together makes a great difference between easy code and spaghetti code.
– spi
10 hours ago
Imagine that you had a main constructor with 10 arguments (a bad idea to start) and the fields were set with defaults. Instead of having multiple constructors for setting only certain values, you can use the Builder design pattern to set various values without confusion, while retaining the defaults for the other values.
– jim829
10 hours ago
add a comment |
Using a builder pattern has a few advantages:
Unlike with setters (which make your class mutable), a builder can be used to contruct immutable objects. In many cases immutable objects are preferred over mutable objects, because they are easier to understand and maintain, and because they avoid the need for locking in multithreaded environments.
A builder can make sure that the object satisfies some invariants even directly after construction. For example, if your class has a
name
field which must never benull
, the builder can check this condition and fail to construct the object when not satisfied.
Both things you can also accomplish by using a constructor which takes all the class contents as parameters, but that will be quite unreadable when your class has more than a few fields to initialize.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55748815%2fwhy-do-we-need-to-use-the-builder-design-pattern-when-we-can-do-the-same-thing-w%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
The builder pattern can be useful to:
- apply some check on the data used to initialize the object. For example if you need a double check between variables
- create immutable objects. You can't change an object once initialized, so you can't use setters
- add readability of code.
- reduce the code used to initialize the object
- have the instance in a valid state. Using setters the object instance can be in a not valid state before all the setters are called.
Note on using the builder to create immutable objects.
When you work in a multithread environment an immutable object can be shared between threads without explicit synchronization. Because the object can't change during the time is not possible to have a race condition accessing and modifying it by two threads at the same time.
Also it makes it so you don't need a temp variable
– mackycheese21
4 hours ago
add a comment |
The builder pattern can be useful to:
- apply some check on the data used to initialize the object. For example if you need a double check between variables
- create immutable objects. You can't change an object once initialized, so you can't use setters
- add readability of code.
- reduce the code used to initialize the object
- have the instance in a valid state. Using setters the object instance can be in a not valid state before all the setters are called.
Note on using the builder to create immutable objects.
When you work in a multithread environment an immutable object can be shared between threads without explicit synchronization. Because the object can't change during the time is not possible to have a race condition accessing and modifying it by two threads at the same time.
Also it makes it so you don't need a temp variable
– mackycheese21
4 hours ago
add a comment |
The builder pattern can be useful to:
- apply some check on the data used to initialize the object. For example if you need a double check between variables
- create immutable objects. You can't change an object once initialized, so you can't use setters
- add readability of code.
- reduce the code used to initialize the object
- have the instance in a valid state. Using setters the object instance can be in a not valid state before all the setters are called.
Note on using the builder to create immutable objects.
When you work in a multithread environment an immutable object can be shared between threads without explicit synchronization. Because the object can't change during the time is not possible to have a race condition accessing and modifying it by two threads at the same time.
The builder pattern can be useful to:
- apply some check on the data used to initialize the object. For example if you need a double check between variables
- create immutable objects. You can't change an object once initialized, so you can't use setters
- add readability of code.
- reduce the code used to initialize the object
- have the instance in a valid state. Using setters the object instance can be in a not valid state before all the setters are called.
Note on using the builder to create immutable objects.
When you work in a multithread environment an immutable object can be shared between threads without explicit synchronization. Because the object can't change during the time is not possible to have a race condition accessing and modifying it by two threads at the same time.
edited 10 hours ago
answered 10 hours ago
Davide Lorenzo MARINODavide Lorenzo MARINO
19.5k22140
19.5k22140
Also it makes it so you don't need a temp variable
– mackycheese21
4 hours ago
add a comment |
Also it makes it so you don't need a temp variable
– mackycheese21
4 hours ago
Also it makes it so you don't need a temp variable
– mackycheese21
4 hours ago
Also it makes it so you don't need a temp variable
– mackycheese21
4 hours ago
add a comment |
There is no need to use any pattern. You can even avoid setters with making the variables public. However,
the intent of the Builder design pattern is to separate the
construction of a complex object from its representation
Source: https://en.wikipedia.org/wiki/Builder_pattern
... and this is easier to use, as most Builder's methods return a reference tothis
to allow chaining of call. One could write:Employee jonSkeet = new Employee.Builder().withName("Jon").withLastname("Skeet").withSalary(1_000_000).build()
– spi
10 hours ago
@spi It makes code so much more easy to read and debug. Is this the only reason to use builder design pattern?
– Priyanka Taneja
10 hours ago
@PriyankaTaneja the only one no... You can also build several "Jon Skeet" just callingbuild()
several times. Again, this may seem a minor advantage, but these little things put together makes a great difference between easy code and spaghetti code.
– spi
10 hours ago
Imagine that you had a main constructor with 10 arguments (a bad idea to start) and the fields were set with defaults. Instead of having multiple constructors for setting only certain values, you can use the Builder design pattern to set various values without confusion, while retaining the defaults for the other values.
– jim829
10 hours ago
add a comment |
There is no need to use any pattern. You can even avoid setters with making the variables public. However,
the intent of the Builder design pattern is to separate the
construction of a complex object from its representation
Source: https://en.wikipedia.org/wiki/Builder_pattern
... and this is easier to use, as most Builder's methods return a reference tothis
to allow chaining of call. One could write:Employee jonSkeet = new Employee.Builder().withName("Jon").withLastname("Skeet").withSalary(1_000_000).build()
– spi
10 hours ago
@spi It makes code so much more easy to read and debug. Is this the only reason to use builder design pattern?
– Priyanka Taneja
10 hours ago
@PriyankaTaneja the only one no... You can also build several "Jon Skeet" just callingbuild()
several times. Again, this may seem a minor advantage, but these little things put together makes a great difference between easy code and spaghetti code.
– spi
10 hours ago
Imagine that you had a main constructor with 10 arguments (a bad idea to start) and the fields were set with defaults. Instead of having multiple constructors for setting only certain values, you can use the Builder design pattern to set various values without confusion, while retaining the defaults for the other values.
– jim829
10 hours ago
add a comment |
There is no need to use any pattern. You can even avoid setters with making the variables public. However,
the intent of the Builder design pattern is to separate the
construction of a complex object from its representation
Source: https://en.wikipedia.org/wiki/Builder_pattern
There is no need to use any pattern. You can even avoid setters with making the variables public. However,
the intent of the Builder design pattern is to separate the
construction of a complex object from its representation
Source: https://en.wikipedia.org/wiki/Builder_pattern
answered 10 hours ago
maio290maio290
2,232616
2,232616
... and this is easier to use, as most Builder's methods return a reference tothis
to allow chaining of call. One could write:Employee jonSkeet = new Employee.Builder().withName("Jon").withLastname("Skeet").withSalary(1_000_000).build()
– spi
10 hours ago
@spi It makes code so much more easy to read and debug. Is this the only reason to use builder design pattern?
– Priyanka Taneja
10 hours ago
@PriyankaTaneja the only one no... You can also build several "Jon Skeet" just callingbuild()
several times. Again, this may seem a minor advantage, but these little things put together makes a great difference between easy code and spaghetti code.
– spi
10 hours ago
Imagine that you had a main constructor with 10 arguments (a bad idea to start) and the fields were set with defaults. Instead of having multiple constructors for setting only certain values, you can use the Builder design pattern to set various values without confusion, while retaining the defaults for the other values.
– jim829
10 hours ago
add a comment |
... and this is easier to use, as most Builder's methods return a reference tothis
to allow chaining of call. One could write:Employee jonSkeet = new Employee.Builder().withName("Jon").withLastname("Skeet").withSalary(1_000_000).build()
– spi
10 hours ago
@spi It makes code so much more easy to read and debug. Is this the only reason to use builder design pattern?
– Priyanka Taneja
10 hours ago
@PriyankaTaneja the only one no... You can also build several "Jon Skeet" just callingbuild()
several times. Again, this may seem a minor advantage, but these little things put together makes a great difference between easy code and spaghetti code.
– spi
10 hours ago
Imagine that you had a main constructor with 10 arguments (a bad idea to start) and the fields were set with defaults. Instead of having multiple constructors for setting only certain values, you can use the Builder design pattern to set various values without confusion, while retaining the defaults for the other values.
– jim829
10 hours ago
... and this is easier to use, as most Builder's methods return a reference to
this
to allow chaining of call. One could write: Employee jonSkeet = new Employee.Builder().withName("Jon").withLastname("Skeet").withSalary(1_000_000).build()
– spi
10 hours ago
... and this is easier to use, as most Builder's methods return a reference to
this
to allow chaining of call. One could write: Employee jonSkeet = new Employee.Builder().withName("Jon").withLastname("Skeet").withSalary(1_000_000).build()
– spi
10 hours ago
@spi It makes code so much more easy to read and debug. Is this the only reason to use builder design pattern?
– Priyanka Taneja
10 hours ago
@spi It makes code so much more easy to read and debug. Is this the only reason to use builder design pattern?
– Priyanka Taneja
10 hours ago
@PriyankaTaneja the only one no... You can also build several "Jon Skeet" just calling
build()
several times. Again, this may seem a minor advantage, but these little things put together makes a great difference between easy code and spaghetti code.– spi
10 hours ago
@PriyankaTaneja the only one no... You can also build several "Jon Skeet" just calling
build()
several times. Again, this may seem a minor advantage, but these little things put together makes a great difference between easy code and spaghetti code.– spi
10 hours ago
Imagine that you had a main constructor with 10 arguments (a bad idea to start) and the fields were set with defaults. Instead of having multiple constructors for setting only certain values, you can use the Builder design pattern to set various values without confusion, while retaining the defaults for the other values.
– jim829
10 hours ago
Imagine that you had a main constructor with 10 arguments (a bad idea to start) and the fields were set with defaults. Instead of having multiple constructors for setting only certain values, you can use the Builder design pattern to set various values without confusion, while retaining the defaults for the other values.
– jim829
10 hours ago
add a comment |
Using a builder pattern has a few advantages:
Unlike with setters (which make your class mutable), a builder can be used to contruct immutable objects. In many cases immutable objects are preferred over mutable objects, because they are easier to understand and maintain, and because they avoid the need for locking in multithreaded environments.
A builder can make sure that the object satisfies some invariants even directly after construction. For example, if your class has a
name
field which must never benull
, the builder can check this condition and fail to construct the object when not satisfied.
Both things you can also accomplish by using a constructor which takes all the class contents as parameters, but that will be quite unreadable when your class has more than a few fields to initialize.
add a comment |
Using a builder pattern has a few advantages:
Unlike with setters (which make your class mutable), a builder can be used to contruct immutable objects. In many cases immutable objects are preferred over mutable objects, because they are easier to understand and maintain, and because they avoid the need for locking in multithreaded environments.
A builder can make sure that the object satisfies some invariants even directly after construction. For example, if your class has a
name
field which must never benull
, the builder can check this condition and fail to construct the object when not satisfied.
Both things you can also accomplish by using a constructor which takes all the class contents as parameters, but that will be quite unreadable when your class has more than a few fields to initialize.
add a comment |
Using a builder pattern has a few advantages:
Unlike with setters (which make your class mutable), a builder can be used to contruct immutable objects. In many cases immutable objects are preferred over mutable objects, because they are easier to understand and maintain, and because they avoid the need for locking in multithreaded environments.
A builder can make sure that the object satisfies some invariants even directly after construction. For example, if your class has a
name
field which must never benull
, the builder can check this condition and fail to construct the object when not satisfied.
Both things you can also accomplish by using a constructor which takes all the class contents as parameters, but that will be quite unreadable when your class has more than a few fields to initialize.
Using a builder pattern has a few advantages:
Unlike with setters (which make your class mutable), a builder can be used to contruct immutable objects. In many cases immutable objects are preferred over mutable objects, because they are easier to understand and maintain, and because they avoid the need for locking in multithreaded environments.
A builder can make sure that the object satisfies some invariants even directly after construction. For example, if your class has a
name
field which must never benull
, the builder can check this condition and fail to construct the object when not satisfied.
Both things you can also accomplish by using a constructor which takes all the class contents as parameters, but that will be quite unreadable when your class has more than a few fields to initialize.
answered 10 hours ago
HoopjeHoopje
10.3k52644
10.3k52644
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55748815%2fwhy-do-we-need-to-use-the-builder-design-pattern-when-we-can-do-the-same-thing-w%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Possible duplicate of When would you use the Builder Pattern?
– jaco0646
3 hours ago