Friday, September 18, 2020

Difference between Design pattern and framework?

Design Pattern:-  

  • Design pattern solves many software architecture issues 
  • Design pattern is a category of patterns that deals with object oriented software. 
  • Design pattern captures the static and dynamic structure and collaboration among key participants in software designs.
  • They can be used across different domains.
  • They have tight scope

Framework:-

  • Framework is made up of group of concrete classes which can be directly implemented on an existing platform.
  • Frameworks are written in programming languages. It is a large entity comprising of several design patterns.
  • Frameworks are concerned with specific application domain e.g. database, web application etc.
  • It has large scope.

 




A pattern is a way of doing something, or a way of pursuing intent. This idea applies to cooking, making fireworks, developing software, and to any other craft. It is a solution to a problem in a context. Patterns are classified into 1) Design Pattern, 2) Architectural Pattern, 3) Macro – Architecture, 4) Micro – Architecture, 5) Idioms or Coding Patterns, 6) Language Paradigms etc.

Design Pattern:

Design pattern is a category of patterns that deals with object oriented software. They represent solutions to problems that arise when developing software within a particular context. Design pattern captures the static and dynamic structure and collaboration among key participants in software designs. They can be used across different domains.

Framework:

Framework is made up of group of concrete classes which can be directly implemented on an existing platform. Frameworks are written in programming languages. It is a large entity comprising of several design patterns. Frameworks are concerned with specific application domain e.g. database, web application etc.

Above definition very much clarifies the difference among three. A design pattern is a type of pattern and is more like a concept, whereas a framework is something already coded to be used repetitively.




Hope you find this information useful.

Tuesday, September 15, 2020

Object Oriented Implementation


Programming and Development Process

- Coding is an end goal of software development.
- Iterative and incremental development process results in the feeding of prior iteration into the beginning of next iteration, continuously refining the implementation works.


Mapping Design to Code

- It involves the implementations of object oriented design into the object oriented programming code.
- It requires writing code for:
a) Class and interface definitions
b) Method definitions
- Class definitions are created by mapping design class diagrams to code.
- Method definitions are created by mapping interaction diagrams to code.


Creating Class Definitions from Design Class Diagram

Example 1


Example 2


Creating Methods from Collaboration Diagram

- The sequence diagram consists of sequence of messages which are translated to a series of statements in the method definitions.

Example 1


Updating Class Definitions

Collection Classes in Code

- One to many relationships are common.
- Such relationships is implemented using collection object such as list, map or array.
- The choice of collection class is influenced by the requirements. i.e. key based lookup requires Map while growing ordered list requires a List.
- If object implements an interface, declare the variable in terms of the interface.


Example 1


Example 2


Exception and Error Handling

Exception

- An exception is a condition that is caused by a runtime error in the program.
- An exception may occur due to following reasons:
a) Invalid data entered by a user.
b) File to be opened can not be found.
c) The network connection has lost in the middle of the communication


Sources for Exceptions

1. User errors
2. Programmer errors
3. Physical resource failure


Categories of Exception

1. Checked Exception:
- It is the exception that can not be foreseen by the programmer.
- Eg: FileNotFoundException

2. Runtime Exception:
- It is the exception that could be avoided by the programmer.
- It is ignored at the time of compilation.

3. Errors:
- They are the problems beyond the control of user and programmer.
- Eg: StackOverflowException


Exception Handling Process

- In object oriented programming languages, there is a mechanism to handle exceptions in a proper manner.
- Try, throw and catch are the basic exception handling paradigms used.
- The general code is put in try block. It means try to execute the code.
- If the system succeeds to execute the code, execution flows in general or normal order.
- If something goes wrong while executing the try block, this code throws an exception object and stops executing code of try block.
- The error handler catches the exception object and make necessary actions needed.
- Execution continues with the next instructions following the catch block.

Example of Error Handling in JAVA


