SlideShare una empresa de Scribd logo
1 de 61
Descargar para leer sin conexión
SOLID Principles
Hubert (@yhchan)
關於我
• Hubert (@yhchan)
• 趨勢科技
• Python Programmer
• http://blog.hubert.tw
好的程式碼?
• Readability
• Maintainability
• Reusability
Code Quality
完美的程式碼
Big Design Up Front
完美 v.s. 夠好
⼀一次做好 v.s 改得動
原本今天要說
Design Pattern
⽐比 Design Pattern
更重要的事情
• Maintainability
• Principles
• Refactoring
• Unit Testing
• Testability
據說只能講 30 分鐘
講完天都⿊黑了...
SOLID Principles
• Single Responsibility Principle (SRP)
• Open-Closed Principle (OCP)
• Liskov substitution principle (LSP)
• Interface segregation principle (ISP)
• Dependency inversion principle (DIP)
Single Responsibility
Principle
• 每個 Class 只有「⼀一個」職責
• 如果需要修改,只能因為這個職責⽽而修改
三個權責
class Employee
{
public function calculatePay() {} // Business Logic?
public function save() {} // Schema change?
public function reportHours() {} // Format string?
}
https://www.flickr.com/photos/pennuja/5363518281
SRP 的好處
• Unit Test 單純化
• 減少 Code Bloat 的機會
• ⼀一個 class 1000 ⾏行?
• Code Reuse
• 維護性
⼀一輩⼦子做好⼀一件事
就功德圓滿
Keep it simple stupid
(KISS)
Open Close Principle
• Open for extension, closed for modification
• 不⽤用修改原本的 code,就可以增加新功能!
• 增加功能的⼿手段
• subclass and override
• strategy injection
• template pattern
OCP Violation
class Rectangle
{
public $width;
public $height;
}
!
class AreaCalculator
{
public function area(array $shapes) {
$area = 0;
foreach ($shapes as &$shape) {
if ($shape instanceof Rectangle) {
$area += $shape->width * $shape->height;
}
}
return $area;
}
}
Shotgun Surgery
• Bad Smells
• 增加⼀一個 feature,要改⾮非常多零碎的地⽅方
• 過份使⽤用 if / else 作為增加 feature 的⼿手段
Interface and override
interface Area {
public function area();
}
!
class Rectangle implements Area {
public $width;
public $height;
!
public function area() {
return $this->width * $this->height;
}
}
!
class AreaCalculator {
public function area(array $shapes) {
$area = 0;
foreach ($shapes as &$shape) {
$area += $shape->area();
}
return $area;
}
}
Adapter Connections
class FacebookAdapter
{
private $pool;
!
public function doAPI($params) {
// Make $request from $params
$this->sendRequest($request);
}
!
private function sendRequest($request) {
$pool = $this->makeConnectionPool();
$pool->doRequest($request);
}
!
private function makeConnectionPool() {
if ($this->pool) {
return $this->pool;
}
// connection pool implementation
}
}
Connection Pool
不⽤用嗎?
Google / Twitter
Adapter?
使⽤用 Mixin 或 Abstract class
trait AdapterMixin
{
private $pool;
!
private function sendRequest($request) {
$pool = $this->makeConnectionPool();
$pool->doRequest($request);
}
!
private function makeConnectionPool() {
if ($this->pool) {
return $this->pool;
}
// connection pool implementation
}
}
!
class FacebookAdapter
{
use AdapterMixin;
public function doAPI($params) {
// Make $request from $params
$this->sendRequest($request);
}
}
Once and Only Once
Bug 修⼀一個地⽅方就好
Template Method
abstract class RESTAdapter {
abstract protected function createConnection();
!
protected function parseResponse() {
// Default implementation
}
public function apiRequest($uri, $body) {
$conn = $this->createConnection();
$resp = $conn->request($uri, $body);
return $resp;
}
}
!
class HTTPRestAdatper extends RESTAdapter {
protected function createConnection() {
// create HTTP connection
}
}
!
class HTTPSRestAdatper extends RESTAdapter {
protected function createConnection() {
// create HTTPS connection
}
}
流程固定
Override 不同
Don’t Repeat Yourself
(DRY)
Cohesion 凝聚⼒力
多少相關連的 

