Meaning of Leaky Abstraction?

后端 未结 11 1122
面向向阳花
面向向阳花 2020-12-23 02:33

What does the term \"Leaky Abstraction\" mean? (Please explain with examples. I often have a hard time grokking a mere theory.)

11条回答
  •  渐次进展
    2020-12-23 03:24

    Leaky abstraction is all about encapsulating state. very simple example of leaky abstraction:

    $currentTime = new DateTime();
    
    $bankAccount1->setLastRefresh($currentTime);
    $bankAccount2->setLastRefresh($currentTime);
    $currentTime->setTimestamp($aTimestamp);
    
    class BankAccount {
        // ...
    
        public function setLastRefresh(DateTimeImmutable $lastRefresh)
        {
            $this->lastRefresh = $lastRefresh;
        } }
    

    and the right way(not leaky abstraction):

    class BankAccount
    {
        // ...
    
        public function setLastRefresh(DateTime $lastRefresh)
        {
            $this->lastRefresh = clone $lastRefresh;
        }
    }
    

    more description here.

提交回复
热议问题