class WithExceptionHandling{
public static void main (String [ ] args) {
int a, b;
float r;
a = 7; b = 0;
try {
r = a / b;
System.out.println("Result = " + r);
}
catch (ArithmeticException e) {
System.out.println("B is zero");
}
}
}


Exception Hierarchy

The exception hierarchy is shown in the given figure:


User Defined Exceptions

- All the exceptions must inherit Throwable class.
- For runtime exception, extend RuntimeException class.
- For checked exception, extend Exception class.


Miscellaneous Topics on OOAD

Forward Engineering

- Forward engineering is the process of building from a high level model or concept to build in complexities and lower level details.
- It moves from logic implementation to the physical implementations of a system.
- It transforms a model into code through mapping to an implementation language.
- It may cause loss in information as models are semantically richer than OOP languages.
- The structural and behavioral features are clearly visualized from the model but not from raw code.


Reverse Engineering

- Reverse engineering is the process of extracting knowledge or design information from the code.
- It includes disassembling of a computer program and analyze its components and working in detail.
- It transforms code into a model through mapping from a specific implementation language.
- It is generally incomplete as the model can not be completely recreated due to information loss during forward engineering process.


Roundtrip Engineering

- Roundtrip engineering is a functionality that synchronizes two or more software artifacts like source code, models and so on.
- It is necessary when same information is present in multiple artifacts and needed to be updated.
- It has ability to synchronize existing artifacts that evolved concurrently by incrementally updating each artifact to reflect changes made to other artifacts.


Interfaces

- Interface is a concept of abstraction and encapsulation.
- It defines a set of methods that an instance of a class that has that interface.
- It declares the non private methods.
- It does not show the method implementation.
- It describes the actions that an object can do.

- No variables are allowed to be declared.
- All the functions listed must be public.
- The function description is not mentioned.

Example


public interface vehicle
{
function start_engine();
}

public class car implements vehicle
{
function start_engine()
{
...................
}
}


Activity Diagram

- It models the dynamic aspects of the system.
- It is a flowchart showing flow of control from activity to activity.
- It contains activity states, transitions and objects.
- Transition may be branching, forking and joining.


Branching

- A branch have one incoming transition and two or more outgoing transitions.
- Each output transition has a boolean expression called guard expression stating condition to execute that branch.


Forking and Joining

- Fork and join are used to model concurrent processes.
- Fork represents splitting of a single flow into two or more concurrent flow of control.
- Join represents joining of concurrent flows to a single flow.
- Join and fork must balance in an activity diagram.


Swim Lanes

- To model the workflow of business process, the activity states on an activity diagram are partitioned into groups, each group representing business organization responsible for those activities.
- Each group is separated by a vertical solid line.
- Each group is known as swimlane.


Example of Activity Diagram and Swim Lanes

Q) Draw activity diagram to withdraw money from ATM. Assume necessary and suitable data.


Statechart Diagram

- It models the dynamic aspect of the system.
- It is event oriented diagram.
- It tracks the states that an object goes through.
- It shows the behavior of an individual object.
- It models the lifetime of a reactive system.
- It consists of state, event and signal.


Example of State Diagram

Q) Draw state diagram for login verification system of online banking system. Assume necessary and suitable data.


Case : Interaction Diagram

Q) Draw a sequence diagram and collaboration diagram for the given case.


A customer wants to draw money from his bank account. He enters his card in ATM. The ATM prompts
enter pin. The customer enters his pin. The ATM retrieves bank account number, encrypt pin and account
number and sends it over to the bank. The bank verifies it. If the pin is correct, ATM displays "Enter amount",
draws money from bank account and pays out the amount.


Sequence Diagram for the given case is:


Collaboration Diagram for the given case is:


Case : Use Case Diagram

Q) A patient calls clinic to make appointment for a yearly checkup. The receptionist finds nearest empty time slot in appointment book and schedules for that time slot. Draw the use case diagram for the given case.

Object Oriented Design


Analysis to Design

Input

