CS2340 Exam 3
Stable Abstractions Principle
"abstractness increases with stability," stable packages should be more abstract, containing classes and modules that can be extended, more prepared for changes because the abstract dependency will rarely change/is very stable
Common Reuse Principle (CRP)
"classes that are used together are packaged together", helps decide which classes are placed into a package, classes that tend to be reused together belong in the same package, why: packages in Java are distributed in JAR files, if one package uses a class in another package it has a strong dependency; how: CRP says something about which classes to put in a package but mostly which classes not to put in the package
Single Responsibility Principle (again with iterator pattern)
(class should only have one reason to change) supports iterator pattern, collections should focus on storing members and providing access to them, an iterator focuses on looping over the members of a collection
Agile Methodology Principles
1. Focus on the code rather than design 2. people over process 3. iterative approach (evolved quickly on feedback) 4. customer involvement (to receive feedback) 5. expectation that requirements will change - need to be able to handle them (cant rely on requirements to be still and immutable) 6. simplicity (simple code, simple design - as simple as possible)
dealing with multithreading (singleton pattern)
1. make getInstance a synchronized method (public static synchronized Singleton) - means no two threads may enter the method at the same time, not efficient, no need to sync after first time 2. eagerly created instance, have a static method create instance 3. first check if null, then synchronize ( if (uniqueInstance == null) { synchronized (Singleton.class) {...)
patterns catalogue
5 main classes: fundamental patterns (basic, feed into other subclasses as well, ex: interface pattern), creational patterns (support object creation, ex: in java, new operator), structural patterns (help compose or put objects together, vary depending on type and purpose of structure), behavioral patterns (mostly focused on realizing interactions b/w diff objects, concerned with alg and assignment of resp.), concurrency patterns (support concurrency)
Agile Methodology
Aims for customer satisfaction through early and continuous delivery of useful software components developed by an iterative process using the bare minimum requirements; aim at flat cost (there is value in waiting - upfront work == liability)
Which class of design patterns does the Factory Pattern belong to? a) Fundamental patterns b) Creational patterns c) Behavioral patterns d) Concurrency patterns e) Structural patterns
B (Creational patterns) --> provides a method for creating objects
Which type of relationship between objects does Observer Pattern define? a) One to One b) One to Many c) Many to Many
B (one to many) --> when one object changes states, all dependents are notified and updated automatically
Which metric is used to measure stability of a package? a) the A metric b) The I metric c) the AI metric d) None of the above
B (the I metric) --> value ranges from 0 - 1, 1 is highly unstable
Which of the following statements is FALSE about code review? a) Complementary to testing b) Used for staff assessment c) A cost-effective way of finding faults d) None of the above
B (used for staff assessment) --> otherwise would lead to negative effects (avoiding submitting code for inspection, submitting small points, holding reviews that waste time and skew metrics, not pointing out flaws)
which of the following complies with the "programming to an interface" design principle? a) Dog d = new Dog(); d.bark(); b) Animal a = new Dog(); a.makeSound();
B --> A rep. programming to an implementation; B rep. programming to interface or super type, can reference polymorphically and don't need to know concrete type of object to use method
Which class of design patterns does the Singleton pattern belong to?
B) Creational Patterns --> example of a creational pattern, deals with the creation of a single instance of a class while providing global access point to instance
which class of design patterns does the Observer Pattern belong to? a) Fundamental patterns b) Creational patterns c) Behavioral patterns d) Concurrency patterns e) Structural patterns
C (Behavioral patterns) --> mostly focused on realizing interactions between different objects
which SOLID principle does the factory method pattern follow?
C (Dependency Inversion Principle) --> concrete products rely on abstract product
which SOLID principle does the decorator pattern follow? a) Information Expert b) Don't Repeat Yourself c) Open-Closed Principle d) Dependency Inversion Principle
C (Open Closed Principle) --> extending an obejcts behavior by wrapping object with decorators while each decorator extends a certain behavior **without modifying the existing code**
Which class of design patterns does the Iterator Pattern belong to? a) Fundamental b) Creational c) Behavioral d) Concurrency e) Structural
C (behavioral) --> lets you define the traversal behavior to traverse elements of a collection without exposing underlying elements of its composition
Which SOLID design principle is behind the idea that collections should not implement traversals? a) Information Expert b) Liskov Substitution Principle c) Single Responsibility Principle d) Dependency inversion Principle
C (single resp. principle) --> allows us to separate the management from the traversal of the collection, every resp. is an area of potential change (SRP says there should only be one reason for code to change)
Common Closure Principle (CCP)
Classes that change together belong together, would rather have changes focused to a single package (so only need to release one changed package)
"Don't Talk to Strangers" is a special case of which GRASP pattern? a) Polymorphism b)Information Expert c) Controller d) Protected Variations
D --> one of 9 grasp patterns, mechanism to protect from structure changes
strategy pattern
Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Lets the algorithm vary independently from clients that use it.
Dependency Inversion Principle
Depend on abstractions, not concretions; interface lives in upper level that hides the concrete class in the lower level
Which class of design patterns does the composite pattern belong to?
E (Structural Pattern) --> can create tree structures from objects and can work with tree like individual objects
which class of design patterns does the Decorator Pattern belong to? a) Fundamental patterns b) Creational patterns c) Behavioral patterns d) Concurrency patterns e) Structural patterns
E (Structural Patterns) --> helps compose objects/put objects together, extending objects behavior by adding new behaviors at run time using decorators (or wrappers)
Agile approach values planning over responding to change (T/F?)
False
GRASP Patterns
General Responsibility Assignment Software Patterns, Craig Larman, reduce impact of change on the system over time (easier maintenance), 9 topics (basic - creator, info expert, low coupling, controller, high coheasion and advanced)
measuring stability: the I Metric
I = C-out / (C-in + C-out) C-in: num classes outside package that depend on a class inside the package C- out: number classes outside the package that any class inside the package depends on I value is between 0 and 1 (I = 0: highly stable, I = 1: highly unstable)
review possible outcomes
accept: some bugs conditional accept: few major bugs, to be fixed by author and verified by moderator re-inspect: many major bugs, artifact must be re-inspected reject product outright
adding iterator to composite
add a createIterator() to menuComponent, have leaf return a nullIterator (hasNext() method always returns false), implement the traversal you want (pre, in or post)
Command pattern
allows you to decouple the requester of the action from the objects that performs the action, a command object encapsulates a request to do something, Command interface (in lecture example) just does one thing - executes a command
formal code review
alternative to testing code, group of people examine software and documentation for problems, makes judgements about quality
Polymorphism
alternatives based on type, assign responsibility for the behavior to the types for which the behavior varies, advantages (easier to add additional behaviors, reduces coupling between functionalities), disadvantages (increases number of classes in design and code is less easy to follow)
pure fabrication
assign a highly cohesive set of responsibilities to an artificial or convenience class that doesn't represent a problem domain concept, fabrication of imagination - compromise to preserve/support high cohesion and low coupling and reuse
review roles
author: answers questions reader: leads the team by reading and paraphrasing as needed recorder: records defects and issues inspectors: whole team, analyze and detect defects moderator: selects participants, evaluates preparedness of team, keeps meetings on track, technically competent
guidelines (3)
avoid problem solving during the inspection meeting, cost of inspection should be between 10-20%
review types (from least to most effective and formality)
casual conversation, peer group review, informal presentation, formal presentation, walk through, inspection
granularity
classes are too finely grained to be used as an organizational unit for large application, need a larger granule - a package (like JavaScript libraries, Node modules, Java JAR files)
inspections
complementary to other verification techniques such as testing, cost-effect way of finding results, redundant inspections by diff teams may find even more faults
singleton pattern
creational design pattern, used to ensure that only one instance of a particular class ever gets created and that there is just one (global) was to gain access to that instance
indirection
decouple objects - reuse potential stays high, assign responsibilities to an intermediate object to mediate between other components to avoid direct coupling (pure fabrification, observer patter, façade controller pattern)
Stable Dependencies Principle
depend in the direction of stability, parts of the system that change frequently should depend on parts that don't change much, things that change a lot should have few dependents
Acyclic Dependencies Principle (ADP)
dependency graph of packages must have no cycles, when two or more packages are involved in a cycle, it becomes very difficult to stabilize, has no cycles if starting at any vertex cannot bring us back to original vertex (following dependency arrows from root arrows, cannot trace back to root)
purpose (of reviews and inspections)
detection of faults (bugs or defects), adherence to standards, not education of staff nor fault correction nor staff assessment
Release-Reuse Equivalency Principle (REP)
disadvantages of code copying (own code you copy, have to maintain it, fix bugs, update it if the original code changes), what you want (never have to look at source code, be notified about updates, able to decide when to integrate changes), "granule of reuse is the granule of release"; ex: io package - only include if use outputStream or IO Exception
guidelines (2)
do not allow additional participants, avoid use of "you," author should not be moderator, recorder, or reader, each type of inspection should have its own checklist
the problem with "new"
each time "new" is used, we violate the "Code to an Interface" design principle
collections
ex: arrays, stacks, queues, hash tables, etc.; don't want to expose details of collections (would increase coupling of system)
third design principle
favor composition over inheritance - provides more flexibility, can encapsulate a family of algorithms and can change behavior at runtime
Designing with Packages
goal to partition classes according to some criteria and allocate partitions to packages, high level organization of classes
Encapsulation (protected variations)
group related entities into a unit and provide restricted external view, packaging of operations and attributes, state is accessible only by operations (protection from changes in data representation and changes in algorithm), example robot in a maze
protected variations
identify points of predicted variation or instability; assign responsibility to create a stable interface around them; protecting one part of program from changes in another part (protected var, open - closed), examples - encapsulation, abstraction, poly, indirection
review step 4
inspection meeting: conducted by moderator, line-by-line walkthrough, goal: find and note faults (up to 2 hours)
guidlines (1)
inspections should not be used for personnel eval, managers should not attend, hold a separate overview meeting to educate staff, spread out inspections over time
observer pattern
intent (observer is a behavioral design pattern that lets you define a subscription mechanism to notify mult. objects about any events that happen to the object they're observing); ex: subscribers signing up for a publisher - wouldn't want to couple publisher with every subscriber, so it's crucial that all subscribers implement the same interface and publisher communicated with them via interface, observes a 1 to many relationship, belongs to class of behavioral patterns - focused on realizing interactions between different objects
Factory method pattern
is used to encapsulate the code that creates objects is similar to the Template method pattern; defines an interface for creating an object but lets subclasses decide which class to instantiate, lets a class defer instantiation to subclasses
diamond problem
java does not support multiple inheritance, does not know which class to draw from if parents are siblings (ambiguous situation), causes compiler time error, solution: use default methods and interfaces (can implement multiple interfaces) and override the default method (interfaces : implements B,C and call with B.super.m();)
XP
lightweight methodology for small to medium teams dev. software in the face of rapidly changing requirements; mentality of sufficiency - practices 1. incremental planning 2. small releases 3. simple design 4. test first 5. refactoring 6. pair programming 7. continuous integration 8. on-site customer
Abstraction (protected variations)
low-level abstractions (procedural - subroutines, data abstractions - classes), higher-level (protection against multiple classes)
A metric
measures abstractness, A = C-abstract / (C-concrete + C-abstract), C-abs: num of abstract classes and interfaces in a package, C-concrete: num concrete classes A value is between 0 and 1 (A = 0: highly concrete, A = 1: highly abstract)
Format (Subset) of Pattern Definitions
name, intent (goal of pattern), applicability (list of applicable situations), structure sample code
package diagrams
package is a grouping of related UML elements like classes, other packages, use cases, etc., common to show dependencies (coupling), logical architecture of system, provides structural (static) view of the system - opposed to behavioral (dynamic) view of system
notation (package diagram)
packages - rectangle with tabs at top, name on tab or inside, dependencies - dotted arrows
review steps 1-3
planning: prep overview: education of participants preparation: individual study
singleton pattern code
private constructor, private static instance variable to store instance, public static method to gain access to instance (creates object if needed, returns it)
Design Principles (observer pattern)
protected variations (you can vary the observers without changing the subject), program to an interface - not an implementation (both subject and observer use interfaces), favor composition over inheritance (relationship b/w observers and subject is set up at runtime by composition)
shared vocabulary
provided by design patterns, can understand on the architectural level instead of itty gritty
Open Closed Principle (decorator pattern why?)
provides a way in which a class' runtime behavior can be extended without requiring modification to the class, principle: classes should be open for extension but closed for modification
conducting the review
raise issues; do not resolve them, review product not producer, avoid making accusations
inheritance
relation between two classes where on class inherits the properties of the other class (extends key word), diff types: single, multilevel, hierarchical, multiple, hybrid
review steps 5-6
rework: confirm and remove defects, team responsible for checking revisions follow-p: verify corrections; analyze results; update database
composite pattern
structural design pattern, allows us to build structures of objects in the form of trees that contain both objects and other composites (like grouping objects in a vector drawing tool, can apply operations to group or to parts)
iterator pattern
the design pattern that provides a way to access the elements of an aggregate object sequentially without exposing the underlying representation; behavioral design pattern, provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation, allows traversal of the elements of an aggregate without exposing the underlying implementation, places the task of traversal on the iterator object, not on the aggregate
decorator pattern
type of design/structural pattern, common in java esp with streams (input reader/writer etc), problem: working on UI toolkit and want to include border decoration and scroll bars, intent: lets you attach new behaviors to objects by placing these objects inside wrapper objects that contain the behaviors; wrapping = "delegation" but both delegator and delegate implement same interface
decorator pattern example
wearing clothes: if you're cold put on coat - garments extend behavior but are not part of you, can remove when not needed
applicability (observer pattern)
when changes to the state of one object may require the changing of other objects
Don't Talk to Strangers (Law of Demeter)
within a method, messages should only be sent to the following: this or self object, parameter of the method, attribute of this, element of a collection which is an attribute of this, object created within the method; more classes/methods traversed in a program = more fragile