vendredi 11 octobre 2019

How to create a external builder for a class with private setters?

Is there some way of build a class from a external builder class without letting their setters public? I don't want to allow a invalid instance of a class to exist without the necessary validations.

The only way I found so far is creating a constructor with the required parameters and validations.

I made a example with few properties to be filled, but imagine a case with various.

    public class Computer
    {
        public string Motherboard { get; private set; }
        public string RamMemory { get; private set; }
        public string Cpu { get; private set; }

        public Computer(string motherboard, string ramMemory, string cpu)
        {
            ValidateMotherboard(motherboard);
            ValidateRamMemory(ramMemory);
            ValidateCpu(cpu);

            Motherboard = motherboard;
            RamMemory = ramMemory;
            Cpu = cpu;
        }

        private void ValidateMotherboard(string motherboard)
        {
            if (motherboard == null)
                throw new ArgumentNullException(nameof(motherboard));
        }

        private void ValidateRamMemory(string ramMemory)
        {
            if (ramMemory == null)
                throw new ArgumentNullException(nameof(ramMemory));
        }

        private void ValidateCpu(string cpu)
        {
            if (cpu == null)
                throw new ArgumentNullException(nameof(cpu));
            else if (!cpu.ToLower().Contains("ryzen"))
                throw new ArgumentException("Only AMD Ryzen CPU's is good enough.");
        }
    }

    public class ComputerBuilder
    {
        private string _motherboard;
        private string _ramMemory;
        private string _cpu;

        public ComputerBuilder SetMotherboard(string motherboard)
        {
            _motherboard = motherboard;
            return this;
        }

        public ComputerBuilder SetRamMemory(string ramMemory)
        {
            _ramMemory = ramMemory;
            return this;
        }

        public ComputerBuilder SetCpu(string cpu)
        {
            _cpu = cpu;
            return this;
        }

        public Computer Build() => new Computer(_motherboard, _ramMemory, _cpu);
    }

I just want to have builders that easies the construction of classes with too much parameters. Any ideias of how do this putting the validations on the builder without allow a invalid instance to exist?

Aucun commentaire:

Enregistrer un commentaire