- The output of object oriented analysis is provided as input to object oriented design.
- Analysis and design may occur in parallel with incremental and iterative process.
- Conceptual model, use case, system sequence diagram, UI documentation and relational data model are the input artifacts.


Design

- With the help of the input artifacts, we can conclude the following:
1. Define object and class diagram from conceptual model.
2. Attributes are identified.
3. A description of solution to a common problem (design patterns) are used.
4. Application framework is defined.
5. The persistent objects or data are identified.
6. The remote objects are identified and defined.


Output

- Sequence diagram and design class diagram are the typical output artifacts of object oriented design.
- The comparison of analysis model and design model is shown in given table:

Analysis ModelDesign Model
  • Classes
  • Attributes
  • Methods
  • Relationships
  • Behavior
  • Objects
  • Data Structures
  • Algorithm
  • Messaging
  • Control


Describing and Elaborating Use Cases

Class Responsibility Collaboration (CRC) Cards

- It is a text oriented modelling techniques or tools used in design of object oriented software.
- It is a paper index cards in which the responsibilities and collaborators of classes are written.
- Each card represents a single class.
- The general format of CRC card is shown below:

Class Name
ResponsibilitiesCollaborators


Realization of Use Cases

- It represents the implementation of use case in terms of collaborating objects.
- It may include textual document, class diagrams of participating classes and interaction diagrams.


UML Interaction Diagram

- Interaction diagram shows how objects interact via messages.
- It is used for dynamic object modelling.
- It is of two types. They are as follows:
1. Sequence diagram
2. Communication or collaboration diagram


Sequence Diagram

- A sequence diagram shows the interaction among objects as a two dimensional chart, in a fence format, in which each new object is added to the right.
- The objects participating are shown at the top of the chart as boxes attached to a vertical dashed line.
- The name of object with a semicolon separating it from the name of the class is written inside the box.
- The name of object and the class is underlined.
- The vertical dashed line indicates the lifeline of objects.
- The rectangle drawn on the lifeline is called activation symbol, which indicates that the object is active as long as the rectangle exists.
- Each message is indicated as an arrow between the lifeline of two objects.
- The messages are shown in chronological order.
- Each message is labeled with the message name.


Advantages:

- It shows the time sequence of messages.
- It has large set of detailed notation options.


Disadvantages:

- It is forced to extend to right when new objects are added, which consumes horizontal space, making it difficult to view by the user.

Basic Notations


Collaboration Diagram

- Collaboration diagram shows both structural and behavioral aspects.
- Structural aspect includes objects and link between them.
- It illustrates the object interactions in a graph format in which objects can be placed anywhere.
- The link between objects is shown as a solid line.
- The messages are labelled with a arrow and prefixed with sequence number.


Advantages:

- It is flexible to add new objects.


Disadvantages:

- It is difficult to know the sequence of messages.
- It includes fewer notation options.


Basic Notations:

1. Class

Sale

2. Instance

:Sale

3. Named instance

S1 : Sale

4. Messages
seq no return := message (parameter : parameterType) : returnType ---------------->

5. Links
---------------------------------

6. Conditional messages
1[color = red] : calculate() --------------->

7. Iteration
1 * [r = 1 .. N] : num := nextInt()


Objects and Patterns

Patterns

- Patterns is a way of doing something.
- Design pattern is a category of patterns that deals with object oriented software.
- Design pattern is a general repeatable solution to a commonly occurring problem in software design.
- It is a description for how to solve a problem that can be used in many different situations.


Components

1. Pattern Name
2. Pattern Description
3. Solution
4. Consequences


Advantages

- It reduces a complex form to a simple one.
- It provides clear concept of the problem and its solutions.
- It provides a mean to model a good solution.
- It facilitates communication.


Usage

- It can speed up the development process, so used in Rapid Application Development (RAD)
- It provides a general solution, so can be used in any platform.


GRASP Design Pattern

- GRASP stands for General Responsibility Assignment Software Patterns.
- These principles are important to design object oriented software.
- It guides choices in where to assign responsibilities.

