SlideShare a Scribd company logo
1 of 39
Refactoring
Ways to improve your code
Roman Sevastyanov
Software developer
Co-founder doge.codes
Twitter: @romasevastyanov
Github: @sevastyanovio
Telegram: @davex69
Refactoring
is a small intermediate steps in the
direction of heaven
It’s a teamwork
Refactoring steps
Refactoring steps
1. Figure out the problem
Refactoring steps
1. Figure out the problem
2. Allocate time and plan
Refactoring steps
1. Figure out the problem
2. Allocate time and plan
3. Configure “refactoring tools” and tests
Refactoring steps
1. Figure out the problem
2. Allocate time and plan
3. Configure “refactoring tools” and tests
4. Refactoring
Refactoring steps
1. Figure out the problem
2. Allocate time and plan
3. Configure “refactoring tools” and tests
4. Refactoring
5. Make problems visible
Static analysis
Psalm
Phan
phpstan
PHP-CS-Fixer
Build the libraries
Code smells
Long method
Long method
Switch operator
Switch operator
Duplicated code
Conditional Complexity
Conditional Complexity
Comments
Type Embedded in Name
Uncommunicative Name
Large Class
Dead Code
Speculative Generality
Oddball Solution
Data Class
Refused Bequest
Shotgun Surgery
What next?
● Refactoring - Martin Fowler (book)
What next?
● Refactoring - Martin Fowler (book)
● Refactoring Guru (interactive course)
What next?
● Refactoring - Martin Fowler (book)
● Refactoring Guru (interactive course)
● https://blog.codinghorror.com/code-smells/
● SOLID
● TDD
● DDD

More Related Content

Similar to Roman Sevastyanov "Рефакторинг - пути улучшения кода"

Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Editionjexp
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsJarrod Overson
 
Refactoring, A First Example
Refactoring, A First ExampleRefactoring, A First Example
Refactoring, A First ExampleVorleak Chy
 
javabasics_ programming development chapter01
javabasics_ programming development chapter01javabasics_ programming development chapter01
javabasics_ programming development chapter01Udeshg90
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
Code Review
Code ReviewCode Review
Code ReviewRavi Raj
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - GreachHamletDRC
 
Workshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublinWorkshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublinMichelangelo van Dam
 
Howto Test A Patch And Make A Difference!
Howto Test A Patch And Make A Difference!Howto Test A Patch And Make A Difference!
Howto Test A Patch And Make A Difference!Joel Farris
 
Refactoring Fest
Refactoring FestRefactoring Fest
Refactoring FestNaresh Jain
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your CodeNate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0Nate Abele
 
Ruby codebases in an entropic universe
Ruby codebases in an entropic universeRuby codebases in an entropic universe
Ruby codebases in an entropic universeNiranjan Paranjape
 

Similar to Roman Sevastyanov "Рефакторинг - пути улучшения кода" (20)

Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Edition
 
Testing and symfony2
Testing and symfony2Testing and symfony2
Testing and symfony2
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web Applications
 
Refactoring, A First Example
Refactoring, A First ExampleRefactoring, A First Example
Refactoring, A First Example
 
Why You Should Be Fixing Bugs
Why You Should Be Fixing BugsWhy You Should Be Fixing Bugs
Why You Should Be Fixing Bugs
 
javabasics_ programming development chapter01
javabasics_ programming development chapter01javabasics_ programming development chapter01
javabasics_ programming development chapter01
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Code Review
Code ReviewCode Review
Code Review
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
 
Workshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublinWorkshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublin
 
Howto Test A Patch And Make A Difference!
Howto Test A Patch And Make A Difference!Howto Test A Patch And Make A Difference!
Howto Test A Patch And Make A Difference!
 
Refactoring Fest
Refactoring FestRefactoring Fest
Refactoring Fest
 
DeepPavlov 2019
DeepPavlov 2019DeepPavlov 2019
DeepPavlov 2019
 
Untangling6
Untangling6Untangling6
Untangling6
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
Ruby codebases in an entropic universe
Ruby codebases in an entropic universeRuby codebases in an entropic universe
Ruby codebases in an entropic universe
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 
Refactoring 2 The Max
Refactoring 2 The MaxRefactoring 2 The Max
Refactoring 2 The Max
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 

More from Fwdays

"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y..."How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...Fwdays
 
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil TopchiiFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro SpodaretsFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua", Maksym KindritskyiFwdays
 
"Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl..."Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl...Fwdays
 
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T..."How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...Fwdays
 
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ..."The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...Fwdays
 
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu..."[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...Fwdays
 
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care..."[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...Fwdays
 
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"..."4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...Fwdays
 
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast..."Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...Fwdays
 
"Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others..."Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others...Fwdays
 
"Mission (im) possible: How to get an offer in 2024?", Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?", Oleksandra MyronovaFwdays
 
"Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv..."Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv...Fwdays
 
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin..."How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...Fwdays
 

More from Fwdays (20)

"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y..."How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
 
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
 
"Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl..."Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl...
 
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T..."How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
 
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ..."The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
 
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu..."[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
 
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care..."[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
 
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"..."4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
 
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast..."Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...
 
"Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others..."Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others...
 
"Mission (im) possible: How to get an offer in 2024?", Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?", Oleksandra Myronova
 
"Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv..."Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv...
 
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin..."How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 

Roman Sevastyanov "Рефакторинг - пути улучшения кода"

Editor's Notes

  1. Всем привет, я Рома Севастьянов. Я создатель doge.codes. Мы делаем онлайн образование great again. Также я работал 6-7 лет как разработчик в американских стартапах/компаниях
  2. Чтоб такого не было, нужно рефАкторить. Но не сразу все, а (следующий слайд)
  3. Keep taking small steps. In the right direction of course. Progress is way more important than achieving perfection. РефАкторинг – это процесс. Постепенно улучшая и рефАкторя код – он становиться лучше. Даже если вы думаете, что проект очень плохой – лучше его не переписывать, а рефакторить Также зацепить такое понятие, как КУЛЬТУРА РЕФАКТОРИНГА
  4. Вам нужно делать рефакторинг и париться, чтоб код был хорошим. Не терпите небрежность в коде, это нонсенс. Но не только вы должны ЭТО делать, но и ВСЯ команда. Не имеет значения, как тяжко вы работали чтоб зарефакторить код, если кто-то один его факапит и портит. Командная дисциплина тут очень нужна. Если кто-то начинает делать левый код, вся команда в это скатиться. Не допускайте ЭТОГО.
  5. Правильный процесс рефакторинга позволит не превратить в mess его. Делайте МАЛЕНЬКИЕ шаги итеративно. И будет результат. Small victories generate momentum. Прогресс НАМНОГО важнее, чем единожды идеальный код. Вы со временем, зависит от размера вашего проекта УВИДЕТЕ хороший результат от рефакторинга.
  6. Для того, чтоб начать рефАкторить. Определитесь с проблемой. Не нужно переписывать тонны кода. Пусть для начала это будет 1 класс / контроллер. Или несколко методов. Все будет, со временем.
  7. Это важная тема. У нас в Украине и даже в мире, я очень редко видел КУЛЬТУРУ рефАкторинга. Поэтому, очень вероятно, что менеджмент БУДЕТ против этой непонятной штуки, которая не приносит денег. Прокачивайте свой эмоциональный интеллект, чтоб понять, как другие люди видят ситуацию. Вот вы приходите к менеджеру (я говорю о тех, кто не понимает зачем нужен рефакторинг), и просите выделить время на рефАкторинг, допустим, модели одной. Или какой-то бизнес-логики. Потому что она плохо написана и с ней сложно работать. Как это слышит и видит менеджер? Привет, я написал плохой код, вы мне заплатили за это. Давайте я сейчас попытаюсь сделать лучше и вы мне еще раз заплатите. Поэтому, попытайтесь донести для менеджера что такое рефАкторинг Это как ходить в душ Что сжатые сроки не всегда позволяют быстро писать хорошо Что продукт меняется и то, что раньше ожидалось – сейчас не подходит, другие реалии
  8. Настройте refАctoring tools. Под refАctoring tools я имею ввиду static analytics библиотеки и плагины, которые УПРОЩАЮТ вашу жизнь. О них я поговорю чуть позже. Это делается очень просто. Тесты помогут вам понять ваш проект. И не зафакапить после рефакторинга.
  9. Кроме тестов нужно еще и видеть проблемы. Настройте логирование и мониторинг ошибок (Sentry) и нагрузки. Посмотри на эти 5 шагов. Тут нету ничего сложного. Возможно часть вещей уже используется у вас на проекте. Но если это делать, допустим, сначала раз в месяц. Или выделят одну иттерацию на это – то результаты будут ошеломляющие.
  10. Обзор тулз для рефакторинга Эти программы / либы позволяют УПРОСТИТЬ работу разработчика. Меньше париться и меньше держать в голове ньюансов. Лучше фокусироваться на разработке ФИЧ и продукта. git hooks Psalm Phpstan https://github.com/exakat/php-static-analysis-tools
  11. Psalm - тулза, которую разработала компания Vimeo Статический анализатор кода. Проверяет основные ошибки в PHP коде и подсказывает, что где исправить Очень просто устанавливается через Компосер ДАЖЕ ЕСТЬ ОНЛАЙН Советую запускать перед и после рефакторинга Отлично подходит для того, чтоб превентить ошибки в проде
  12. Phan - более комплексная тулза, создал ее Расмус Лердорф, создатель PHP Немного сложно установить Тоже статический анализатор кода, но умеет очень много всего. Чекает PHPDoc (@property, @deprecated, @method анотации) Чекает классы, методы, уровни доступа, мертвый код и тд и многое другое Есть разные плагины к нему
  13. phpstan - прикольная и простая утилита, которая помогает НАХОДИТЬ PHP errors БЕЗ запуска кода Простая в использовании, подходит даже для дебага
  14. PHP-CS-Fixer - PHP Coding Standards Fixer Скорей всего некоторый из вас УЖЕ пользовались этим. Он используется в многих плагинах. Фиксит стиль кода по стандартам.
  15. git hooks Отличная и очень простая тулза, которая позволяет на определенных событиях запускать нужные скрипты. Например, PSR-2 чекер стиля Или что-то другое Это, по ститик аналитик туллс все
  16. Хорошим показателем цивилизации является количество библиотек на квадратный метр. Поэтому, чтобы внедрить цивилизованность в ваш проект, это может быть отличным подходом. Так же помимо библиотек – можно делать самодостаточные микросервисы с которыми общаться по API МЕНЬШЕ КОДА – МЕНЬШЕ ПРОБЛЕМ
  17. Разбор признаков плохого кода Code smell (запахи кода) – это не баги, но это признаки, что нужно рефакторить код. Термин придумал Kent Beck в 90-тых.
  18. Проблема: Часто бывает такое, что пишешь что-то новое в метод и он разрастается очень большим. Чем больше фукнция – тем сложнее ее понять Решение: Вынести часть метода в отдельный метод (или даже класс)
  19. Проблема: Часто бывает такое, что пишешь что-то новое в метод и он разрастается очень большим. Чем больше фукнция – тем сложнее ее понять Решение: Вынести часть метода в отдельный метод (или даже класс)
  20. Очень часто SWITCH оператор является очень опасным местом для рефакторинга Его можно использовать в местах, где ОН очень просто используется или например, в Фабричном паттерне ООП
  21. Очень часто SWITCH оператор является очень опасным местом для рефакторинга Его можно использовать в местах, где ОН очень просто используется или например, в Фабричном паттерне ООП
  22. Проблема: Какой-то код повторяется или повторяется частично. Происходит часто из-за того, что лень писать новый код. Или джун увидел почти такой же код, скопировал и отправил Решение: Удалить один из методов или сделать темплейт для кода
  23. Проблема: Сложное условие. Или много if-ов Решение: Вынести в отдельный метод, разбить на части. Использовать стратегию
  24. Проблема: Сложное условие. Или много if-ов Решение: Вынести в отдельный метод, разбить на части. Использовать стратегию, decorator
  25. Проблема: Когда в коде много комментариев, особенно, когда они объясняют не “зачем?”, а “что?” Мы говорим не об @phpdoc Также, не стоить удалять комментарии, которые объясняют сложный алгоритм Решение: Писать комментарии для людей, не машин. Делать названия функция таким, чтоб было и так понятно без комментариев.
  26. Проблема: Тип записан в названии переменной, это устаревший подход. Так лучше не делать. Потому что если поменяется ее тип – нужно будет изменять название Решение: Переименовать
  27. Проблема: Непонятное или не точное название класса, переменной, метода Решение: Переименовать
  28. Проблема: Есть большой класс, в котором много лишнего. Сложно работать с ним и поддерживать Решение: Большой класс, так же как и большой метод можно разбить на маленькие классы.
  29. Проблема: Есть код, который не работал уже давно. Мертвый код Решение: Удалить такой код
  30. Проблема: Пишим когд, который будет спасать нас от всех проблем в мире Решение: Пишем код, который нам нужен сегодня, сжимаєм иерархию
  31. Проблема: Представим, что у нас есть 1 проблема в двух разных частях системы. И это решено разными способами Решение: Нужно делать одним способом. Тут нам помогает Интерфейс с Адаптерами
  32. Проблема: Избегайте классов, которые просто сторят данные Решение: Либо удалять такие классы и переносить куда-то поля, либо делать их полезными
  33. Проблема: Унаследовались от класса, но его методы никогда не используются Решение: Замените наследование – делегированием. Засуньте в род класс нужные методы, если они нужны
  34. Проблема: Когда хотите сделать простое изменение, а это требует много изменений Решение: Move Method [F 142] Move Field [F 146] Inline Class [F 154]