I wouldn’t recommend the set
and yes the use of builders in your case.
In OOP, it is usually clearer to use small classes and start objects through their constructors. Use set
for all fields leaves the object open to any kind of change of values at any time, which is normally not what is desired.
Beginning with Juridica
, she could have the following fields in her builder:
nome, endereco, bairro, cep, cidade, estado, cnpj, tipo
And Fisica
:
nome, endereco, bairro, cep, cidade, estado, rg, cpf
However, we can improve this, because we still have many parameters instead of many methods set
. As I said earlier, using smaller objects, with greater meaning, facilitates understanding.
Therefore, I would create 4 more classes: Endereco
, Cpf
, Rg
, and Cnpj
. Each with the following fields in their builders:
- Addressee:
endereco, bairro, cep, cidade, estado
- Cpf:
numero
- Rg:
numero
- Cnpj:
numero, tipo
See that now you have a more organized representation of the information that Fisica
and Juridica
receive.
Thus, the class Juridica
would receive in your builder:
nome, Endereco, Cnpj
And in the Fisica
:
nome, Endereco, Cpf, Rg
What is this
set
he looks really weird. Theget
also a little, can explain better, mainly what return.– Maniero
the set method is to register the name, address, etc... the get will return the values.
– Cleriston Martins Cardoso
@Shouldn’t this be the constructor? The get/set methods are usually related to only one field of the class.
– Woss
That doesn’t make sense.
– Maniero
Instead of the set, use the class constructor by passing the parameters. Another option is to search for a Pattern design called
Builder
, that serves for cases where your object has many fields. Here have an example.– StatelessDev
Thank you all, I will follow the recommendation of the builder and I will read about the design Pattern Builder.
– Cleriston Martins Cardoso
@Cleristonmartinscardoso Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.
– Maniero