GRASP

7 minute read

General Responsibility Assignment Software Patterns

Craig Larman’s 9 principles

Information Expert
 Creator
 Controller
 Low Coupling
 High Cohesion
 Polymorphism
 Pure Fabrication  Indirection
 Protected variations

Create design model

• Add attributes and methods to the software classes
• Define the interactions between the objects
 Okay, I got it. But, how ???
 GRASP
 will guide you how to assign responsibilities to collaborating objects

Responsibility

A responsibility is not the same as a method,
but methods are implemented to fulfil responsibilities.

하나의 책임이 여러개의 메소드에 의해 구현될 수 있다. 예를 들어 하나의 퍼블릭 인터페이스와 거기서 호출하는 여러개의 프라이빗 메소드

9 principle

Modularity

 Goal of design
 partition the system into modules and assign responsibility among the
components
 Modularity reduces the total complexity a programmer has to deal with at any one time:
 functions are assigned to modules in a way that groups similar functions together (Separation of Concerns), and
 there are small, simple, well-defined interfaces between modules (Information Hiding)
Measuring Modularity(측정방법)
 Coupling: measure of the inter-dependencies between modules
 Cohesion: measure of how strongly the elements in a module are related

Common forms of coupling in OO languages

TypeX depends on TypeY if
 TypeX has an attribute referencing a TypeY instance, or TypeY itself.
 TypeX has a method referencing a TypeY instance, or TypeY itself, by any means. (e.g. a parameter or local variable of type TypeY, or the returned object is an instance of TypeY, etc) 파라메터 지역변수 리턴값 등에 어떤 타입을 사용한다면 그것은 커플링이다.
 TypeX is a direct or indirect subclass of TypeY.  TypeX implements interface TypeY.

Concept of Cohesion

 Cohesion
 measure of how strongly the elements in a class (module) are related  the related responsibilities are placed into one manageable unit.
related to Single Responsibility Principle (SRP)
Pursue High Cohesion!
 Advantages of High Cohesion
 Easily understandable and maintainable  Code reuse
 Low coupling

Creator Pattern

Problem
Who creates an A?
Solution
Assign class B the responsibility to create an instance of class A, if one of these is true (the more the better):
아래의 경우들이라면 B가 A를 만드는게 좋다
• B contains or aggregates A.
• B records A.
• B closely uses A.
• B has the initializing data for A.
if there is a choice, prefer “B contains or aggregates A”

Discussion:
 Guides assigning creation responsibilities
 Contradictions: creation may require significant complexity
• using recycled instances for performance reasons
• conditionally creating an instance from one of a family of similar class es
• sometimes desired to outsource object wiring (“dependency injection”)
•  Benefits:
 Low Coupling is supported
 Related patterns:
 Abstract Factory, Singleton

Information Expert pattern

Problem
What is a basic principle by which to assign responsibilities to objects?
Solution
Assign a responsibility to the class that has the information needed to fulfill it.
관련된 정보를 갖는 객체가 책임을 갖는게 좋겠다라는말
(Entity가 비지니스 로직을 갖는게 좋겠다? DDD? JPA?)

참고: 주문 서비스의 주문과 주문 취소 메서드를 보면 비즈니스 로직 대부분이 엔티티에 있다. 서비스 계층 은 단순히 엔티티에 필요한 요청을 위임하는 역할을 한다. 이처럼 엔티티가 비즈니스 로직을 가지고 객체 지 향의 특성을 적극 활용하는 것을 도메인 모델 패턴(http://martinfowler.com/eaaCatalog/ domainModel.html)이라 한다. 반대로 엔티티에는 비즈니스 로직이 거의 없고 서비스 계층에서 대부분 의 비즈니스 로직을 처리하는 것을 트랜잭션 스크립트 패턴(http://martinfowler.com/eaaCatalog/ transactionScript.html)이라 한다.

참고: 폼 객체 vs 엔티티 직접 사용 > 참고: 요구사항이 정말 단순할 때는 폼 객체( MemberForm ) 없이 엔티티( Member )를 직접 등록과 수정 화면 에서 사용해도 된다. 하지만 화면 요구사항이 복잡해지기 시작하면, 엔티티에 화면을 처리하기 위한 기능이 점점 증가한다. 결과적으로 엔티티는 점점 화면에 종속적으로 변하고, 이렇게 화면 기능 때문에 지저분해진 엔티티는 결국 유지보수하기 어려워진다. > 실무에서 엔티티는 핵심 비즈니스 로직만 가지고 있고, 화면을 위한 로직은 없어야 한다. 화면이나 API에 맞 는 폼 객체나 DTO를 사용하자. 그래서 화면이나 API 요구사항을 이것들로 처리하고, 엔티티는 최대한 순수 하게 유지하자.

Discussion
 Most used principle in the assignment of responsibilities
 Information is spread across different objects -> they need to inte ract
 Contraindication: Conflict with Separation of Concerns
• Example: Responsibility for saving a sale in the database
• Adding this responsibility to Sale
 distribute database logic over many classes : low cohesion
 Benefits
 Information encapsulation  supports low coupling

Controller pattern

Problem
What first object beyond the UI layer receives and coordinates (“controls”) a system operation?
Solution
Assign the responsibility to an object representing one of these choices:
• 1st option: Overall “system,” a “root object,” a device that
the software is running within, or a major subsystem
(facade controller)
• 2nd option: Use case scenario within which the system
operation occurs
(use case or session controller)
유아이가 던지는 이벤트를 누가 처리할 것인가에 대한 이야기

Discussion
 Controller class is called bloated if overloaded with too many res
ponsibilities
• Add more controllers (façade -> use-case controllers) • Delegatestootherobjects
 Benefits
 No application logic in the GUI
 Increased potential for reusable components
 Reason about the state of the use case
• Useful when operations must be performed in a specific order Example) MakePayment cannot occur until EndSale has occurred