1. Information Expert:
- Problem : Which class should be responsible for doing certain things?
- Solution : Assign responsibility to the class that has the information necessary to fulfill the required responsibility.
- It describes that the objects do things related to the information they have.

2. Creator:
- Problem : Who should be responsible for creating a new instance of some class?
- Solution : Assign class B the responsibility to create an instance of class A if one or more of the following is true:
a) B aggregates A objects.
b) B contains A objects
c) B records instances of A objects
d) B closely uses A objects
- If more than one option applies, prefer a class B which aggregates class A.

3. High Cohesion:
- Problem : How to keep objects focused, understandable and manageable?
- Assign responsibility so that cohesion remains high.
- Cohesion is a measure of how strongly the responsibilities of an element are related.
- An element with highly related responsibilities and which does not do a tremendous amount of work has high cohesion.
- The classes with low cohesion suffers from:
a) hard to comprehand
b) hard to reuse
c) hard to maintain
d) constantly affected by change

4. Low Coupling:
- Problem : How to support low dependency, low change impact and increased reuse?
- Assign responsibility so that coupling remains low.
- Coupling is a measure of how strongly one element is connected to other elements.
- The class with high coupling suffers from:
a) forced local changes
b) harder to understand in isolation
c) harder to reuse

5. Controller:
- Problem : What first object beyond UI controls a system operation?
- Assign responsibility to a class representing one of the following choices:
a) Represents overall system
b) Represents a use case scenario within which system events occur


Frameworks

- Framework is a group of concrete classes which can be directly implemented on an existing platform.
- They are written in programming languages.
- They are concerned with specific application domain.


Patterns vs Frameworks

- Pattern is a concept while framework is code to be used.
- Pattern supports reuse of software architecture and design while framework supports reuse of detailed design and code.


Model View Controller (MVC) Framework

- It is a software architectural pattern to implement UI.
- It divides the given software application into three inter connected parts, to separate internal representation of information from the ways they are presented to the users.
- The central component is model that captures the behavior of the application independent of UI. It manages data, logic and rules of the application.
- A view can be any output representation of information visible to the users.
- The controller accepts input and converts it to commands for the model or view. It links model and view together.


Determining Visibility

Visibility

- It is the ability of an object to have a reference to another object.
- It indicates the scope of the objects.
- For a sender object to send message to a receiver object, the sender must be visible to the receiver.


Attribute Visibility

- Attribute visibility from A to B exists when B is an attribute of A.
- It is relatively permanent i.e. it persists as long as A and B both exists.


Parameter Visibility

- Parameter visibility from A to B exists when B is passed as a parameter to a method of A.
- It is relatively temporary i.e. it exists within the scope of the method.
- It is generally transformed into attribute visibility within a method.


Local Visibility

- Local visibility from A to B exists when B is declared as a local object within a method of A.
- It is temporary as it persists only within the scope of the method.
- It can be achieved by:
1. Create a new local instance and assign it to local variable.
2. Assign returning object from a method invocation to a local variable.


Global Visibility

- Global visibility from A to B exists when B is global to A.
- It is permanent.
- It can be achieved by:
1. Assign an instance to a global variable.


Visibility in UML

1. Public
- Any outside classifier with the visibility to the given classifier.
- It is denoted by '+'

2. Protected
- Any descendant of classifier can use this feature.
- It is denoted by '#'

3. Private
- Only the classifier itself can use the feature.
- It is denoted by '-'


Visibility Example

The example that shows details of the visibility is shown in figure below:


Class Diagram

- Class diagram is used for static modeling that illustrates classes, interfaces and their relationships.
- It shows the structural view of the system.


Types of Relationships

1. Association:
- It enables objects to communicate with each other.
- It describes a connection between classes.
- A link is the physical or conceptual connection between object instances.
- The association relationship of a class with itself is known as recursive association.
- It is represented by drawing a straight line between concerned classes.
- Arrow head can be used to indicate reading direction.
- The multiplicity is noted on each side.

