Doubt about the responsibility of a get ()

14

Is it acceptable to have a getter method that gets a parameter to be able to have a return variance? Example:

getAllNome("M"); <- retorna tudo que for masculino.
getAllNome("F"); <- retorna tudo que for feminino.
getAllNome(); <- retorna todos os nome, não importa o sexo.
The getter responsibility is to return values, so using parameters for it can cause confusion?

Note: Many places I've studied about getters and setters say they should not get argument. Why not? Is not it simpler a getter that gets arguments to have different returns? When I say "acceptable" it is if I am making a mistake. Or running away from some pattern I do not know?

GET E SET

  

Get

     

Name an accessor method with get every time this method is   check some field or attribute of a class.

     

As this method will check for a value, it will always have a return   such as String, int, float, etc. But you will have no argument.

    
asked by anonymous 28.03.2014 / 21:12

3 answers

10

I do not know if this can be considered subjective or not, but there is evidence that the number of bugs in a program is proportional to the number of lines of code in that program. Regardless of language. More expressive languages / libraries (i.e. that do a lot with little code) tend to produce shorter codes, and therefore with fewer bugs.

And what does this have to do with the question? Simple: if you pass optional parameters serve to make your code more concise, then do it! Do not worry too much about the "purity" of the code: good practices are good not because "someone said they are", but because they solve / avoid a series of problems. But if you do not see any problem in an approach, there's no need to avoid it.

I do not like getters and setters . I do not like private attributes. But depending on the type of project and team, they may be necessary things (eg, numerous teams composed of inexperienced programmers, who are more likely to make mistakes). In this case, more important than following the X or Y pattern, it is important to follow a consistent pattern.

For example, jQuery has several functions that work as properties: html , text , attr , prop , css , data ... All of them work in the same way: no arguments, are a getter ; with an argument, are a setter (additional arguments may exist at the beginning). The name is short, you do not have to write the prefix ( getText vs. setText ) ... And most important: the same convention is used throughout the library, so no surprises!

In Java, there is a very rigid convention about the names of the methods and what they should do. Fleeing from this convention is problematic, as it forces those unfamiliar with your code to learn / decorate a new convention. However, getAllNome does not follow - as far as I know - no pre-established convention, so you can adopt yours. And even if it does follow, you need to weigh the pros and cons as discussed earlier.

Finally, consider transferring this responsibility to another class to make its use more consistent. Java unfortunately does not have first class functions (nor extension methods ), so it is necessary to do this through an auxiliary class. For example, if your function returns a List , create the interface / class:

interface ListaFiltravel<T> extends List<T> {
    public ListaFiltravel<T> filtrar(String variacao);
    public ListaFiltravel<T> filtrar(String variacao, boolean inPlace);
}

class ArrayListFiltravel<T> extends ArrayList<T> implements ListaFiltravel<T> {
    public ListaFiltravel<T> filtrar(String variacao) {
        return filtrar(variacao, false);
    }

    public ListaFiltravel<T> filtrar(String variacao, boolean inPlace) {
        // Código para filtrar
        // Retorne a própria lista filtrada (inPlace == true) ou uma outra lista
    }
}

And call your method as follows:

meuObjeto.getAllNome().filtrar("M")

In this way, the responsibilities are well separated. If this is something that you only have to do once, I still favor leaving the purity aside and putting the functionality into the getter itself.

But if it can be reused in various parts of your system, then that approach is better.)

    
28.03.2014 / 23:44
9

In my opinion there is a confusion about the concept of getters and setters as accessor methods, whose purpose is to ensure encapsulation by protecting the attributes of a class, and the proposed method example getAllNome("M"); that although it has a prefix get does not have the sole responsibility of exposing a property, thus avoiding the definition of what access methods are, such as a getNome() method.

If we want to retrieve the nome attribute of a set of a type, say Pessoa , as is the case of getAllNome("M"); , this method should not participate in the Pessoa class, but another class with that responsibility , which in turn would only access the names by get, or accessor method, getNome() as exposed by @mgibsonbr. However if the method needs to participate in the class, it could not be considered an accessor method.

Finally, although its necessity can be discussed, when we are talking about accessor methods, a get will never receive arguments and a set will receive one, and only one, argument, of the same type that is returned by the getter.

    
29.03.2014 / 14:22
5

Speaking of object orientation, there are reasons to use getters and setters.

Let's say a Product class that contains the Price property. This price is discounted and whenever we get this amount, we want you to have applied the discount. In this case, the private property guarantees that the price will not be obtained directly without the discount and implemented in get value reduction.

In your case, I imagine you are dealing with a person class. A (single) person has only one sex. Therefore, get will return this individual value. (Char)

In your suggested case, get works like a custom query. It would be an object method that contains multiple people and will return an array of Person objects that meet the parameters of your query. There are design patterns to implement this type of logic. The Repository pattern design provides exactly this kind of custom query: you implement a getAllPessoas (), which returns an array of all Person obejtos a getAllSexo (char sex), which returned an array of Person objects of that sex. Then from each of these Person objects you could call the function getNome () or another to get data from each.

Design Patterns, the book < a href="http://books.google.com.br/books?id=U91CYCqTCgkC&printsec=frontcover&dq=padr%C3%B5es%20de%20projeto&hl=en&sa=X&ei=hjs2U7OfK4XH0QGUkIAo& ved = 0CCoQ6AEwAA # v = onepage & q =% C3% standard B5es% 20of% 20projeto & f = false "> Design Patterns: Reusable Solutions , and Agile Principles, Practices and patterns in C # . They are the classic patterns, but there are many others, like the Repository, which is not in this book. The standards help a lot to understand the Object Guidance application.

    
29.03.2014 / 04:26