Low Coupling pattern

Problem
How to reduce the impact of change?
Solution
Assign responsibilities so that (unnecessary) coupling remains low.
Use this principle to evaluate alternatives.

About Low Coupling Pattern
 Discussion
 Low coupling encourages designs to be more independent which
reduces the impact of change.
 Needs to be considered with other patterns such as Information Expert and High Cohesion.
 High coupling to stable “global” objects is not problematic Example) coupling to Java libraries such as java.util

자바쩜유틸처럼 글로벌한것과의 커플링은 괜찮다

High Cohesion

Problem
How to keep objects focused, understandable, and manageable, and as a side effect, support Low Coupling?
Solution
Assign responsibilities so that cohesion remains high. Use this to evaluate alternatives.

Pure Fabrication pattern

Problem
Who is responsible when you are desperate, and do not want to violate high cohesion and low coupling?
Solution
Assign a highly cohesive set of responsibilities to an artificial or convenience “behavior” class that does not represent a problem domain concept something made up, in order to support high cohesion, low coupling, and reuse.

=> JDBC같은것처럼 도메인모델에 없지만 공유되는 특정 기능에 대해서 전문 클래스를 만들고 각 도메인에서 공유하면 도메인들간의 코드중복이 줄지않겠느냐? high cohesion, low coupling, and reuse. 달성

Polymorphism pattern

Problem
Who is responsible when behavior varies by type?
Solution
When related alternatives or behaviors vary by type (class), assign responsibility for the behavior using polymorphic operations to the types for which the behavior varies.

About Polymorphism Pattern
 Benefits
 Easier and more reliable than using explicit selection logic  Easier to add additional behaviors later on
 Costs
 Increases the number classes in a design  May make the code less easy to follow
 Discussion
 fundamental principle in design: how to handle similar variations.
 Avoid excessive use for “future-proofing” against yet unknown poten tial future variations
• Agile approach: no significant “upfront design” and add the variation poi nt only when the need arises

Indirection pattern

Problem
How to assign responsibilities to avoid direct coupling?
Solution
Assign the responsibility to an intermediate object to mediate between other components or services, so that they are not directly coupled.

By adding a level of indirection and adding polymorphism, the adapter objects protect the inner design against variations in the external interfaces

About Indirection Pattern
 How can we avoid a direct coupling between two or more elements?
 Indirection introduces an intermediate units (classes) to communicate between the other units, so that the other units are not directly coupled.
 Benefits
 Low Coupling
 Example: Adapter, Facade, Proxy, Mediator, …

Protected Variations Pattern

Name
Protected Variations
Problem
How to assign responsibilities to objects, subsystems, and systems so that the variations or instability in these elements do not have an undesirable impact on other elements?
Solution
Identify points of predicted variation or instability
Assign responsibilities to create a stable “interface” around them.

About Protected Variations Pattern
 OCP and PV are two expressions of the same principle  protection against change to the existing code and design at
variation and evolution points with minor differences in emphasis
 Benefits
 Flexibility and Protection from Variations  Provides more structured design
 Mechanisms motivated by PV
 Uniform access in C#, Ada, and Eiffel
• Express both method and filed access in the same way
 Service lookup • JNDI
 Reflective or meta-model designs