La qualità del codice che maneggiamo tutti i giorni è molto importante ma difficile da ottenere. Non si tratta di un traguardo da raggiungere ma di un processo di continuo miglioramento.
Nel talk vedremo quali sono le più comuni debolezze del codice, vedremo come sia possibile manipolarlo senza paura e come approfittare di ogni occasione per migliorarlo seguendo alcuni principi di design.
https://brewbox.community/
https://www.facebook.com/events/1673978505997779
https://www.youtube.com/watch?v=aQQWrQZYliU
Ten years analysing large code bases: a perspectiveRoberto Di Cosmo
Looking back at ten years analysing free an open source distributions, we take a step back and analyse what made this kind of research possible. Availability, traceability and uniformity of the software code base arise as key factors, and they are also essential properties needed for reproducibility and preservation.
This is why we are starting a new project to make sure these properties will be ensured for all software, and not only well structured ecosystems like Debian.
At the end, a call for action to the scientific community to contribute to the project.
In questa sessione a quattro mani introdurremo alcuni dei refactorings più comuni e più facilmente applicabili nell'utilizzo quotidiano, e vedremo come risolverli in maniera facile, veloce ed indolore utilizzando ReSharper e pochi colpi di tastiera.
Incidentalmente, inseriremo nel mentre un pò di patterns e di Test-Driven Development, perchè "se non è testato, allora non funziona"
Presentation I held before my colleagues about the book Clean Code (http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882).
It contains the highlights of several chapters and hint/guidelines a developer should know.
Ten years analysing large code bases: a perspectiveRoberto Di Cosmo
Looking back at ten years analysing free an open source distributions, we take a step back and analyse what made this kind of research possible. Availability, traceability and uniformity of the software code base arise as key factors, and they are also essential properties needed for reproducibility and preservation.
This is why we are starting a new project to make sure these properties will be ensured for all software, and not only well structured ecosystems like Debian.
At the end, a call for action to the scientific community to contribute to the project.
In questa sessione a quattro mani introdurremo alcuni dei refactorings più comuni e più facilmente applicabili nell'utilizzo quotidiano, e vedremo come risolverli in maniera facile, veloce ed indolore utilizzando ReSharper e pochi colpi di tastiera.
Incidentalmente, inseriremo nel mentre un pò di patterns e di Test-Driven Development, perchè "se non è testato, allora non funziona"
Presentation I held before my colleagues about the book Clean Code (http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882).
It contains the highlights of several chapters and hint/guidelines a developer should know.
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard WorkJoseph Yoder
Big Ball of Mud (BBoM) architectures are viewed as the culmination of many design decisions that, over time, result in a system that is hodgepodge of steaming and smelly anti-patterns. It can be arguably claimed that one of the reasons for the growth and popularity of agile practices is partially due to the fact that the state of the art of software architectures was not that good. Being agile, with its focus on extensive testing and frequent integration, has shown that it can make it easier to deal with evolving architectures (possibly muddy) and keeping systems working while making significant improvements and adding functionality. Time has also shown that Agile practices are not sufficient to prevent or eliminate Mud. It is important to recognize what is core to the architecture and the problem at hand when evolving an architecture.
This talk will examine the paradoxes that underlie Big Balls of Mud, what causes them, and why they are so prominent. I’ll explore what agile practices can help us avoid or cope with mud. I’ll also explain why continuous delivery and TDD with refactoring is not enough to help ensure clean architecture and why it is important to understand what is core to the architecture and the problem at hand. Understanding what changes in the system and at what rates can help you prevent becoming mired in mud. By first understanding where a system’s complexities are and where it keeps getting worse, we can then work hard (and more intelligently) at sustaining the architecture. This can become a key value to the agile team. The results will leave attendees with practices and patterns that help clean your code (refactor) as well as keeping the code clean or from getting muddier.
Additionally, I’ll talk about some practices and patterns that help keep the code clean or from getting muddier. Some of these include: Testing, Divide & Conquer, Gentrification, Demolition, Quarantine, Refactoring, Craftmanship and the like.. The original Big Ball of Mud paper described some best practices such as SHEARING LAYERS and SWEEPING IT UNDER THE RUG as a way to help deal with muddy architectures. Additionally there are some other practices such as PAVING OVER THE WAGON TRAIL and WIPING YOUR FEET AT THE DOOR that can make code more habitable.
You are already the Duke of DevOps: you have a master in CI/CD, some feature teams including ops skills, your TTM rocks ! But you have some difficulties to scale it. You have some quality issues, Qos at risk. You are quick to adopt practices that: increase flexibility of development and velocity of deployment. An urgent question follows on the heels of these benefits: how much confidence we can have in the complex systems that we put into production? Let’s talk about the next hype of DevOps: SRE, error budget, continuous quality, observability, Chaos Engineering.
Code we've written once has to be kept readable, maintainable, understandable and extensible for many years. Good code is not self-serving but the foundation for working together.
Refactoring can help you to keep the quality of the relevant parts of our systems high.
The technique is really easy (almost too easy) - improve the naming, structure, and responsibility in small steps that don't change behavior and run your tests after each step.
18 years ago I got hooked on Refactoring when Martin Fowler's first book came out. I've been using it since then on a daily basis on many different projects. Since then a lot has changed, especially with the help of modern IDEs with their automated refactorings and intentions.
Now he asked me to help review the 2nd edition. Our discussions reminded me that each generation of developers should be taught this crucial skill. That's why I want to give an overview of core refactorings and code-smells but also demonstrate the tips and tricks of today's tools that make this task so much easier.
Plus a sneak preview of the upcoming book.
With JustDecompile, Telerik's free .NET decompiler, you can easily recover lost source code or peer into assemblies to discover the root cause of an external bug. The same engine that powers JustDecompile is also used in Telerik JustCode, a Visual Studio add-in designed to enhance developer productivity. In this webcast, you will learn how to use JustDecompile and JustCode for decompilation scenarios you are likely to encounter in the office.
Periodic Table of Agile Principles and PracticesJérôme Kehrli
Recently I fell by chance on the Periodic Table of the Elements... Long time no see... Remembering my physics lessons in University, I always loved that table. I remembered spending hours understanding the layout and admiring the beauty of its natural simplicity.
So I had the idea of trying the same layout, not the same approach since both are not comparable, really only the same layout for Agile Principles and Practices.
The result is in this presentation: The Periodic Table of Agile Principles and Practices:
Talk given in DevFest Asturias 2019 (GDG Google Developer Group Asturias)
16.11.2019 Gijón (Spain)
The Legacy Code came to stay
(spanish)
El legacy vino para quedarse
RESUMEN
Es una charla que pone en relieve que los servicios que damos los agilistas, no están orientados a sustituir el trabajo de otros, sino que entre todos conseguimos mejorar nuestros productos y nuestra vida diaria en el trabajo.
ABSTRACT
Casi todos sabemos lo que es el Legacy Code, ese proyecto al que todos nos hemos enfrentado alguna vez y que cuesta trabajar con él.
Lo que era algo a evitar o a sustituir, en los últimos años por diversas razones, se ha convertido en algo que debe seguir existiendo durante mucho tiempo, por lo que se busca la manera de seguir manteniendolo con confianza.
Esta necesidad parece técnica, y a lo sumo se entiende que involucra a los equipos que lo mantienen, pero realmente es una estrategia empresarial en la que se busca además de mantener la funcionalidad existente, avanzar el producto y cubrir la necesidad actual, con la ayuda de un equipo al que hay que mantener motivado, practicando además, eso tan difícil que hoy se conoce como La Retención del Talento.
Explicaremos en esta charla los diferentes tipos de retos enmarcados en Código Legado, tantos técnicos como con los equipos a los que nos hemos enfrentado en Codesai y qué estrategias usamos para afrontarlos.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
More Related Content
Similar to 2018 01-29 - brewbox - refactoring. sempre, senza pietà
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard WorkJoseph Yoder
Big Ball of Mud (BBoM) architectures are viewed as the culmination of many design decisions that, over time, result in a system that is hodgepodge of steaming and smelly anti-patterns. It can be arguably claimed that one of the reasons for the growth and popularity of agile practices is partially due to the fact that the state of the art of software architectures was not that good. Being agile, with its focus on extensive testing and frequent integration, has shown that it can make it easier to deal with evolving architectures (possibly muddy) and keeping systems working while making significant improvements and adding functionality. Time has also shown that Agile practices are not sufficient to prevent or eliminate Mud. It is important to recognize what is core to the architecture and the problem at hand when evolving an architecture.
This talk will examine the paradoxes that underlie Big Balls of Mud, what causes them, and why they are so prominent. I’ll explore what agile practices can help us avoid or cope with mud. I’ll also explain why continuous delivery and TDD with refactoring is not enough to help ensure clean architecture and why it is important to understand what is core to the architecture and the problem at hand. Understanding what changes in the system and at what rates can help you prevent becoming mired in mud. By first understanding where a system’s complexities are and where it keeps getting worse, we can then work hard (and more intelligently) at sustaining the architecture. This can become a key value to the agile team. The results will leave attendees with practices and patterns that help clean your code (refactor) as well as keeping the code clean or from getting muddier.
Additionally, I’ll talk about some practices and patterns that help keep the code clean or from getting muddier. Some of these include: Testing, Divide & Conquer, Gentrification, Demolition, Quarantine, Refactoring, Craftmanship and the like.. The original Big Ball of Mud paper described some best practices such as SHEARING LAYERS and SWEEPING IT UNDER THE RUG as a way to help deal with muddy architectures. Additionally there are some other practices such as PAVING OVER THE WAGON TRAIL and WIPING YOUR FEET AT THE DOOR that can make code more habitable.
You are already the Duke of DevOps: you have a master in CI/CD, some feature teams including ops skills, your TTM rocks ! But you have some difficulties to scale it. You have some quality issues, Qos at risk. You are quick to adopt practices that: increase flexibility of development and velocity of deployment. An urgent question follows on the heels of these benefits: how much confidence we can have in the complex systems that we put into production? Let’s talk about the next hype of DevOps: SRE, error budget, continuous quality, observability, Chaos Engineering.
Code we've written once has to be kept readable, maintainable, understandable and extensible for many years. Good code is not self-serving but the foundation for working together.
Refactoring can help you to keep the quality of the relevant parts of our systems high.
The technique is really easy (almost too easy) - improve the naming, structure, and responsibility in small steps that don't change behavior and run your tests after each step.
18 years ago I got hooked on Refactoring when Martin Fowler's first book came out. I've been using it since then on a daily basis on many different projects. Since then a lot has changed, especially with the help of modern IDEs with their automated refactorings and intentions.
Now he asked me to help review the 2nd edition. Our discussions reminded me that each generation of developers should be taught this crucial skill. That's why I want to give an overview of core refactorings and code-smells but also demonstrate the tips and tricks of today's tools that make this task so much easier.
Plus a sneak preview of the upcoming book.
With JustDecompile, Telerik's free .NET decompiler, you can easily recover lost source code or peer into assemblies to discover the root cause of an external bug. The same engine that powers JustDecompile is also used in Telerik JustCode, a Visual Studio add-in designed to enhance developer productivity. In this webcast, you will learn how to use JustDecompile and JustCode for decompilation scenarios you are likely to encounter in the office.
Periodic Table of Agile Principles and PracticesJérôme Kehrli
Recently I fell by chance on the Periodic Table of the Elements... Long time no see... Remembering my physics lessons in University, I always loved that table. I remembered spending hours understanding the layout and admiring the beauty of its natural simplicity.
So I had the idea of trying the same layout, not the same approach since both are not comparable, really only the same layout for Agile Principles and Practices.
The result is in this presentation: The Periodic Table of Agile Principles and Practices:
Talk given in DevFest Asturias 2019 (GDG Google Developer Group Asturias)
16.11.2019 Gijón (Spain)
The Legacy Code came to stay
(spanish)
El legacy vino para quedarse
RESUMEN
Es una charla que pone en relieve que los servicios que damos los agilistas, no están orientados a sustituir el trabajo de otros, sino que entre todos conseguimos mejorar nuestros productos y nuestra vida diaria en el trabajo.
ABSTRACT
Casi todos sabemos lo que es el Legacy Code, ese proyecto al que todos nos hemos enfrentado alguna vez y que cuesta trabajar con él.
Lo que era algo a evitar o a sustituir, en los últimos años por diversas razones, se ha convertido en algo que debe seguir existiendo durante mucho tiempo, por lo que se busca la manera de seguir manteniendolo con confianza.
Esta necesidad parece técnica, y a lo sumo se entiende que involucra a los equipos que lo mantienen, pero realmente es una estrategia empresarial en la que se busca además de mantener la funcionalidad existente, avanzar el producto y cubrir la necesidad actual, con la ayuda de un equipo al que hay que mantener motivado, practicando además, eso tan difícil que hoy se conoce como La Retención del Talento.
Explicaremos en esta charla los diferentes tipos de retos enmarcados en Código Legado, tantos técnicos como con los equipos a los que nos hemos enfrentado en Codesai y qué estrategias usamos para afrontarlos.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfJay Das
With the advent of artificial intelligence or AI tools, project management processes are undergoing a transformative shift. By using tools like ChatGPT, and Bard organizations can empower their leaders and managers to plan, execute, and monitor projects more effectively.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
5. Fonti
Clean Code: A Handbook of Agile
Software Craftsmanship
Robert C. Martin (2008)
Extreme Programming Explained:
Embrace Change
Kent Beck (1999)
Refactoring: Improving
the Design of Existing Code
Martin Fowler (1999)
@milanoxpug
@milanoxpug
6. “
”
Any fool can write code
that a computer can understand.
Good programmers write
code that humans can understand
Refactoring: Improving the Design of Existing Code: Martin Fowler
7. “
”
Programming is the art of
telling another human being
what one wants the computer to do
Donald Knuth
9. Contesti e stili
contesti diversi generano stili diversi
Linguaggi
Tecnologie
Framework
Community
Competenze
Personalità
10. Mi ispiro a OOP
Ma molti concetti sono applicabili a qualunque contesto
Attenzione
11. “
”
Problems with projects
can invariably be traced back to
somebody not talking to somebody else
about something important
Kent Beck, Extreme Programming Explained: Embrace Change
12. La comunicazione può essere problematica
Faticoso da leggere
10 a 1
Nasconde bachi
Comportamenti non evidenti aiutano a nascondersi
Difficile da modificare
Comprensione del design e delle intenzioni
Invita al degrado
Finestra rotta
13. “
”
is a surface indication
that usually corresponds to
a deeper problem in the system
Code smell
14. Duplicated code
Liar Names
Uncommunicative Name
Inconsistent Names
Comments
Mixing levels of abstraction
within a function
Data Clumps
Primitive Obsession
Long Method
Long Names
Long Parameter List
Large Class
Code Smells (catalogo completo?)
Feature Envy
Inappropriate Intimacy
Incomplete Library Class
Middle Man
Message Chains
Alternative Classes with
Different Interfaces
Refused Bequest
Switch Statements
Temporary Field
Divergent Change
Shotgun Surgery
Parallel Inheritance
Hierarchies
Dead Code
Data Class
Lazy Class
Speculative Generality
Incomplete Library Class
Message Chains
Middle Man
Conditional Complexity
Combinatorial Explosion
Type Embedded in Name
Oddball Solution
Indecent Exposure
Solution Sprawl
Excessive use of literals
Cyclomatic complexity
Downcasting
Orphan variable or constant
class
Excessively short identifiers
Excessively long identifiers
Excessive return of data
15. Code Smells: Duplicated code
“Number one in the stink parade”
(Martin Fowler - Refactoring
“Root of all evil”
(Robert C. Martin - Clean Code)
“The bane of software development”
(Jeff Atwood - blog.codinghorror.com)
16. Code Smells: smells nei nomi
Liar names
Metodi con effetti collaterali, diversi da quel che ci si aspetta
Uncommunicative names
Descrivono efficacemente? Lasciano intendere quello che accadrà?
Inconsistent names
Terminologia, convenzioni.
20. Code Smells: Data Clumps
“Data items tend to be like children;
they enjoy hanging around in groups together”
void drawPoint(int xPos, int yPos);
double valueBetween(Date startDate, Date endDate);
void drawPoint(Point point);
double valueBetween(DateInterval interval);
21. Code Smells: Primitive Obsession
double computeValue(List<Invoice> invoices){ … }
List<Invoice> readAllInvoicesOfMonth(Date mese){ … }
List<Invoice> readAllInvoicesOfMonth(int anno, int mese){ … }
Packages findByTrackingCode(String bfTrackingCode){ … }
“Use small objects for small tasks”
22. Code Smells: Feature Envy
“a method that seems more interested
in a class other than the one it actually is in.”
public class Amount {
public void computeTotal(Item item) {
int amount1 = item.getAmountOne();
int amount2 = item.getAmountTwo();
int amount3 = item.getAmountThree();
int total = amount1 + amount2 + amount3;
item.setTotal(total);
}
27. Organizzare la riscrittura
Tempo, Risorse e Organizzazione
Ma il valore è poco visibile
Sviluppo interrotto o parallelo?
Risorse suddivise o nuove?
Rilascio big bang o incrementale?
Quale valore si ottiene?
28. Cosa si riscrive?
Bisogna riportare TUTTE le features
Nascoste, dimenticate, bug
La verità sta solo nel codice
non nella memoria o nella documentazione
31. La riscrittura è la soluzione giusta
‣ Per adeguamento tecnologico
‣ Quando l’accesso al sorgente è difficile
‣ Per accedere a nuove tecnologie
‣ …
Non per fare le pulizie
33. “
”
Programmers restructure the system
without changing its behavior
to remove duplication,
improve communication,
simplify, or add flexibility
Refactoring
Kent Beck da “Extreme Programming Explained”
34. “
”
Refactoring is a disciplined technique
for restructuring an existing body of code,
altering its internal structure
without changing its external behavior
Refactoring
Martin Fowler dalla home page di www.refactoring.com
35. 1. Miglioramento del codice
2. Nessuna aggiunta o modifica
di funzionalità
3. Tecnica disciplinata
Refactoring
36. ‣ Dopo aver aggiunto una feature: per pulire
‣ Prima di aggiungere una feature: per fare spazio
‣ Per consolidare un livello di comprensione del
problema
“as I gain understanding about the program, I embed that understanding
into the code for later so I don't forget what I learned”
‣ Per comprendere codice ignoto che si sta
esplorando
‣ Per stanare un baco
‣ Ogni volta che puzza
Quando? Sempre!
37. Come? Senza pietà!
‣ Coraggio
‣ Costanza e disciplina
‣ Nessuna tolleranza per i difetti
38. 1. Two hats
2. Baby steps
3. Test automatici
4. Undo
In pratica: 4 punti fondamentali
39. In pratica: (1) Two hats
Make it work
Aggiungi le features
Punti a una soluzione semplice che funzioni
Make it clean
Non modifichi il comportamento del sistema
Approfitti della conoscenza acquisita
40. In pratica: (2) Baby steps
Modifiche semplici
La probabilità di sbagliare è bassa
Sistema rimane sempre funzionante
Ogni modifica non rompe il sistema
41. In pratica: (3) Test automatici
Evitare le regressioni
Rete di sicurezza
Evitare la paura
La confidenza è fondamentale
per affrontare le ristrutturazioni più audaci
42. In pratica (4) Undo
Deve essere facile ricominciare
commit, refactor, commit, refactor, REVERT
Quando ricominciare?
Quando sei insicuro a metà di un refactoring
Quando sei fuori controllo
Come si ricomincia
Con passi più piccoli e idee più chiare
43. Passi di refactoring: catalogo completo (?)
Add Parameter
Change Bidirectional
Association to Unidirectional
Change Reference to Value
Change Unidirectional
Association to Bidirectional
Change Value to Reference
Collapse Hierarchy
Consolidate Conditional
Expression
Consolidate Duplicate
Conditional Fragments
Decompose Conditional
Duplicate Observed Data
Dynamic Method Definition
Eagerly Initialized Attribute
Encapsulate Collection
Encapsulate Downcast
Encapsulate Field
Extract Class
Extract Interface
Extract Method
Extract Module
Extract Subclass
Extract Superclass
Extract Surrounding Method
Extract Variable
Form Template Method
Hide Delegate
Hide Method
Inline Class
Inline Method
Inline Module
Inline Temp
Introduce Assertion
Introduce Class Annotation
Introduce Expression Builder
Introduce Foreign Method
Introduce Gateway
Introduce Local Extension
Introduce Named Parameter
Introduce Null Object
Introduce Parameter Object
Isolate Dynamic Receptor
Lazily Initialized Attribute
Move Eval from Runtime to
Parse Time
Move Field
Move Method
Parameterize Method
Preserve Whole Object
Pull Up Constructor Body
Pull Up Field
Pull Up Method
Push Down Field
Push Down Method
Recompose Conditional
Remove Assignments to
Parameters
Remove Control Flag
Remove Middle Man
Remove Named Parameter
Remove Parameter
Remove Setting Method
Remove Unused Default
Parameter
Rename Method
Replace Abstract Superclass
with Module
Replace Array with Object
Replace Conditional with
Polymorphism
Replace Constructor with
Factory Method
Replace Data Value with
Object
Replace Delegation With
Hierarchy
Replace Delegation with
Inheritance
Replace Dynamic Receptor
with Dynamic Method
Definition
Replace Error Code with
Exception
Replace Exception with Test
Replace Hash with Object
Replace Inheritance with
Delegation
Replace Loop with Collection
Closure Method
Replace Magic Number with
Symbolic Constant
Replace Method with Method
Object
Replace Nested Conditional
with Guard Clauses
Replace Parameter with
Explicit Methods
Replace Parameter with
Method
Replace Record with Data
Class
Replace Subclass with Fields
Replace Temp with Chain
Replace Temp with Query
Replace Type Code with Class
Replace Type Code with
Module Extension
Replace Type Code With
Polymorphism
Replace Type Code with
State/Strategy
Replace Type Code with
Subclasses
Self Encapsulate Field
Separate Query from Modifier
Split Temporary Variable
Substitute Algorithm
44. Replace Nested Conditional with Guard Clauses
double getPayAmount() {
double result;
if (isDead){
result = deadAmount();
} else {
if (isSeparated) {
result = separatedAmount();
} else {
if (isRetired) {
result = retiredAmount();
} else {
result = normalPayAmount();
}
}
}
return result;
}
double getPayAmount() {
if (isDead) {
return deadAmount();
}
if (isSeparated) {
return separatedAmount();
}
if (isRetired) {
return retiredAmount();
}
return normalPayAmount();
}
Prima Dopo
45. Introduce Parameter Object (prima)
public int getValBetween(Date startDate, Date endDate) {
int result = 0;
for (Entry each : entries) {
if ((each.getDate().after(startDate)
&& each.getDate().before(endDate))
|| each.getDate().equals(startDate)
|| each.getDate().equals(endDate)) {
result += each.getValue();
}
}
return result;
}
46. Introduce Parameter Object (dopo)
public int getValBetween(DateInterval dateInterval) {
int result = 0;
for (Entry each : entries) {
if (dateInterval.include(each.getDate())) {
result += each.getValue();
}
}
return result;
}
47. Introduce Parameter Object (dopo)
public class DateInterval {
private final Date startDate;
private final Date endDate;
public DateInterval(Date startDate, Date endDate) {
this.startDate = startDate;
this.endDate = endDate;
}
public boolean include(Date date) {
if ((date.after(startDate) && date.before(endDate))) {
return true;
}
if (date.equals(startDate) || date.equals(endDate)) {
return true;
}
return false;
}
}
48. Da dove si comincia? In quale direzione? Chi guida?
Principi di design
Clean code, GRASP, SOLID
Soluzioni a problemi comuni
Design pattern
Provare più soluzioni possibili
Spike, refactor/revert