### Scenario Structure Example Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Demonstrates the basic structure of an interactive scenario, including ID, language, steps, starting code, resulting code, and actions. ```plaintext extract-method:java ### 1. Some step. 2. Another step. ### ``` class Example { } ``` ### ``` class Example { public int field; } ``` ### Set step 1 # Here's the first popover ``` -------------------------------- ### Replace Temp with Query - Initial Setup Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/replace-temp-with-query.md This snippet illustrates the initial state of the code before refactoring, highlighting temporary variables like 'basePrice' and 'discountFactor' that will be replaced. ```java int basePrice; double discountFactor; // ... other code ... basePrice = quantity * itemPrice; discountFactor = discount; // ... usage of basePrice and discountFactor ... ``` -------------------------------- ### Extract Superclass: Initial Setup Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/extract-superclass.md This snippet shows the initial state of the 'Employee' and 'Department' classes before the refactoring begins. It highlights the common 'Name' property and the distinct 'GetAnnualCost' and 'GetTotalAnnualCost' methods. ```csharp public class Employee { public string Name { get; private set; } public int GetAnnualCost() { // ... calculation logic ... return 0; } } public class Department { public string Name { get; private set; } public int GetTotalAnnualCost() { // ... calculation logic ... return 0; } } ``` -------------------------------- ### Move Field: Initial Setup and Accessor Methods Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/move-field.md This snippet shows the initial state of the target class (AccountType) after creating the moved field and its corresponding getter and setter methods. This is a preparatory step in the 'Move Field' refactoring process. ```php class AccountType { private $interestRate; public function getInterestRate() { return $this->interestRate; } public function setInterestRate($arg) { $this->interestRate = $arg; } } ``` -------------------------------- ### Extract Superclass: Initial Setup Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/extract-superclass.md This snippet shows the initial state of the Employee and Department classes, highlighting common fields like 'name' and methods like 'getName'. It sets the stage for extracting a common superclass. ```java class Employee { private String name; public String getName() { return name; } } class Department { private String name; public String getName() { return name; } } ``` -------------------------------- ### Loading Customers from Data Source (PHP) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/change-value-to-reference.md This static method `loadCustomers` is responsible for initializing the customer registry. It populates the `$instances` array with `Customer` objects, typically loaded from a persistent data source like a database or file upon application launch. The example uses explicit instantiation for simplicity. ```php public static function loadCustomers() { Customer::instances["Lemon Car Hire"] = new Customer("Lemon Car Hire"); Customer::instances["Associated Coffee Machines"] = new Customer("Associated Coffee Machines"); Customer::instances["Bilston Gasworks"] = new Customer("Bilston Gasworks"); } ``` -------------------------------- ### Move Method Refactoring Example Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/move-method.md Demonstrates the 'Move Method' refactoring. The example shows the initial state of a bank account class and the process of moving the `overdraftCharge` method to an `AccountType` class. ```php class Account { private $type; private $daysOverdrawn; public function overdraftCharge() { if ($this->type->isPremium()) { $result = 10; if ($this->daysOverdrawn > 7) { $result += ($this->daysOverdrawn - 7) * 0.85; } return $result; } else { return $this->daysOverdrawn * 1.75; } } } class AccountType { // ... other methods and properties public function overdraftCharge() { if ($this->isPremium()) { $result = 10; if ($this->daysOverdrawn > 7) { $result += ($this->daysOverdrawn - 7) * 0.85; } return $result; } else { return $this->daysOverdrawn * 1.75; } } } ``` -------------------------------- ### Move Method: Initial OverdraftCharge Calculation Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/move-method.md This snippet shows the initial state of the `OverdraftCharge` method within the `Account` class, which calculates overdraft fees based on account type and days overdrawn. It serves as the starting point for the 'Move Method' refactoring. ```csharp public double OverdraftCharge() { if (type.IsPremium()) { double result = 10; if (daysOverdrawn > 7) { result += (daysOverdrawn - 7) * 0.85; } return result; } else { return daysOverdrawn * 1.75; } } ``` -------------------------------- ### Replace Constructor With Factory Method Example Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/replace-subclass-with-fields.md Demonstrates the application of the 'Replace Constructor With Factory Method' refactoring. It shows how to create factory methods for subclasses to abstract the instantiation process. ```C# public static Person CreateMale() { return new Male(); } public static Person CreateFemale() { return new Female(); } ``` -------------------------------- ### Client Code Usage Example Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/extract-subclass.md Demonstrates how to instantiate and use the `JobItem`, `LaborItem`, `PartsItem`, and `Employee` classes in client code to calculate the total price. ```csharp // Somewhere in client code Employee kent = new Employee(50); JobItem j1 = new LaborItem(5, kent); JobItem j2 = new PartsItem(15, 10); int total = j1.GetTotalPrice() + j2.GetTotalPrice(); ``` -------------------------------- ### Popover Configuration Options Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Illustrates various options for configuring popovers, such as direction, delay, remaining visible, and attachment to steps. ```plaintext # Simple popover #<2000+ Popover to the right of selected text, which will fire next action in 2 seconds, but will remain visible. #= Close all visible popovers and show new one. #Q Show final popover, attached to steps. ``` -------------------------------- ### Self-Encapsulate Start Text Field Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/duplicate-observed-data.md Creates a string property 'Start' to encapsulate the 'tbStart.Text' field. This allows for controlled access to the text field's content. ```C# private string Start { get{ return tbStart.Text; } set{ tbStart.Text = value; } } ``` -------------------------------- ### Go to Command Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Navigates the cursor to a specific location in the code. Supports simple text search, multiline targets, and named targets like start/end of files, methods, or parameters. It can also target specific classes or two-word identifiers. ```APIDOC Go to " |||" Go to: ``` ``` Go to the end of file Go to start of "" Go to end of "" Go to before "" in "" Go to after "" Go to parameters of "" Go to the end of parameters of "" in "" ``` -------------------------------- ### Update Interval Start Field Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/duplicate-observed-data.md Updates the 'Start' field of the Interval class when the corresponding text box value changes. This is part of the refactoring process to encapsulate fields. ```cs if (tb == tbStart) { this.Start = tb.Text; } ``` -------------------------------- ### Basic Select Action Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Demonstrates the fundamental 'Select' action to highlight specific code or text. ```plaintext Select "private int field;" ``` -------------------------------- ### Add Parameter Refactoring - Initial State Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/add-parameter.md This snippet shows the initial state of a PHP class `Calendar` with a `findAppointment` method. This method is used to find appointments on a specific date. The example also includes client code that uses this method. ```php class Calendar { // ... private $appointments; // array public function findAppointment(DateTime $date) { $result = array(); foreach ($this->appointments as $each) { if ($date->format('Y-m-d') == $each->date->format('Y-m-d')) { $result[] = $date; } } return $result; } } // Somewhere in client code $today = new DateTime(); $appointments = $calendar->findAppointment($today); ``` -------------------------------- ### Replace Array with Object - Initial Class Structure Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/replace-array-with-object.md This snippet shows the initial structure of a class used in the 'Replace Array with Object' refactoring example. It serves as a starting point before introducing data fields. ```java class Performance { } ``` -------------------------------- ### Value Object Example (Before Refactoring) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/change-value-to-reference.md This snippet shows the initial state where customer information is likely passed as simple values (e.g., strings) within the Order class. The `Customer` class here is a basic representation, and the `Order` class directly instantiates it. ```php class Customer { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } class Order { //… private $customer; // Customer public function getCustomerName() { return $this->customer->getName(); } public function setCustomer($customerName) { $this->customer = new Customer($customerName); } public function __construct($customerName) { $this->customer = new Customer($customerName); } } // Some client code, which uses Order class. private static function numberOfOrdersFor($orders, $customer) { $result = 0; foreach ($orders as $order) { if ($order->getCustomerName() === $customer) { $result++; } } return $result; } ``` -------------------------------- ### Encapsulate Fields: Start and Length Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/duplicate-observed-data.md This snippet illustrates the refactoring process for the 'Start' and 'Length' fields within the 'IntervalWindow' class. It includes the addition of getter and setter methods for the 'startField', mirroring the encapsulation of the 'end' field. ```Java String getStart() { return startField.getText(); } void setStart(String arg) { startField.setText(arg); } ``` -------------------------------- ### Select Specific Parts of Methods/Classes Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Details how to select specific components of a method or class, such as parameters, body, or name. ```plaintext Select "interval" in parameters of "doSomething" Select "interval" in body of "doSomething" in "ExampleClass" Select "interval" in whole "doSomething" Select name of "doSomething" Select visibility of "doSomething" in "ExampleClass" Select type of "doSomething" Select parameters of "doSomething" Select body of "doSomething" Select whole of "doSomething" ``` -------------------------------- ### Redirect Calls to Converting Constructor Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/introduce-local-extension.md Shows how to redirect calls from other constructors (like the default constructor) to the converting constructor. This promotes code reuse and simplifies constructor logic. ```csharp public MfDateTimeWrap() { this.date = new DateTime(); } ``` -------------------------------- ### Update Start Field in FocusLost Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/duplicate-observed-data.md This snippet demonstrates updating the 'Start' field within the 'StartField_FocusLost' method. It shows the direct assignment of the text from `startField` to the `setStart` method, indicating a refactoring step to align with the new encapsulation. ```Java setStart(startField.getText()); ``` -------------------------------- ### Get Character Code Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/replace-subclass-with-fields.md This snippet demonstrates how to override a method to return a specific character code. ```java @Override char getCode() { return 'F'; } ``` -------------------------------- ### ArticleMarkdown::intro Method Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/form-template-method.md Generates the introduction part of a markdown formatted article. It prepends a '>' symbol and two newlines to the article's introduction. ```php private function intro() { return "> " . $this->article->getIntro() . "\n\n"; } ``` -------------------------------- ### ArticleHtml::intro Method Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/form-template-method.md Generates the introduction part of an HTML formatted article. It wraps the article's introduction in
tags and appends a newline character. ```php private function intro() { return "
" . $this->article->getIntro() . "
" . "\n"; } ``` -------------------------------- ### Final Testing and Completion Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/extract-class.md Messages indicating the start of final testing and confirmation of successful completion of the refactoring process. ```en Let's start the final testing. Wonderful, it's all working! ``` ```ru Запускаем финальное тестирование. Отлично, все работает! ``` ```uk Запускаємо фінальне тестування. Супер, все працює. ``` -------------------------------- ### Get Employee Type Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/replace-type-code-with-subclasses.md Retrieves the type of the employee. This method is initially concrete and returns the type stored in a private field. ```php public function getType() { return $this->type; } ``` -------------------------------- ### Loading and Storing Customers (Java) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/change-value-to-reference.md Demonstrates the process of loading customer data, likely from a persistent source, and storing them in the registry. The `Store` method adds the customer instance to the `instances` Hashtable, keyed by name. This code is intended to be executed at application launch. ```Java //TODO: This code should be executed at the program launch. public static void LoadCustomers() { new Customer("Lemon Car Hire").Store(); new Customer("Associated Coffee Machines").Store(); new Customer("Bilston Gasworks").Store(); } private void Store() { instances.Add(this.Name, this); } ``` -------------------------------- ### Multiline Select Action Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Demonstrates the syntax for selecting multiple lines of text. ```plaintext Select: ``` Multiple lines go here ``` ``` -------------------------------- ### Add Domain Class Fields Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/duplicate-observed-data.md Adds private string fields for 'start', 'end', and 'length' to the domain class. These fields will be managed by public properties. ```cs private string start = "0", end = "0", length = "0"; ``` -------------------------------- ### Update Interval Setters with Notification Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/duplicate-observed-data.md Updates the setters for the 'Start', 'End', and 'Length' properties to call the 'OnValueChanged' method, ensuring that changes are propagated to observers. ```cs start; } set{ OnValueChanged(ref start, value); } ``` ```cs end; } set{ OnValueChanged(ref end, value); } ``` ```cs length; } set{ OnValueChanged(ref length, value); } ``` -------------------------------- ### Select with Origin Targeting Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Explains how to specify an origin (like a class or method name) to refine the selection. ```plaintext Select "private int field;" in "ExampleClass" Select "private int field;" in "class ExampleClass" Select "doSomething()" in "int someMethod" Select "doSomething()" in "someMethod" of "ExampleClass" ``` -------------------------------- ### Customer Class with Factory Method (Before Refactoring) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/change-reference-to-value.md This PHP code snippet shows a Customer class that uses a private constructor and a static factory method 'get' to manage instances. It includes a setter method for birthDate, which violates the principle of immutability for value objects. The example also demonstrates client code usage. ```php class Customer { private $name; private $birthDate; public function getName() { return $this->name; } public function getBirthDate() { return $this->birthday; } public function setBirthDate(DateTime $birthDate) { $this->birthDate = $birthDate; } private function __construct($name) { $this->name = $name; } private static $instances = array(); public static function get($name) { if (!isset($this->instances[$name])) { $value = new Customer($name); $this->instances[$name] = $value; } else { $value = $this->instances[$name] } return value; } } // Somewhere in client code $john = Customer::get("John Smith"); $john->setBirthDate(new DateTime("1985-01-01")); ``` -------------------------------- ### Remove Old Date Parameters Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/introduce-parameter-object.md Demonstrates the removal of the old 'start' and 'end' DateTime parameters from the 'getFlowBetween' method signature and its calls, after they have been replaced by the DateRange object. ```php public function getFlowBetween(DateTime $start, DateTime $end) ``` ```php $account->getFlowBetween($startDate, $endDate) ``` -------------------------------- ### Create Wrapper Class for DateTime Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/introduce-local-extension.md Demonstrates the initial creation of a wrapper class in C# to extend the functionality of the DateTime structure. This is the first step in the 'Introduce Local Extension' refactoring. ```csharp // Local extension class. public class MfDateTimeWrap { } ``` -------------------------------- ### Get Department Delegate Method Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/remove-middle-man.md This Java code snippet shows the creation of a method to access the department delegate. It encapsulates the department instance within the Person class. ```java public Department getDepartment() { return department; } ``` -------------------------------- ### Select with Item Number Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Shows how to select a specific chunk of text when multiple selections are possible by using an item number. ```plaintext Select 3rd "getSomething()" ``` -------------------------------- ### Select with Sub-selection Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Shows how to use sub-selection markers (|||) to pinpoint specific parts within a larger selection. ```plaintext Select: ``` Multiple |||lines||| go here. I also wan to select |||this|||. ``` ``` -------------------------------- ### Bidirectional Association (Before Refactoring) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/change-bidirectional-association-to-unidirectional.md Illustrates a bidirectional association between Order and Customer classes where each class holds a reference to the other. This setup requires careful management of the relationship to maintain consistency. ```php class Order { // ... private $customer; // Customer public function getCustomer() { return $this->customer; } public function setCustomer(Customer $arg) { // Remove order from old customer. if ($this->customer != null) { $this->customer->friendOrders()->remove($this); } $this->customer = $arg; // Add order to new customer. if ($this->customer != null) { $this->customer->friendOrders()->add($this); } } public function getDiscountedPrice() { return $this->getGrossPrice() * (1 - $this->getCustomer()->getDiscount()); } } class Customer { // ... private $orders = array(); // Should be used in Order class only. public function friendOrders() { return $orders; } public function addOrder(Order $arg) { $arg->setCustomer($this); } public function getPriceFor(Order $order) { assert(array_search($order, $this->orders, TRUE), "Order can not be found"); return $order->getDiscountedPrice(); } } ``` -------------------------------- ### Create Constructor Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/replace-method-with-method-object.md Implements a constructor for the 'Gamma' class that accepts the necessary parameters and initializes the class fields. ```php public function __construct(Account $source, $inputValArg, $quantityArg, $yearToDateArg) { $this->account = $source; $this->inputVal = $inputValArg; $this->quantity = $quantityArg; $this->yearToDate = $yearToDateArg; } ``` -------------------------------- ### Loading Customers at Launch (C#) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/change-value-to-reference.md Demonstrates loading customer data from an external source (like a database or file) at application startup. It creates and stores new customer instances using a `store` method. ```csharp // This code should be executed at the program launch. static void loadCustomers() { new Customer("Lemon Car Hire").store(); new Customer("Associated Coffee Machines").store(); new Customer("Bilston Gasworks").store(); } private void store() { instances.put(this.getName(), this); } ``` -------------------------------- ### Customer Class with Factory Method (Before Refactoring) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/change-reference-to-value.md This Java code snippet shows a Customer class that uses a private constructor and a static factory method 'get' to manage instances. It also includes a mutable 'birthDate' field with a setter, violating the principle of immutability for value objects. The example client code demonstrates how to obtain and modify a Customer object. ```java class Customer { private final String name; private Date birthDate; public String getName() { return name; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } private Customer(String name) { this.name = name; } private static Dictionary instances = new Hashtable(); public static Customer get(String name) { Customer value = (Customer)instances.get(name); if (value == null) { value = new Customer(name); instances.put(name, value); } return value; } } // Somewhere in client code Customer john = Customer.get("John Smith"); john.setBirthDate(new Date(1985, 1, 1)); ``` -------------------------------- ### Additive Select Actions Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Illustrates how to add new selections to previously selected text using a plus sign. ```plaintext Select "something" + Select "soemthing else" ``` -------------------------------- ### Update getFlowBetween Method Signature Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/introduce-parameter-object.md Shows how to update the signature of the 'getFlowBetween' method to accept a DateRange object instead of individual start and end dates. This simplifies the method's interface. ```php public function getFlowBetween(DateRange $range) ``` -------------------------------- ### Compilation Simulation Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Simulates compilation feedback. It uses '#C' to introduce a compilation message, followed by '#S' for success with a message, or '#F' for failure with an error message and location. ```APIDOC #C #S #C #F Select "" in "" ``` -------------------------------- ### Create DateRange Class Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/introduce-parameter-object.md Demonstrates the creation of an immutable DateRange class to encapsulate start and end dates. This class is designed to be used as a parameter object, replacing multiple date parameters. ```php class DateRange { private $start; // DateTime private $end; // DateTime public function __construct(DateTime $start, DateTime $end) { $this->start = $start; $this->end = $end; } public function getStart() { return $this->start; } public function getEnd() { return $this->end; } } ``` -------------------------------- ### Set Step Command Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Manages the progression of steps in a refactoring process. It allows setting a specific step number or marking the final step. ```APIDOC Set step Set final step ``` -------------------------------- ### Interval Window Class Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/duplicate-observed-data.md Demonstrates a GUI window for editing numeric intervals, consisting of Start, End, and Length input fields. Recalculations occur when input fields lose focus. ```csharp public class IntervalWindow { private Interval subject; // ... other methods and properties } ``` -------------------------------- ### Refactoring Order.getCustomer Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/change-bidirectional-association-to-unidirectional.md This snippet demonstrates an alternative way to get a customer object without using a field. It iterates through customer instances to find the one associated with the current order. ```Java Iterator iter = Customer.getInstances().iterator(); while (iter.hasNext()) { Customer each = (Customer)iter.next(); if (each.containsOrder(this)) { return each; } } return null; ``` -------------------------------- ### Перенесення методу: Обробка залежностей та приватних членів Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/move-method.md Цей приклад демонструє критичні кроки в рефакторингу 'Перенесення методу'. Він показує, як передати екземпляр вихідного класу як параметр, коли метод залежить від інших членів або методів класу. Він також ілюструє створення властивостей для доступу до приватних полів у цільовому класі. ```csharp Account account // ... всередині перенесеного методу ... public int DaysOverdrawn { get { return daysOverdrawn; } } // ... виклик перенесеного методу ... account.MethodCall(this); ``` -------------------------------- ### Calculate End Method in Java Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/duplicate-observed-data.md This Java method calculates the 'end' value based on 'start' and 'length', handling potential NumberFormatException. It's part of a class likely dealing with intervals or ranges. ```java void calculateEnd() { try { int start = Integer.parseInt(getStart()); int length = Integer.parseInt(getLength()); int end = start + length; setEnd(String.valueOf(end)); } catch (NumberFormatException e) { throw new RuntimeException ("Unexpected Number Format Error"); } } ``` -------------------------------- ### Apply Percentage Discount Method Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/replace-parameter-with-explicit-methods.md This snippet demonstrates the extraction of a method to apply a percentage-based discount to a price. It takes a discount percentage as input and modifies the Price accordingly. ```csharp public void ApplyPercentDiscount(double discount) { Price *= discount; } ``` -------------------------------- ### Create Public Properties for Interval Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/duplicate-observed-data.md Defines public properties (Start, End, Length) for the Interval class to access the private fields. The setters are initially empty, to be updated later with notification logic. ```cs public string Start { get{ return start; } set{ } } public string End { get{ return end; } set{ } } public string Length { get{ return length; } set{ } } ``` -------------------------------- ### Apply Fixed Discount Method Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/replace-parameter-with-explicit-methods.md This snippet demonstrates the extraction of a method to apply a fixed discount to a price. It takes a discount amount as input and modifies the Price accordingly. ```csharp public void ApplyFixedDiscount(double discount) { Price -= discount; } ``` -------------------------------- ### Update getFlowBetween Method Calls Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/introduce-parameter-object.md Illustrates how to modify existing calls to the 'getFlowBetween' method to pass a new DateRange object, constructed from the original start and end dates. This ensures compatibility after the signature change. ```php $account->getFlowBetween(new DateRange($startDate, $endDate)) ``` -------------------------------- ### Print/Type Command Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Inserts text at the current cursor position or replaces selected text. It handles both single-line and multiline text insertion. ```APIDOC Print "" Print: ``` ``` ``` -------------------------------- ### Interval Class Initialization and State Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/duplicate-observed-data.md Defines the initial state of the Interval class by declaring private String variables for 'start' and 'length', initializing them to '0'. This sets up the fundamental data members for interval representation. ```java private String start = "0"; private String length = "0"; ``` -------------------------------- ### Create Constructor Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/replace-method-with-method-object.md Implements a constructor for the new class that accepts the original method's parameters and initializes the class fields. This sets up the object with the necessary data. ```java public Gamma(Account source, int inputValArg, int quantityArg, int yearToDateArg) { this.account = source; inputVal = inputValArg; quantity = quantityArg; yearToDate = yearToDateArg; } ``` -------------------------------- ### Get Weeks Delinquent (PHP) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/introduce-null-object.md This snippet shows a PHP function that returns the number of weeks a customer has been delinquent in the last year. It's part of a refactoring example where null checks are being replaced. ```PHP public function getWeeksDelinquentInLastYear() { return 0; } ``` -------------------------------- ### Move Method: Handling Dependencies and Private Members Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/move-method.md This example demonstrates the critical steps in the 'Move Method' refactoring. It shows how to pass the original class instance as a parameter when the method depends on other class members or methods. It also illustrates the creation of properties to access private fields in the target class. ```csharp Account account // ... inside the moved method ... public int DaysOverdrawn { get { return daysOverdrawn; } } // ... calling the moved method ... account.MethodCall(this); ``` -------------------------------- ### Initialize Domain Class and Observer Pattern Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/duplicate-observed-data.md This snippet shows the initialization of the 'Interval' domain class within the 'IntervalWindow' constructor. It also sets up the observer pattern by making the 'IntervalWindow' an observer of the 'Interval' subject, ensuring that GUI updates reflect changes in the domain model. ```java subject = new Interval(); subject.addObserver(this); update(subject, null); ``` -------------------------------- ### Update Text Fields with Encapsulated Properties Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/duplicate-observed-data.md Replaces direct references to text field content (e.g., 'tbStart.Text') with references to their corresponding encapsulated properties (e.g., 'this.Start'). This is done for 'Start', 'End', and 'Length' fields. ```C# Type "this.Start" Type "this.End" Type "this.Length" ``` -------------------------------- ### Wait Command Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Introduces a delay into the sequence of operations. This is useful for synchronizing automated actions with user perception, typically with delays between 500ms and 1000ms. ```APIDOC Wait ms ``` -------------------------------- ### Customer Class (Before Refactoring) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/change-reference-to-value.md This C# code snippet shows a Customer class before applying the 'Change Reference to Value' refactoring. It uses a static factory method 'Get' for instance retrieval and has a mutable 'BirthDate' property. ```csharp public class Customer { private static Hashtable instances = new Hashtable(); public string Name { get; private set; } public DateTime BirthDate { get; set; } private Customer(string Name) { this.Name = Name; } public static Customer Get(string name) { Customer result = (Customer)instances[name]; if (result == null) { result = new Customer(name); instances.Add(name, result); } return result; } } // Somewhere in client code Customer john = Customer.Get("John Smith"); john.BirthDate = new DateTime(1985, 1, 1); ``` -------------------------------- ### Before Parameterize Method Refactoring (PHP) Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/parameterize-method.md This code snippet shows the initial state before applying the Parameterize Method refactoring. It includes multiple methods for salary adjustments and promotion, with some duplicated logic. ```php class Employee { // ... public function promoteToManager() { $this->type = Employee::MANAGER; $this->salary *= 1.5; } public function tenPercentRaise() { $this->salary *= 1.1; } public function fivePercentRaise() { $this->salary *= 1.05; } } // Somewhere in client code if ($employee->yearsOfExperience > 5) { if (count($employee->clients) > 10) { $employee->promoteToManager(); } else { $employee->fivePercentRaise(); } } ``` -------------------------------- ### Moving calculateLength to Interval Class Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/duplicate-observed-data.md Demonstrates the refactoring process of moving the 'calculateLength' method into the Interval class. This method calculates the length of an interval based on its start and end points, handling potential number format exceptions. ```java void calculateLength() { try { int start = Integer.parseInt(getStart()); int end = Integer.parseInt(getEnd()); int length = end - start; setLength(String.valueOf(length)); } catch (NumberFormatException e) { throw new RuntimeException ("Unexpected Number Format Error"); } } ``` -------------------------------- ### Resource Management with Database Connections Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/replace-exception-with-test.md Demonstrates managing expensive and reusable resources, such as database connections, using pools of available and allocated resources. It shows how to handle requests for resources and return them. ```java if (available.empty()) { } else { result = (Resource) available.pop(); allocated.push(result); return result; } ``` ```java result = new Resource(); allocated.push(result); return result; ``` ```java try { result = (Resource) available.pop(); allocated.push(result); return result; } catch (EmptyStackException e) { result = new Resource(); allocated.push(result); return result; } ``` ```java throw new RuntimeException("Should not reach here."); ``` -------------------------------- ### Replace Command Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/README.md Similar to the Print command but includes a slight delay before execution. This delay is beneficial when used with the Select command, providing better visual feedback to the user. ```APIDOC Replace "" ``` -------------------------------- ### Interval Class Getters and Setters Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/duplicate-observed-data.md Demonstrates the implementation of getter and setter methods for the 'start' and 'length' fields within the Interval class. These methods are crucial for encapsulating data and managing state changes, including notifying observers. ```java String getStart() { return start; } void setStart(String arg) { start = arg; setChanged(); notifyObservers(); } String getLength() { return length; } void setLength(String arg) { length = arg; setChanged(); notifyObservers(); } ``` -------------------------------- ### Declare Employee as Subclass of Person Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/replace-delegation-with-inheritance.md Starts the refactoring by declaring the Employee class to inherit from the Person class. This step is crucial for establishing the inheritance relationship. It's recommended to compile and run autotests after this to check for conflicting methods. ```csharp public class Employee : Person ``` -------------------------------- ### Extracting discountFactor Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/replace-temp-with-query.md Demonstrates the process of extracting a method to represent a calculation, specifically extracting `discountFactor`. This improves the readability of the `getPrice()` method by replacing a direct calculation with a method call. ```php $discountFactor = $this->discountFactor(); ``` -------------------------------- ### Extract DateRange Class Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/introduce-parameter-object.md This snippet demonstrates the creation of an immutable DateRange class to encapsulate start and end dates. This class will be used to replace multiple date parameters in methods, improving code readability and reducing potential errors. ```Java class DateRange { private final Date start; private final Date end; public DateRange(Date start, Date end) { this.start = start; this.end = end; } public Date getStart() { return start; } public Date getEnd() { return end; } } ``` -------------------------------- ### Original Constructor and Client Code Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/replace-constructor-with-factory-method.md This snippet shows the initial state of a class with a public constructor and how it's used in client code. The constructor directly handles object instantiation. ```csharp public class Employee { // ... public const int ENGINEER = 0, SALESMAN = 1, MANAGER = 2; public Employee(int type) { Type = type; } } // Some clinet code. Employee eng = new Employee(Employee.ENGINEER); ``` -------------------------------- ### Declare Employee as Subclass of Person Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/replace-delegation-with-inheritance.md Starts the refactoring process by declaring the Employee class as a subclass of the Person class. This step is crucial for establishing the inheritance relationship. Autotests should be run to check for conflicting methods, which can be resolved using 'Rename Method'. ```php class Employee extends Person { // ... existing Employee code } ``` -------------------------------- ### Create Constructor Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/csharp/replace-method-with-method-object.md Implements a constructor for the new class that initializes its fields with provided arguments. ```java public Gamma(Account source, int inputValArg, int quantityArg, int yearToDateArg) { this.account = source; inputVal = inputValArg; quantity = quantityArg; yearToDate = yearToDateArg; } ``` -------------------------------- ### Extract validateEmailAddress() Method Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/java/consolidate-duplicate-conditional-fragments.md Moves the 'validateEmailAddress()' function call to the beginning of the method. This example shows how to handle calls that appear in different locations, prioritizing placement closer to the method's start for better readability and logic flow. ```java validateEmailAddress(); ``` ```java validateEmailAddress(); ``` -------------------------------- ### Modify Client Code to Call Delegate Directly Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/remove-middle-man.md Updates the client code that previously called a method through the middle man (Person) to now call the delegate method (Department) directly. This involves getting the delegate object first and then invoking the desired method on it. ```php $manager = $john->getDepartment()->getManager(); ``` -------------------------------- ### PHP Local Extension Class Source: https://github.com/refactoringguru/refactoring-examples/blob/main/interactive/php/introduce-local-extension.md Demonstrates creating a local extension class by subclassing an existing class (DateTime). This involves replicating constructors and adding new methods or refactoring existing ones. ```PHP // Local extension class. class MyNewDate extends DateTime { } ``` ```PHP public function __construct() { $args = func_get_args(); call_user_func_array([$this, 'parent::__construct'], $args); } ``` ```PHP public function __construct() { $args = func_get_args(); if (isset($args[0]) && is_a($args[0], 'DateTime')) { call_user_func_array([$this, 'parent::__construct'], [$args[0]->format('Y-m-d H:i:s')]); } else { call_user_func_array([$this, 'parent::__construct'], $args); } } ``` ```PHP public static function nextWeek(DateTime $arg) { $previousDate = clone $arg; return $previousDate->modify('+7 days'); } ``` ```PHP public function nextWeek() { return $this->modify('+7 days'); } ``` ```PHP $previousDate = new MyNewDate($this->previousDate); $previousDate->nextWeek() ```