What is the best way to leverage bank data for functions related to retrieved content?

1

When I need to use database information for more than one task, what is the best solution for object orientation (eg list the products in a cart and perform calculations):

1 - Create a single method that already does everything (1 bank access and 1 while)

// recupera a lista de produtos do banco
$lista_produtos = $carrinho->listar_produtos();

// percorre os produtos e realiza as tarefas necessarias
while($carrinho_produto = $lista_produtos)
{
    $valor_produto = $carrinho_produto ->valor * $carrinho_produto ->quantidade;

    $valor_frete += $valor_produto * $fator_frete;'insira o código aqui'

    $valor_total += $valor_produto;
}

2 - Create 3 methods and list the products in each of them, consequently making more access to the bank (1 access to the bank by method and multiple while).

$carrinho->calcular_preco();
$carrinho->calcular_frete();
$carrinho->calcular_valor_total();

3 - Retrieve the list of products from the database, store in a vector, pass the vector in all methods (1 access to the database and multiple while)

$vetor_produtos = $carrinho->listar_produtos();
$carrinho->calcular_preco( $vetor_produtos );
$carrinho->calcular_frete( $vetor_produtos );
$carrinho->calcular_valor_total( $vetor_produtos );
    
asked by anonymous 04.07.2016 / 04:15

1 answer

0

Math,

The best option among the ones you have listed is the third one from the performance point of view (queries in the database are costly for performance), maintainability (each function executes a task, if an error occurs it will be clear from where it comes from and so it will be easier to fix) and from the standpoint of style too, considering that your code is much more readable.

It's also important to think about whether these products will be changed by a single instance of your application, otherwise you may be working with information without having to query the database, possibly working with a copy of the data that is not updated.

I hope I have helped.

    
04.07.2016 / 04:28