S
S
Serge Tkach2017-03-10 15:42:25
PHP
Serge Tkach, 2017-03-10 15:42:25

How much more workload does it actually increase if you write code that breaks everything into separate actions?

I appeal to senior comrades who understand all the intricacies of programming at the hardware level.
It's not very clear to me how really critical it can be to break all the actions into separate ones.
=== Option 1 ===
All actions are separated from each other
Easy to read
Easy to debug, since you can always just take and print $price to the screen
But to execute the script (especially if there are a lot of such places), more memory is required

foreach ($this->cart->getProducts() as $product) {
              $price = get_product_price_without_sale($product['product_id']); // Значение получено заранее. Оно хранится в памяти и занимает лишнее место
              $data_deal['products'][] = array(
                    'name'     => htmlspecialchars($product['name']),
                    'count' => $product['quantity'],
                    'price'    => $this->currency->format($price, $order_info['currency_code'], $order_info['currency_value'], false)
                );
            }

=== Option 2 ===
Harder to read
For debugging, we need to copy the construction more carefully, which will show what we get there
Memory does not deal with intermediate variables
foreach ($this->cart->getProducts() as $product) {
              $data_deal['products'][] = array(
                    'name'     => htmlspecialchars($product['name']),
                    'count' => $product['quantity'],

                    'price'    => $this->currency->format(get_product_price_without_sale($product['product_id']), $order_info['currency_code'], $order_info['currency_value'], false)
                );
            }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Saboteur, 2017-03-10
@saboteur_kiev

When you write something, the load should be considered not only on the hardware, but also on the developer.
In the vast majority of cases, development and support are tasks that scale much harder than hardware.
In the vast majority of cases, the iron does not even have to be scaled - it just suffices.
Therefore, in the vast majority of cases, code readability is more important than performance.
And where performance is important - it will always be possible to do performance analysis, identify a bottleneck and do refactoring - and with a readable code, this will be much easier to do.

F
Falseclock, 2017-03-10
@Falseclock

You are thinking in the right direction.... but still far from perfect.
each action should be done in one method (functions for PHP)
Your code should repeat the logic of the algorithm or block diagram, and where variables are present, put everything into class variables if possible..

<?php
// хендлер реализаций
class WaybillHandler
{
  protected $debug	= true;

  protected $db		= null;
  protected $socket	= array();
  protected $structure= array();
  protected $doc		= null;
  protected $crmData	= array();
  
  public function __construct($waybill)
  {
    $this->db = DBPool::me()->getLink();
    $this->doc = $waybill;
    
    self::Handler();
  }
  
  private function Handler()
  {
    $db = $this->db;
    
    // Если реализация не привязана к счету, то ничего не делаем
    if ($this->doc['ДокументОснование']['#type'] != 'jcfg:DocumentRef.СчетНаОплатуПокупателю') {
      return;
    }
    
    $this->structure = Utils1c::prepareStructure($this->doc,'waybill');
    
    // Усли реализация поставлена на удаление, то автоматически будет отменена проводка
    // либо мы вручную убрали проводку, а значит мы должны удалить запись из CRM
    if ($this->doc['Posted'] == false) {
      $this->structure['debug'][] = "Реализация не проведена, делаем попытку удаление данных"." (".__LINE__.")";
      self::deleteWaybillFromCRM();
    } else {
      if (self::isRelatedToOurInvoice()) {
        self::findDataFromCRMforWaybill();
        if (count($this->crmData)) {
          self::deleteWaybillDataOnDeleteInERP();
          self::insertMissingWaybillDataToERP();
          self::compareWaybillDataBetweenCRMandERP();
        } else {
          self::insertWaybillDataOnNewRowInERP();
        }
        self::updateStructureFinally();
      } else {
        $this->structure['debug'][] = "Мы не нашли связь между этой реализацией и счетами в CRM"." (".__LINE__.")";
      }
    }
    if (!$this->debug) {
      $this->structure['debug'] = array();
    }
    $this->socket[] = Driver1c::SOCKET_MARKER.json_encode($this->structure, JSON_UNESCAPED_UNICODE);
    
    new WebSocketClient($this->socket);
    
    return;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question