The document discusses the SOLID principles of object-oriented design:
- The Single Responsibility Principle states that a class should have one single responsibility.
- The Open/Closed Principle states that software entities should be open for extension but closed for modification.
- The Liskov Substitution Principle states that objects should be replaceable with their subtypes without altering correctness.
- The Interface Segregation Principle states that many specific client interfaces are better than one general interface.
- The Dependency Inversion Principle states that high-level modules shouldn't depend on low-level modules but both should depend on abstractions.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard assertions like 'assertEquals()' or 'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
The most hated thing a developer can imagine is writing documentation but on the other hand nothing can compare with a well documented source code if you want to change or extend some code. PhpDocumentor is one of many tools enabling you to parse the inline documentation and generate well structured and referenced documents. This tallk will show you how to get the most out of phpDocumentor and shall enable you to write fantastic documentation.
The most hated thing a developer can imageine is writing documentation but on the other hand nothing can compare with a well documented source code if you want to change or extend some code. PhpDocumentor is one of many tools enabling you to parse the inline documentation and generate well structured and referenced documents. This tallk will show you how to get the most out of phpDocumentor and shall enable you to write fantastic documentation.
So S.O.L.I.D Fu - Designing Better CodeNeil Crookes
A chat about some of the most important principles in software development. Discover or get a refresher on these tried and tested techniques for designing better code.
Code: https://github.com/neilcrookes/SoSOLIDFu/
A lot of people using PHPunit for testing their source code. While I was observing my team I recognized most of them are only using the standard assertions like 'assertEquals()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis and it digs deep into uncommon features of PHPUnit.
I present four design patterns that make your development easier and better. Design patterns are a fantastic way to make more readable code, as they make use of common ideas that many developers know and use. These patterns are tried and tested in the enterprise world.
The first one is dependency injection. This covers putting the variables that a class needs to function preferably inside a constructor.
The second one is the factory pattern. A factory moves the responsibility of instantiating an object to a third-party class.
The third one is dependency injection. This allows us to place a class' dependencies at one time, making it easy to come back and see what the class needs to survive.
Finally, we discuss the chain of responsibility. This allows complex operations to be handled by a chain of classes. Each class in the chain determines whether it is capable of handling the request and, if so, it returns the result.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard assertions like 'assertEquals()' or 'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
The most hated thing a developer can imagine is writing documentation but on the other hand nothing can compare with a well documented source code if you want to change or extend some code. PhpDocumentor is one of many tools enabling you to parse the inline documentation and generate well structured and referenced documents. This tallk will show you how to get the most out of phpDocumentor and shall enable you to write fantastic documentation.
The most hated thing a developer can imageine is writing documentation but on the other hand nothing can compare with a well documented source code if you want to change or extend some code. PhpDocumentor is one of many tools enabling you to parse the inline documentation and generate well structured and referenced documents. This tallk will show you how to get the most out of phpDocumentor and shall enable you to write fantastic documentation.
So S.O.L.I.D Fu - Designing Better CodeNeil Crookes
A chat about some of the most important principles in software development. Discover or get a refresher on these tried and tested techniques for designing better code.
Code: https://github.com/neilcrookes/SoSOLIDFu/
A lot of people using PHPunit for testing their source code. While I was observing my team I recognized most of them are only using the standard assertions like 'assertEquals()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis and it digs deep into uncommon features of PHPUnit.
I present four design patterns that make your development easier and better. Design patterns are a fantastic way to make more readable code, as they make use of common ideas that many developers know and use. These patterns are tried and tested in the enterprise world.
The first one is dependency injection. This covers putting the variables that a class needs to function preferably inside a constructor.
The second one is the factory pattern. A factory moves the responsibility of instantiating an object to a third-party class.
The third one is dependency injection. This allows us to place a class' dependencies at one time, making it easy to come back and see what the class needs to survive.
Finally, we discuss the chain of responsibility. This allows complex operations to be handled by a chain of classes. Each class in the chain determines whether it is capable of handling the request and, if so, it returns the result.
PHP7 brings a tremendous number of new features. Tonight, we will take a look at the null coalesce operator, new execution order (uniform variable syntax), new exceptions and more.
Con la versione 7 di Drupal è stato introdotto il concetto di Entity, poi evoluto con la versione 8, utilizzato come base di buona parte degli elementi core (nodi, tassonomie, utenti, ...), ma - soprattutto - è stata data la possibilità di costruire entity custom. L'utilizzo di queste apre le possibilità di personalizzazione dello strumento ad un livello superiore velocizzando notevolmente lo sviluppo.
Verranno mostrate le potenzialità nell'uso delle Entity custom e le integrazioni possibili.
Rich Model And Layered Architecture in SF2 ApplicationKirill Chebunin
Presentation for Symfony Camp UA 2012.
* What are Rich Model, Service Layer & Layered Architecture
* Layered architecture in Sf2 Application
* Integration with 3rd party bundles
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
Slides from my talk presented during Dutch PHP Conference in Amsterdam - 25 June 2016
More Domain-Driven Design related content at: https://domaincentric.net/
This DrupalCon 2019 Amsterdam talk provides a look beyond the world of PHP and Javascript. It explores how other languages such as Ruby, Java, Rust and Perl handle things and highlights some interesting features of those languages. Not all the things that other languages can do can be done in PHP or Javascript but the concepts and ideas can still be used.
PHP 7 was recently released, bringing some much-desired changes and improvements to the language. However, many developers haven't had the opportunity to use it for their projects and may not be familiar with the changes it brings. We'll remedy this by checking out the new "spaceship operator," demonstrating how static type hints produce clean code, and using anonymous classes to quickly implement interfaces on the fly. Attendees will also learn about breaking changes and "gotchas" to watch out for when making the upgrade and will receive pointers on getting started with PHP 7 today.
Essa palestra foi feita no TDC 2016 na trilha de PHP Architecture onde a idéia principal é mostrar como aplicar boas práticas e organização de código para atender as necessidades do negócio com uso de uma linguagem simples e autoexplicativa.
PHP7 brings a tremendous number of new features. Tonight, we will take a look at the null coalesce operator, new execution order (uniform variable syntax), new exceptions and more.
Con la versione 7 di Drupal è stato introdotto il concetto di Entity, poi evoluto con la versione 8, utilizzato come base di buona parte degli elementi core (nodi, tassonomie, utenti, ...), ma - soprattutto - è stata data la possibilità di costruire entity custom. L'utilizzo di queste apre le possibilità di personalizzazione dello strumento ad un livello superiore velocizzando notevolmente lo sviluppo.
Verranno mostrate le potenzialità nell'uso delle Entity custom e le integrazioni possibili.
Rich Model And Layered Architecture in SF2 ApplicationKirill Chebunin
Presentation for Symfony Camp UA 2012.
* What are Rich Model, Service Layer & Layered Architecture
* Layered architecture in Sf2 Application
* Integration with 3rd party bundles
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
Slides from my talk presented during Dutch PHP Conference in Amsterdam - 25 June 2016
More Domain-Driven Design related content at: https://domaincentric.net/
This DrupalCon 2019 Amsterdam talk provides a look beyond the world of PHP and Javascript. It explores how other languages such as Ruby, Java, Rust and Perl handle things and highlights some interesting features of those languages. Not all the things that other languages can do can be done in PHP or Javascript but the concepts and ideas can still be used.
PHP 7 was recently released, bringing some much-desired changes and improvements to the language. However, many developers haven't had the opportunity to use it for their projects and may not be familiar with the changes it brings. We'll remedy this by checking out the new "spaceship operator," demonstrating how static type hints produce clean code, and using anonymous classes to quickly implement interfaces on the fly. Attendees will also learn about breaking changes and "gotchas" to watch out for when making the upgrade and will receive pointers on getting started with PHP 7 today.
Essa palestra foi feita no TDC 2016 na trilha de PHP Architecture onde a idéia principal é mostrar como aplicar boas práticas e organização de código para atender as necessidades do negócio com uso de uma linguagem simples e autoexplicativa.
Software development is hard! SOLID coding principles can help you develop better code. Come learn what the SOLID principles are and practical examples on how to use each strategy when developing in PHP. Leave with the tools needed to architect code that follows established design patterns that lead to better code.
Esta charla comprende las lecciones aprendidas convirtiendo la app de Android de Teambox (una app repleta de deuda técnica y con un alto nivel de acoplamiento entre clases), en la versión actual de Redbooth, que intenta cumplir la arquitectura Hexagonal y los principios SOLID. Durante la exposición explicaremos como fuimos desenredando el código paso a paso; como aplicamos por partes los conceptos de la arquitectura hexagonal; como dejamos de lado componentes del framework de Android que dificultaban el mantenimiento de la app; y que errores cometimos, como los solucionamos y como se podrían haber evitado.
4Developers 2015: Be pragmatic, be SOLID - Krzysztof MenżykPROIDEA
Krzysztof Menżyk
Language: Polish
Wiemy jak projektować dobry kod obiektowy? Ilu z nas zna 5 zasad SOLID? Ilu z nas przestrzega ich w codziennej pracy z kodem? Nie tylko wyjaśnię co to SOLID, ale również pokażę, że to nie sucha teoria a praktyczne rady, które warto aplikować w naszych projektach.
Podczas prezentacji szczegółowo omówię każdą z pięciu zasad. Pokażę konkretne przykłady, które naruszają ww. zasady. Zaprezentuję przykładowe rozwiązania i techniki refaktorowania kodu. Omówię również, w jakich sytuacjach można pominąć niektóre z zasad oraz jaki może to mieć wpływ na projekt.
Presented at #PHPLX 11 September 2013
The 2013 edition of OWASP (Open Web Application Security Project) top 10 has just been released and unfortunately Injections (not only SQL injection) is still the most common security problem. In this talk we will review the top 10 list of security problems looking at possible attack scenarios and ways to protect against them mostly from a PHP programmer perspective.
Os princípios SOLID surgiram para trazer as melhores práticas do desenvolvimento de softwares seguindo o paradigma de orientação a objetos. Nesta Palestra vamos entender de forma prática quais são estes princípios e como podemos utilizá-los no nosso dia-a-dia.
SOLID Design Principles applied in JavaIonut Bilica
Video: https://www.youtube.com/watch?v=0cU-4LrcWI0
SOLID Design Principles applied in Java: rules to develop scalable and easily maintainable code
Speaker: Ionut Bilica - Senior Software Developer @ Luxoft Romania.
During this talk we will discuss about the SOLID Principles described by Robert C. Martin, applying them in the Java programming language. Each principle will be explained in detail, with practical Java examples.
We will asses how these principles make it easy to develop the software for the entire duration of the project, and how some problems can appear if these principles are not applied. We will present common code fragments that do not respect these principles, and we'll see how we can correct them. Taking the SOLID principles into consideration, we will also analyse a real Java project using a Static Code Analyzer tool (e.g. STAN).
Finally, we will discuss the strategies on how to apply these design principles in "greenfield" projects, as well as "legacy" projects, while offering some tips and tricks.
Zarządzanie złożonością - czyli jak budować, żeby nie żałować. Będzie to o strukturze aplikacji, narzędziach, metodologiach w zastosowaniu, czyli w sumie wszystkiego po trochu co trzeba wziąć pod uwagę rozpoczynając projekt.
Kamil Ruczyński - W jaki sposób ocenić czy test, który napisaliśmy dokładnie weryfikuje poprawność kodu? Można napisać test do testu i o tym w tej prezentacji, czyli o tak zwanych testach mutacyjnych.
W swojej prezentacji Wojtek Pilich pokaże z jakimi problemami mierzą się najczęściej początkujący programiści PHP, omówi to na przykładach realnego kodu. Pokaże też wskazówki jak unikać tych błędów i pisać czystszy, prostszy oraz bardziej optymalny kod w PHP.
Założenia, technologie, tips and tricks do codziennego zastosowania przy zabezpieczaniu aplikacji webowych od strony serwerowej. Analiza ruchu sieciowego w oparciu o narzędzia systemowe celem ułatwienia rozpoznania ewentualnych zagrożeń, monitorowanie usług.
Dlaczego ważne jest samodoskonalenie w zawodzie programisty? Czy dotyczy tylko początkujących? Prelekcja poruszy zarówno temat miękkiego wejścia w świat programowania PHP jak i koncentracji nad dalsza ścieżką w karierze.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
3. “On the one hand, if the bricks aren’t well made, the architecture of the building
doesn’t matter much. On the other hand, you can make a substantial mess with
well-made bricks.”
Robert C. Martin
4. SOLID
SOLID is a acronym for five design principles intended to make software
designs more understandable, flexible and maintainable.
● Zebrane przez Robert C. Martin
● Nazwane przez Michael Feathers w 2004
5. S R P
O C P
L S P
I S P
D I P
Single Responsibility Principle
Open/Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
7. SOLID
Single Responsibility Principle
“A class should only have a single responsibility, that is, only changes to one
part of the software's specification should be able to affect the specification of
the class.”
14. SOLID
class Publisher
{
public function display($type)
{
switch($type) {
case 'screen':
/* some logic */
break;
case 'rss':
/* some logic */
break;
}
}
}
$publsher = new Publisher();
$publsher->display('screen');
$publsher->display('rss');
15. SOLID
interface PublisherInterface
{
public function getContent();
}
class Publisher
{
public function display(PublisherInterface $publisher)
{
$publisher->getContent();
}
}
class ScreenPublisher implements PublisherInterface
{
public function getContent() { /* some logic */ }
}
class RssPublisher implements PublisherInterface
{
public function getContent() { /* some logic */ }
}
16. SOLID
$publsher = new Publisher();
$screenPublisher = new ScreenPublisher();
$publsher->display($screenPublisher);
$rssPublisher = new RssPublisher();
$publsher->display($rssPublisher);
class PrintPublisher implements PublisherInterface
{
public function getContent() { /* some logic */ }
}
$printPublisher = new PrintPublisher();
$publsher->display($printPublisher);
20. SOLID
class Ptak
{
public function lec() { /* some logic */ }
}
class Golab extends Ptak
{
}
class Strus extends Ptak
{
public function lec()
{
throw new Exception('Not Implemented');
}
}
class Ptak
{
}
class LatajacyPtak extends Ptak
{
public function lec() { /* some logic */ }
}
public class Golab extends LatajacyPtak
{
}
public class Strus extends Ptak
{
}
21. SOLID
interface Jednoslad
{
public function jedz();
}
class Rower implements Jednoslad
{
public function jedz();
}
$notebook = new Rower();
$notebook->jedz();
class Motor implements Jednoslad
{
public function wlacz()
{
/* some logic */
}
public function jedz()
{
/* some logic */
}
}
$tablet = new Motor();
$tablet->jedz();
// throw new Exception("You need to start the engine")
25. SOLID
interface FormatterInterface
{
public function toPDF($content);
public function toXML($content);
public function toJSON($content);
}
class Formatter implements FormatterInterface
{
public function toPDF($content)
{
throw new Exception('Not Implemented');
}
public function toXML($content)
{
/* some logic */
}
public function toJSON($content)
{
/* some logic */
}
}
26. SOLID
interface PdfFormatterInterface
{
public function toPDF($content);
}
interface XmlFormatterInterface
{
public function toXML($content);
}
interface JsonFormatterInterface
{
public function toJSON($content);
}
class Formatter implements JsonFormatterInterface, XmlFormatterInterface
{
public function toJSON($content)
{
/* some logic */
}
public function toXML($content)
{
/* some logic */
}
}
31. SOLID
class MysqlConnection
{
public function connect()
{
/* some logic */
}
}
class PasswordReminder
{
private $connection;
public function __construct(MysqlConnection $connection)
{
$this->connection = $connection;
}
}
32. SOLID
interface DbConnectionInterface
{
public function connect();
}
class MysqlConnection implements DbConnectionInterface
{
public function connect()
{
/* some logic */
}
}
class PasswordReminder
{
private $connection;
public function __construct(DbConnectionInterface $connection)
{
$this->connection = $connection;
}
}
33. Podsumowanie
● klasa powinna mieć jeden i tylko jeden powód do zmiany
● pozwól na zmianę zachowania systemu poprzez dodawanie nowego kodu,
a nie modyfikowanie istniejącego
● buduj elementy tak aby były wzajemnie wymienne
● unikaj tworzenia zależności od elementów których nie potrzebujesz
● uniezależnij od siebie kod implementujący poszczególne warstwy
programista PHP
obecnie pracuję w firmie Aurora Creation sp. z o.o.
zajmuję się pracą ze sklepami na platformie Magento
tutaj są moje dane kontaktowe
na wstępie chciałbym jeszcze dodać że nie mam doświadczenia w publicznych prezentacjach, dlatego proszę o wyrozumiałość
oraz że będę posiłkował się notatkami
kiedy szef poprosił aby powiedzieć kilka słów na PHPStock’u
musiałem się zastanowić nad tematem o którym chciałbym powiedzieć
jednym z popularnych tematów jest SOLID
nie jest to temat nowy i na pewno wielu z was doskonale go zna
Nie był on omawiany na PHPStock’u dlatego wypada nadrobić to niedopatrzenie
Zaczynamy
na początek cytat
z jednej strony jeżeli cegiełki nie są solidnie zbudowane to architektura nie ma większego znaczenia. Z drugiej, można zrobić niezły bałagan z dobrze zbudowanych cegiełek
to cytat z książki Roberta C. Martina (Uncle Bob)
dość dobrze opisuje to z czym stykamy się na co dzień
wiadomo że dobrą architekturę poznaje się nie po tym jak aplikacja działa w momencie puszczenia live a po tym jak znosi zmiany wymagań w trakcie wieloletniego procesu utrzymania
czasem trzeba się dobrze nagłowić nad strukturą naszej aplikacji
SOLID został stworzony aby pomóc nam tworzyć dobrą architekturę
SOLID to akronim nazw 5 zasad traktujacych o dobrych praktykach tworzenia oprogramowania obiektowego
Zostały zebrane przez Robert C. Martin pomiędzy końcówką lat ‘80 a początkiem lat 2000
nazwa SOLID została zaproponowana przez Michael’a Feather w mailu ok 2004 roku
SOLID ma pomóc tworzyć kod który będzie dobrze znosił zmiany, będzie łatwiejszy w utrzymaniu i prostszy do zrozumienia
SOLID to tak naprawdę trochę więcej liter
jak wspomniałem to zbiór 5 zasad
Nie są one czymś czego bezwzględnie trzeba przestrzegać, ale ich przestrzeganie pozwala budowa lepsze aplikacje
teraz przejdziemy do omówienia poszczególnych reguł
Każdy moduł/klasa powinny mieć jeden i tylko jeden powód do zmiany.
Każda klasa powinna odpowiadać przed jednym aktorem systemu, tak aby zmiany wymagań jednego aktora nie wpływały na to jak działa aplikacja dla innych aktorów
Załóżmy że mamy w firmie dział kadr, księgowości oraz techniczny.
Programując system POWIĄZALIŚMY klasę Emploee z każdym z tych działów.
Księgowość -> calculatepay
Kadry -> reportHours
Techniczny -> save
W pewnym momencie księgowość uznała że trzeba zmienić sposób obliczania godzin
Programista wprowadza zmiany w klasie regularHours
Prowadzi to do niezamierzonej zmiany funkcjonowania metody reportHours
Przykład kodu
Klasa Menu
Odpowiedzialna za pobranie i przeparsowanie zasobów z jakiegoś zewnętrznego źródła
Na załączonym przykładzie klasa posiada metody
Download - odpowiedzialną za pobranie danych
Parse - odpowiedzialną za przeparsowanie pobranych danych
Log - odpowiedzialną za zapisanie błędu
Na tym przykładzie jedna klasa ma wiele odpowiedzialności
W związku z tym zmiana dowolnej z tych funkcji może powodować błędy w pozostałych
Na kolejnym przykładzie
Poszczególne odpowiedzialności zostały wydzielone
Do klas XmlParser oraz HttpClient
Błędy natomiast są zwracane jako wyjątki
Dzięki temu poszczególne funkcjonalności zostały rozdzielone
I zmiana w klasie XmlParser nie wpłynie na działanie pozostałych elementów
Otwarty na rozszerzenie / zamknięty na modyfikację
Reguła rozsławiona przez Bertrand Meyer w latach ‘80
“Jeżeli oprogramowanie ma pozwalać na łatwe wprowadzanie zmian, to musi zostać zaprojektowane tak, żeby pozwalało na zmianę zachowania systemu poprzez dodawanie nowego kodu, a nie modyfikowanie istniejącego.”
Załóżmy że piszemy klasę prezentującą jakąś treść, jakiś kontent
Na początku ma ona być wyświetlane na ekranie
Po pewnym czasie wymagania stawiane przed naszą klasą są rozszerzane i ma obsłużyć również drukarkę
Dodajemy ify
Po kolejnej zmianie wymagań klasa ma obsłużyć również kanał RSS
Dodajemy ify
Każda zmiana wymagała od nas powrotu do kodu i jego zmodyfikowania
Uniknęlibyśmy tego gdybyśmy logikę odpowiedzialną za prezentacje danych wydzielili do oddzielnych klas
A klasę menu zaprojektowali tak aby ich używała
Przykład kodu
Mamy klasę Publisher której zadaniem jest zaprezentowanie informacji w odpowiednim formacie
Logika odpowiedzialna za sformatowanie danych została zawarta w prostym Switch’u
Zmusza nas to do zmodyfikowania tego swicha za każdym razem gdy chcemy dodać nowy format
Kolejny przykład definiuje interfejs
Oraz zmusza klasę Publisher do pracy z interfejsem
Logikę odpowiedzialną za formatowanie umieszczamy w klasach implementujących nasz interfejs
Sposób w jaki mają zostać sformatowane dane przekazujemy z zewnątrz
Dzięki temu dodanie nowego formatu ogranicza się do utworzenia klasy implementującej nasz interfejs
W taki sposób uniknęliśmy modyfikowania istniejącego kodu przy dodawaniu nowych funkcji
Powinna istnieć możliwość zastąpienia klas ich potomkami w taki sposób aby nie psuło to aplikacji
Reguła liskov mówi nam o tym że elementy aplikacji powinny być na tyle wymienialne że możemy wziąć sobie jedną klasę, wstawić w to miejsce inną i wszystko powinno działać
Załóżmy że do restauracji codziennie o 8 rano przywożą owoce, dzięki temu od tej godziny kucharz może przygotowywać dania gościom
Któregoś dnia właściciel podpisał umowę z innym dostawcą, ale zapomniał powiedzieć mu że warzywa mają przyjechać o 8
Firma nie dostarczyła warzyw, kucharz nie miał jak przygotować potraw gościom
Stało się tak bo został złamany kontrakt
Gydby dostawa przyjechała na czas to wszystko działało by jak dawniej
Unikaj tworzenia zależności od elementów których nie potrzebujesz
Zgodnie z tą zasadą - tworzone interfejsy powinny zawierać minimalną liczbę deklaracji metod.
Mniejsza ilość metod może być zrekompensowana możliwością dziedziczenia wielu interfejsów
Najtrudniej było mi wymyślić przykład do tej zasady
Każdy z nas ma klucze
Ja swoje nosze w kieszeni
Gdy interfejs ma wiele metod
To implementując go musimy zaimplementować wszystkie jego metody
Nie da się wydzielić kilku z nich
Tak jak na przykładzie - musimy zaimplementować niewspieraną metodę toPDF
Jeżeli natomiast mamy kilka interfejsów zawierających mniejszą liczbę metod
To możemy dowolnie kształtować to co implementuje nasza klasa
Klasy powinny zależeć od abstrakcji nie od konkretnych implementacji.
Jeżeli Klasa 2 zależy od Klasy 1 to nie mamy możliwości zmienić jej implementacji
Jeżeli natomiast Klasa 2 Będzie zależeć od interfejsu
To możemy swobodnie podmienić Klasę 1 na inną klasę implementującą ten sam interfejs.
nie mogłem się powstrzymać aby umieścić tu ten rysunek
to ilustracja do wiersza Juliama Tuwima a nie do popularnego teleturnieju
i z rzepki nie wystrzelą pieniążki
Kto pamięta ten wiersz to wie że w ostatniej zwrotce wszystkie postacie leżały na ziemi
Tak samo i my możemy leżeć jeżeli szef poprosi o wymianę klasy która leży w fundamentach systemu
A która nie posiada abstrakcji
Dla przykładu
Klasa PasswordReminder zależy od MysqlConnection
To znaczy że do konstruktora PasswordReminder zawsze musimy wrzucić MysqlConnection
Jeżeli jednak utworzymy interfejs DbConnectionInterface
I klasę PasswordReminder uzależnimy od tego interfejsu
To do konstruktora będziemy mogli podać dowolną klasę implementującą ten interfejs.
Innymi słowy “Nasza klasa klasę PasswordReminder będzie niezależna od konkretnej implementacji interfejsu DbConnectionInterface”
Zasada odwracania zależności to zwieńćzenie całego SOLID.
Zachęca do uzależniania się od abstrakcji, a nie od konkretnych implementacji rozwiązań.