14
My leader uses this pattern in ALL his classes (I’ll give the examples in C#, but it goes for any . NET language):
public class MeuTipo
{
private MeuTipo() { } // esconder o construtor
public static MeuTipo CriarMeuTipo()
{
MeuTipo meuTipo = new MeuTipo();
return meuTipo;
}
}
I really don’t understand why this is happening. Its classes are not even immutable (although I also do not think that there would be an advantage even if the class were immutable), so, besides this seems to me a pattern without much utility, it also prevents us from using constructors with properties, as for example... (I will use a supposed class Pessoa
)
new Pessoa { Nome = "João", Sobrenome = "Doe", (...) } // não é possível nesse padrão
Therefore, we are obliged to imagine all the scenarios in which a constructor would be possible. For example, supposing that on one occasion the Pessoa
can start without any data, or only with the first name, or with both names, we are obliged to do the class like this:
public class Pessoa {
private string _nome;
public string nome {
get { return this._nome; }
set { this._nome = value; }
}
private string _sobrenome;
public string sobrenome {
get { return this._sobrenome; }
set { this._sobrenome = value; }
}
private Pessoa() { }
public static Pessoa CriarPessoa() {
return CriarPessoa(null);
}
public static Pessoa CriarPessoa(string nome) {
return CriarPessoa(null, null);
}
public static Pessoa CriarPessoa(string nome, string sobrenome) {
Pessoa pessoa = new Pessoa();
pessoa.nome = nome;
pessoa.sobrenome = nome;
return pessoa;
}
}
While we could do so:
public class Pessoa {
public string Nome { get; set; }
public string Sobrenome { get; set; }
}
I really can’t understand why I go to so much trouble to lose a language resource, so I can’t help but think that there might be a reason for it. If there is a reason, be it Design Patterns or some kind of reason for legacy code, can anyone enlighten me?
Note: I NAY I want opinions here, because this is not a review site. I asked this question because I believe that some programmer longer than me, or who has worked with Object Orientation outside the . Give me an answer to why that would be an advantage.
By the way, my leader used Java in the past. So I think there is an answer certain to that question.
I was going to comment exactly on your last line. I saw this Pattern in Java programmers, but I don’t see the advantage in . net
– Gadonski