The document discusses various refactoring techniques for restructuring code to improve design, readability, and extensibility without changing external behavior. It provides examples of techniques like extracting methods, replacing temporary variables, simplifying conditional expressions, and dealing with generalization through inheritance/polymorphism. The techniques are organized into categories like composing methods, organizing data, simplifying method calls, and dealing with generalization.
We get it. Our website is a process, not a project. Without a content plan redesign projects are just short-term fixes. We need content governance. But where does the process start? In this session, learn how to plan for content governance—managing content roles, responsibilities, processes, documentation, tools and training. Create a sustainable content plan stakeholders can buy into and a website that can survive day two of your website redesign launch.
Best Practices for Running SQL Server on Amazon RDS (DAT323) - AWS re:Invent ...Amazon Web Services
Amazon Relational Database Service (Amazon RDS) provides a managed service to run SQL Server databases in AWS. While Amazon RDS handles provisioning and maintaining the SQL Server instance, there are things you can do to ensure that the SQL Server instance is healthy. We'll review some best practices involved in configuring the Amazon RDS SQL Server instance, focusing on availability, security and migration. We'll also hear from our customer Allstate, sharing details about their use of Amazon RDS.
We get it. Our website is a process, not a project. Without a content plan redesign projects are just short-term fixes. We need content governance. But where does the process start? In this session, learn how to plan for content governance—managing content roles, responsibilities, processes, documentation, tools and training. Create a sustainable content plan stakeholders can buy into and a website that can survive day two of your website redesign launch.
Best Practices for Running SQL Server on Amazon RDS (DAT323) - AWS re:Invent ...Amazon Web Services
Amazon Relational Database Service (Amazon RDS) provides a managed service to run SQL Server databases in AWS. While Amazon RDS handles provisioning and maintaining the SQL Server instance, there are things you can do to ensure that the SQL Server instance is healthy. We'll review some best practices involved in configuring the Amazon RDS SQL Server instance, focusing on availability, security and migration. We'll also hear from our customer Allstate, sharing details about their use of Amazon RDS.
Applying Real-time SQL Changes in your Hazelcast Data GridHazelcast
In this webinar
When you have an existing relational database that you want to scale out in a Hazelcast grid and third party applications are making changes to the underlying database, you get into a state where Hazelcast is unaware of these changes and will have stale data. Speedment solves this problem by tracking the database and pushing any changes into the Hazelcast grid automatically and continuously. The model supports transaction safe updates. Speedment is able to track the relational database regardless of how it is updated: using third party applications of any kind, SQL commands or even stored procedures.
This webinar aims to give you an overview on how changes to an existing SQL database can be propagated to objects in the Hazelcast grid. We will demonstrate how easy you could get a really strong database synchronisation with continuous updates of Hazelcast data-maps in glorious real-time
We’ll cover these topics:
- How to install Speedment Reflector on a relational database
- How Speedment Reflector can be integrated with Hazelcast
- Live Q&A
Presenter:
Per-Åke Minborg, CTO at Speedment
Per-Åke Minborg is founder and CTO at Speedment AB. He is a passionate Java developer, dedicated to OpenSource software and an expert in finding new ways of solving problems – the harder problem the better. As a result, he has 15+ US patent applications and invention disclosures. He has a deep understanding of in-memory databases, high-performance solutions, cloud technologies and concurrent programming. He has previously served as CTO and founder of Chilirec and the Phone Pages. Per-Åke has a M.Sc. in Electrical Engineering from Chalmers University of Technology and several years of studies in computer science and computer security at university and PhD level.
Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?!
So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?
Implementing CQRS and Event Sourcing with RavenDBOren Eini
CQRS stands for Command Query Responsibility Segregation. That is, that command stack and query stack are designed separately. This leads to a dramatic simplification of design and potential enhancement of scalability.
Events are a new trend in software industry. In real-world, we perform actions and these actions generate a reaction. Event Sourcing is about persisting events and rebuilding the state of the aggregates from recorded events.
In this talk I will share a lot of examples about how to effective implementing CQRS and Event Sourcing with RavenDB
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
- How to adapt to requirement changes using first-class functions
- How you can enhance code reusability using currying
- How you can make your code more robust by favouring immutability over mutability
- How you can design better APIs and reduce unintended null pointer exceptions using an optional data type"
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceIvan Chepurnyi
It is a pity, but I have to admit, that Magento 2 has issues in layout generation process. You'll learn during the talk about the benefits of compiling XML structures into PHP code, and even use the compilation of PHP code into PHP code to speed up your modules complex logic.
MCE^3 - Hannes Verlinde - Let The Symbols Do The WorkPROIDEA
Syntactic symbol manipulation may be the universal way of deriving new knowledge in science and engineering, but the technique is still rarely used in the act of writing software. We will explore this alternate way of reasoning about code, while demonstrating the power of formal refactoring and its potential for automation.
Introduction material for 360 Video. This includes Multimedia Pipeline and Rendering pipeline for playback. Comparison of projections for 360 video rendering.
More Related Content
Similar to Martin Fowler's Refactoring Techniques Quick Reference
Applying Real-time SQL Changes in your Hazelcast Data GridHazelcast
In this webinar
When you have an existing relational database that you want to scale out in a Hazelcast grid and third party applications are making changes to the underlying database, you get into a state where Hazelcast is unaware of these changes and will have stale data. Speedment solves this problem by tracking the database and pushing any changes into the Hazelcast grid automatically and continuously. The model supports transaction safe updates. Speedment is able to track the relational database regardless of how it is updated: using third party applications of any kind, SQL commands or even stored procedures.
This webinar aims to give you an overview on how changes to an existing SQL database can be propagated to objects in the Hazelcast grid. We will demonstrate how easy you could get a really strong database synchronisation with continuous updates of Hazelcast data-maps in glorious real-time
We’ll cover these topics:
- How to install Speedment Reflector on a relational database
- How Speedment Reflector can be integrated with Hazelcast
- Live Q&A
Presenter:
Per-Åke Minborg, CTO at Speedment
Per-Åke Minborg is founder and CTO at Speedment AB. He is a passionate Java developer, dedicated to OpenSource software and an expert in finding new ways of solving problems – the harder problem the better. As a result, he has 15+ US patent applications and invention disclosures. He has a deep understanding of in-memory databases, high-performance solutions, cloud technologies and concurrent programming. He has previously served as CTO and founder of Chilirec and the Phone Pages. Per-Åke has a M.Sc. in Electrical Engineering from Chalmers University of Technology and several years of studies in computer science and computer security at university and PhD level.
Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?!
So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?
Implementing CQRS and Event Sourcing with RavenDBOren Eini
CQRS stands for Command Query Responsibility Segregation. That is, that command stack and query stack are designed separately. This leads to a dramatic simplification of design and potential enhancement of scalability.
Events are a new trend in software industry. In real-world, we perform actions and these actions generate a reaction. Event Sourcing is about persisting events and rebuilding the state of the aggregates from recorded events.
In this talk I will share a lot of examples about how to effective implementing CQRS and Event Sourcing with RavenDB
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
- How to adapt to requirement changes using first-class functions
- How you can enhance code reusability using currying
- How you can make your code more robust by favouring immutability over mutability
- How you can design better APIs and reduce unintended null pointer exceptions using an optional data type"
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceIvan Chepurnyi
It is a pity, but I have to admit, that Magento 2 has issues in layout generation process. You'll learn during the talk about the benefits of compiling XML structures into PHP code, and even use the compilation of PHP code into PHP code to speed up your modules complex logic.
MCE^3 - Hannes Verlinde - Let The Symbols Do The WorkPROIDEA
Syntactic symbol manipulation may be the universal way of deriving new knowledge in science and engineering, but the technique is still rarely used in the act of writing software. We will explore this alternate way of reasoning about code, while demonstrating the power of formal refactoring and its potential for automation.
Introduction material for 360 Video. This includes Multimedia Pipeline and Rendering pipeline for playback. Comparison of projections for 360 video rendering.
High performance browser networking ch7,8Seung-Bum Lee
Presentation material including summary of "High Performance Browser Networking" by Ilya Grigorik. This book includes very good summary of computer network not only for internet browsing but also multimedia streaming.
High performance browser networking ch5,6Seung-Bum Lee
Presentation material including summary of "High Performance Browser Networking" by Ilya Grigorik. This book includes very good summary of computer network not only for internet browsing but also multimedia streaming.
High performance browser networking ch1,2,3Seung-Bum Lee
Presentation material including summary of "High Performance Browser Networking" by Ilya Grigorik. This book includes very good summary of computer network not only for internet browsing but also multimedia streaming.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
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.
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.
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/
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
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
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
AI Genie Review: World’s First Open AI WordPress Website CreatorGoogle
AI Genie Review: World’s First Open AI WordPress Website Creator
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-genie-review
AI Genie Review: Key Features
✅Creates Limitless Real-Time Unique Content, auto-publishing Posts, Pages & Images directly from Chat GPT & Open AI on WordPress in any Niche
✅First & Only Google Bard Approved Software That Publishes 100% Original, SEO Friendly Content using Open AI
✅Publish Automated Posts and Pages using AI Genie directly on Your website
✅50 DFY Websites Included Without Adding Any Images, Content Or Doing Anything Yourself
✅Integrated Chat GPT Bot gives Instant Answers on Your Website to Visitors
✅Just Enter the title, and your Content for Pages and Posts will be ready on your website
✅Automatically insert visually appealing images into posts based on keywords and titles.
✅Choose the temperature of the content and control its randomness.
✅Control the length of the content to be generated.
✅Never Worry About Paying Huge Money Monthly To Top Content Creation Platforms
✅100% Easy-to-Use, Newbie-Friendly Technology
✅30-Days Money-Back Guarantee
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
#AIGenieApp #AIGenieBonus #AIGenieBonuses #AIGenieDemo #AIGenieDownload #AIGenieLegit #AIGenieLiveDemo #AIGenieOTO #AIGeniePreview #AIGenieReview #AIGenieReviewandBonus #AIGenieScamorLegit #AIGenieSoftware #AIGenieUpgrades #AIGenieUpsells #HowDoesAlGenie #HowtoBuyAIGenie #HowtoMakeMoneywithAIGenie #MakeMoneyOnline #MakeMoneywithAIGenie
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.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
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
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.
Martin Fowler's Refactoring Techniques Quick Reference
1. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
1 | 11
Composing
Methods
Extract Method
- Code that can be grouped
- Meaningful name for method
void printOwing(double amount){
//print details
System.out.println(“name:” +name);
System.out.println(“amount: “ + amount);
}
void printOwing(double mount){
printDetails(name, amount);
}
void printDetails(String name, double amount){
System.out.println(“name:”+name);
System.out.println(“amount: “ + amount);
}
Inline Method
- inverse of “Extract Method”
- Method body is more obvious
int getRating() {
return (morethanFiveLateDeliveries()?2:1;
}
Boolean moreThanFiveLateDeliveries() {
return numberOfLateDeliveries > 5;
}
int getRating() {
return (numberOfLateDeliveries >5)?2:1;
}
Extract Variable
- Expression: hard to understand
- Separate self-explanatory var
if((platform.toUpperCase().indexOf(“MAC”) > -1) &&
(browser.toUpperCase().indexOf(“IE”) > -1) &&
wasInitialized() && resize > 0) {
//do something
}
final boolean isMacOs = platform.toUpperCase().indexOf(“MAC”) > -1;
final boolean isIEBrowser = browser.toUpperCase().indexOf(“IE”) > -1;
final Boolean wasResized = resize > 0;
if (isMacOs && isIEBrowser && wasInitialized() && wasResized) {
//do something
}
Inline Temp double basePrice = anOrder.basePrice();
return (basePrice > 1000);
return (anOrder.BasePrice() > 1000);
Replace Temp with Query
- Temp var holding expression
- Extract Expression into method
double basePrice = quantity * itemPrice;
if (basePrice > 1000)
return basePrice * 0.95;
else
return basePrice;
if (basePrice() > 1000)
return basePrice() * 0.95;
else
return basePrice() * 0.98;
double basePrice() {
return quantity * itemPrice;
}
Split Temporary Variable
- different var for different value
double temp = 2 * (height + width);
System.out.println(temp);
temp = height * width;
System.out.println(temp);
2. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
2 | 11
Composing
Methods
final double perimeter = 2 * (height + width);
System.out.println(perimeter);
final double area = height * width;
System.out.println(area);
Remove Assignments to Param
- use temp var instead
int discount(int inputVal, int Quantity, int yearToDate){
if (intputVal>50)
inputVal -=2;
}
int discount(int inputVal, int Quantity, int yearToDate) {
int result = inputVal;
if (inputVal > 50)
result - = 2;
}
Replace Method with Method Obj
- Extract Method cannot be applied
- Separate class
class Order {
…
double price() {
double primaryBasePrice;
double secondaryBasePrice;
double TeriaryBasePrice;
//long computation
…
}
}
class Order {
…
public double price() {
return new PriceCalculator(this).compute();
}
}
class PriceCalculator {
private double primaryBasePrice;
private double seconadaryBasePrice;
private double tertiaryBasePrice;
PriceCalculator(Order order) {
//copy relevant info
}
public double compute() {
//…
}
}
Substitute Algorithm
- Replace existing algorithm
- Replace body of the method
String foundPerson(String[] people) {
for(int I = 0;i<people.length;i++) {
if(people[i].equals(“Don”))
return “Don”;
if((people[i].equals(“John”))
return “John”;
if(people[i].equals(“Kent”))
return “Kent”;
}
return “”;
}
3. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
3 | 11
Composing
Methods
String foundPerson(String[] people) {
ListCandidates = Arrays.asList(new String[] {“Don”, “John”, “Kent”});
for(int i = 0;i<people.length;;i++) {
if (candidates.contains(people[i])) {
return people[i];
}
}
return “”;
}
Moving
Feature btwn
Obj
Move Method
- Use more features in another class
Move Field
- Field used by another class more
Extract Class
- One class does the work of two
Inline Class
- Class does almost nothing
Hide Delegate
- use A for getting B info
- new method of A delegating B
Remove Middle Man
- too many methods that simply
delegate
- force the client to call the end methods
directly
Introduce Foreign method
- server class cannot contain the needed
class
- add a method in the client
Date newStart = new Date(previousEnd.getYear(), previousEnd.getMonth(),
previousEnd.getDate() + 1);
Date newStart = nextDay(previousEnd);
private static Date nextDay(Date arg) {
return new Date(arg.getYear(), arg.getMonth(), arg.getDate() + 1);
}
4. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
4 | 11
Moving
Feature btwn
Obj
Introduce Local Extension
- server class cannot contain some
methods that you need
Organizing
Data
Self Encapsulate Field
- Create a getter and setter
private int low, high
Boolean includes(int arg) {
return arg >= low && arg <= high;
}
private int low, high
Boolean includes(int arg) {
return arg >= getLow() && arg <= getHigh();
}
int getLow() {
return low;
}
int getHigh() {
rturn high;
}
Replace Data Value with Object
- Contain a data field with its own
behavior and associated data
- Change the data item into an object
Change Value to Reference
- Many identical instances of a single
class
- Converted to a single reference object
Change Reference to Value
- Reference object is too small
- Converted it into a value object
Replace Array with Object
- Arrays containing various types of data
- Replace array with an object
String[] row = new String[];
row[0] = “Liverpool”;
row[1] = “15”;
Performance row = new Performance();
row.setName(“Liverpool”);
row.setWins(“15”);
Duplicate Observed Data
- Domain data in GUI control
- Copy data to model and set up
observer
Change Unidirectional Association to
Bidirectional
- Add missing association
Change Bidirectional Association to
Unidirectional
- Remove unused association
5. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
5 | 11
Organizing
Data
Replace Magic Number with Symbolic
Constant
- number having a certain meaning
- Replace with constant
double potentialEnergy(double mass, double height) {
return mass * 9.81 * height;
}
double potentialEnergy(double mass, double height) {
return mass * GRAVITATION_CONSTANT * height;
}
static final double GRAVITATION_ONSTANT = 9.81;
Encapsulate Field
- make public field as private
- provide accessors
public String name;
private String name;
public String getName() {
return name;
}
public String setName(String arg) {
name = arg;
}
Encapsulate Collection
- Collection Field with a simple
getter/setter
- Getter returns read-only, Setter
replaced with adding/removing elements
Replace Type Code with Class
- fields containing type code
- Create a new class and use its objects
instead
(Obsolete: Java enumeration is another
option)
Replace Type Code with Subclasses
- immutable type code affecting the
behavior
- Create subclasses for each value
(OCP)
Replace Type Code with State/Strategy
- Type code affects behavior, but cannot
use subclassing
- Replace Type code with State/Strategy
Replace Subclass with Fields
- Subclass differs in constant-returning
methods
- Remove subclass
6. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
6 | 11
Simplifying
Conditional
Expression
Decompose conditional
- Complex conditional
- Decompose to separate methods
if(data.before(SUMMER_START)||date.after(SUMMER_END))
charge = quantity * winterRate + winterServiceCharge;
else
charge = quantity * summerRate;
if(notSummer(date))
charge = winterCharge(quantity);
else
charge = summerCharge(quantity);
Consolidate Conditional Expression double disabilityAmount() P
if (seniority < 2)
return 0;
if(mounthsDisabled > 12)
return 0;
if (isPatTime)
return 0;
…
}
double disabilityAmount() {
if(isNortEligableForDisability())
return 0;
…
}
Consolidate Duplicate Conditional
Fragments
if (isSpecialDeal()) {
total = price* 0.95;
send();
} else {
total = price * 0.98;
send();
}
if (isSpecialDeal()) {
total = price* 0.95;
} else {
total = price * 0.98;
}
send();
Remove Control Flag void checkSecurity(String[] people) {
boolean found = false;
for (int i = 0; i < people.length; i++) {
if (! found) {
if (people[i].equals ("Don")){
sendAlert();
found = true;
}
if (people[i].equals ("John")){
sendAlert();
found = true;
}
}
}
}
7. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
7 | 11
Simplifying
Conditional
Expression
Remove Control Flag void checkSecurity(String[] people) {
boolean found = false;
for (int i = 0; i < people.length; i++) {
if (people[i].equals ("Don")){
sendAlert();
found = true;
break;
}
if (people[i].equals ("John")){
sendAlert();
found = true;
break;
}
}
}
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();
};
Replace Conditional with Polymorphism
Introduce Null Object
Introduce Assertion double getExpenseLimi() {
//should have either expense limit or a primary project
return (expenseLimit != NULL_EXPSENSE)? expenseLimit
;:primaryProject.getMemberExpenseLimit()
}
9. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
9 | 11
Simplifying
Method Calls
Remove Setting Method
Hide Method
Replace Constructor With Factory
Method
Employee (int type) {
_type = type;
}
static Employee create(int type) {
return new Employee(type);
}
Encapsulate Downcast
(Needed?)
Object lastReading() {
return readings.lastElement();
}
Reading lastReading() {
return (Reading) readings.lastElement();
}
Replace Error Code With Exception int withdraw(int amount) {
if (amount > _balance)
return -1;
else {
_balance -= amount;
return 0;
}
}
void withdraw(int amount) throws BalanceException {
if (amount > _balance) throw new BalanceException();
_balance -= amount;
}
Replace Exception With Test double getValueForPeriod (int periodNumber) {
try {
return _values[periodNumber];
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
double getValueForPeriod (int periodNumber) {
if (periodNumber >= _values.length) return 0;
return _values[periodNumber];
}
Dealing with
Generalizatio
n
Pull Up Field
10. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
10 | 11
Dealing with
Generalizatio
n
Pull Up Method
Pull Up Constructor Body class Manager extends Employee...
public Manager (String name, String id, int grade) {
_name = name;
_id = id;
_grade = grade;
}
public Manager (String name, String id, int grade) {
super (name, id);
_grade = grade;
}
Push Down Method
Push Down Field
Extract Subclass
Extract Superclass
Extract Interface
Collapse Hierarchy
11. Refactoring Techniques Quick Reference https://technical-leader.tistory.com
11 | 11
Dealing with
Generalizatio
n
From Template Method
Replace Inheritance with Delegation
Replace Delegation with Inheritance
Big
Refractorings
Tease Apart Inheritance
Convert Procedural Design to Objects
Separate Domain from Presentation
Extract Hierarchy