Uma apresentação sobre Refactoring e Code Smells, abordando características do software em estado de apodrecimento, identificação de alguns code smells, e refactoring, e focado em melhoria contínua profissional em relação a engenharia de software.
Code Smells y SOLID: A qué huele tu código?Johnny Ordóñez
A qué huele tu código? Cómo detectar olores en mi código?
Una mirada hacia las buenas prácticas de programación y la forma de detectar y corregir problemas frecuentes para de esta forma crear un código de calidad aplicando los principios SOLID.
Code Smells y SOLID: A qué huele tu código?Johnny Ordóñez
A qué huele tu código? Cómo detectar olores en mi código?
Una mirada hacia las buenas prácticas de programación y la forma de detectar y corregir problemas frecuentes para de esta forma crear un código de calidad aplicando los principios SOLID.
I have worked with and studied several top developers (e.g., leaders of an open source project with millions of downloads) as they write code. Both anecdotal and video evidence shows that these developers are fixing bugs 10-15X faster than others. Yet when analyzing these developers' performances it's not their superior brainpower that sets them apart, it's their workflow strategy. Instead of wasting time clicking around the Solution Explorer for a starting point they search for relevant files and get started instantly. Instead of haphazardly scrolling through open files they navigate the code by following its structure (e.g., references and calls), eliminating many costly distractions. Adopting this search-driven, structured workflow allows even more modest developers (like myself) to dramatically increase their productivity.
In this talk I'll focus on two things: providing evidence of the problem and offering practical advice on how to implement this approach in your own Visual Studio. To understand the problem we'll analyze videos of developers working on real bug tasks, listen to interviews with top developers, and even delve (briefly) into a few academic studies. To help implement this approach in your own workspace we'll download the appropriate tool support (e.g., the free, open source Sando extension), work through an example bug together on my machine, and finally I'll provide an example for you to try on your own laptop. By the end of this session you should be able to search and navigate code, and ultimately squash bugs, much more efficiently.
The Sieve of Eratosthenes - Part 1 - with minor correctionsPhilip Schwarz
In this slide deck we are going to see some examples of how the effort required to read an understand the Sieve of Eratosthenes varies greatly depending on the programming paradigm used to implement the algorithm.
We'll see code in Java, Scheme, Haskell and Scala.
This version of the deck contains some minor corrections (see errata section in first version for details)
In this slide deck we are going to see some examples of how the effort required to read an understand the Sieve of Eratosthenes varies greatly depending on the programming paradigm used to implement the algorithm.
We'll see code in Java, Scheme, Haskell and Scala.
Errata:
slide 10: "points asserts" should be "asserts"
slide 22,23,25: "// larger than that root.private static int" should be "// larger than that root"
slide 29: "three slides" should be "two slides"
slide 45,46,48,49: List.range(m,n + 1) should be List.range(2,maxValue + 1)
Some of the most common and easy-to-calculate/easy-to-measure code metrics. Understanding these can help you make your code better: avoiding code rot and writing maintainable code all starts here. Content is created for C# .net, however, the underlying principles apply to other languages/frameworks as well.
Refactoring: Improve the design of existing codeValerio Maggio
Refactoring: Improve the design of existing code
Software Engineering class on main refactoring techniques and bad smells reported in the famous Fawler's book on this topic!
Getting Unstuck: Working with Legacy Code and DataCory Foy
From this presentation for the IASA in 2007, Cory covers common challenges in dealing with Legacy Code and Data, and some tools and techniques for handling them.
Presentation I gave at the Houston TechFest Sept 2009. This presentation goes over Extension Methods, Lambdas, Expression Trees, and Fluent Interfaces. I also show examples from popular frameworks using these techniques.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Chris Laning
Got a legacy application? Trying to turn into a modern one? This presentation, given by Chris Laning, takes you through a methodical process that helps you attack that seemingly insurmountable task and tame it like a pro! The presentation is ColdFusion focused, but many of the methods employed could be used by programmers in other languages. This presentation was given at NCDevCon on September 13, 2014 in Raleigh, NC.
Chris is a Senior WebDeveloper and has been doing web development since 1996.
I have worked with and studied several top developers (e.g., leaders of an open source project with millions of downloads) as they write code. Both anecdotal and video evidence shows that these developers are fixing bugs 10-15X faster than others. Yet when analyzing these developers' performances it's not their superior brainpower that sets them apart, it's their workflow strategy. Instead of wasting time clicking around the Solution Explorer for a starting point they search for relevant files and get started instantly. Instead of haphazardly scrolling through open files they navigate the code by following its structure (e.g., references and calls), eliminating many costly distractions. Adopting this search-driven, structured workflow allows even more modest developers (like myself) to dramatically increase their productivity.
In this talk I'll focus on two things: providing evidence of the problem and offering practical advice on how to implement this approach in your own Visual Studio. To understand the problem we'll analyze videos of developers working on real bug tasks, listen to interviews with top developers, and even delve (briefly) into a few academic studies. To help implement this approach in your own workspace we'll download the appropriate tool support (e.g., the free, open source Sando extension), work through an example bug together on my machine, and finally I'll provide an example for you to try on your own laptop. By the end of this session you should be able to search and navigate code, and ultimately squash bugs, much more efficiently.
The Sieve of Eratosthenes - Part 1 - with minor correctionsPhilip Schwarz
In this slide deck we are going to see some examples of how the effort required to read an understand the Sieve of Eratosthenes varies greatly depending on the programming paradigm used to implement the algorithm.
We'll see code in Java, Scheme, Haskell and Scala.
This version of the deck contains some minor corrections (see errata section in first version for details)
In this slide deck we are going to see some examples of how the effort required to read an understand the Sieve of Eratosthenes varies greatly depending on the programming paradigm used to implement the algorithm.
We'll see code in Java, Scheme, Haskell and Scala.
Errata:
slide 10: "points asserts" should be "asserts"
slide 22,23,25: "// larger than that root.private static int" should be "// larger than that root"
slide 29: "three slides" should be "two slides"
slide 45,46,48,49: List.range(m,n + 1) should be List.range(2,maxValue + 1)
Some of the most common and easy-to-calculate/easy-to-measure code metrics. Understanding these can help you make your code better: avoiding code rot and writing maintainable code all starts here. Content is created for C# .net, however, the underlying principles apply to other languages/frameworks as well.
Refactoring: Improve the design of existing codeValerio Maggio
Refactoring: Improve the design of existing code
Software Engineering class on main refactoring techniques and bad smells reported in the famous Fawler's book on this topic!
Getting Unstuck: Working with Legacy Code and DataCory Foy
From this presentation for the IASA in 2007, Cory covers common challenges in dealing with Legacy Code and Data, and some tools and techniques for handling them.
Presentation I gave at the Houston TechFest Sept 2009. This presentation goes over Extension Methods, Lambdas, Expression Trees, and Fluent Interfaces. I also show examples from popular frameworks using these techniques.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Chris Laning
Got a legacy application? Trying to turn into a modern one? This presentation, given by Chris Laning, takes you through a methodical process that helps you attack that seemingly insurmountable task and tame it like a pro! The presentation is ColdFusion focused, but many of the methods employed could be used by programmers in other languages. This presentation was given at NCDevCon on September 13, 2014 in Raleigh, NC.
Chris is a Senior WebDeveloper and has been doing web development since 1996.
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
Takashi Kobayashi and Hironori Washizaki, "SWEBOK Guide and Future of SE Education," First International Symposium on the Future of Software Engineering (FUSE), June 3-6, 2024, Okinawa, Japan
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
What is Augmented Reality Image Trackingpavan998932
Augmented Reality (AR) Image Tracking is a technology that enables AR applications to recognize and track images in the real world, overlaying digital content onto them. This enhances the user's interaction with their environment by providing additional information and interactive elements directly tied to physical images.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
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/
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
Launch Your Streaming Platforms in MinutesRoshan Dwivedi
The claim of launching a streaming platform in minutes might be a bit of an exaggeration, but there are services that can significantly streamline the process. Here's a breakdown:
Pros of Speedy Streaming Platform Launch Services:
No coding required: These services often use drag-and-drop interfaces or pre-built templates, eliminating the need for programming knowledge.
Faster setup: Compared to building from scratch, these platforms can get you up and running much quicker.
All-in-one solutions: Many services offer features like content management systems (CMS), video players, and monetization tools, reducing the need for multiple integrations.
Things to Consider:
Limited customization: These platforms may offer less flexibility in design and functionality compared to custom-built solutions.
Scalability: As your audience grows, you might need to upgrade to a more robust platform or encounter limitations with the "quick launch" option.
Features: Carefully evaluate which features are included and if they meet your specific needs (e.g., live streaming, subscription options).
Examples of Services for Launching Streaming Platforms:
Muvi [muvi com]
Uscreen [usencreen tv]
Alternatives to Consider:
Existing Streaming platforms: Platforms like YouTube or Twitch might be suitable for basic streaming needs, though monetization options might be limited.
Custom Development: While more time-consuming, custom development offers the most control and flexibility for your platform.
Overall, launching a streaming platform in minutes might not be entirely realistic, but these services can significantly speed up the process compared to building from scratch. Carefully consider your needs and budget when choosing the best option for you.
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
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
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
13. Rigidez
Parece simples, mas difícil de mudar
Mudanças em cascata
Dependências entre módulos
Medo de correção de bugs
14. Fragilidade
Code and Fix
Manutenção Adventure
Desenvolvimento fora de controle
Credibilidade começa a cair
Terminei a feature!!!
Ei mah, tua feature quebrou!
15. Imobilidade
Não é possível reutilizar software
Muitas Dependências
Responsabilidades de mais
Risco alto para reutilizar
25. “Refactoring is a disciplined
technique for restructuring an
existing body of code, altering its
internal structure without
changing its external behavior.”
Martin Fowler
26. By continuously improving the design of code, we
make it easier and easier to work with. This is in
sharp contrast to what typically happens: little
refactoring and a great deal of attention paid to
expediently adding new features. If you get into the
hygienic habit of refactoring continuously, you'll
find that it is easier to extend and maintain code.
Joshua Kerievsky
31. Long Method
The object programs that live best and longest are those with short
methods.
[…]
The key here is not method length but the semantic distance
between what the method does and how it does it.
[…]
32. Long Method
[…]
Development environments that allow you to see two methods at
once help to eliminate this step, but the real key to making it easy to
understand small methods is good naming.
[…]
33. public int fechaFolha(String folha) {
// imprime a folha adicionando bla bla bla
try {
FileReader arq = new FileReader(folha);
BufferedReader lerArq = new BufferedReader(arq);
String linha = lerArq.readLine();
while (linha != null) {
System.out.printf("%sn", linha);
this.linha += linha;
linha = lerArq.readLine();
}
arq.close();
} catch (IOException e) {
System.err.printf("Erro na abertura do arquivo: %s.n",
e.getMessage());
}
// verifica se a folha é especial
if (linha.contains("ARS0010304")) {
this.folhaEspecial = true;
}
35. public int fechaFolha(String folha) {
imprimeFolha(folha);
eFolhaEspecial();
atualizaDadosDePagamento();
}
private void ehFolhaEspecial() {
if (linha.contains("ARS0010304")) {
this.folhaEspecial = true;
}
}
private void imprimeFolha(String folha) {
try {
FileReader arq = new FileReader(folha);
BufferedReader lerArq = new BufferedReader(arq);
String linha = lerArq.readLine();
while (linha != null) {
System.out.printf("%sn", linha);
this.linha += linha;
linha = lerArq.readLine();
}...
I throw away
commented code
36. Few Short Methods Per Class
★ Fácil de testar.
★ Fácil para reusar.
★ Fácil para modificar.
★ Menos bugs são descoberto, estatisticamente em métodos
curtos e classes curtas.
★ Equipe de desenvolvimento coda mais rápido, porque há menos
necessidade de refactoring.
40. Shotgun Surgery
You whiff this when every time you make a kind of change, you have
to make a lot of little changes to a lot of different classes. When
the changes are all over the place, they are hard to find, and it's
easy to miss an important change.
43. Feature Envy
A classic smell is a method that seems more interested in a class
other than the one it actually is in.
[ . . . ]
The most common focus of the envy is the data.
44. Feature Envy
Mova o método quando todo o método quer estar claramente em
outro lugar, ou…
Extraia o método quando apenas uma parte do método é invejoso,
ou…
Extraia a classe se você tem vários métodos invejosos e a
funcionalidade não chega a pertencer a outro objeto.
46. Long Parameter List
public Object method(int var,int var1,int
var2,int var3,int var4,int var5,int var6,int
var7) {
...
}
47. Long Parameter List
[…]
long parameter lists are hard to understand, because they become
inconsistent and difficult to use, and because you are forever
changing them as you need more data.
[…]
51. Duplicated Code
Large Class
Method
Shotgun Surgery Long Parameter List
Refused Bequest
BBAADD SSMMDatEEa ClLaLssLLSS
Comments Lazy Class
Divergent Change
Parallel Inheritance Hierarchies
Switch Statements
Primitive Obsession
Data Clumps
Feature
Envy Incomplete Library Class
Alternative Classes with Different Interfaces
Inappropriate
Intimacy
Middle Man
Message Chains
Temporary Field
Speculative Generality
53. Extract Method
Motivation
Extract Method is one of the most common refactorings I do. I look at a method that is too long or look at code
that needs a comment to understand its purpose. I then turn that fragment of code into its own method.
I prefer short, well-named methods for several reasons. First, it increases the chances that other methods can
use a method when the method is finely grained. Second, it allows the higher-level methods to read more like a
series of comments. Overriding also is easier when the methods are finely grained.
It does take a little getting used to if you are used to seeing larger methods. And small methods really work only
when you have good names, so you need to pay attention to naming. People sometimes ask me what length I
look for in a method. To me length is not the issue. The key is the semantic distance between the method name
and the method body. If extracting improves clarity, do it, even if the name is longer than the code you have
extracted.
54. void printOwing() {
Enumeration e = _orders.elements();
double outstanding = 0.0;
System.out.println("**************************");
System.out.println("***** Customer Owes ******");
System.out.println("**************************");
while (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
System.out.println("name:" + _name);
System.out.println("amount" + outstanding);
}
55. void printOwing() {
Enumeration e = _orders.elements();
double outstanding = 0.0;
System.out.println("**************************");
System.out.println("***** Customer Owes ******");
System.out.println("**************************");
while (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
System.out.println("name:" + _name);
System.out.println("amount" + outstanding);
}
64. Replace Temp with Query
Motivation
The problem with temps is that they are temporary and local. Because they can be seen only in the context of
the method in which they are used, temps tend to encourage longer methods, because that's the only way you
can reach the temp. By replacing the temp with a query method, any method in the class can get at the
information. That helps a lot in coming up with cleaner code for the class.
Replace Temp with Query often is a vital step before Extract Method. Local variables make it difficult to extract,
so replace as many variables as you can with queries.
The straightforward cases of this refactoring are those in which temps are assigned only to once and those in
which the expression that generates the assignment is free of side effects. Other cases are trickier but possible.
You may need to use Split Temporary Variable or Separate Query from Modifier first to make things easier. If
the temp is used to collect a result (such as summing over a loop), you need to copy some logic into the query
method.
80. double getPreco() {
int pb = q * p;
double fd;
if (pb > 1000) fd = 0.95;
else fd = 0.98;
return pb * fd;
}
“Quem foi o FDP que
escreveu isso aqui?”
81. Replace Conditional with Polymorphism
Motivation
One of the grandest sounding words in object jargon is polymorphism. The essence of polymorphsim is that it
allows you to avoid writing an explicit conditional when you have objects whose behavior varies depending on
their types.
As a result you find that switch statements that switch on type codes or if-then-else statements that switch on
type strings are much less common in an object-oriented program.
Polymorphism gives you many advantages. The biggest gain occurs when this same set of conditions appears in
many places in the program. If you want to add a new type, you have to find and update all the conditionals.
But with subclasses you just create a new subclass and provide the appropriate methods. Clients of the class
don't need to know about the subclasses, which reduces the dependencies in your system and makes it easier
to update.
82. Replace Conditional with Polymorphism
double getSpeed() {
switch (_type) {
case EUROPEAN:
return getBaseSpeed();
case AFRICAN:
return getBaseSpeed() - getLoadFactor() * _numberOfCoconuts;
case NORWEGIAN_BLUE:
return (_isNailed) ? 0 : getBaseSpeed(_voltage);
}
throw new RuntimeException ("Should be unreachable");
}
85. public class Employee {
private EmployeeType _type;
int payAmount() {
switch (getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
int getType() {
return _type.getTypeCode();
}
86. public class Employee {
private EmployeeType _type;
int payAmount() {
switch (getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
int getType() {
return _type.getTypeCode();
}
87. public class Employee {
private EmployeeType _type;
int payAmount() {
switch (getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
int getType() {
return _type.getTypeCode();
}
88. public class Employee {
private EmployeeType _type;
int payAmount() {
switch (getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
int getType() {
return _type.getTypeCode();
}
public int getMonthlySalary() {
return _monthlySalary;
}
public int getCommission() {
return _monthlySalary + _commission;
}
public int getBonus() {
return _monthlySalary + _bonus;
}
89. public class Employee {
private EmployeeType _type;
int payAmount() {
switch (getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
int getType() {
return _type.getTypeCode();
}
90. public class EmployeeType ...
int payAmount(Employee emp) {
switch (getTypeCode()) {
case ENGINEER:
return emp.getMonthlySalary();
case SALESMAN:
return emp.getMonthlySalary() + emp.getCommission();
case MANAGER:
return emp.getMonthlySalary() + emp.getBonus();
default:
throw new RuntimeException("Incorrect Employee");
}
}
…
91. public class EmployeeType ...
int payAmount(Employee emp) {
switch (getTypeCode()) {
case ENGINEER:
return emp.getMonthlySalary();
case SALESMAN:
return emp.getMonthlySalary() + emp.getCommission();
case MANAGER:
return emp.getMonthlySalary() + emp.getBonus();
default:
throw new RuntimeException("Incorrect Employee");
}
}
…
92. public class Employee {
…
int payAmount() {
switch (getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
…
}
94. public class Salesman extends EmployeeType{
int payAmount(Employee emp) {
return emp.getMonthlySalary() + emp.getCommission();
}
…
public class Manager extends EmployeeType {
int payAmount(Employee emp) {
return emp.getMonthlySalary() + emp.getBonus();
}
…
95. Decompose Conditional
Motivation
One of the most common areas of complexity in a program lies in complex conditional logic. As you write code
to test conditions and to do various things depending on various conditions, you quickly end up with a pretty
long method. Length of a method is in itself a factor that makes it harder to read, but conditions increase the
difficulty. The problem usually lies in the fact that the code, both in the condition checks and in the actions, tells
you what happens but can easily obscure why it happens.
As with any large block of code, you can make your intention clearer by decomposing it and replacing chunks of
code with a method call named after the intention of that block of code. With conditions you can receive
further benefit by doing this for the conditional part and each of the alternatives. This way you highlight the
condition and make it clearly what you are branching on. You also highlight the reason for the branching.
101. Tá funcionando então deixa!?
The code "works", you know it works,
but you need to refactor in order to put
the code into a form you can understand
and work with in order to extend its
functionality.
102. Tá funcionando então deixa!?
you write tests against the code, knowing
that if the test fails, you wrote the test
wrong. Don't change the code until you
are confident you have enough tests to
let you know if one of your refactorings
broke something.
104. Não tenha medo
de mudar, isto só
perigoso quando
você não tem
testes de unidade
automatizados!
105. … permita-se ser um
profissional melhor…
Use teste automatizados!
@rponte
Testes de unidade
automatizados!
106. Projete para suas
necessidades atuais, prever
o futuro pode não ser a
melhor opção.
Se você não precisa, não
faça!
@OficialMaeDinah
Eu sei fazer isso chapa,
você não! Bjus ;***
120. Simples é um adjetivo de dois gêneros e
dois números, que descreve uma coisa
que não é complicada, que não possui
enfeites, ou que é clara, evidente ou
natural. Também pode designar uma
tarefa fácil de concretizar ou resolver
(um problema de simples resolução).
121. Um projeto simples sempre leva menos
tempo para terminar do que um problema
complexo. Então, sempre faça a coisa mais
simples que poderia funcionar em seguida.
Se você encontrar algo que é complexo
substituí-lo por algo simples. É sempre
mais rápida e barata para substituir código
complexo agora, antes de perder muito
mais tempo com ela.
122. Um projeto simples sempre leva menos
tempo para terminar do que um problema
complexo. Então, sempre faça a coisa mais
simples que poderia funcionar em seguida.
Se você encontrar algo que é complexo
substituí-lo por algo simples. É sempre
mais rápida e barata para substituir código
complexo agora, antes de perder muito
mais tempo com ela.
123. Um projeto simples sempre leva menos
tempo para terminar do que um problema
complexo. Então, sempre faça a coisa mais
simples que poderia funcionar em seguida.
Se você encontrar algo que é complexo
substituí-lo por algo simples. É sempre
mais rápida e barata para substituir código
complexo agora, antes de perder muito
mais tempo com ela.
124. Manter as coisas o mais simples possível,
desde que seja possível, nunca adicione
funcionalidades antes de serem agendada.
Cuidado, porém, manter um design simples
é um trabalho difícil.
125. Manter as coisas o mais simples possível,
desde que seja possível, nunca adicione
funcionalidades antes de serem agendada.
Cuidado, porém, manter um design simples
é um trabalho difícil.
126. Simplicidade: a arte de maximizar a quantidade
de trabalho que não precisou ser feito.
127. The Zen of Python
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
129. Links
The principles of OOD ~ http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf
Simplicity ~ http://www.extremeprogramming.org/rules/simple.html
Refactoring ~ http://refactoring.com
Refactoring to Patterns ~ http://goo.gl/k8fGol
Bad Smells ~ http://sourcemaking.com/refactoring/bad-smells-in-code
Cod Smells ~ http://c2.com/cgi/wiki?CodeSmell
Using Good Naming To Detect Bad Code ~ http://c2.com/cgi/wiki?UsingGoodNamingToDetectBadCode
Few Short Methods Per Class ~ http://c2.com/cgi/wiki?FewShortMethodsPerClass
Refactoring Legacy Code ~ http://c2.com/cgi/wiki?RefactoringLegacyCode