+ 2

Constructor vs setters and getters

When using classes is there any advantage of using constructors to set values over setter and getter functions and also is there any advantage of using setters and getters over constructors?

19th Aug 2018, 9:12 PM
Sbusiso SGT😜
Sbusiso SGT😜 - avatar
5 ответов
+ 1
It's actually often better to use only constructor without setters because it makes object immutable, especially when it's value class. The problem with setters is that, in big programs, it's becomes hard to tell which part of your code changes what; if it's immutable, you can pass your objects wherever you want and you can be 100% sure they won't end up in invalid state. They are also almost a must if you want to multithread. There are some classes that should be mutable, but it's better in the long run to make what you can immutable.
21st Aug 2018, 6:41 AM
BlazingMagpie
BlazingMagpie - avatar
+ 3
If you know the set of values while instantiating the object of a class, use the constructor. There is no need to call the setter methods explicitly for each field to initialize it. You can also define default values for your fields within a constructor or do some other extra stuff. Use setters when you want to change the current value. What is more, if you want to initialize const fields, you must use a constructor and assign a value to a field using a member initialization list (that specific syntax, e.g. MyClass() : const_field(value) {}).
19th Aug 2018, 10:01 PM
Steppenwolf
Steppenwolf - avatar
+ 1
In my opinion, constructors can be used in replacement of setter method and vice versa but there are 2 scenarios 1- If you know about the values of your field members in advance, you can use constructor, otherwise 2- leave the constructor as default , and set the values of field members on run time using setter method.
20th Aug 2018, 5:44 AM
Ubaidullah Anwar 🇵🇰
Ubaidullah Anwar 🇵🇰 - avatar
+ 1
i like to create setters and getters even for values i have already set in the construcor, so later on in case when i realise that i actualy need to edit these values or get them from outside, i will already have myself a setter and a getter
20th Aug 2018, 1:14 PM
Data
Data - avatar
0
Data undoubtedly, it is worth creating both constructors and setters.
20th Aug 2018, 1:36 PM
Steppenwolf
Steppenwolf - avatar