member data / function
Liskov Substitution Principle
• 定義
• 使⽤用⽗父類別的 reference 或 pointer 操作
function 時,不需要知道實際指向的類別
• Design by Contract
• ⽗父類別跟⼦子類別的「⾏行為」
• Function Prototype
Liskov Substitution Principle
interface PersistentResource
{
public function load();
}
!
class PostData implements PersistentResource
{
// ...
}
!
class AuthData implements PersistentResource
{
// ...
}
!
$postData = new PostData();
$loadPostData = $postData->load();
!
$authData = new AuthData();
$loadAuthData = $authData->load();
Design by Contract
• Design by Contract
• 講定的介⾯面與⾏行為
• Interface / Function Prototype
• ⾏行為
• pre-condition
• post-condition
• Side Effects
LSP Violation
interface PersistentResource
{
public function load();
}
!
class PostData implements PersistentResource
{
public function load()
{
return $this->db->load('post_data');
}
}
!
class AuthData implements PersistentResource
{
public function load()
{
$authData = $this->db->load('auth_data');
$this->authenticator->auth($authData);
return $authData;
}
}
Design by Contract?
• 沒有預期的 Side Effect
• 來看看之前的範例
• Pre-condition
• $this->db is ready
• Post-condition
• 把資料讀取出來
• Unexpected Side Effect
• Authentication
Function Prototype
• Function Prototype

class Foo
{
public function bar(array $bar) {}
}
!
class Baz extends Foo
{
public function bar(array $bar, array $beer) {}
}



Strict Standards: Declaration of Baz::bar() should be compatible
with Foo::bar(array $bar)
– PEP20 The Zen of Python
Explicit is better than implicit
明確⽐比隱誨更好
Interface Segregation
Principle
• Interface 的使⽤用者不該被強迫使⽤用⾃自⼰己不需要的
function
• 把介⾯面切割乾淨
• 不該是我的,就不要放進來,想想 SRP
ISP Violation
interface Bird
{
public function fly();
public function run();
}
!
!
class Dove implements Bird
{
public function fly() {}
public function run() {}
}
!
class Penguin implements Bird
{
public function fly() {
// Ahhh, I cannot fly
}
public function run() {}
}
Java 與 ISP
• Java 的介⾯面設計
• Serializable
• AutoClosable
• Readable
• DataOutput
Dependency Inversion
Principle
• Principle
• 依賴抽象類別,⽽而⾮非實體類型
• 低耦合 decoupling
• 好處
• Open Close Principle
• 擴充性 / 測試性 / Reuse
DIP Violation
• Singleton 不好測試
class UserRepository {
const BY_USERNAME_SQL = "Select ...";
!
public function loadUser($user) {
$db = Database::getInstance();
return $db->query(self::BY_USERNAME_SQL, $user);
}
}
⽼老闆說這邊想放在Redis?
DIP Example
• Use ISP in practice
class UserRepository {
const BY_USERNAME_SQL = "Select ...";
!
private $_db = null;
!
function __construct($db) {
$this->_db = $db;
}
!
public function loadUser($user) {
return $this->_db->query(self::BY_USERNAME_SQL, user);
}
}
從測試的⾓角度出發
class UserRepository {
const BY_USERNAME_SQL = "Select ...";
!
private $_db = null;
!
function __construct($db) {
$this->_db = $db;
}
public function loadUser($user) {
return $this->_db->query(self::BY_USERNAME_SQL, $user);
}
}
!
class UserRepositoryTest extends PHPUnit_Framework_TestCase {
public function testLoadUser() {
$stubDB = $this->getMock('FakeDB');
$stubDB->expects($this->any())
->method('query')
->will($this->returnValue(array('name' => 'hubert')));
$repo = new UserRepository($stubDB);
$repo->loadUser('hubert');
}
}
PDO('sqlite::memory:')
DIP Patterns
• Dependency Injection
• Constructor injection
• Setter injection
• Service Locator
• IoC Framework
Testability
Is TDD Dead?
• 我⾃自⼰己的看法
• 透過測試來改善軟體架構
• 幫助你思考 SOLID 跟責任分離
• 先有 SOLID,然後 Design Pattern
• TDD 不是萬能
• 為了測試⽽而測試?
良好的封裝
Tell, Don’t Ask
• 結帳的時候,你會把⾃自⼰己交給櫃臺嗎?

class Clerk {
Store store;
void SellGoodsTo(Client client) {
money = client.GetWallet().GetMoney();
store.ReceiveMoney(money);
}
};
Tell, Don’t Ask
• 媽媽,我要錢,只要你的錢

