Chapter 11: Design Patterns for SaaS Apps

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What are types of creational patterns?

- Abstract Factory, Factory Method - Singleton - Prototype - Builder

What are the Behavior Diagrams?

- Activity: Describes the business and operational step-by-step workflows of components in a system. An activity diagram shows the overall flow of control. - State machine: Describes the states and state transitions of the system. - Use Case: Describes the functionality provided by a system in terms of actors, their goals represented as use cases, and any dependencies among those use cases.

What are types of structural patterns?

- Adapter, Proxy, Facade, Bridge - Decorator - Composite - Flyweight

What is the difference between the Strategy pattern or Template Method pattern?

- Both support the case in which there is a general approach to doing a task but many possible variants. - difference between the two is the level at which commonality is captured Template method: set of steps is the same for all variants; hence it is usually implemented using inheritance Strategy method: set of steps may be different in each variant; hence it is usually implemented using composition.

What are the structure diagrams?

- Class: Describes the structure of a system by showing the system's classes, their attributes, and the relationships among the classes. - Component: Describes how a software system is split up into components and shows the dependencies among these components. - Composite structure: Describes the internal structure of a class and the collaborations that this structure makes possible. - Deployment: Describes the hardware used in system implementations and the execution environments and artifacts deployed on the hardware. - Object: Shows a complete or partial view of the structure of an example modeled system at a specific time. - Package: Describes how a system is split up into logical groupings by showing the dependencies among these groupings. - Profile: Describes reusable domain-specific "stereotype" objects from which specific object types can be derived for use in a particular application.

What are Interaction Diagrams?

- Communication: Shows the interactions between objects or parts in terms of sequenced messages. They represent a combination of information taken from Class, Sequence, and Use Case Diagrams describing both the static structure and dynamic behavior of a system. - Interaction overview: Provides an overview in which the nodes represent communication diagrams. - Sequence: Shows how objects communicate with each other in terms of a sequence of messages. Also indicates the lifespans of objects relative to those messages. - Timing diagrams: A specific type of interaction diagram where the focus is on timing constraints.

What are the behavioral patterns?

