Force every instance to have 2 attributes

Asked

Viewed 105 times

3

Hello, I have an Employee class with the attributes name, code and salary (all private), and a Manager class - which extends Employee - with the attribute quantityFunctionaries, also private.

How can I oblige every instance of Manager to have a value?

  • I don’t quite understand your question, but if Manager is Employee’s son, nome will also be a private Manager attribute.

2 answers

4

@Ana, in addition to using the constructor, validates the methods, so you create invariants for your class and impose rules for the states your class may be in. In other words, it is not enough to create a manager with a number of quantityFunctures It is important to ensure that this quantidaed is >= 0 (greater than or equal to zero) or even greater than zero.

Another important validation at the time of creation, is to make sure that users of your class will not define a name nulo or empty ""

public Gerente(String nome, int quantidadeFuncionarios) {
        if(nome == null || nome.isEmpty()){
            throw new IllegaArgumentException("Nome não pode ser vazio");
        }
        if(quantidadeFuncionarios < 0){
            throw new IllegalArgumentException("Quantidade funcionarios não opde ser inferior a zero");
        }
        this.setNome(nome); // herdando do funcionário
        this.quantidadeFuncionarios = quantidadeFuncionarios;
    }

The best way to really force your objects to be in a valid state is this.

Ch the documentation this exception: http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html

Consider making your objects immutable.

Another way to ensure the invariants of your class is to redesign it to be immutable.

There are some trade offs to be considered, check this tutorial: http://www.caelum.com.br/apostila-java-testes-xml-design-patterns/o-modelo-da-bolsa-de-valores-datas-e-objetos-imutaveis/

1


Just create a single builder in class Manager with the 2 parameters, this way it will not be possible to instantiate Manager without parameters.

Example:

Funcionario.java

public class Funcionario {
    private String nome;

    public Funcionario(String nome) {
        this.nome = nome;
    }    

    public void setNome(String nome) {
        this.nome = nome;
    }
}

Java manager.

public class Gerente extends Funcionario {
    private int quantidadeFuncionarios;

    public Gerente(String nome, int quantidadeFuncionarios) {
        super(nome); // construtor do funcionário
        if(nome == null || nome.isEmpty()){
            throw new IllegalArgumentException("Nome não pode ser vazio");
        }
        if(quantidadeFuncionarios < 0){
            throw new IllegalArgumentException("Quantidade funcionarios não opde ser inferior a zero");
        }
        this.quantidadeFuncionarios = quantidadeFuncionarios;
    }

    public int getQuantidadeFuncionarios() {
        return quantidadeFuncionarios;
    }

    public void setQuantidadeFuncionarios(int quantidadeFuncionarios) {
        this.quantidadeFuncionarios = quantidadeFuncionarios;
    }
}

I incremented the code above with the validations segeridas by Filipe Gonzaga Miranda.

Using

public static void main(String[] argv) {
    Gerente gerente = new Gerente("Ana", 3); /* sem parâmetros da erro */
    System.out.println(gerente.getNome() + " - " + gerente.getQuantidadeFuncionarios());
}

Exit

Ana - 3

  • First, thank you for helping :) I did exactly as you showed me, but on the first line of the constructor - this.setNome(name); - Netbeans displays the error "cannot find Symbol".

  • @Ana you created the get/set of the attribute nome in the employee class and is inheriting correctly?

  • @Ana updated my answer with the employee code, take a look.

  • I found the mistake here, thanks!

  • I really do not understand these people who raise competitiveness above information, even though my answer is not the best, it has met the need of the author of the question. Which need to be negative only for another answer stand out more being that copied the code of my answer including the comment.

  • 1

    Council: the name of the official should be immutable, and injected by the builder, without Setter.

  • @dcastro I updated the code and as it already marked as the correct one I added the validations that Filipe suggested.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.