class Clerk {
Store store;
void SellGoodsTo(money) {
store.ReceiveMoney(money);
}
};
Law of Demeter
• 物件 O 中的函⽰示 m 只能使⽤用哪些物件
1. O ⾃自⼰己
2. m 的 parameter
3. m 當中 new 出來的物件
4. O 所能直接存取的成員函⽰示及物件
5. 全域變數
Law of Demeter Violation
• Mock 的 Mock 的 Mock 的 Mock …
• Law of Demeter Violation



final String outputDir =
ctxt.getOptions().getScratchDir().getAbsolutePath();
結語
• SOLID 是物件導向的基本
• 因為有限制,才得以出類拔萃
• 好的設計 / 好的測試
• 物件的封裝與權責
• Design Pattern
Q & A
Global Variables?
int fprintf(
FILE* stream,
HEAP* heap,
int* errno,
const char *format, ...);
!
int main(GLOBALS *globals)
{
int errno = 0;
fprintf(
globals->stdio->out,
globals->heap,
&errno,
"Hello world.n”);
}
int printf(
const char *format, ...);
int main() {
printf("Hello world.n");
return 0;
}
https://docs.google.com/presentation/d/
17Hg3-42fygPd_JUJHorjs1Ah2KCYnjBUBEQJGZgpT6E/edit?usp=sharing

Más contenido relacionado

La actualidad más candente

Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmersAlexander Varwijk
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2Yi-Huan Chan
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript LiteracyDavid Jacobs
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperNyros Technologies
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Jalpesh Vasa
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptDhruvin Shah
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in phpAshish Chamoli
 
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Mark Niebergall
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Functional Java 8 - Introduction
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - IntroductionŁukasz Biały
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPRobertGonzalez
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design PrinciplesJon Kruger
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic JavascriptBunlong Van
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 

La actualidad más candente (19)

Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Developing SOLID Code
Developing SOLID CodeDeveloping SOLID Code
Developing SOLID Code
 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 
What's new with PHP7
What's new with PHP7What's new with PHP7
What's new with PHP7
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in php
 
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Functional Java 8 - Introduction
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - Introduction
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHP
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 

Destacado

Success by Challenging Assumptions (Part 2)
Success by Challenging Assumptions (Part 2)Success by Challenging Assumptions (Part 2)
Success by Challenging Assumptions (Part 2)LaDonna Coy
 
Make yourself replaceable at DevOpsCon 2016 Berlin
Make yourself replaceable at DevOpsCon 2016 BerlinMake yourself replaceable at DevOpsCon 2016 Berlin
Make yourself replaceable at DevOpsCon 2016 BerlinErno Aapa
 
SOLID Principles of Refactoring Presentation - Inland Empire User Group
SOLID Principles of Refactoring Presentation - Inland Empire User GroupSOLID Principles of Refactoring Presentation - Inland Empire User Group
SOLID Principles of Refactoring Presentation - Inland Empire User GroupAdnan Masood
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID PrinciplesGanesh Samarthyam
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 
Success by Challenging Assumptions (Part I)
Success by Challenging Assumptions (Part I)Success by Challenging Assumptions (Part I)
Success by Challenging Assumptions (Part I)LaDonna Coy
 
Object Oriented Design SOLID Principles
Object Oriented Design SOLID PrinciplesObject Oriented Design SOLID Principles
Object Oriented Design SOLID Principlesrainynovember12
 
The SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsThe SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsHayim Makabee
 
SOLID Principles and Design Patterns
SOLID Principles and Design PatternsSOLID Principles and Design Patterns
SOLID Principles and Design PatternsGanesh Samarthyam
 
Implementing DDD Concepts in PHP
Implementing DDD Concepts in PHPImplementing DDD Concepts in PHP
Implementing DDD Concepts in PHPSteve Rhoades
 
Geokit In Social Apps
Geokit In Social AppsGeokit In Social Apps
Geokit In Social AppsPaul Jensen
 
Projducció i consum d'energia AitoooR
Projducció i consum d'energia AitoooRProjducció i consum d'energia AitoooR
Projducció i consum d'energia AitoooRAitor Padilla Mulero
 
Guia procediment reclamacions
Guia procediment reclamacionsGuia procediment reclamacions
Guia procediment reclamacionsmanuel.casanova
 
Design for asatizah Slides
Design for asatizah SlidesDesign for asatizah Slides
Design for asatizah SlidesSyukran
 
Q1 2009 Earning Report of Du Pont E I De Nemours
Q1 2009 Earning Report of Du Pont E I De NemoursQ1 2009 Earning Report of Du Pont E I De Nemours
Q1 2009 Earning Report of Du Pont E I De Nemoursguestc4fcf72
 
Proyek penciptaan dan digitalisasi konten
Proyek penciptaan dan digitalisasi kontenProyek penciptaan dan digitalisasi konten
Proyek penciptaan dan digitalisasi kontenWikimedia Indonesia
 

Destacado (20)

Solid principles
Solid principlesSolid principles
Solid principles
 
Success by Challenging Assumptions (Part 2)
Success by Challenging Assumptions (Part 2)Success by Challenging Assumptions (Part 2)
Success by Challenging Assumptions (Part 2)
 
Make yourself replaceable at DevOpsCon 2016 Berlin
Make yourself replaceable at DevOpsCon 2016 BerlinMake yourself replaceable at DevOpsCon 2016 Berlin
Make yourself replaceable at DevOpsCon 2016 Berlin
 
SOLID Principles of Refactoring Presentation - Inland Empire User Group
SOLID Principles of Refactoring Presentation - Inland Empire User GroupSOLID Principles of Refactoring Presentation - Inland Empire User Group
SOLID Principles of Refactoring Presentation - Inland Empire User Group
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID Principles
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
Success by Challenging Assumptions (Part I)
Success by Challenging Assumptions (Part I)Success by Challenging Assumptions (Part I)
Success by Challenging Assumptions (Part I)
 
Object Oriented Design SOLID Principles
Object Oriented Design SOLID PrinciplesObject Oriented Design SOLID Principles
Object Oriented Design SOLID Principles
 
SOLID Principles part 2
SOLID Principles part 2SOLID Principles part 2
SOLID Principles part 2
 
SOLID Principles part 1
SOLID Principles part 1SOLID Principles part 1
SOLID Principles part 1
 
The SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsThe SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design Patterns
 
SOLID Principles and Design Patterns
SOLID Principles and Design PatternsSOLID Principles and Design Patterns
SOLID Principles and Design Patterns
 
Implementing DDD Concepts in PHP
Implementing DDD Concepts in PHPImplementing DDD Concepts in PHP
Implementing DDD Concepts in PHP
 
Kelas lontar 1
Kelas lontar 1Kelas lontar 1
Kelas lontar 1
 
Geokit In Social Apps
Geokit In Social AppsGeokit In Social Apps
Geokit In Social Apps
 
Projducció i consum d'energia AitoooR
Projducció i consum d'energia AitoooRProjducció i consum d'energia AitoooR
Projducció i consum d'energia AitoooR
 
Guia procediment reclamacions
Guia procediment reclamacionsGuia procediment reclamacions
Guia procediment reclamacions
 
Design for asatizah Slides
Design for asatizah SlidesDesign for asatizah Slides
Design for asatizah Slides
 
Q1 2009 Earning Report of Du Pont E I De Nemours
Q1 2009 Earning Report of Du Pont E I De NemoursQ1 2009 Earning Report of Du Pont E I De Nemours
Q1 2009 Earning Report of Du Pont E I De Nemours
 
Proyek penciptaan dan digitalisasi konten
Proyek penciptaan dan digitalisasi kontenProyek penciptaan dan digitalisasi konten
Proyek penciptaan dan digitalisasi konten
 

Similar a SOLID Principles

Modernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesModernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesiMasters
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class designNeetu Mishra
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibilitymachuga
 
Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)Dave Hulbert
 
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...Dariusz Drobisz
 