2. Aggregation:
- It is the association in which the involved classes represent a whole-part relationship.
- It takes the responsibility of leadership.
- When an instance of one object contains instances of some other objects, then aggregation exists between composite object and component object.
- It is represented by a diamond symbol at the end of a relationship.
- It can never be recursive and symmetric.

3. Composition:
- It is the strict form of aggregation, in which the parts are existence-dependent on the whole.
- It is represented as a filled diamond drawn at composite end.
- The part instance can only be the part of one composite at a time.
- Creation and deletion of parts is managed by composite.

4. Inheritance (Generalization and Specialization):
- It describes 'is a kind of' relationships between classes.
- Object of derived class inherits the properties of base class.
- It is defined statically.

5. Dependency:
- It indicates that one element has knowledge of another element.
- It states that a change in specification of one thing may affect another thing using it, but not necessarily the reverse.
- It depicts non-attribute visibility between classes.

6. Realization:
- It indicates the implementation of functionality defined in one class by another class.


Attributes

- The format of attribute is given as:


visibility name : type multiplicity = default {property - string}


Association Class

- It allows you treat an association itself as a class.


Constraints

- It is visualized in text between braces.


Qualified Association

- It is the association with a qualifier.

Object Oriented Analysis


Building Conceptual Model

Domain Modelling

- Domain model is the important conceptual model that illustrates the noteworthy concepts in a domain.
- It represents the context in which the system must operate.
- A domain model in UML is illustrated with a set of class diagrams omitting the operations.
- It shows the following concepts:
1. Domain classes
2. Associations between domain class
3. Attributes of domain class
- It visualizes and relates concepts of the domain.


Noun Phrase Analysis

- It is the method to find the domain classes.
- Identify the nouns and noun phrases in the textual descriptions of domain.
- Consider them as candidate conceptual classes or attributes.


Adding Associations and Attributes

- Association is the relationship between classes.
- The ends of association may contain multiplicity.
- Multiplicity refers to the numerical relationship between instances of the class.
- Associations should be named with verb phrase in a readable and meaningful way.
- Association name starts with a capital letter.
- Each end of an association is called role.
- Two classes can also have multiple associations.
- Attributes is a logical data value of an object.
- Attributes are shown in second compartment of class box.
- Attribute name is compulsory.
- type and other information are optional.
- The basic syntax is:
visibility name : type multiplicity = default { property - string }
- The derived attributes have a '/' symbol before attribute name.


Create a domain model : Example 1

XYZ restaurant in Kathmandu would like to automate its building service. A waiter takes order for each table in restaurant along with order details (item name and quantity). Customers are allowed to order more items after their first order. A bill is generated at the end for each customer having details (restaurant name, date, bill no. item, quantity, and total amount)


Create a domain model : Example 2

Courses may have recommended items of Reading material, which may be either Books or individual chapters. Items of reading material may also allow user or floppy for every NFA there is for have reviews associated with them.


Representation of System Behavior

- System behavior describes what a system does.
- It hides the implementational details of how system performs.
- It provides the dynamic model of the system.
- A system behavior is depicted as a black box.
- It must shows the reaction of system with external events, timer events and faults with a time frame embedded within it.
- System behavior can be represented by:
1. Use Case
2. System Sequence Diagram (SSD)
3. Operation Contracts


System Sequence Diagram

- Actor generates events by requesting something to the system.
- The request event initiates an operation in the system.
- Ordering of events should follow their order in the scenario.
- SSD can be constructed from use case as:
a) Draw system as black box on right side.
b) For each actor, draw stick figure and lifeline.
c) For each events that each actor generates, draw message.


Operation Contracts

-It gives detailed representation of system behavior.
- Contract describes outcome of executing system operation in terms of state changes to domain objects.
- It is a document containing:
1. Operation
2. Cross Reference
3. Pre conditions
4) Post conditions