Principii SOLID în practică

Am fost întrebat mai deunăzi dacă pot îmbunătăți codul de mai jos:

class Tooltip
{
  protected $dataIsProcessed = false;

  public function __construct(array $data) {
    $this->data = $data;  
  }

  protected function processData() {
    if($this->dataIsProcessed) {
      return;
    }

    $this->dataIsProcessed = true;

    $this->data = array_merge([
      'title' => '',
      'body' => '',
      'meta' => ''
    ], $this->data);

    $this->data['body'] = stripslashes($this->data['body']);
    $this->data['title'] = do_some_stuff_with_the_title($this->data['title']);
    $this->data['meta'] = do_some_other_stuff_with_meta($this->data['meta']);
  }

  protected function getAttribute($attribute) {
    $this->processData();
    return $this->data[$attribute] ?? '';
  }

  public function style1() {
    return sprintf('<h2>%s</h2>',
      $this->getAttribute('title')
    );
  }

  public function style2() {
    printf('<h2>%s</h2><p>%s</p>',
      $this->getAttribute('body')
    );
  }

  public function style3() {
    return sprintf('<p>%s</p><div>%s</div>',
      $this->getAttribute('body'),
      $this->getAttribute('meta')
    );
  }
}


$tooltip = new Tooltip([
  'title' => 'Hello World!',
  'body' => 'Nice to meet you.',
  'meta' => 'Last update: last year'
])

echo $tooltip->style1();
echo $tooltip->style2();
echo $tooltip->style3();

Continuă să citești Principii SOLID în practică

windows apple dropbox facebook twitter