SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
/evrone.
Принципы проектирования
ООП приложений
НИКИТА СКАЛКИН, EVRONE
/evrone.
Изменения
/evrone.
Зависимости
/evrone.
ХОРОШО ПОДДЕРЖИВАЕМЫЙ КОД
▸ Изменения не имеют неожиданных побочных эффектов
▸ Незначительные изменения в требованиях несут незначительные
изменения в коде
▸ Код легко поддается повторному использованию
/evrone.
Проектирование -
управление зависимостями
/evrone.
ИНСТРУМЕНТЫ ПРОЕКТИРОВАНИЯ
▸ Принципы проектирования
▸ Шаблоны проектирования
▸ Опыт и здравый смысл
/evrone.
ПРИНЦИПЫ ПРОЕКТИРОВАНИЯ
▸ SOLID
▸ DRY
▸ Law of Demeter
/evrone.
Single Responsibility Principle
/evrone.
SINGLE RESPONSIBILITY PRINCIPLE
▸ Делает бороду более шелковистой
▸ Классы и методы становятся небольшими и легко читаемыми
▸ SRP позволяет строить более четкую архитектуру классов
▸ Код легче тестировать
/evrone.
SINGLE RESPONSIBILITY PRINCIPLE
О чем говорит принцип единственной обязанности?
▸ Loose coupling / High cohension
▸ Класс должен иметь одну причину для изменения. Эта причина и
называется ответственностью
/evrone.
SINGLE RESPONSIBILITY PRINCIPLE
class VideoFilesController
def publish
video.update_attribute(:published, true)
VideoMailer.deliver_video_published(video)
end
end
/evrone.
SINGLE RESPONSIBILITY PRINCIPLE
class Video
after_save :deliver_published, if: -> { cond. }
private
def deliver_published
VideoMailer.deliver_video_published(self)
end
end
class VideosController
def publish
video.update_attribute(:published, true)
VideoMailer.deliver_video_published(video)
end
end
/evrone.
SINGLE RESPONSIBILITY PRINCIPLE
class VideosController
def publish
VideoPublisher.new(video).publish
end
end
class VideoPublisher
….
def publish
video.update_attribute(:published, true)
VideoMailer.deliver_video_published(video)
end
end
/evrone.
Open / Closed Principle
/evrone.
OPEN / CLOSED PRINCIPLE
▸ Классы должны быть открыты для расширения
▸ Классы должны быть закрыты для модификации
/evrone.
OPEN / CLOSED PRINCIPLE
class FileConverter
attr_reader :file
def initialize(file)
@file = file
end
…
def convert!
case file.format
when :image
convert_image
when :video
convert_video
end
end
/evrone.
OPEN / CLOSED PRINCIPLE
class FileConverter
attr_reader :file, converter
def initialize(file, converter)
@file = file
@converter = converter
end
…
def convert!
converter.convert(file)
end
/evrone.
OPEN / CLOSED PRINCIPLE
class ImageConverter
def convert(image)
end
end
class VideoConverter
def convert(image)
end
end
/evrone.
Liskov Substitution Principle
/evrone.
LISKOV SUBSTITUTION PRINCIPLE
“Пусть q(x) бла бла бла x бла бла бла T. Тогда q(y)
бла бла бла y бла бла бла S, где S является
подтипом типа T.” -
формальное описание принципа подстановки Барбары Лисков
/evrone.
LISKOV SUBSTITUTION PRINCIPLE
Программа должна иметь возможность заменить
любое вхождение базового класса на инстанс его
потомка без негативных сайд эффектов.
/evrone.
Interface Segregation
Principle
/evrone.
Клиент не должен зависеть от
методов, которые он не использует
/evrone.
INTERFACE SEGREGATION PRINCIPLE
class Video
def publish; end
def delete; end
end
/evrone.
INTERFACE SEGREGATION PRINCIPLE
class Video
def publish; end
def delete; end
end
class VideoPublisher
extend Forwardable
def_delegators :@video, :publish
def initialize(video); @video = video; end
end
VideoPublisher.new(video).publish # => true
VideoPublisher.new(video).delete #=> NoMethorError
/evrone.
Dependency Inversion
Principle
/evrone.
DEPENDENCY INVERSION PRINCIPLE
Высокоуровневые объекты не должны опираться
на детали реализации низкоуровневых объектов
/evrone.
Don’t Repeat Yourself
/evrone.
DRY
“Duplication is far cheaper than the wrong
abstraction” -
Sandi Metz
/evrone.
DRY
Когда DRY goes wrong
1. Программист А видит дублирование кода и выносит его в отдельный
метод. Это создает новую абстракцию.
2. Приходят новые требования, которые почти подходят этой
абстракции.
3. Программист Б решает сохранить предыдущую абстракцию, добавив
новый параметр методу и условие.
4. Так продолжается, пока абстракция становится не поддерживаемой.
/evrone.
Law of Demeter
/evrone.
LAW OF DEMETER
Метод объекта должен вызывать только методы следующих объектов:
▸ самого себя;
▸ его параметров;
▸ объектов, которые он создает;
▸ компонентов объекта.
/evrone.
LAW OF DEMETER
Аналогия от Peter Van Rooijen:
▸ You can play with yourself.
▸ You can play with your own toys (but you can’t take them apart),
▸ You can play with toys that were given to you.
▸ And you can play with toys you’ve made yourself.
/evrone.
LAW OF DEMETER
def user_email
video.user&.email
end
/evrone.
LAW OF DEMETER
class Video
delegate :email, to: :user, prefix: :true
end
def user_email
video.user_email
end
/evrone.
ПОЧИТАТЬ
▸ Статьи Thoughtbot
▸ POODR Sandi Metz
/evrone.
Спасибо за внимание!
Задавайте вопросы :)

Contenu connexe

En vedette

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

En vedette (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Принципы проектирование ООП приложений - Скалкин Никита (Evrone) Блог программиста