Responsibility to keep information of items in a class

-2

Here's an issue that I need to resolve urgently:

Consider the code Venda.java .

Unassign to maintain information about items sold in class Venda , creating a new class ItemDeVenda .

import java.util.ArrayList;
import java.util.List;


public class Venda {

    private List<Double> itemValores = new ArrayList<Double>();
    private List<Double> itemQuantidades = new ArrayList<Double>();

    public double total() {
        double soma = 0;
        for (int i = 0; i < itemValores.size(); i++) {
            soma += itemValores.get(i) * itemQuantidades.get(i);
        }
        return soma;
    }

    public void adicionarItem(double valor) {
        itemValores.add(valor);
        itemQuantidades.add(1.0);
    }

    public void adicionarItem(double valor, double quantidade) {
        itemValores.add(valor);
        itemQuantidades.add(quantidade);
    }

}
    
asked by anonymous 23.11.2015 / 20:14

1 answer

3
  •   

    Question : What's in an item sold?

      

    Response: Value and quantity.

    Then you create a ItemDeVenda class with the value and quantity, which are double s.

  •   

    Question : What exactly represents the class Venda ?

      

    Answer: A list of items sold.

    So you replace the two List<Double> with a single List<ItemDeVenda> .

  •   

    Question : After putting List<ItemDeVenda> , adicionarItem methods do not compile anymore. And now?

      

    Answer: Change the methods for an instance of ItemDeVenda to be created and then add this instance to the list.

  •   

    Question : And the method total ?

      

    Answer: Create a getter getTotal() in class ItemDeVenda that multiplies the value by quantity. Then in the method total() of class Venda , you only scroll through the list elements by adding the totals of each.

  •   

    Question: And the responsibilities?

      

    Response: In making the above changes, you will have the values for an item of sale as well as the methods that operate on each item separated into its own class, while the Venda class % refers only to a list of sales items with the methods that operate on that list. As a result, the Venda class does not need to know the details of the operation of the sale items and the details of each item of the sale need not know the whole concept of the sale as a whole. The name of this is concept separation .

         

    One direct advantage you gain from this is to keep values and quantities together within the same object, rather than being separated into different lists. In addition, it is much easier to add new fields of sales items if necessary in the future (eg a field to tell if the item has been reversed or returned after purchase) because they will all be together rather than kept on separate lists .

  • 23.11.2015 / 22:21