Cohesion: Abstract Data Type
Cohesion: Abstract Data Type
Cohesion: Abstract Data Type
When a software program is modularized, its tasks are divided into several modules based on some
characteristics. As we know, modules are set of instructions put together in order to achieve some
tasks. They are though, considered as single entity but may refer to each other to work together.
There are measures by which the quality of a design of modules and their interaction among them
can be measured. These measures are called coupling and cohesion.
Cohesion
Cohesion is a measure that defines the degree of intra-dependability within elements of a module.
The greater the cohesion, the better is the program design.
Co-incidental cohesion - It is unplanned and random cohesion, which might be the result of
breaking the program into smaller modules for the sake of modularization. Because it is
unplanned, it may serve confusion to the programmers and is generally not-accepted.
Logical cohesion - When logically categorized elements are put together into a module, it is
called logical cohesion.
Temporal Cohesion - When elements of module are organized such that they are processed
at a similar point in time, it is called temporal cohesion.
Procedural cohesion - When elements of module are grouped together, which are executed
sequentially in order to perform a task, it is called procedural cohesion.
Communicational cohesion - When elements of module are grouped together, which are
executed sequentially and work on same data (information), it is called communicational
cohesion.
Sequential cohesion - When elements of module are grouped because the output of one
element serves as input to another and so on, it is called sequential cohesion.
Functional cohesion - It is considered to be the highest degree of cohesion, and it is highly
expected. Elements of module in functional cohesion are grouped because they all contribute
to a single well-defined function. It can also be reused.
Coupling
Coupling is a measure that defines the level of inter-dependability among modules of a program. It
tells at what level the modules interfere and interact with each other. The lower the coupling, the
better the program.
Content coupling - When a module can directly access or modify or refer to the content of
another module, it is called content level coupling.
Common coupling- When multiple modules have read and write access to some global
data, it is called common or global coupling.
Control coupling- Two modules are called control-coupled if one of them decides the
function of the other module or changes its flow of execution.
Stamp coupling- When multiple modules share common data structure and work on
different part of it, it is called stamp coupling.
Data coupling- Data coupling is when two modules interact with each other by means of
passing data (as parameter). If a module passes data structure as parameter, then the
receiving module should use all its components.
Class: In general Class is a group of similar objects, example Fruits, Vehicle, Employee, Student
etc.
Class is user defined datastructure which tieds data and functions together, it is a blueprint of
objects. Class definition will not reserve memory
In python a class can be defined using the syntax
class ClassName:
'Optional class documentation string'
Data members # to access in all the objects
Functions definition
class is a keyword and class name can be any user defined name, normally the class name will be
of title case.
A class creates a new local namespace where all its attributes are defined. Attributes may be data or
functions.
Document string is not mandetory, it can accessed using the magic function __doc__ using the
syntax. Class_name.__doc__ . docstring is used to brief description about the class.
Example:
class Student:
A class representing a student
Student-count=0
def __init__(self , n, a):
self.full_name = n
self.age = a
def get_age(self): #Method
return self.age
Student_count is a data member that can be accesed in all the methods.
__init__( )
Class functions that begins with double underscore (__) are called special functions as they have
special meaning.
__init__ is one such function that gets called when a new object is created. This function is
normally used to initialize all the instance variables.
get_age() is a method i,e a member function of student class.
Self: The first argument of every method is a reference to the current instance of the class.
In __init__, self refers to the object currently being created; so, in other class methods, it refers to
the instance whose method was called.
Object: Object is a thing which has data and exits Ex. Mango, Bike. Object is an instance
(Variable) of type Class, memmory will be resorved once the object is created. Object is a
combination of functions, variables and data structures.
Once a class is defined user can create any number of objects using the syntax
Object name=Class-name(values)
Ex: f = student(Python, 14)
Class attributes can be accessed using the syntax
Object-name.method()
Object-name.data-member
Class attributes can also be accessed using the python built in functions
getattr(obj, attribute): to access the attribute of object.(Retruns value of attribute for that object)
hasattr(obj,attribute): to check if an attribute exists or not.( Returns true if exists)
setattr(obj,name,value): to set new value to an attribute. If attribute does not exist, then it would
be created.
delattr(obj, name): to delete an attribute
One major difference between objects and class is in the way attributes and methods are treated in
objects and classes. A class is a definition about objects; the attributes and methods in a class are
thus declarations that do not contain values. However, objects are created instances of a class. Each
has its own attributes and methods. The values of the set of attributes describe the state of the
objects.
Class Variables: The variables accessed by all the objects(instances) of a class are called
class variable. There is only copy of the class variable and when any one object makes a change to a
class variable, the change is reflected in all the other instances as well. Class variables can be
accessed using the syntax
Class_name.Class variable
Object_name. Class variable
Note: if user changes the value of class variable using class name, then it reflects to all objects
if user changes the value of class variable using object name, then it reflects only to
that objects
Object/instance Variable: Variables owned by each individual object (instance of a class)
are called object variables. Each object has its own copy of the field i.e. they are not shared and are
not related in any way to the field by the same name in a different instance of the same class.
In the above Student class example Student-count is Class variable and full_name is a
Object variable.
2. Member function(method): A method is a function that is defined inside a class. Methods are
members of classes. A method is a function that is available for a given object. There are different
types of methods like Class methods, Instance methods, Service methods, and Support methods.
Class method: A "class method" is a method where the initial parameter is not an instance
object(self), but the class object , which by convention is called cls . This is implemented with the
@classmethod decorator. The class method does not require object to invoke it.
Ex:
class Foo(object):
@classmethod
def hello(cls):
print("hello from %s" % cls.__name__)
Foo.hello()
-> "Hello from Foo"
Foo().hello()
-> "Hello from Foo"
Instance Method:An "Instance method" is a method where the initial parameter is an instance of
object(self) and requires no decorator. These are the most common methods used.
class Foo(object):
def hello(self):
print("hello)
f=Foo()
f.hello()
Built-in Class attributes:Every Python class keeps the following built-in attributes and they can be
accessed using dot operator like any other attribute.
__dict__: Dictionary containing the class's namespace.
__doc__: Class documentation string or none, if undefined.
__name__: Class name.
__module__: Module name in which the class is defined. This attribute is
"__main__" in interactive mode
Example:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name,", Salary: ", self.salary)
emp1 = Employee("Ranga", 2000)
emp2 = Employee("Soma", 5000)
print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__ )
Classes and functions: Program
Encapsulation : Encapsulation is the mechanism of embeding the data with function for restricting
the access to some of an objects's components, this means, that the internal representation of an
object can't be seen from outside of the objects definition.
Encapsulation provides the different levels of accessing to the class members this is called visibility
of class members. OOPs languages provides three access specifiers to controll the accessing of class
members.
Private: This specifies that the class members (variables and methods) can be accessed only within
that class means that only the member functions can use the class members and can not be used
outside the class. In C++ all the members are private by default. In python to make the class
member private begin the name of the member with double under_score(__)
Example:
class Visibility:
def __init__(self,a,b):
self.atta=a
self.__attb=b #private data
def __disp(self):# private method
print ("Inside private method",self.atta,self.__attb)
def display(self):
print("Inside public method",self.atta)
self.__disp()#calling private method
ob1=Visibility(2,20)
ob1.display()
ob1.__disp()# will not work as it can not access outside
Public: This specifies that all attributes and methods are visible to every one. Class members can
be accesed even outside the class using object_name.class member. In C++ to make the class
members public, have all the members in the public: section.
In pyhton by defalut all the members are public.
Example:
class Cup:
def __init__(self):
self.color = None
self.content = None
Example:
class Cup:
def __init__(self):
self.color = None
self._content = None # protected variable
Destructor: Destructor is member function, which is invoked when the instance is about to be
destroyed. This method is used to cleanup the resources used by an instance. Destructor is used for
destroying the objects which are not needed, to free the memory space. The process of periodically
reclaiming the block of memory that are no longer needed is called Garbage collection. In
python Python's garbage collector runs during program execution and is triggered when an object's
reference count reaches zero. An object's reference count changes as the number of
class Advice(Thought):
def __init__(self):
super(Advice, self).__init__()
def message(self):
print "Warning: Dates in calendar are closer than they appear"
super(Advice, self).message()
class X: pass
class Y: pass
class Z: pass
class A(X,Y): pass
class B(Y,Z): pass
class M(B,A,Z): pass
# Output:
# [<class '__main__.M'>, <class '__main__.B'>,
# <class '__main__.A'>, <class '__main__.X'>,
# <class '__main__.Y'>, <class '__main__.Z'>,
# <class 'object'>]
Exception:
An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions. Even if a statement or expression is syntactically correct, it may
cause an error when an attempt is made to execute it. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. In Python exception is an object that
represents an error.
Exception Handling:If there is some suspicious code which may raise an exception, then place
the suspicious code in a try: block. After the try: block, include an except: statement, followed by a
block of code which handles the problem as elegantly as possible.
Standard Exceptions in Python:
Syntax:
try:
statements to be executed
-------
-------
except ExceptionI:
If there is ExceptionI, then execute this block.
-------------
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
-----------------------------
A single try statement can have multiple except statements. This is useful when the try block
contains statements that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
Example:
sname=input("Enter Existing file name")
dname=input("Enter new file name")
try:
sh=open(sname, "r")
dh = open(dname, "w")
str=sh.read()
dh.write(str)
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("File successfully copied")
sh.close()
dh.close()
except clacuse with no exceptions.
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
If no specific exception is specified then it catches all the exceptions that occurs. But drawback of
this kind is the programmer can not identify the root cause of the problem.
Except clause with multiple exceptions:
try:
You do your operations here
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,then execute this block.
......................
else:
If there is no exception then execute this block.
Abstract Class: An abstract class is a class that cannot be directly instantiated. Instead, you
instantiate an instance of a subclass. Typically, an abstract class has one or more operations that are
abstract. An abstract operation has no implementation; it is pure declaration so that clients can bind
to the abstract class. The most common way to indicate an abstract class or operation in the UML is
to italicize the name.
You can also make properties abstract, indicating an abstract property or accessor methods. Italics
are tricky to do on a whiteboards, so you can use the label: {abstract}.
Dynamic Binding:Dynamic binding also called dynamic dispatch is the process of linking
procedure call to a specific sequence of code (method) at run-time. It means that the code to be
executed for a specific procedure call is not known until run-time. Dynamic binding is also known
as late binding or run-time binding.
Dynamic binding is an object oriented programming concept and it is related with polymorphism
and inheritance.
Deligation: In object-oriented programming, delegation refers to evaluating a member (property or
method) of one object (the receiver) in the context of another, original object (the sender).
Delegation can be done explicitly, by passing the sending object to the receiving object, which can
be done in any object-oriented language; or implicitly, by the member lookup rules of the language,
which requires language support for the feature. Implicit delegation is the fundamental method for
behavior reuse in prototype-based programming, corresponding to inheritance in class-based
programming.
Class Library:In object-oriented programming , a class library is a collection of prewritten classes
or coded templates, any of which can be specified and used by a programmer when developing an
application program. The programmer specifies which classes are being used and furnishes data that
instantiate s each class as an object that can be called when the program is executed. Access to and
use of a class library greatly simplifies the job of the programmer since standard, pretested code is
available that the programmer doesn't have to write. In python import stament is used include the
prewritten modules into the required script.
Model:A model is a simplification of reality. Modeling is a proven and well-accepted engineering
technique. A model provides the blueprints of a system. Models may encompass detailed plans, a
good model includes those elements that have broad effect and omits those minor elements that are
not relevant to the given level of abstraction. Every system may be described from different aspects.
We build models so that we can better understand the system we are developing.
Through modeling, we achieve four aims.
1. Models help us to visualize a system as it is or as we want it to be.
2. Models permit us to specify the structure or behavior of a system.
3. Models give us a template that guides us in constructing a system.
4. Models document the decisions we have made.
In software the two most common ways are from
1) An algorithmic perspective
2)An object-oriented perspective.
In algorithmic approach the main building block of all software is the procedure or function. This
view leads developers to focus on issues of control and the decomposition of larger algorithms into
smaller ones.
In object-oriented approach, the main building block of all software systems is the object or class.
A Modeling language is a language whose vocabulary and rules focus on the conceptual and
physical representation of a system.
UML(Unified Modeling Language):The Unified Modeling Language (UML) is a standard
language for writing software blueprints. The UML may be used to visualize, specify, construct, and
document the artifacts of a software system. The Unified Modeling Language (UML) is a family of
graphical notations,that help in describing and designing software systems, particularly software
systems built using the object-oriented (OO) style.
UML builds the model that are precise, unambiguous, and complete. It addresses the
specification of all the important analysis, design, and implementation decisions that must
be made in developing and deploying a software system.
UML is not a visual programming language, but its models can be directly connected to a
variety of programming languages i.e UML model can be directly mapped to programming
OOP languages. This mapping permits forward engineering: The generation of code from a
UML model into a programming language. The reverse is also possible: You can reconstruct
a model from an implementation back into the UML.
UML addresses the documentation of a system's architecture and all of its details. software
organization produces all sorts of artifacts in addition to raw executable code.
These artifacts include (but are not limited to) Requirements, Architecture, Design,
Source code, Project plans, Tests, Prototypes, Releases.
Building Blocks of the UML: UML encompasses three kinds of building blocks
1. Things 2. Relationships 3. Diagrams
Things
Things are the basic object-oriented building blocks of the UML. There are four kinds of things in
the UML:
a). Structural things b). Behavioral things c). Grouping things d). Annotational things
Structural things: are the nouns of UML models. These are the mostly static parts of a model,
representing elements that are either conceptual or physical. There are seven kinds of structural
things.
Class: A class is a description of a set of objects that share the same attributes, operations,
relationships, and semantics. Graphically, a class is rendered as a rectangle, usually including its
name, attributes, and operations.
Collabrations:a collaboration defines an interaction and is a society of roles and other elements
that work together to provide some cooperative behavior that's bigger than the sum of all the
elements, given class might participate in several collaborations. Graphically, a collaboration is
rendered as an ellipse with dashed lines, usually including only its name,
Use Case:use case is a description of set of sequence of actions that a system performs that yields
an observable result of value to a particular actor. A use case is used to structure the behavioral
things in a model. A use case is realized by a collaboration. Graphically, a use case is rendered as an
ellipse with solid lines, usually including only its name.
Active Class: An active class is a class whose objects own one or more processes or threads and
therefore can initiate control activity. An active class is just like a class except that its objects
represent elements whose behavior is concurrent with other elements. Graphically, an active class is
rendered just like a class, but with heavy lines, usually including its name, attributes and operations.
Component: a component is a physical and replaceable part of a system that conforms to and
provides the realization of a set of interfaces. components may be the artifacts of the development
process, such as source code files. A component typically represents the physical packaging of
otherwise logical elements, such as classes, interfaces, and collaborations. Graphically, a component
is rendered as a rectangle with tabs, usually including only its name.
Node: A node is a physical element that exists at run time and represents a computational resource,
generally having at least some memory and often, processing capability. Graphically, a node is
rendered as a cube, usually including only its name.
2. Behavioral Things: Behavioral things are the dynamic parts of UML models. These are the
verbs of a model, representing behavior over time and space. There are two primary kinds of
behavioral things.
Interaction : An interaction is a behavior that comprises a set of messages exchanged among a set
of objects within a particular context to accomplish a specific purpose. The behavior of a society of
objects or of an individual operation may be specified with an interaction. Graphically, a message is
rendered as a directed line, almost always including the name of its operation.
State Machine: A state machine is a behavior that specifies the sequences of states an object or an
interaction goes through during its lifetime in response to events, together with its responses to
those events. The behavior of an individual class or a collaboration of classes may be specified with
a state machine. Graphically, a state is rendered as a rounded rectangle, usually including its name
and its substates, if any
3. Grouping things: are the organizational parts of UML models. These are the boxes into which a
model can be decomposed. In all, there is one primary kind of grouping thing, namely, packages.
Package: A package is a general-purpose mechanism for organizing elements into groups.
Structural things, behavioral things, and even other grouping things may be placed in a package.
Graphically, a package is rendered as a tabbed folder, usually including only its name and,
sometimes, its contents.
Annotational things:are the explanatory parts of UML models. These are the comments you may
apply to describe, illuminate, and remark about any element in a model. There is one primary kind
of annotational thing, called a note.
Note :A note is simply a symbol for rendering constraints and comments attached to an element or a
collection of elements. Graphically, a note is rendered as a rectangle with a dog-eared corner,
together with a textual or graphical comment.
Relationships
A relationship is a connection among things, Graphically, a relationship is rendered as a path, with
different kinds of lines used to distinguish the kinds of relationships.
There are four kinds of relationships in the UML:
Dependency
Association
Generalization
Realization
1. Dependency: A dependency is a using relationship that states that a change in specification of one
thing (for example, class Channel) may affect another thing that uses it (for example, class Filim
Clip), but not necessarily the reverse. Graphically, a dependency is rendered as a dashed directed
line, directed to the thing being depended on. Use dependencies when you want to show one thing
using another.
Example:
2. Association:an association is a structural relationship that describes a set of links, a link being a
connection among objects. association is a structural relationship that specifies that objects of one
class are connected to objects of another. Given an association connecting two classes, you can
navigate from an object of one class to an object of the other class, and vice versa. Graphically, an
association is rendered as a solid line, possibly directed, occasionally including a label, and often
containing other adornments, such as multiplicity and role names.
The multiplicity of a property is an indication of how many objects may fill the property. The most
common multiplicities are,
1 exactly one object
0..1 ( may or may not have a single object)
* (0 object or there is no upper limit to the number of objects.
Example:
Example:
Example:
Diagrams in the UML
A diagram is the graphical presentation of a set of elements, most often rendered as a connected
graph of vertices (things) and arcs (relationships).
1. Class diagram
2. Object diagram
3. Component diagram
4. Deployment diagram. 1 to 4 conceptualize the static part of system
5. Use case diagram
6. Sequence diagram
7. Collaboration diagram
8. Statechart diagram
9. Activity diagram 5 to 9 conceptualize the dynamic(behavioral) part of system
Class Diagram: A class diagram shows a set of classes, interfaces, and collaborations and their
relationships.A class diagram describes the types of objects in the system and the various kinds of
static relationships that exist among them. Class diagrams also show the properties and operations
of a class and the constraints that apply to the way objects are connected.
Object Diagram: An object diagram is a graph of instances, including objects and data values for
things found in the class diagram. A static object diagram is an instance of a class diagram; it shows
the static snapshot of the detailed state of a system at a point in time. An object diagram shows a
set of objects and their relationships.
Object diagrams commonly contain
Objects
Links
Like all other diagrams, object diagrams may contain notes and constraints.
Transition
A solid arrow represents the path between different states of an object. Label the transition with the
event that triggered it and the action that results from it. A state can have a transition that points
back to itself.
Initial State
A filled circle followed by an arrow represents the object's initial state.
Final State
An arrow pointing to a filled circle nested inside another circle represents the object's final state.
Example:
Use case diagram:Use case diagrams are usually referred to as behavior diagrams used to describe
a set of actions (use cases) that a system can perform in collaboration with one or more external
users of the system (actors). It also specifies the relationship between use case and actor. Use cases
are a technique for capturing the functional requirements of a system.
Use case diagrams commonly contain
Use cases (Functionalities)
Actors
Dependency, generalization, and association relationships
Use case: A use case is a set of scenarios (actions) tied together by a common user goal.
Actor: An actor is a role that a user plays with respect to the system. Actors carry out use cases. A
single actor may perform many use cases; conversely, a use case may have several actors
performing it.
Shows Two or more Player actors are involved in the Play Game use case. Each Player participates
in one Play Game.
Generalization: Generalization among use cases is just like generalization among classes. Here it
means that the child use case inherits the behavior and meaning of the parent use case; the child
may add to or override the behavior of its parent; and the child may be substituted any place the
parent appears (both the parent and the child may have concrete instances).
Scenario: A scenario
is a sequence of steps describing an interaction between a user and a system. So if we have a Web-
based on- line store, we might have a Buy a Product scenario that would say this:
The customer browses the catalog and adds desired items to the shopping basket. When the
customer wishes to pay, the customer describes the shipping and credit card information and
confirms the sale. The system checks the authorization on the credit card and confirms the sale both
immediately and with a follow-up email.
System boundary : The rectangle around the use cases is called the system boundary box and as
the name suggests it indicates the scope of the system - the use cases inside the rectangle represent
the functionality that you intend to implement.
Parameterizing other objects with different requests in our analogy means that the button used to
turn on the lights can later be used to turn on stereo or maybe open the garage door.
queue or log requests, and support undoable operations means that Commands Execute operation
can store state for reversing its effects in the Command itself. The Command may have an added
unExecute operation that reverses the effects of a previous call to execute.It may also support
logging changes so that they can be reapplied in case of a system crash.
Intent: Encapsulate a request in an object and allows the parameterization of clients with
different requests, saving the requests in a queue.
Participants:
Command - declares an interface for executing an operation;
ConcreteCommand - extends the Command interface, implementing the Execute method
by invoking the corresponding operations on Receiver. It defines a link between the
Receiver and the action.
Client - creates a ConcreteCommand object and sets its receiver;
Invoker - asks the command to carry out the request;
Receiver - knows how to perform the operations;