- Template Method, Strategy: Uniformly encapsulate multiple varying strategies for same task - Observer: One or more entities need to be notified when something happens to an object Iterator - Visitor: Separate traversal of a data structure from operations performed on each element of the data structure - Null Object: (Doesn't appear in GoF catalog) Provide an object with defined neutral behaviors that can be safely called, to take the place of conditionals guarding method calls - State: Encapsulate an object whose behaviors (methods) differ depending on which of a small number of internal states the object is in - Chain of Responsibility: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request, passing request up the chain until someone handles it - Mediator: Define an object that encapsulates how a set of objects interact without those objects having to refer to each other explicitly, allowing decoupling - Interpreter: Define a representation for a language along with an interpreter that executes the representation - Command: Encapsulate an operation request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations

When do you use UML?

- UML is useful for modeling very large applications divided into subsystems being worked on by widely-distributed teams - since UML notation is language-neutral, it can be helpful for coordinating international teams

What is a refused bequest?

- a design smell that often indicates an LSP violation - a subclass either destructively overrides a behavior inherited from its superclass or forces changes to the superclass to avoid the problem - The problem is that inheritance is all about implementation sharing, but if a subclass won't take advantage of its parent's implementations, it might not deserve to be a subclass at all

What is Unified Modeling Language or UML?

- is not a textual language! - a set of graphical notation techniques to "specify, visualize, modify, construct, and document the artifacts of an object-oriented software-intensive system under development." - UML comprises a family of diagram types to illustrate various aspects of a software design and implementation. - UML class diagrams are widely used even by engineers who don't use other UML features. They show a class's name, its most important public and private methods and attributes, and its relationship to other classes

What is a tip-off of violating SRP?

- lack of cohesion - cohesion: the degree to which the elements of a single logical entity, in this case a class, are related. - two methods are related if they access the same subset of instance or class variables or if one calls the other

What are extension points?

- places we think extensions might be needed in the future. - used to make a class open for extension but closed against modification

What does SOLID tell us?

- stands for a set of five design principles that clean code should respect. -5 Design principles that all patterns abide by - can tell us when we're in danger of violating one or more SOLID guidelines; the fix is often a refactoring that eliminates the problem by bringing the code in line with one or more design patterns.

How to fix a violation of LSP?

- to again use composition and delegation rather than inheritance - violations can be fixed by using composition of classes rather than inheritance, achieving reuse through delegation rather than through subclassing.

What design patterns address common scenarios that could otherwise lead to Demeter violations?

1. Visitor pattern 2. Iterator pattern 3. Observer pattern

What are the two design smells can tip us off to possible Demeter violations?

1. inappropriate intimacy: arise in any situation where you feel you are "reaching through" an interface to get some task done, thereby exposing yourself to dependency on implementation details of a class that should really be none of your business. - If a class shows many instances of Inappropriate Intimacy with another class, it is sometimes said to have Feature Envy with respect to the other class. 2. mock trainwreck

Classes you should know?

Abstract. adapter, composite, decorator, factory, interpreter, iterator, proxy, observer, singleton, visitor

What is the Decorator pattern?

Attach additional responsibilities to an object dynamically, keeping the same interface. Helps with "Prefer composition or delegation over inheritance."

Why is dependency injection often seen together with the Adapter pattern?

Because dependency injection is often used to vary which of a collection of implementations is used at runtime, it's often seen together with the Adapter pattern, in which a class converts one API into another that a client expects to use.

How are design smells different from code smells?

Code smells: apply to methods within a class Design smells: apply to relationships between classes and how responsibilities are divided among them.

What the Adapter, Proxy, Facade, Bridge pattern?

Convert the programming interface of a class into another (sometimes simpler) interface that clients expect, or decouple an abstraction's interface from its implementation, for dependency injection or performance

What is a warning sign that a good class is evolving toward the "multiple responsibilities" antipattern?

Data Clumps design smell: group of variables or values that are always passed together as arguments to a method or returned together as a set of results from a method. - "traveling together" is a sign that the values might really need their own class

How do you resolve DP violations?

Delegation!

What is the goal of design patterns?

Design patterns are proven solutions to accommodate evolutionary change gracefully. hey work by providing a clean way to separate the things that may change or evolve from those that stay the same and a clean way to accommodate those changes.

What is the Singleton pattern?

Ensure a class has only one instance, and provide a global point of access to it

What are variations on Adapter?

Facade: in which the API is not only adapted but also simplified Proxy: in which the API is exactly imitated but the behaviors changed to accommodate different usage conditions without the client (caller of the API) having to change its behavior.

True or False: Agile design is an oxymoron.

False. Although there is no separate design phase in Agile development, the refactoring that is the norm in Agile can incorporate design patterns.

True or false: one measure of the quality of a piece of software is the degree to which it uses design patterns.

False: while design patterns provide proven solutions to some common problems, code that doesn't exhibit such problems may not need those patterns, but that doesn't make it poor code. The GoF authors specifically warn against measuring code quality in terms of design pattern usage.

When does it make sense to you the Template method?

If every kind of formatter followed the same high-level steps—for example, generate the header, generate the report body, and then generate the footer

Here are two statements about delegation: 1. A subclass delegates a behavior to an ancestor class 2. A class delegates a behavior to a descendant class Looking at the examples of the Template Method, Strategy, and Decorator patterns, which statement best describes how each pattern uses delegation?

In Template Method and Strategy, the ancestor class provides the "basic game plan" which is customized by delegating specific behaviors to different subclasses. In Decorator, each subclass provides special functionality of its own, but delegates back to the ancestor class for the "basic" functionality.

Why does proper use of DIP have higher impact in statically typed languages?

In such languages, you cannot create a runtime seam to override a "hardwired" behavior as you can in dynamic languages like Ruby, so the seam must be provided in advance by injecting the dependency.

Should the relationship "University has many Departments" be modeled as an aggregation or a composition?

It should be a composition, since departments wouldn't survive the closing of a university.

Which ActiveRecord association would NOT appear in a Rails app that follows this simplified UML class diagram? - Item has one AccountCode - Voucher belongs to Vouchertype - Customer has many Donations - Show has many Vouchers, through Showdate

Item has one AccountCode Explanation: It is true that a given Item has only a single AccountCode, but has-one is a 1-to-1 relationship, and the diagram shows that an AccountCode has many Items. So the relationship expressed here is Item belongs to AccountCode and AccountCode has many Items.

What is the Iterator pattern?

Iterator separates the implementation of traversing a collection from the behavior you want to apply to each collection element. Without iterators, the behavior would have to "reach into" the collection, thereby knowing inappropriately intimate details of how the collection is organized.

What is the Liskov Substitution Principle (LSP)?

LSP states that a method designed to work on an object of type TT should also work on an object of any subtype of TT. That is, all of TT's subtypes should preserve TT's "contract." - When a subclass differs behaviorally from one of its parents, an LSP violation can arise.

Which is true about a class's observance of the Single Responsibility Principle? - Low cohesion is a possible indicator of an opportunity to extract a class - In general, we would expect to see a correlation between poor cohesion score and poor SOFA metrics - If a class's methods respect SOFA, the class probably respects SRP - If a class respects SRP, its methods probably respect SOFA

Low cohesion is a possible indicator of an opportunity to extract a class Explanation: While good style and freedom from smells are important at both the method and class level, they are largely orthogonal. A class with too many responsibilities could have lots of small methods that all follow SOFA, and a class with one responsibility might implement that responsibility with methods that run afoul of SOFA.

In SOLID, what is Single Responsibility?

Meaning: A class should have one and only one reason to change Warning smells: Large class, poor LCOM (Lack of Cohesion Of Methods) score, data clumps Refactoring Fix: Extract class, move methods

In SOLID, what is Open/-Closed?

Meaning: Classes should be open for extension but closed for modification Warning smells: Conditional complexity, case-based dispatcher Refactoring Fix: Use Strategy or Template Method, possibly combined with Abstract Factory pattern; use Decorator to avoid explosion of subclasses

In SOLID, what is Injection of Dependencies?

Meaning: Collaborating classes whose implementation may vary at runtime should depend on an intermediate "injected" dependency Warning smells: Unit tests that require ad hoc stubbing to create seams; constructors that hardwire a call to another class's constructor, rather than allowing runtime determination of which other class to use Refactoring Fix: Inject a dependency on a shared interface to isolate the classes; use Adapter, Facade, or Proxy patterns as needed to make the interface uniform across variants

In SOLID, what is Demeter Principle?

Meaning: Speak only to your friends; treat your friends' friends as strangers Warning smells: Inappropriate intimacy, feature envy, mock trainwrecks Refactoring Fix: Delegate behaviors and call the delegate methods instead

In SOLID, what is Liskov Substitution?

Meaning: Substituting a subclass for a class should preserve correct program behavior Warning smells: Refused bequest: subclass destructively overrides an inherited method Refactoring Fix: Replace inheritance with delegation

Why is Forwardable in the Ruby standard library provided as a module rather than a class?

Modules allow the delegation mechanisms to be mixed in to any class that wants to use them, which would be awkward if Forwardable were a class. That is, Forwardable is itself an example of preferring composition to inheritance!

Which of the following statements is FALSE? - Most design patterns are specific to a particular subset of programming languages. - Well-designed software can evolve to the point where patterns become antipatterns. - Software that uses more design patterns isn't necessarily better. - Trying to apply design patterns too early can be just as bad as applying them too late.

Most design patterns are specific to a particular subset of programming languages. Explanation: While a few design patterns arise from language-specific constraints, the great majority of them can be applied no matter what language you use, because design patterns are about relationships among different classes or entities in your code.

Which statement regarding design patterns is FALSE? - Agile developers may plan for SW architectures and design patterns they expect to need based on previous, similar projects - P&D drawback: initial architecture & design patterns may change as code written and system evolves - P&D processes have an explicit design phase that is a natural fit to the use of design patterns and thus will have a good SW architecture - None are false; all are true

None are false; all are true

OmniAuth defines a handful of RESTful endpoints your app must provide to handle authentication with a variety of third parties. To add a new auth provider, you create a gem that works with that provider. Which statement is FALSE about OmniAuth? - Using OmniAuth helps your app follow OCP (with respect to 3rd-party authentication) - OmniAuth is an example of the Template pattern - OmniAuth is an example of the Strategy pattern - OmniAuth is itself compliant with OCP

OmniAuth is an example of the Template pattern Explanation: From your app's point of view, the API to authentication is just a few URL endpoints, but the process by which it's done varies wildly depending on the auth provider. Some are OAuth, some implement proprietary protocols, some aren't authentication protocols at all but just testing stubs. So OmniAuth is more like Strategy, since it doesn't consist of overriding a fixed sequence of steps that are basically the same for all authentication providers.

(a) In duck-typed languages, LSP violations can occur even when inheritance is not used (b) In statically-typed languages, if the compiler reports no type errors/warnings, then there are no LSP violations - Both are true - Only (b) is true - Both are false - Only (a) is true

Only (a) is true Explanation: For example, in Ruby, you might mix in the Comparable module but define <=> in a way that doesn't obey the triangle inequality. Even though there is no inheritance here, you've violated the contract expected by the mixed-in module. (b) is false: The Square/Rectangle example explained in the lecture (and at http://pastebin.com/nf2D9RYj) would pass static type checks, yet it violates LSP.

Compare Plan-and-Document processes to Agile process concerning Design patterns

Plan-and-Document: have an explicit design phase that is a natural fit to the use of design patterns in the software development process. One potential drawback is uncertainty as to whether the initial architecture and design patterns will need to change as the code is written and as the system evolves. Agile: relies on refactoring to incorporate design patterns as the code evolves, although experienced developers may lay plans for software architectures and design patterns that they expect to need based on previous, similar projects.

What are the two overarching principles of good object-oriented design that inform most of the patterns?

Prefer Composition and Delegation over Inheritance. Program to an Interface, not an Implementation.

What is the Abstract Factory, Factory Method?

Provide an interface for creating families of related or dependent objects without specifying their concrete classes

What is the Composite Pattern?

Provide operations that work on both an individual object and a collection of that type of object

What are the two most common variants of the LCOM metric?

Revised Henderson-Sellers LCOM: - Scores: 0 (best) to 1 (worst) - Interpretation: 0 means all instance methods access all instance variables. 1 means any given instance variable is used by only one instance method, that is, the instance methods are fairly independent of each other. LCOM-4: - Scores: 1 (best) to nn(worst) - Interpretation: Estimates number of responsibilities in your class as number of connected components in a graph in related methods' nodes are connected by an edge. A score n>1n>1 suggests that up to n−1n−1 responsibilities could be extracted into their own classes.

What is the Prototype pattern?

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. As we'll see in Chapter 6, prototype-based inheritance is part of the JavaScript language.

In a UML class diagram depicting the relationship "University has many Departments," what multiplicities would be allowable on each side of the association?

The University side has multiplicity 1, because a Department must belong to exactly one University. The Department side has multiplicity 1...**, because one or more Departments can belong to a University.

What is the flyweight pattern?

Use sharing to support large numbers of similar objects efficiently

What are various problems that thwart productivity?

Viscosity: it's easier to fix a problem using a quick hack, even though you know that's not the right thing to do. Immobility: it's hard to be DRY and because the functionality you want to reuse is wired into the app in a way that makes extraction difficult. Needless repetition: possibly as a consequence of immobility, the app has similar functionality duplicated in multiple places. As a result, a change in one part of the app often ripples to many other parts of the app, so that a small change in functionality requires a lot of little changes to code and tests, a process sometimes called shotgun surgery. Needless complexity: the app's design reflects generality that was inserted before it was needed.

Suppose Order belongs to Customer, and a view has @order.customer.name. Is this a Demeter violation? - Yes...replace with Order#customer_name which delegates to Customer#name - Yes...you can make a case for either of the above - Yes...but probably reasonable to just expose object graph in the view in this case - No...by using belongs_to we're already exposing info about the Customer anyway

Yes...you can make a case for either of the above Explanation: A view is about showing information about the models, so it's not unusual for a view to be somewhat coupled to its models and be able to display a representation of the 'object graph'. On the other hand, purists could indeed create a delegate to handle this, and we could hardly disagree with that. So technically it is a Demeter violation, but reasonable people could make a case for either a non-fix or a delegate fix.

Notwithstanding that "delegation is the key mechanism" for resolving Demeter violations, why should you be concerned if you find yourself delegating many methods from class A to class B just to resolve Demeter violations present in class C?

You might ask yourself whether there should be a direct relationship between class C and class B, or whether class A has "feature envy" for class B, indicating that the division of responsibilities between A and B might need to be reengineered.

What issue does the decorator pattern address?

a OCP violation that arises when we want to add behaviors to an existing class and discover that we cannot do so without modifying it.

What does the abstract factory pattern provide?

a common interface for instantiating an object whose subclass may not be known until runtime. example: Formatter isn't known until runtime, when it is stored in the @format instance variable

What is the visitor pattern?

a data structure is traversed and you provide a callback method to execute for each member of the data structure, allowing you to "visit" each element while remaining ignorant of the way the data structure is organized. - separating traversal of an aggregate from behavior

What does the The Demeter Principle or Law of Demeter state?

a method can call other methods in its own class, and methods on the classes of its own instance variables; everything else is taboo.

What is an antipattern?

a piece of code that seems to want to be expressed in terms of a well-known design pattern, but isn't—often because the original (good) code has evolved to fill new needs without refactoring along the way. - a piece of code that would be better structured if it followed a design pattern.

What is the general definition of a design pattern?

a reusable structure, behavior, strategy, or technique that captures a proven solution to a collection of similar problems by separating the things that change from those that stay the same.

What is the difference between aggregation and composition?

aggregation: the owned objects survive destruction of the owning object. For example, Course has many Students is an aggregation because the students happily don't get destroyed when the course is over! composition, the owned objects are usually destroyed when the owning object is destroyed. For example, Movie has many Reviews is a composition since deleting a Movie should cause all of its reviews to be deleted.

In statically typed compiled languages, what is the the cost of violating SRP?

any change to a class requires recompilation and may also trigger recompilation or relinking of other classes that depend on it

What are examples of architectural patterns and structural patterns?

architectural patterns: Client-Server structural patterns: Model-View-Controller

What are some critiques of UML-based diagrams?

being too "bloated" and heavyweight

In RSpec controller tests, it's common to stub ActiveRecord::Base.where, an inherited method. Which statements are true of such tests: a. The controller under test is tightly coupled to the model b. In a static language, we'd have to use DI to achieve the same task in the testing framework. - only (a) - only (b) - both (a) and (b) - neither (a) and (b)

both (a) and (b) Explanation: a. The controller is calling where directly, suggesting that it has detailed knowledge of the database schema for the model. b. Injecting a dependency would allow whichever method is called to be replaced at testing time with a double.

How does Dependency injection insert a seam between two classes?

by passing in (injecting) a dependency whose value may not be known until runtime, rather than hardwiring a dependency into the source code.

How does refactoring to fix code smells differ from refactoring to fix design smells?

code smells: refactoring a method involves moving code around within a class, Design smells: refactoring a design involves moving code between classes, creating new classes or modules (perhaps by extracting commonality from existing ones), or removing classes that aren't pulling their weight.

What is the Null Object pattern?

create a "dummy" object that has all the same behaviors as a real object but doesn't do anything when those behaviors are called - mechanism for replacing unwieldy conditionals with safe "neutral" behaviors as a way of disabling a feature.

What does a class diagram do?

depicts each actual class in the app, its most important class and instance variables and methods, and its relationship to other classes, such as has-many or belongs-to associations

What makes design patterns different from architectural and structural patterns?

design patterns apply to classes and class structure - Creational, Structural, and Behavioral

When does it make sense to use the Strategy method?

if the steps themselves were quite different, it would make more sense to use Strategy. example: OmniAuth -> many apps need third-party authentication, and the steps are quite different depending on the auth provider, but the API to all of them is the same. Indeed, OmniAuth even refers to its plug-ins as "strategies."

What does the dependency injection principle (DIP), sometimes also called dependency inversion, state?

if two classes depend on each other but their implementations may change, it would be better for them to both depend on a separate abstract interface that is "injected" between them.

What the LCOM metric (Lack of Cohesion Of Method) do?

measures cohesion for a class: in particular, it warns you if the class consists of multiple "clusters" in which methods within a cluster are related, but methods in one cluster aren't strongly related to methods in other clusters

What is the Observer pattern?

provides a canonical way for the subject to maintain a list of its observers and notify them automatically of any state changes in which they have indicated interest, using a narrow interface to separate the concept of observation from the specifics of what each observer does with the information. - used when one class (the observer) wants to be kept aware of what another class is doing (the subject) without knowing the details of the subject's implementation. - separating notification of "interesting" events from the details of the class being observed

Describe the refactoring process for Design smells?

refactoring: the process of improving the structure of a class architecture to make the code more maintainable and evolvable by moving code across classes as well as refactoring within the class.

What is The Single Responsibility Principle (SRP) of SOLID?

states that a class should have one and only one responsibility—that is, only one reason to change. - As a rule of thumb, if you cannot describe the responsibility of a class in 25 words or less, it may have more than one responsibility, and the new ones should be split out into their own classes.

What does the Open/Closed Principle of SOLID state?

that classes should be "open for extension, but closed against modification." - it should be possible to extend the behavior of classes without modifying existing code on which other classes or apps depend.

What happens if the extension point takes the form of selecting different subsets of features that "add on" to existing class behaviors,

the Decorator pattern may apply. The Rack application server is designed this way.

What happens if the extension point takes the form of a task with varying implementations for the steps

the Strategy and Template Method patterns may apply. Both are often used in conjunction with the Abstract Factory pattern, since the variant to create may not be known until runtime.

What are Design smells?

warning signs that your code may be headed towards an antipattern.

What does the decorator pattern do?

we "decorate" a class or method by wrapping it in an enhanced version that has the same API, allowing us to compose multiple decorations as needed.

What is the Proxy Pattern?

which one object "stands in" for another that has the same API. The client talks to the proxy instead of the original object; the proxy may forward some requests directly to the original object (that is, delegate them) but may take other actions on different requests, perhaps for reasons of performance or efficiency. ex) - ActiveRecord's all, where and find-based methods - ActiveRecord's associations


Ensembles d'études connexes

GRE MATH, GRE Math Formula Sheet, GRE Math Formulas, GRE Math Formulas, GRE Kaplan Math Formula, GRE - Math Formulas, Magoosh Math GRE Formulas, Magoosh Math GRE Formulas, GRE Math Formula Sheet, GRE Math Formula Sheet, GRE Math Formula Sheet, GRE Ka...

View Set

Citrus College My Plan, My Courses, My major class.

View Set