java beans
java beansjava beans
java beanslapa
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS偉格 高
 
Why should we use an INTERFACE even when we only have one concrete class?
Why should we use an INTERFACE even when we only have one concrete class?Why should we use an INTERFACE even when we only have one concrete class?
Why should we use an INTERFACE even when we only have one concrete class?Rafal Ksiazek
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#Daniel Fisher
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Damien Seguy
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application ArchitectureMark Trostler
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021Scott Keck-Warren
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 

Similar a SOLID Principles (20)

Modernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesModernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul Jones
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
 
java beans
java beansjava beans
java beans
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
Why should we use an INTERFACE even when we only have one concrete class?
Why should we use an INTERFACE even when we only have one concrete class?Why should we use an INTERFACE even when we only have one concrete class?
Why should we use an INTERFACE even when we only have one concrete class?
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application Architecture
 
13 java beans
13 java beans13 java beans
13 java beans
 
Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021Getting Started with Test-Driven Development at Midwest PHP 2021
Getting Started with Test-Driven Development at Midwest PHP 2021
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 

Último

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 

Último (20)

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

SOLID Principles

  • 2. 關於我 • Hubert (@yhchan) • 趨勢科技 • Python Programmer • http://blog.hubert.tw
  • 9. ⽐比 Design Pattern 更重要的事情 • Maintainability • Principles • Refactoring • Unit Testing • Testability
  • 11. SOLID Principles • Single Responsibility Principle (SRP) • Open-Closed Principle (OCP) • Liskov substitution principle (LSP) • Interface segregation principle (ISP) • Dependency inversion principle (DIP)
  • 12. Single Responsibility Principle • 每個 Class 只有「⼀一個」職責 • 如果需要修改,只能因為這個職責⽽而修改
  • 13. 三個權責 class Employee { public function calculatePay() {} // Business Logic? public function save() {} // Schema change? public function reportHours() {} // Format string? }
  • 15. SRP 的好處 • Unit Test 單純化 • 減少 Code Bloat 的機會 • ⼀一個 class 1000 ⾏行? • Code Reuse • 維護性
  • 17. Keep it simple stupid (KISS)
  • 18. Open Close Principle • Open for extension, closed for modification • 不⽤用修改原本的 code,就可以增加新功能! • 增加功能的⼿手段 • subclass and override • strategy injection • template pattern
  • 19. OCP Violation class Rectangle { public $width; public $height; } ! class AreaCalculator { public function area(array $shapes) { $area = 0; foreach ($shapes as &$shape) { if ($shape instanceof Rectangle) { $area += $shape->width * $shape->height; } } return $area; } }
  • 20.
  • 21. Shotgun Surgery • Bad Smells • 增加⼀一個 feature,要改⾮非常多零碎的地⽅方 • 過份使⽤用 if / else 作為增加 feature 的⼿手段
  • 22. Interface and override interface Area { public function area(); } ! class Rectangle implements Area { public $width; public $height; ! public function area() { return $this->width * $this->height; } } ! class AreaCalculator { public function area(array $shapes) { $area = 0; foreach ($shapes as &$shape) { $area += $shape->area(); } return $area; } }
  • 23. Adapter Connections class FacebookAdapter { private $pool; ! public function doAPI($params) { // Make $request from $params $this->sendRequest($request); } ! private function sendRequest($request) { $pool = $this->makeConnectionPool(); $pool->doRequest($request); } ! private function makeConnectionPool() { if ($this->pool) { return $this->pool; } // connection pool implementation } }
  • 26. 使⽤用 Mixin 或 Abstract class trait AdapterMixin { private $pool; ! private function sendRequest($request) { $pool = $this->makeConnectionPool(); $pool->doRequest($request); } ! private function makeConnectionPool() { if ($this->pool) { return $this->pool; } // connection pool implementation } } ! class FacebookAdapter { use AdapterMixin; public function doAPI($params) { // Make $request from $params $this->sendRequest($request); } }
  • 29. Template Method abstract class RESTAdapter { abstract protected function createConnection(); ! protected function parseResponse() { // Default implementation } public function apiRequest($uri, $body) { $conn = $this->createConnection(); $resp = $conn->request($uri, $body); return $resp; } } ! class HTTPRestAdatper extends RESTAdapter { protected function createConnection() { // create HTTP connection } } ! class HTTPSRestAdatper extends RESTAdapter { protected function createConnection() { // create HTTPS connection } }
  • 34. Liskov Substitution Principle • 定義 • 使⽤用⽗父類別的 reference 或 pointer 操作 function 時,不需要知道實際指向的類別 • Design by Contract • ⽗父類別跟⼦子類別的「⾏行為」 • Function Prototype
  • 35. Liskov Substitution Principle interface PersistentResource { public function load(); } ! class PostData implements PersistentResource { // ... } ! class AuthData implements PersistentResource { // ... } ! $postData = new PostData(); $loadPostData = $postData->load(); ! $authData = new AuthData(); $loadAuthData = $authData->load();
  • 36. Design by Contract • Design by Contract • 講定的介⾯面與⾏行為 • Interface / Function Prototype • ⾏行為 • pre-condition • post-condition • Side Effects
  • 37. LSP Violation interface PersistentResource { public function load(); } ! class PostData implements PersistentResource { public function load() { return $this->db->load('post_data'); } } ! class AuthData implements PersistentResource { public function load() { $authData = $this->db->load('auth_data'); $this->authenticator->auth($authData); return $authData; } }
  • 38. Design by Contract? • 沒有預期的 Side Effect • 來看看之前的範例 • Pre-condition • $this->db is ready • Post-condition • 把資料讀取出來 • Unexpected Side Effect • Authentication
  • 39. Function Prototype • Function Prototype
 class Foo { public function bar(array $bar) {} } ! class Baz extends Foo { public function bar(array $bar, array $beer) {} }
 
 Strict Standards: Declaration of Baz::bar() should be compatible with Foo::bar(array $bar)
  • 40. – PEP20 The Zen of Python Explicit is better than implicit
  • 42. Interface Segregation Principle • Interface 的使⽤用者不該被強迫使⽤用⾃自⼰己不需要的 function • 把介⾯面切割乾淨 • 不該是我的,就不要放進來,想想 SRP
  • 43. ISP Violation interface Bird { public function fly(); public function run(); } ! ! class Dove implements Bird { public function fly() {} public function run() {} } ! class Penguin implements Bird { public function fly() { // Ahhh, I cannot fly } public function run() {} }
  • 44. Java 與 ISP • Java 的介⾯面設計 • Serializable • AutoClosable • Readable • DataOutput
  • 45. Dependency Inversion Principle • Principle • 依賴抽象類別,⽽而⾮非實體類型 • 低耦合 decoupling • 好處 • Open Close Principle • 擴充性 / 測試性 / Reuse
  • 46. DIP Violation • Singleton 不好測試 class UserRepository { const BY_USERNAME_SQL = "Select ..."; ! public function loadUser($user) { $db = Database::getInstance(); return $db->query(self::BY_USERNAME_SQL, $user); } }
  • 48. DIP Example • Use ISP in practice class UserRepository { const BY_USERNAME_SQL = "Select ..."; ! private $_db = null; ! function __construct($db) { $this->_db = $db; } ! public function loadUser($user) { return $this->_db->query(self::BY_USERNAME_SQL, user); } }
  • 49. 從測試的⾓角度出發 class UserRepository { const BY_USERNAME_SQL = "Select ..."; ! private $_db = null; ! function __construct($db) { $this->_db = $db; } public function loadUser($user) { return $this->_db->query(self::BY_USERNAME_SQL, $user); } } ! class UserRepositoryTest extends PHPUnit_Framework_TestCase { public function testLoadUser() { $stubDB = $this->getMock('FakeDB'); $stubDB->expects($this->any()) ->method('query') ->will($this->returnValue(array('name' => 'hubert'))); $repo = new UserRepository($stubDB); $repo->loadUser('hubert'); } }
  • 51. DIP Patterns • Dependency Injection • Constructor injection • Setter injection • Service Locator • IoC Framework
  • 53. Is TDD Dead? • 我⾃自⼰己的看法 • 透過測試來改善軟體架構 • 幫助你思考 SOLID 跟責任分離 • 先有 SOLID,然後 Design Pattern • TDD 不是萬能 • 為了測試⽽而測試?
  • 55. Tell, Don’t Ask • 結帳的時候,你會把⾃自⼰己交給櫃臺嗎?
 class Clerk { Store store; void SellGoodsTo(Client client) { money = client.GetWallet().GetMoney(); store.ReceiveMoney(money); } };
  • 56. Tell, Don’t Ask • 媽媽,我要錢,只要你的錢
 class Clerk { Store store; void SellGoodsTo(money) { store.ReceiveMoney(money); } };
  • 57. Law of Demeter • 物件 O 中的函⽰示 m 只能使⽤用哪些物件 1. O ⾃自⼰己 2. m 的 parameter 3. m 當中 new 出來的物件 4. O 所能直接存取的成員函⽰示及物件 5. 全域變數
  • 58. Law of Demeter Violation • Mock 的 Mock 的 Mock 的 Mock … • Law of Demeter Violation
 
 final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
  • 59. 結語 • SOLID 是物件導向的基本 • 因為有限制,才得以出類拔萃 • 好的設計 / 好的測試 • 物件的封裝與權責 • Design Pattern
  • 60. Q & A
  • 61. Global Variables? int fprintf( FILE* stream, HEAP* heap, int* errno, const char *format, ...); ! int main(GLOBALS *globals) { int errno = 0; fprintf( globals->stdio->out, globals->heap, &errno, "Hello world.n”); } int printf( const char *format, ...); int main() { printf("Hello world.n"); return 0; } https://docs.google.com/presentation/d/ 17Hg3-42fygPd_JUJHorjs1Ah2KCYnjBUBEQJGZgpT6E/edit?usp=sharing