Builder without parameters is not working, is leaving the object as null [closed]

-3

I have a class with two constructors. The empty constructor (no arguments) is not working. The program does not display an error. One of the constructors receives the parameters nome and limitedecredito ; and another, empty, initializes CPF .

It turns out that the cpf (TCPF) field is getting the value NULL .

Client class constructor:

public Cliente():base()
{ 
}

Main Program:

(...)
case 1:
    Console.Clear();
    c1 = new Cliente();
    Console.Write("CPF:");
    CPF = Console.ReadLine();
    if (c1.setCPF(CPF) == false)
    {
        Console.WriteLine("CPF inválido");
        Console.ReadKey();
        break;
    }
    Console.Write("Nome:");
    string nome = Console.ReadLine();
    Console.Write("Limite de credito R$:");
    double limitecredito = double.Parse(Console.ReadLine());
    c1 = new Cliente(nome, limitecredito);
    LC.Add(c1);
    Console.Write("Cadastro realizado com sucesso");
    Console.ReadKey();
    break;
(...)

Class Cliente :

private double limitecredito;

public Cliente():base()
{ 
}

public Cliente(string n, double limitec) : base(n)
{
    limitecredito = limitec;
}

Class Pessoa (Mother):

private string nome;
private TCPF cpf;

public Pessoa()
{
    cpf = new TCPF();
}

public Pessoa(string n)
{
    cpf = new TCPF();
    nome = n;
}

public string Nome
{
    get { return nome; }
}

public bool setCPF(string X)
{
    return cpf.ValidaCpf(X);
}

public string Cpf
{
    get { return cpf.Cpf; }
}
    
asked by anonymous 07.05.2018 / 00:00

1 answer

1

If with such a simple flow it was possible to reach this complexity of this size, the fate of this program will certainly be the discard.

A problem is quite trivial, but the path you have chosen to go through is really painful.

About your question and the code you posted, there are several things going on, except what the title suggests:

  • At first you instantiate a client ( c1 = new Cliente(); ), receive the cpf and name, but after the user informs the credit limit you replace the previous instance of the client ( c1 = new Cliente(nome, limitecredito); );
  • Your method setCpf does not arrow the cpf. It validates. And if the ValidarCpf arrow he does not know who he is in this card game;
  • Its cpf ( TCPF ) is not null. It has an instance, but its properties are probably not initialized (we did not have access to the TCPF class to confirm);
  • In conclusion, the builders are working fine, but you're making a tremendous mess in programming logic and in using OO concepts. In this example implementation of your code , you can see that the instance is 'alive', but the value of the CPF itself is null. / p>

    This same program (considering its modeling and programming line) could be done in a slightly simpler way with less rewriting .

    I hope I have helped.

        
    07.05.2018 / 15:41