text
stringlengths 3
2.83k
| label
int64 0
1
|
---|---|
There are two cases when tests can break down after refactoring: | 0 |
Use the Composite pattern when you have to implement a tree-like object structure. | 0 |
Solution | 1 |
Use the Observer pattern when changes to the state of one object may require changing other objects, and the actual set of objects is unknown beforehand or changes dynamically. | 0 |
 | 0 |
Pseudocode | 1 |
 | 0 |
Sometimes business circumstances might force you to roll out features before they’re completely finished. In this case, patches and kludges will appear in the code to hide the unfinished parts of the project. | 0 |
- _Single Responsibility Principle_. Organize the code related to particular states into separate classes.
- _Open/Closed Principle_. Introduce new states without changing existing state classes or the context.
- Simplify the code of the context by eliminating bulky state machine conditionals. | 0 |
Bugs in code behave just like those in real life: they live in the darkest, dirtiest places in the code. Clean your code and the errors will practically discover themselves. | 0 |
Structure | 1 |
Problem | 1 |
Solution | 1 |
You can’t just find a pattern and copy it into your program, the way you can with off-the-shelf functions or libraries. The pattern is not a specific piece of code, but a general concept for solving a particular problem. You can follow the pattern details and implement a solution that suits the realities of your own program. | 0 |
Problem | 1 |
A car is a complex object that can be constructed in a hundred different ways. Instead of bloating the `Car` class with a huge constructor, we extracted the car assembly code into a separate car builder class. This class has a set of methods for configuring various parts of a car. | 0 |
Imagine a complex object that requires laborious, step-by-step initialization of many fields and nested objects. Such initialization code is usually buried inside a monstrous constructor with lots of parameters. Or even worse: scattered all over the client code. | 0 |
- You can use [Command](https://refactoring.guru/pattern/command) and [Memento](https://refactoring.guru/pattern/memento) together when implementing “undo”. In this case, commands are responsible for performing various operations over a target object, while mementos save the state of that object just before a command gets executed.
- You can use [Memento](https://refactoring.guru/pattern/memento) along with [Iterator](https://refactoring.guru/pattern/iterator) to capture the current iteration state and roll it back if necessary.
- Sometimes [Prototype](https://refactoring.guru/pattern/prototype) can be a simpler alternative to [Memento](https://refactoring.guru/pattern/memento). This works if the object, the state of which you want to store in the history, is fairly straightforward and doesn’t have links to external resources, or the links are easy to re-establish. | 0 |
Structure | 1 |
Clean code is obvious for other programmers.
And I’m not talking about super sophisticated algorithms. Poor variable naming, bloated classes and methods, magic numbers -you name it- all of that makes code sloppy and difficult to grasp. | 1 |
1. The **Product** declares the interface, which is common to all objects that can be produced by the creator and its subclasses.
2. **Concrete Products** are different implementations of the product interface.
3. The **Creator** class declares the factory method that returns new product objects. It’s important that the return type of this method matches the product interface.
You can declare the factory method as `abstract` to force all subclasses to implement their own versions of the method. As an alternative, the base factory method can return some default product type.
Note, despite its name, product creation is **not** the primary responsibility of the creator. Usually, the creator class already has some core business logic related to products. The factory method helps to decouple this logic from the concrete product classes. Here is an analogy: a large software development company can have a training department for programmers. However, the primary function of the company as a whole is still writing code, not producing programmers.
4. **Concrete Creators** override the base factory method so it returns a different type of product.
Note that the factory method doesn’t have to **create** new instances all the time. It can also return existing objects from a cache, an object pool, or another source. | 0 |
Real-World Analogy | 1 |
Inheritance vs. Aggregation | 0 |
The much more elegant solution would be to put the missing functionality into an adapter class. Then you would wrap objects with missing features inside the adapter, gaining needed features dynamically. For this to work, the target classes must have a common interface, and the adapter’s field should follow that interface. This approach looks very similar to the [Decorator](https://refactoring.guru/pattern/decorator) pattern. | 0 |
The same UI elements in a cross-platform application are expected to behave similarly, but look a little bit different under different operating systems. Moreover, it’s your job to make sure that the UI elements match the style of the current operating system. You wouldn’t want your program to render macOS controls when it’s executed in Windows. | 0 |
In addition to implementing the algorithm itself, an iterator object encapsulates all of the traversal details, such as the current position and how many elements are left till the end. Because of this, several iterators can go through the same collection at the same time, independently of each other. | 0 |
This is when the developer just doesn’t know how to write decent code. | 0 |
For example, let’s return to our video conversion framework. It can be broken down into two layers: video- and audio-related. For each layer, you can create a facade and then make the classes of each layer communicate with each other via those facades. This approach looks very similar to the [Mediator](https://refactoring.guru/pattern/mediator) pattern. | 0 |
Use the Facade pattern when you need to have a limited but straightforward interface to a complex subsystem. | 0 |
Relations with Other Patterns | 1 |
In this example, the **Decorator** pattern lets you compress and encrypt sensitive data independently from the code that actually uses this data. | 0 |
 | 0 |
In this case, the proxy passes the client request over the network, handling all of the nasty details of working with the network. | 0 |
Single Responsibility Principle says that “a class should have only one reason to change” which means every class should have a single responsibility or single job or single purpose.
Consider the example of developing software, the task is divided into different members doing different things as front-end designers do design, the tester does testing and backend developer takes care of backend development part then we can say that everyone has a single job or responsibility.
Most of the time it happens that when programmers have to add features or new behavior they implement everything into the existing class which is completely wrong. It makes their code lengthy, complex and consumes time when later something needs to be modified. Use layers in your application and break God classes into smaller classes or modules. | 0 |
- **Intent** of the pattern briefly describes both the problem and the solution.
- **Motivation** further explains the problem and the solution the pattern makes possible.
- **Structure** of classes shows each part of the pattern and how they are related.
- **Code example** in one of the popular programming languages makes it easier to grasp the idea behind the pattern. | 0 |
That’s how a help request traverses GUI objects. | 0 |
But then someone reasonably asked you, “Why can’t you use several notification types at once? If your house is on fire, you’d probably want to be informed through every channel.” | 0 |
Use the pattern when it’s essential to execute several handlers in a particular order. | 0 |
All implementations of the Singleton have these two steps in common: | 0 |
Adding new subscribers to the program doesn’t require changes to existing publisher classes, as long as they work with all subscribers through the same interface. | 0 |
Solution | 1 |
In addition, the director class completely hides the details of product construction from the client code. The client only needs to associate a builder with a director, launch the construction with the director, and get the result from the builder. | 0 |
Solution | 1 |
For example, let’s think about how to create a `House` object. To build a simple house, you need to construct four walls and a floor, install a door, fit a pair of windows, and build a roof. But what if you want a bigger, brighter house, with a backyard and other goodies (like a heating system, plumbing, and electrical wiring)? | 0 |
When does a simple wrapper become the real decorator? As I mentioned, the wrapper implements the same interface as the wrapped object. That’s why from the client’s perspective these objects are identical. Make the wrapper’s reference field accept any object that follows that interface. This will let you cover an object in multiple wrappers, adding the combined behavior of all the wrappers to it. | 0 |
How to make a copy of the object’s private state? | 0 |
It’s crucial that all handler classes implement the same interface. Each concrete handler should only care about the following one having the `execute` method. This way you can compose chains at runtime, using various handlers without coupling your code to their concrete classes. | 0 |
The most significant change happens to the actual form elements. Let’s consider the submit button. Previously, each time a user clicked the button, it had to validate the values of all individual form elements. Now its single job is to notify the dialog about the click. Upon receiving this notification, the dialog itself performs the validations or passes the task to the individual elements. Thus, instead of being tied to a dozen form elements, the button is only dependent on the dialog class. | 0 |
Solution | 1 |
The Proxy pattern suggests that you create a new proxy class with the same interface as an original service object. Then you update your app so that it passes the proxy object to all of the original object’s clients. Upon receiving a request from a client, the proxy creates a real service object and delegates all the work to it. | 0 |
In our example with ordering systems, a handler performs the processing and then decides whether to pass the request further down the chain. Assuming the request contains the right data, all the handlers can execute their primary behavior, whether it’s authentication checks or caching. | 0 |
1. Decide what class will act as the context. It could be an existing class which already has the state-dependent code; or a new class, if the state-specific code is distributed across multiple classes.
2. Declare the state interface. Although it may mirror all the methods declared in the context, aim only for those that may contain state-specific behavior.
3. For every actual state, create a class that derives from the state interface. Then go over the methods of the context and extract all code related to that state into your newly created class.
While moving the code to the state class, you might discover that it depends on private members of the context. There are several workarounds:
- Make these fields or methods public.
- Turn the behavior you’re extracting into a public method in the context and call it from the state class. This way is ugly but quick, and you can always fix it later.
- Nest the state classes into the context class, but only if your programming language supports nesting classes.
4. In the context class, add a reference field of the state interface type and a public setter that allows overriding the value of that field.
5. Go over the method of the context again and replace empty state conditionals with calls to corresponding methods of the state object.
6. To switch the state of the context, create an instance of one of the state classes and pass it to the context. You can do this within the context itself, or in various states, or in the client. Wherever this is done, the class becomes dependent on the concrete state class that it instantiates. | 0 |
Say the client wants a factory to produce a chair. The client doesn’t have to be aware of the factory’s class, nor does it matter what kind of chair it gets. Whether it’s a Modern model or a Victorian-style chair, the client must treat all chairs in the same manner, using the abstract `Chair` interface. With this approach, the only thing that the client knows about the chair is that it implements the `sitOn` method in some way. Also, whichever variant of the chair is returned, it’ll always match the type of sofa or coffee table produced by the same factory object. | 0 |
- You can control the order of request handling.
- _Single Responsibility Principle_. You can decouple classes that invoke operations from classes that perform operations.
- _Open/Closed Principle_. You can introduce new handlers into the app without breaking the existing client code. | 0 |
 | 0 |
- Subscribers are notified in random order. | 0 |
You can bring order to this chaos by extracting the code related to specific interface-platform combinations into separate classes. However, soon you’ll discover that there are _lots_ of these classes. The class hierarchy will grow exponentially because adding a new GUI or supporting a different API would require creating more and more classes. | 0 |
 | 0 |
Initially, when our app only had the toolbar, it was okay to place the implementation of various operations into the button subclasses. In other words, having the code for copying text inside the `CopyButton` subclass was fine. But then, when you implement context menus, shortcuts, and other stuff, you have to either duplicate the operation’s code in many classes or make menus dependent on buttons, which is an even worse option. | 0 |
Imagine that you’re working on a notification library which lets other programs notify their users about important events. | 0 |
**Singleton** is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance. | 0 |
Real-World Analogy | 1 |
The iterator encapsulates the details of working with a complex data structure, providing the client with several simple methods of accessing the collection elements. While this approach is very convenient for the client, it also protects the collection from careless or malicious actions which the client would be able to perform if working with the collection directly. | 0 |
1. The **Originator** class can produce snapshots of its own state, as well as restore its state from snapshots when needed.
2. The **Memento** is a value object that acts as a snapshot of the originator’s state. It’s a common practice to make the memento immutable and pass it the data only once, via the constructor.
3. The **Caretaker** knows not only “when” and “why” to capture the originator’s state, but also when the state should be restored.
A caretaker can keep track of the originator’s history by storing a stack of mementos. When the originator has to travel back in history, the caretaker fetches the topmost memento from the stack and passes it to the originator’s restoration method.
4. In this implementation, the memento class is nested inside the originator. This lets the originator access the fields and methods of the memento, even though they’re declared private. On the other hand, the caretaker has very limited access to the memento’s fields and methods, which lets it store mementos in a stack but not tamper with their state. | 0 |
A call to tech support can go through multiple operators. | 0 |
Use the pattern when it’s awkward or not possible to extend an object’s behavior using inheritance. | 0 |
Armies of most countries are structured as hierarchies. An army consists of several divisions; a division is a set of brigades, and a brigade consists of platoons, which can be broken down into squads. Finally, a squad is a small group of real soldiers. Orders are given at the top of the hierarchy and passed down onto each level until every soldier knows what needs to be done. | 0 |
You could implement lazy initialization: create this object only when it’s actually needed. All of the object’s clients would need to execute some deferred initialization code. Unfortunately, this would probably cause a lot of code duplication. | 0 |
For instance, when a user clicks a button, the event propagates through the chain of GUI elements that starts with the button, goes along its containers (like forms or panels), and ends up with the main application window. The event is processed by the first element in the chain that’s capable of handling it. This example is also noteworthy because it shows that a chain can always be extracted from an object tree. | 0 |
Imagine that you’re creating a furniture shop simulator. Your code consists of classes that represent: | 0 |
Instead of creating the object when the app launches, you can delay the object’s initialization to a time when it’s really needed. | 0 |
This happens when everyone working on the project writes code as they see fit (i.e. the same way they wrote the last project). | 0 |
The State pattern is closely related to the concept of a _Finite-State Machine_ . | 0 |
**Memento** is a behavioral design pattern that lets you save and restore the previous state of an object without revealing the details of its implementation. | 0 |
Imagine that you’re working on a new text-editor app. Your current task is to create a toolbar with a bunch of buttons for various operations of the editor. You created a very neat `Button` class that can be used for buttons on the toolbar, as well as for generic buttons in various dialogs. | 0 |
1. The **Publisher** issues events of interest to other objects. These events occur when the publisher changes its state or executes some behaviors. Publishers contain a subscription infrastructure that lets new subscribers join and current subscribers leave the list.
2. When a new event happens, the publisher goes over the subscription list and calls the notification method declared in the subscriber interface on each subscriber object.
3. The **Subscriber** interface declares the notification interface. In most cases, it consists of a single `update` method. The method may have several parameters that let the publisher pass some event details along with the update.
4. **Concrete Subscribers** perform some actions in response to notifications issued by the publisher. All of these classes must implement the same interface so the publisher isn’t coupled to concrete classes.
5. Usually, subscribers need some contextual information to handle the update correctly. For this reason, publishers often pass some context data as arguments of the notification method. The publisher can pass itself as an argument, letting subscriber fetch any required data directly.
6. The **Client** creates publisher and subscriber objects separately and then registers subscribers for publisher updates. | 0 |
Usually the need for patterns arises when people choose a programming language or a technology that lacks the necessary level of abstraction. In this case, patterns become a kludge that gives the language much-needed super-abilities. | 0 |
Also known as: Intermediary, Controller | 0 |
Prototype registry implementation | 1 |
- You can use [Iterators](https://refactoring.guru/pattern/iterator) to traverse [Composite](https://refactoring.guru/pattern/composite) trees.
- You can use [Factory Method](https://refactoring.guru/pattern/factory-method) along with [Iterator](https://refactoring.guru/pattern/iterator) to let collection subclasses return different types of iterators that are compatible with the collections.
- You can use [Memento](https://refactoring.guru/pattern/memento) along with [Iterator](https://refactoring.guru/pattern/iterator) to capture the current iteration state and roll it back if necessary.
- You can use [Visitor](https://refactoring.guru/pattern/visitor) along with [Iterator](https://refactoring.guru/pattern/iterator) to traverse a complex data structure and execute some operation over its elements, even if they all have different classes. | 0 |
Relations with Other Patterns | 1 |
In this case, you can create several different builder classes that implement the same set of building steps, but in a different manner. Then you can use these builders in the construction process (i.e., an ordered set of calls to the building steps) to produce different kinds of objects. | 0 |
The first thing you hear is the robotic voice of the autoresponder. It suggests nine popular solutions to various problems, none of which are relevant to your case. After a while, the robot connects you to a live operator. | 0 |
Pseudocode | 1 |
Structure | 1 |
1. The **Handler** declares the interface, common for all concrete handlers. It usually contains just a single method for handling requests, but sometimes it may also have another method for setting the next handler on the chain.
2. The **Base Handler** is an optional class where you can put the boilerplate code that’s common to all handler classes.
Usually, this class defines a field for storing a reference to the next handler. The clients can build a chain by passing a handler to the constructor or setter of the previous handler. The class may also implement the default handling behavior: it can pass execution to the next handler after checking for its existence.
3. **Concrete Handlers** contain the actual code for processing requests. Upon receiving a request, each handler must decide whether to process it and, additionally, whether to pass it along the chain.
Handlers are usually self-contained and immutable, accepting all necessary data just once via the constructor.
4. The **Client** may compose chains just once or compose them dynamically, depending on the application’s logic. Note that a request can be sent to any handler in the chain—it doesn’t have to be the first one. | 0 |
Use the pattern when some objects in your app must observe others, but only for a limited time or in specific cases. | 0 |
Pseudocode | 1 |
The greatest benefit of this approach is that you don’t need to care about the concrete classes of objects that compose the tree. You don’t need to know whether an object is a simple product or a sophisticated box. You can treat them all the same via the common interface. When you call a method, the objects themselves pass the request down the tree. | 0 |
Relations with Other Patterns | 1 |
- The app might consume lots of RAM if clients create mementos too often.
- Caretakers should track the originator’s lifecycle to be able to destroy obsolete mementos.
- Most dynamic programming languages, such as PHP, Python and JavaScript, can’t guarantee that the state within the memento stays untouched. | 0 |
 | 0 |
Use the Adapter class when you want to use some existing class, but its interface isn’t compatible with the rest of your code. | 0 |
Real-World Analogy | 1 |
Relations with Other Patterns | 1 |
The Composite pattern suggests that you work with `Products` and `Boxes` through a common interface which declares a method for calculating the total price. | 0 |
Imagine that you’re creating a stock market monitoring app. The app downloads the stock data from multiple sources in XML format and then displays nice-looking charts and diagrams for the user. | 0 |
- Many designs start by using [Factory Method](https://refactoring.guru/pattern/factory-method) (less complicated and more customizable via subclasses) and evolve toward [Abstract Factory](https://refactoring.guru/pattern/abstract-factory), [Prototype](https://refactoring.guru/pattern/prototype), or [Builder](https://refactoring.guru/pattern/builder) (more flexible, but more complicated).
- [Abstract Factory](https://refactoring.guru/pattern/abstract-factory) classes are often based on a set of [Factory Methods](https://refactoring.guru/pattern/factory-method), but you can also use [Prototype](https://refactoring.guru/pattern/prototype) to compose the methods on these classes.
- You can use [Factory Method](https://refactoring.guru/pattern/factory-method) along with [Iterator](https://refactoring.guru/pattern/iterator) to let collection subclasses return different types of iterators that are compatible with the collections.
- [Prototype](https://refactoring.guru/pattern/prototype) isn’t based on inheritance, so it doesn’t have its drawbacks. On the other hand, _Prototype_ requires a complicated initialization of the cloned object. [Factory Method](https://refactoring.guru/pattern/factory-method) is based on inheritance but doesn’t require an initialization step.
- [Factory Method](https://refactoring.guru/pattern/factory-method) is a specialization of [Template Method](https://refactoring.guru/pattern/template-method). At the same time, a _Factory Method_ may serve as a step in a large _Template Method_. | 0 |
You get a combined effect from wearing multiple pieces of clothing. | 0 |
Aircraft pilots don’t talk to each other directly when deciding who gets to land their plane next. All communication goes through the control tower. | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.