Wednesday, February 18, 2009

OODBMS - Object Oriented Analysis and Design(OOAD)


January-2004 [29]
1.c) State the difference between persistent and transient objects. How persistence is handled In Object Oriented (OO) database systems? [4]


A) Transient Objects are temporary in nature. Object which is permanent in nature till the end of the program or remain active until the accidental termination of the program is called as a persistent object. On the otherhand rest nature of the object type is called an transient object
2. Transient object:They can't be serialized, its value is not persistent and stored in heap
Persistent Object:They can be serialized, its value is persistent as name implies and stored in memory

3. A superclass PersistentObject encapsulates the mechanisms for an object of any class to store itself in, or retrieve itself from a database. This superclass implements operations to get an object by object identifier, store, delete and update objects and to iterate through a set of objects (write and read operations).
Each persistent class could be responsible for its own storage
For each business class that needs to be persistent, there will be an associated database brokerclass.
The broker class provides the mechanisms to materialize objects from the database and dematerialize them back to the database
The database broker object is responsible for: “materialising” objects, “dematerialising” objects,
caching objects.
Application classes are insulated from storage. Allows migration of storage sub-systems, e.g., implement on existing relational system.
Application programs unaffected by change
Objects can be cached for efficiency. The cache is a collection maintained by the database broker.
When an object is requested, the cache is searched first. If the object sought is not in the cache it is materialised by the database broker from the database
To manage transactions, we need to keep track of all changes made by a transaction, in case the transaction is aborted before it completes execution (and commits all its changes.)
Multiple caches can be used for transaction management:
new clean cache: newly created objects
new dirty cache: newly created objects that have been amended
new delete objects: newly created objects that have been deleted
old clean cache: objects retrieved from the database
old dirty cache: retrieved objects that have been ammended
old delete objects: retrieved objects that have been deleted

d) How are relationships are represented in Object Oriented (OO) data model? Discuss also the importance of inverse references in Object Oriented (OO) data model. [4]

``For data to be useful in providing information, they need to be organized so that they can be processed effectively. In data modelling we try to organize data so that:

they represent as closely as possible the real world
they are amenable to representation by computers.''
Components of a data model
Data models (Figure 2.1) have been introduced to help software developers to achieve these two potentially conflicting requirements. As stated by E.F. Codd in his 1981 Turing Award Lecture,
``A data model is a combination of at least three components:


a set of data structure types,
a collection of operators which can be applied to any instance of the data types, to retrieve, derive or modify data from any part of those structures in any combination desired,
a set of integrity rules, which define the consistent database states - these rules are general in the sense that they apply to any database using the model.''
Design advantage
A data model provides the designer and the programmer with substantial advantages: the detailed data design makes use of a few building blocks, and the manipulation of data is performed by a few operators that are the same for all data structures.
The Entity-Relationship (ER) model views the world as consisting of entities and relationships between them, where

an entity is a ``thing'' that can be distinctly identified, e.g. a chamber, a wire, a point, a track, a vertex, etc.,
a relationship is an association between entities, e.g. point belongs to track is an association between a point and a track.
Entity sets
The information about an entity is expressed by several (Attribute, Value) pairs. For example a single point could be:

( X, 0.56 )
( Y, 10.75 )
( Z, 29.14 )

where X is the attribute and 0.569 is its value, etc. An Entity Set (ESet) is a set of entities defined by the same attributes. Figure 2.2 shows an example of an ESet called Point with four entities and with attributes X, Y, Z.
The complete data model for a high energy physics experiment is large, containing many entity sets. In designing such a model it is useful to display it pictorially, particularly the entity sets and the relationships between them. Such a picture is called an Entity Relationship Diagram.

Small ER diagram
Figure 2.3 presents a small section of such an ER diagram showing the entity sets Point and Track.The ESet Point is the same as in Figure 2.2. Track has 8 attributes: the 3 components of the momentum and their errors and the rank and file coordinates (Rhit and Fhit) of the point at which the track strikes the calorimeter.
The relationship between these two ESets is expressed by the arrow joining the two entity sets: the double headed arrow shows a many-to-one relationship (many points may lie on one track), while the vertical bar shows that not all points are related to a track (some points may not lie on a track).


Representing one-to-one relationships and partiality
A one-to-one relationship is represented by a single-headed arrow. Partiality, i.e. having at least one entity in an ESet not related to another entity via the relationship, is represented by a vertical bar on the end of the arrow corresponding to the ESet in question.

Types of relationships
The cardinality of an ESet with respect to a relationship is the range of the number of entities that a single entity in the ESet can be related to. The lower bound of the range is called the minimum cardinality and the upper bound is called the maximum cardinality. These will be referred to as CardMin and CardMax respectively.

Examples of cardinalities
In ER diagrams, only 3 cases are generally of interest: 0, 1 or * (many). Example: Consider ESets Track and Cluster.

The cardinality of Track with respect to the relationship is [0,1]: CardMin is 0 because some tracks do not contribute to any cluster. CardMax is 1 because a given track may only contribute to one cluster.
The cardinality of Cluster with respect to the relationship is [0,*]: CardMin is 0 because some clusters are not associated to known tracks. CardMax is * because a cluster generally results from several tracks.
Possible cardinality values
The possible cardinalities of an ESet with respect to a relationship are [0,1], [1,1], [0,*] and [1,*]. Since ADAMO allows one-to-one and many-to-one but neither one-to-many nor many-to-many relationships only one of any two ESets may have CardMax = * with respect to the same relationship. This implies 8 possible types of relationships, which are shown in Figure 2.4.

Many-to-many relationships
By symmetry, a one-to-many relationship may always be modelled as a many-to-one relationship. Sometimes relationships can be many-to-many. An example would be if a single point could lie on more than one track, e.g. in a region where tracks cross. Such many-to-many relationships are not explicitly supported in ADAMO but must be broken down into two many-to-one relationships and an intermediate entity set.

Intermediate ESet
The intermediate ESet need not have any attributes, its only purpose is to support the two relationships.

Example
Figure 2.8 shows the ER diagram and corresponding tables of a simple many-to-many relationship. The case modelled is that of having the point with ID 5 being also the intersection point of tracks with ID 1 and 2. Note that since the point with ID 4 does not lie on any track there is no reference to it in the table TrackPt
A complete ER diagram
Shown in Figure 2.5 is the complete ER diagram of the example used in this guide. Included in the model is a calorimeter consisting of cells that are capable of making energy measurements. An algorithm may group adjacent cells with energy deposits above given thresholds into clusters. Tracks may originate from secondary vertices. More than one track may hit a given cluster but a track need not produce a cluster (it could miss the calorimeter). A track may not produce more than one cluster and a cluster need not have a track pointing to it (a neutral cluster).

Attribute of a relationship
A further algorithm associates tracks and clusters according to the calculated quantity Chisq which is a measure of how well the two match. Thus Chisq is an attribute of the relationship between Track and Cluster and not of either one individually: it is shown hanging from the relationship arrow.

Convenience considerations
The attributes Rhit and Fhit of Track are really attributes of a relationship between Track and some other ESet called perhaps Calorimeter. While this is strictly true it illustrates the point that frequently we produce a model that is convenient to use rather than one which is more logically correct.

Representing a key of an entity set
Finally, the * character on the attributes Rank and File in the ESet Cell indicate that a key is to be defined on these. ESet keys are used to identify individual entities in an ESet . The Data Definition Language (DDL) description of a data structure is a number of plain text DDL files written by the programmer. Experience suggests that it is wise to divide the model into sections known as subschemas (Section 2.6) of approximately 10 ESets in each and to have a separate DDL file for each subschema. This way, the ER diagram corresponding to a subschema will fit nicely on an A4 sheet of paper. The whole is known as the schema.

Calorimeter subschema
The subschema corresponding to the ER diagram of Section 2.5 is stored in the file calori.ddl and is shown in its entirety in Figure 3.2 to Figure 3.4. It contains the definitions of the entity sets, attributes, relationship sets, and dataflows that constitute the model. The order of definition is not important.

Definition of ESets
Each box in the ER diagram corresponds to an entry in DEFINE ESET, e.g. Cluster. The definition of Cluster's four attributes is local to Cluster. Note that, in addition to the information contained in the ER diagram, the DDL also specifies data types and ranges of validity and allows the inclusion of comments.

Definition of attributes types
Attribute types may also be defined globally in a DEFINE ATTRIBUTE section. In this example, Coord is such an attribute type. The attributes X, Y and Z in both ESets Point and Vertex are then each defined as Coord.

Definition of identifier keys
The identifier Number in the ESet Cell is defined in the KEY ... END KEY block and it corresponds to the *s on the attributes in the ER diagram. This enables any entity in Cell to be uniquely identified by the values of the two attributes Rank and File. The key Number is also used to create an index (Figure 7.9) on Rank and File which will allow the table Cell to be accessed according to the values of these two attributes.

f) What Is versioning? Why Is It Important? [4]
Information, in whatever form: documents, spreadsheets, web pages, or source code, changes over time. Tracking changes of a document over time is what a versioning system does.
In particular a versioning system records who made a specific change, it allows backing-out undesirable changes, it gives the ability to record why a specific change was made and to know what the document contents were at a specific point in time.
Versioning a content is basically archiving important document versions, to have control on changes over time.

4.
c) A car rental company maintains a vehicle database for all vehicles in Its current fleet. For all vehicles, It Includes the vehicle identification number, license number, manufacturer, model, data of purchase and color. Special data are Included for certain types of vehicles;
Trucks:
Sports car. Vans:
Off-road vehicles:
cargo capacity;
horse power, rental age requirement
number of passengers
ground clearance, drlvertraln (four or two wheel drive)
Construct an object oriented database schema definition for this database. Use Inheritance wherever appropriate. [8]
5.
b) Discuss with an example Chen-Chen methodology for object-oriented design. [9]

Chen's original method is the basis for many writings on ERD's. While the traditional aspects of entities and relationships are represented as boxes and lines (respectively), there are a number of unique attributes to his present method:
1. The cloud symbol represents aggregations of smaller ER diagrams, in the context of a logical design (as opposed to a physical design).
2. The double-box represents a weak entity, which is dependent on its parent entity. Note: Visio does not support this feature.
3. A diamond symbol represents a type of relationship.
4. Relationship adornments are added adjacent to the lines to indicate connectivity (I, M, N) and cardinality, e.g. "(0,3)".
5. The data-structure diagram (an alternate form of the ERD) uses arrows to show I:M relationships.
6. Circles represent the attributes of an entity, although Visio labels this icon as value.
7. A human figure represents a user icon.


July-2004 [32]
1.
a) Under what circumstances a relationship is its own inverse? Explain. [4]
An inverse or negative relationship is a mathematical relationship in which one variable decreases as another increases. For example, there is an inverse relationship between education and unemployment — that is, as education increases, the rate of unemployment decreases

f) Class diagrams developed using Booch's methodology can serve as the functional specification of a system. Justify whether this statement is true or false. [4]

The Booch software engineering methodology [#!booch!#] provides an object-oriented development in the analysis and design phases. The analysis phase is split into steps. The first step is to establish the requirements from the customer perspective. This analysis step generates a high-level description of the system's function and structure. The second step is a domain analysis. The domain analysis is accomplished by defining object classes; their attributes, inheritance, and methods. State diagrams for the objects are then established. The analysis phase is completed with a validation step. The analysis phase iterates between the customer's requirements step, the domain analysis step, and the validation step until consistency is reached.

Once the analysis phase is completed, the Booch software engineering methodology develops the architecture in the design phase. The design phase is iterative. A logic design is mapped to a physical design where details of execution threads, processes, performance, location, data types, data structures, visibility, and distribution are established. A prototype is created and tested. The process iterates between the logical design, physical design, prototypes, and testing.

The Booch software engineering methodology is sequential in the sense that the analysis phase is completed and then the design phase is completed. The methodology is cyclical in the sense that each phase is composed of smaller cyclical steps. There is no explicit priority setting nor a non-monotonic control mechanism. The Booch methodology concentrates on the analysis and design phase and does not consider the implementation or the testing phase in much detail.

5.b) Explain the differences between triggers and integrity constraints. [6]
A declarative integrity constraint is a statement about the database that is always true. A constraint applies to existing data in the table and any statement that manipulates the table.

A trigger does not apply to data loaded before the definition of the trigger, therefore, it does not guarantee all data in a table conforms to the rules established by an associated trigger.

A trigger can be used to enforce transitional constraints where as a declarative integrity constraint cannot be used.
A trigger is a piece of code which gets automatically executed upon occurrence of an event. It may not be meant for enforcing integrity. For example you may want to save the user info as soon as he makes an entry into a particular table. This will be achieved by means of a trigger.

An integrity constraint defines basic rules for a table's columns. It will always be enforced, for all data which was there in the table before the rule was added and to the new data which will be added to the table in future
An integrity constraint defines a business rule for a table
column which automatically takes care by Oracle internally.
Intefrity Constraints are NOT NULL,UNIQUE,CHECK ,PRIMARY
KEY,FOREIGN KEY.


A database trigger is a procedure written in PL/SQL and
Will run implicitly when data is modified or when some user
or system actions occur.Triggers are database objects which
gets stored in database and get fires when INSERT or UPDATE
statement attempts to violate the integrity rule, Oracle
must roll back the statement and return an error if trigger
exists.Database triggers are BEFOR/AFTER/{BEFORE|AFTER}
{row|statement etc.
Intigrity constraints are Proactive-- Like they take the cols into consideration before sitting on it like if U levy a PK on a col having duplicate or null values it will not obey to sit on that col

Triggers are reactive-- Triggres react only when a DML occurs. When it comes and sit on a table then its starts working and never considers what happened before it arrival

Both are used to perform business rules

January-2005 [50]

1. Briefly explain the following:
b) How do IS-A and HAS-A relationships help in developing object-oriented design? [4]
In database design and object oriented program architecture, has-a is a relationship where one object (often called the composited object) "belongs" to (is a part or member of) another object (called the composite type), and behaves according to the rules of ownership. Multiple has-a relationships will combine to form a possessive hierarchy. This is contrasted with an Is-a relationship which constitutes a different kind of hierarchy (subtyping). The decision whether the most logical relationship for an object and its subordinate is not always clearly has-a or is-a. Confusion over such decisions have necessitated the creation of these metalinguistic terms. A good example of the has-a relationship is containers in the C++ STL.
Inheritance defines a is-a relationship
Laptop is-a Computer
Circle is-a Shape
Shape is-a Object
One misuse of inheritance is confusing the has-a relationship with the is-a relationship
The has-a relationship means that one class has the second class as an attribute e.g. Circle class has-a Point instance variable, center. Point is another class.

In knowledge representation and object-oriented programming and design, is-a is a relationship where one class D is a subclass of another class B (and so B is a superclass of D).
In other words "D is a B" usually means that concept D is a specialization of concept B, and concept B is a generalization of concept D.

For instance, a "fruit" is a generalization of "apple", "orange", "mango" and many others. One can say that an apple is a fruit.

In object-oriented programming the is-a relationship arises in the context of inheritance concept. One can say that "apple" may inherit all the properties common to all fruits, such as being a fleshy container for the seed of a plant.

The is-a relationship is contrasted with the has-a relationship which constitutes a different kind of hierarchy.

When designing a model (e.g., a computer program) of the real-world relationship between an object and its subordinate a common error is confusing the relations has-a or is-a.

2.b) Declare a class for a Rational Number ADT. (A rational number is represented by P/Q where P and Q are integers). [6]

ADT: Rational Number
Concrete implementation II


typedef struct {

int ar[2] ;

}RATIONAL;


RATIONAL makerational (int x, int y) {

RATIONAL r;

r.ar[0] = x;

r.ar[1] = y;

return r;

}


RATIONAL reduce (RATIONAL r) {

int g;

g = gcd (r.numerator,r.denominator);

r.a[0] /= g;

r.a[1] /= g;

return r;

}


int numerator (RATIONAL r) {

return r.a[0];

}

int denominator (RATIONAL r) {

return r.a[1];

}

The List ADT

A list : of size N.
Special list of size 0 : an empty list
Operations:
makenull () : returns an empty list
makelist (elem) : makes a list containing a single element
printlist (list)
search(elem, list) : searches whether a key is in the list
insert (elem, list)
delete (elem, list)
findKth (list)

Array Implementation of List

typedef int ETYPE;

typedef struct {

ETYPE elements[MAXS];

int size;

} LIST;


LIST makenull () ;

LIST makeList (ETYPE) ;

void printList (LIST) ;

int IsEmpty (LIST) ;

int search (ETYPE, LIST) ;

void delete (ETYPE, LIST * );

void insert (ETYPE, LIST * )

Complex Number ADT

typedef struct {

float real;

float imag;

} COMPLEX;

COMPLEX makecomplex (float, float) ;

COMPLEX addc (COMPLEX, COMPLEX);

COMPLEX subc (COMPLEX, COMPLEX);

COMPLEX multc (COMPLEX, COMPLEX);

COMPLEX divc (COMPLEX, COMPLEX);

SET ADT

Interface functions (1):
SET makenullset () ;

int member (ETYPE, SET) ;

SET adjoin (ETYPE, SET);

SET union (SET, SET) ;

SET intersection (SET, SET);

Void printset (SET) ;


Interface functions (2):

SET makenullset () ;

int member (ETYPE, SET) ;

void adjoin(ETYPE, SET *);

void union (SET, SET, SET*);

void intersection (SET, SET, SET*);

Void printset (SET) ;

Concrete implementation of SET ADT


typedef struct {

ETYPE elem[MAX];

int size;

} SET;

Implementation 1 : sorted array

adjoin : Sorted insert

member : Binary search

delete : ?

union : merge 2 sorted arrays

intersection : ?

Concrete implementation of SET ADT


typedef struct {

ETYPE elem[MAX];

int size;

} SET;

Implementation 2 : unsorted array

keep the elements in the array unsorted.

adjoin : Insert at the end

member : Search till found or till the end

delete : Go through the array sequentially until

element is found, or reach the end.

Then left shift the array.

union , intersection ?

3. Consider the following details of a Library Management system (LMS), which is required by an academic institute to automate book/periodical issuing activities. Carry-out the jobs (a) – (b) listed below: -
- Library books and periodicals are issued o three types of members – faculty, student and staff members.
- All members have a name (string), an address (string) and an Id (integer). In addition, faculty-members have a few research interests (an array of strings) and Office-telephone number (integer); student-numbers have an academic program number (integer) and staff-members have an employee-number (integer).
- You may further assume that a faculty can issue a book for 4 months, a staff for 2 months and a student for 15 days. The Issuing period for a periodical for a faculty-member is 7 days; periodicals are not issued to staff and students.

a) Identify classes and their relationships and represent them using notations of Booch methods. [9]
HOW TO DRAW BOOCH DIAGRAMS


What is Booch?
Grady Booch's Object-Oriented Design (OOD), also known as Object-Oriented Analysis and Design(OOAD), is a precursor to the Unified Modeling (UML). The Booch method includes six types of diagrams: class, object, state transition, interaction, module, and process.
Booch's Static Diagrams
Booch's class and object diagrams differentiate this methodology (at least in notation) from similar object oriented systems.

A Booch class diagram
Booch's Class and Object Diagram Notations


Classes
Illustrate classes using a cloud shape with a dashed border.
You can find the Booch symbol libraries in SmartDraw under Software Design and Other Symbologies. Simply drag and drop shapes to the page and edit them.
Learn how to edit text on this symbol.


Objects
Draw objects using a cloud shape with a solid border.
Learn how to arrange objects on a page.
More Booch's Class and Object Diagram Notations


Class Adornments
Use adornments to provide additional information about a class. You can create an adornment notation using the basic triangle shape in SmartDraw. Place a letter inside the triangle to represent the following:
A - Abstract. An abstract class cannot be instantiated because it represents a wide variety of object classes and does not represent any one of them fully. For example, mammal could be thought of as an abstract class.
F - Friend. A friend class allows access to the nonpublic functions of other classes.
S - Static. A static class provides data.
V - Virtual. A virtual class is a shared base class, the most generalized class in a system.


Metaclass
A metaclass is a class whose instances are also classes.

Class Categories
A class category represents a cluster of similar classes. Illustrate a class category by drawing a rectangle with two compartments.


Class Templates
Draw a template using the standard class symbol attached to a box with a dashed outline. List template parameters or formal arguments in this box. When you draw a class created from a template, replace the dashed border with a solid one.
Learn how to resize grouped objects.


Class Utilities
Class utilities describe a group of non-member functions or subprograms. Illustrate a class utility with a shadowed cloud.
More Booch's Class and Object Diagram Notations


Class Visibility
Visibility markers signify who can access the information contained within a class. Public visibility allows an attribute or an operation to be viewed by any other class. Private visibility means that the attribute or the operation is only accessible by the class itself and its friends. Protected visibility makes an attribute or operation visible only to friend classes and classes that inherit it. Implementation restricts the accessibility of an attribute to the class only (not even friends have access to these attributes).
Place visibility markers next to the attribute they refer to.


Object Visibility
Draw a visibility marker on a link to signify the relationship between the connected objects. These markers can be:
G - Global
P - Parameter
F - Field
L - Local

Relationships
Indicate relationships between objects using lines and arrows. Learn how to connect two objects.

Relationship
Meaning


Aggregation (has)

Aggregation by value

Aggregation by reference

Uses

Instantiates - Compatible type

Instantiates - New type

Inherits - Compatible type

Inherits - New type

Metaclass

Undefined
Booch's Dynamic Diagrams
Use state transition and interaction diagrams to illustrate the dynamic nature of an application. Below is a table that lists what each of the dynamic Booch diagrams corresponds to in UML.
Booch (OOD) Unified Modeling Language (UML)
State transition diagram Statechart diagram

Interaction diagram Sequence diagram



Booch's Dynamic Diagram Notations

State
States represent situations during the life of an object. Draw a Booch state symbol using a rectangle with rounded corners and two compartments. Use the oval-shaped H symbol to indicate the most recently visited state.
Learn how to edit text on this object.
For other dynamic diagram notations and symbols, visit our tutorial on UML statechart and sequence diagrams.
Booch's Physical Diagrams
Draw module and process diagrams to illustrate the physical design of your application. Module diagrams correspond to UML's component diagrams and process diagrams correspond to UML's deployment diagrams.

Processor
Processors are hardware pieces that execute programs. Use devices and processors to draw process diagrams.
Learn how to resize grouped objects.

Device
Use a device notation to illustrate hardware that is not capable of executing programs.

Modules
A module is a unit of code that serves as a building block for the physical structure of a system. The specification module contains the declaration of entities and the body module contains the definition of entities. Learn how to resize grouped objects like modules in SmartDraw.

Main Module
This module is the main program from which the system is activated.

Subsystem
A subsystem refers to a collection of related modules.
Learn how to arrange objects on a page.



5.c) Describe the main strategies that can be used to create persistent objects? [6]

Working with persistent objects (Create, Update, Delete)

Working with persistent object state
To work with persistent object state, a Genome Context has to be instantiated by the client. A persistent object is represented by a Genome proxy, which is independent of the Context. Switching the Context means switching state for the Genome proxy. The proxy itself remains valid after a Context switch or even without any associated Context. However, as long as there is no Context instantiated, the proxy cannot retrieve any state of the referred object.
A Genome proxy holds the object identity values (primary key values) of the referred persistent object. The proxy implicitly looks up the current Context to set or retrieve object state. The Context maintains an identity map to ensure that each object instance state is maintained only once within the Context. The Context also performs automatic lazy loading when the object state does not exist yet. Finally, the Context tracks all updates to persistent objects and commits them to the database when the Context is committed.
Current Context, Context Stack and Context Stack Binding
As previously mentioned, the Genome proxy locates the current Context to work with persistent state in the AppDomain. Genome maintains a Context Stack for storing the current Context and all previously activated Contexts. The client can push and pop Contexts to the Context stack as needed, but only the top element of the stack is used as the current Context by Genome proxies.
Genome implements a strategy pattern to locate the Context Stack providing the current Context to the Genome proxies. By default, Genome implements a context stack binding strategy that associates the Context stack with the current thread, providing an independent Context Stack (and so a separate current Context) for each thread. For other architectural scenarios, different context stack binding strategies might be useful. For example, the Genome Extensions for Web Applications provide a strategy to bind the Context Stack to the HttpContext of the current request that provides a Context Stack for every request. The NorthwindDataBinding sample implements a simple strategy which binds the Context Stack to the AppDomain, providing a single AppDomain-wide Context Stack.
Creating and disposing a Context
The Context might hold references to scarce resources, such as database transactions, and thus should be explicitly disposed when no longer used; hence it implements the IDisposable interface.
Genome provides different factory methods for instantiating Contexts, which can configure Context behaviour for caching, locking and transactional consistency. A Context has to be pushed to the Context stack to become the current Context.
After working with a Context, it has to be popped from the Context stack to make the previous Context current again. Although not mandatory, in most cases the Context is also disposed when popped from the Context stack. If it is to be reused later on (e.g. for caching state from the database retrieved by the Context), it can be kept and pushed to the Context Stack again later.
Since the Context is generally pushed to the Context stack when instantiated and disposed when popped from the Context stack, the Context.Push method returns a context stack cleaner object that implements IDisposable to pop the Context from the Context stack and optionally also disposes the Context. In C# the using statement can be utilised to ensure a Context is popped from the stack and disposed after working with it:
using(Context.Push(LocalContext.Create()))
{
// work with Context here
}
Context creation and activation with the C# using statement and the context stack cleaner
LocalContext.Create() is one of the Genome factory methods for creating a Context. Context.Push() is a static method of Context to push a given Genome Context to the Context stack.
The code above can also be expressed explicitly:
Context ctx;
ctx = LocalContext.Create();
Context.Push(ctx);
try
{
// work with Context here
}

finally
{
Context.Pop();
ctx.Dispose();
}
Explicit context creation and disposal protected with a try/finally to ensure the Context is popped of the stack and disposed
Creating persistent objects
To create persistent objects, a factory method of the DataDomain has to be used. The factory method takes an arbitrary list of parameters to call the appropriate constructor of the class.
The previously implemented Product class specifies a constructor that takes a string for the name of the product and a decimal for the price of the product. A new product can thus be instantiated like this:
Product product;

//Create
using (Context.Push(LocalContext.Create()))
{
product = dd.New("x", 12.00m);
Context.CommitCurrent();
}
Code snippet showing how to create new persistent objects
The product instance is not written to the database until the Context is committed. Disposing a Context that has not been committed discards all recorded changes to persistent objects.
When the product is created, the constructor of the Product class is executed. Please note that the constructor of Product is only executed when it is created in the DataDomain. When product is loaded from the DataDomain with a query, the OnLoad() event of the object is called instead, if it implements the ILoadCallback interface.
Updating persistent objects
Persistent objects can be updated by simply setting the desired property values of the object proxy. When the Context is committed, the changes are written to the database. Otherwise, the changes will be discarded.
We will reuse the previously initialised Genome proxy pointing to the product instance we have created. As we have disposed the Context already, we now create a new Context to perform the update:
//Update
using (Context.Push(LocalContext.Create()))
{
p.Name = "y";
Context.CommitCurrent();
}
Code snippet showing how to update persistent objects
Note that when you set p.Name, the Genome proxy tries to look up the object state of p in the current Context. As the Context was just instantiated, the state of p has not been loaded yet and a lazy load of p occurs.
When the Context is committed, an update statement that sets the Name property of the p is sent to the database.
Deleting persistent objects
Persistent objects can be deleted using the Context.DeleteCurrent() method (same as Context.Current.Delete()). We will again reuse the Genome proxy pointing to p together with a new Context.
//Delete
using (Context.Push(LocalContext.Create()))
{
Context.DeleteCurrent(p);
Context.CommitCurrent();
}
Code snippet showing how to delete persistent objects
Running Sample_CUD()
After putting everything together, the sample looks like this:
static void Sample_CUD()
{
Product p;

//Create
using (Context.Push(LocalContext.Create()))
{
p = Helper.dd.New("x", 12.00m);
Context.CommitCurrent();
}

//Update
using (Context.Push(LocalContext.Create()))
{
p.Name = "y";
Context.CommitCurrent();
}

//Delete
using (Context.Push(LocalContext.Create()))
{
Context.DeleteCurrent(p);
Context.CommitCurrent();
}
}
Sample_CUD() of Client/Program.cs
After replacing the call to InitialiseDatabase() with Sample_CUD() in Main(), the Console shows the following output:

Console output of Client running Sample_CUD()
Note that the product has to be loaded up again for each new Context.
Let us modify the sample to use a single Context for all operations that is only committed in the end:
static void Sample_CUD_SingleContext()
{
Product p;

using(Context.Push(LocalContext.Create()))
{

//Create
p = Helper.dd.New("x", 12.00m);

//Update
p.Name = "y";

//Delete
Context.DeleteCurrent(p);

Context.CommitCurrent();
}
}
Sample_CUD_SingleContext() of Client/Program.cs
Because Genome tries to optimise updates sent by the Context to the database, running Sample_CUD_SingleContext() from Main() yields the following output on the Console:

Console output of Client running Sample_CUD_SingleContext()
The “Genome basics” section, covered in Step1, ends here.


d) What is check pointing? Why is it needed? [4]
Checkpointing modified buffers is a critical aspect of buffer management because it reduces crash recovery times.
scenario: if a batch program reads an input file and updates/inserts/deletes from database into db2 tables, if it abends before the end of the job, is it possible to tell how many records were processed? do we need to start the job from beginning or are there any transactions happened with any of the records?
Assume that commit logic was not coded for large batch jobs that process millions of records.if an abend occurs all database updates will be rolled back and the job can be resubmitted from the beginning.
if an abend occurs near the end of the process, the rollback of all the updates is performed.also, db2 will maintain a large number of locks for a long period of time, reducing concurrency in the system.in fact, the program may abend if it tries to acquire more than the installation-defined maximum number of locks.
Program without commit logic causes excessive memory consumption. So this will not provide workload balancing.
These applications will cause the coupling facility to be over commited with large number of locks and huge storage requirements. To avoid this difficulties, commit-restart logic is recommended for all the batch programs performing transactions with database. This invloves setting up batch-restart control table (checkpoint_restart) to be set up to store the last input record processed and other control information.
Checkpoint/restart logic: to allow the interrupted program to be restarted from the last unit of recovery (commit) or at a point other than the beginning of the program we should have a checkpoint/restart logic. Basically, we need: •a place to store the details (checkpoint-commit record) pertaining to the current execution of the program, like various counts (number of inserts/deletes/updates/selects), number of records processed, processing dates, and other details which are needed in the program after a restart. •a reliable file re-positioning logic with minimal changes to the existing procjcl. •flexibility, to modify the commit frequency without changing the program code. Where we can store this checkpoint-commit record? we can store the checkpoint-commit record, commit-frequency and other relevant information in a db2 table.
Most conventional database systems (including Oracle) follow the no-force-at-commit policy for data blocks [Haerder83] because of its significant performance benefits.The use of this policy implies that a page modified inmemory may need recovery if there is a system crash. A database checkpoint is critical for ensuring quick crash recovery when the no-force-at-commit policy is employed since it limits the amount of redo log that needs to be scanned and applied during recovery.
As the amount of memory available to a database increases, it is possible to have database buffer caches as large as several million buffers. A large buffer cache imposes two requirements on checkpointing. First, it requires that the algorithms be scalable with the size of the buffer cache. Second, it requires that the database checkpoint advance frequently to limit recovery time, since
infrequent checkpoints and large buffer caches can exacerbate crash-recovery times significantly.

Oracle supports a shared-disk architecture; the sharedmemory and group of Oracle processes that run on each node in a multi-node shared disk cluster are collectively known as an instance of Oracle

For the purpose of this discussion, the log may be thought of as an ever-growing file containing redo records generated by an instance. An RBA (redo byte address) indicates a position in the redo log. Oracle uses a set of a dedicated processes (called the database writers or DBWRs) for writing data blocks to disk. A dedicated process (called the checkpoint process or CKP7) records checkpoint information to the Control File which represents stable storage for maintaining bookkeeping information (such as checkpoint progress) for an Oracle database

January-2006 [36]
1. a) Compare object oriented design with procedure-oriented design. [4]
When you are procedure oriented you are concerned about the steps to take to achive some results or a given goal, and how to organize them into logical operations.

When you are object oriented you are concerned about what kind of objects you need and how they should interact in order to reach your goal. In object-oriented design each object comes with a set of methods that can be applied to it to perform some operations (with or without involving or referring to other objects). These are analogous to procedures in procedure-oriented (or structural) design, except they now have something to do with the object they apply on.

Programmers often consider object-oriented design better than procedure-oriented design, although when it comes to the hard work you need both anyway.
Procedure Oriented Programming
1.Prime focus is on functions and procedures that operate on data
2.Large programs are divided into smaller program units called functions
3.Data and the functions that act upo it are treated as separate entities.
4.Data move freely around the systems from one function to another.
5.Program design follows “Top Down Approach”.
--------------------------------------...
Object Oriented Programming
1.Here more emphasis is laid on the data that is being operated and not the functions or procedures
2.Programs are divided into what are called objects.
3.Both data and functions are treated together as an integral entity.
4.Data is hidden and cannot be accessed by external functions.
5.Program design follows “Bottom UP Approach”.
c) What is meant by separation of interface and implementation in object-oriented design? [4]
Any implementation change should not affect user interface. To ease design process: Separation of Design definition, Implementation, Usage through data encapsulation.
Separating implementation from interface allows the use of generic algorithms to process different implementations of an object through a common interface thereby reducing code duplication and development effort. On a larger scale, it permits evolution of the OAPI with minimal impact on the clients of the library- in most cases, only a relink will be necessary to incorporate new features and enhancements to the OAPI in client software.
For example, current OPUS software uses the file system (specifically, file names) to store and communicate run-time state information for processes and data in the pipeline. Using the file system greatly simplifies interprocess communication and automatically leverages the robust, fault tolerant nature and near universal compatibility of NFS
d) Distinguish between coupling and cohesion. Which is encouraged by object-oriented technology? [4]
Cohesion of a single module/component is the degree to which its responsibilities form a meaningful unit; higher cohesion is better. 'Cohesion is inversely proportional to the number of responsibilities a module/component has.' Coupling between modules/components is their degree of mutual interdependence; lower coupling is better.
size: number of connections between routines
intimacy: the directness of the connection between routines
visibility: the prominence of the connection between routines
flexibility: the ease of changing the connections between routines
A first-order principle of software architecture is to increase cohesion and reduce coupling.
2. a) Define inheritance relationship, composition relationship and association relationship in object-oriented technology. Also define and discuss their role in system development. [6]
An association relationship is a structural relationship between two model elements that shows that objects of one classifier (actor, use case, class, interface, node, or component) connect and can navigate to objects of another classifier. Even in bidirectional relationships, an association connects two classifiers, the primary (supplier) and secondary (client),
Inheritance enables one entity type to be derived from another entity type in the Entity Data Model (EDM). For example, Employee and Customer types can both inherit from the Contact type. In this case, Contact is called the base type. Employee and Customer are called derived types.
An inheritance relationship is represented on the design surface as a line that connects the base type and the derived type. The connector has a hollow arrow at the end that points to the base type.
class Fruit {

//...
}

class Apple extends Fruit {

//...
}

In this simple example, class Apple is related to class Fruit by inheritance, because Apple extends Fruit. In this example, Fruit is the superclass and Apple is the subclass.
I won't be talking about multiple inheritance of interfaces through interface extension. That topic I'll save for next month's Design Techniques article, which will be focused on designing with interfaces.
Here's a UML diagram showing the inheritance relationship between Apple and Fruit:

Figure 1. The inheritance relationship
About composition By composition, I simply mean using instance variables that are references to other objects. For example:
class Fruit {

//...
}

class Apple {

private Fruit fruit = new Fruit();
//...
}

In the example above, class Apple is related to class Fruit by composition, because Apple has an instance variable that holds a reference to a Fruit object. In this example, Apple is what I will call the front-end class and Fruit is what I will call the back-end class. In a composition relationship, the front-end class holds a reference in one of its instance variables to a back-end class.
The UML diagram showing the composition relationship has a darkened diamond, as in:

Figure 2. The composition relationship
Dynamic binding, polymorphism, and change
When you establish an inheritance relationship between two classes, you get to take advantage of dynamic binding and polymorphism. Dynamic binding means the JVM will decide at runtime which method implementation to invoke based on the class of the object. Polymorphism means you can use a variable of a superclass type to hold a reference to an object whose class is the superclass or any of its subclasses.
One of the prime benefits of dynamic binding and polymorphism is that they can help make code easier to change. If you have a fragment of code that uses a variable of a superclass type, such as Fruit, you could later create a brand new subclass, such as Banana, and the old code fragment will work without change with instances of the new subclass. If Banana overrides any of Fruit's methods that are invoked by the code fragment, dynamic binding will ensure that Banana's implementation of those methods gets executed. This will be true even though class Banana didn't exist when the code fragment was written and compiled.
Thus, inheritance helps make code easier to change if the needed change involves adding a new subclass. This, however, is not the only kind of change you may need to make.
Changing the superclass interface
In an inheritance relationship, superclasses are often said to be "fragile," because one little change to a superclass can ripple out and require changes in many other places in the application's code. To be more specific, what is actually fragile about a superclass is its interface. If the superclass is well-designed, with a clean separation of interface and implementation in the object-oriented style, any changes to the superclass's implementation shouldn't ripple at all. Changes to the superclass's interface, however, can ripple out and break any code that uses the superclass or any of its subclasses. What's more, a change in the superclass interface can break the code that defines any of its subclasses.
For example, if you change the return type of a public method in class Fruit (a part of Fruit's interface), you can break the code that invokes that method on any reference of type Fruit or any subclass of Fruit. In addition, you break the code that defines any subclass of Fruit that overrides the method. Such subclasses won't compile until you go and change the return value of the overridden method to match the changed method in superclass Fruit.
Inheritance is also sometimes said to provide "weak encapsulation," because if you have code that directly uses a subclass, such as Apple, that code can be broken by changes to a superclass, such as Fruit. One of the ways to look at inheritance is that it allows subclass code to reuse superclass code. For example, if Apple doesn't override a method defined in its superclass Fruit, Apple is in a sense reusing Fruit's implementation of the method. But Apple only "weakly encapsulates" the Fruit code it is reusing, because changes to Fruit's interface can break code that directly uses Apple.
The composition alternative
Given that the inheritance relationship makes it hard to change the interface of a superclass, it is worth looking at an alternative approach provided by composition. It turns out that when your goal is code reuse, composition provides an approach that yields easier-to-change code.
Code reuse via inheritance For an illustration of how inheritance compares to composition in the code reuse department, consider this very simple example:
class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {

System.out.println("Peeling is appealing.");
return 1;
}
}

class Apple extends Fruit {
}

class Example1 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}

When you run the Example1 application, it will print out "Peeling is appealing.", because Apple inherits (reuses) Fruit's implementation of peel(). If at some point in the future, however, you wish to change the return value of peel() to type Peel, you will break the code for Example1. Your change to Fruit breaks Example1's code even though Example1 uses Apple directly and never explicitly mentions Fruit.
Here's what that would look like:
class Peel {

private int peelCount;

public Peel(int peelCount) {
this.peelCount = peelCount;
}

public int getPeelCount() {

return peelCount;
}
//...
}

class Fruit {

// Return a Peel object that
// results from the peeling activity.
public Peel peel() {

System.out.println("Peeling is appealing.");
return new Peel(1);
}
}

// Apple still compiles and works fine
class Apple extends Fruit {
}

// This old implementation of Example1
// is broken and won't compile.
class Example1 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}

Code reuse via composition Composition provides an alternative way for Apple to reuse Fruit's implementation of peel(). Instead of extending Fruit, Apple can hold a reference to a Fruit instance and define its own peel() method that simply invokes peel() on the Fruit. Here's the code:
class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {

System.out.println("Peeling is appealing.");
return 1;
}
}

class Apple {

private Fruit fruit = new Fruit();

public int peel() {
return fruit.peel();
}
}

class Example2 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}

In the composition approach, the subclass becomes the "front-end class," and the superclass becomes the "back-end class." With inheritance, a subclass automatically inherits an implemenation of any non-private superclass method that it doesn't override. With composition, by contrast, the front-end class must explicitly invoke a corresponding method in the back-end class from its own implementation of the method. This explicit call is sometimes called "forwarding" or "delegating" the method invocation to the back-end object.
The composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn't break any code that relies only on the front-end class. For example, changing the return type of Fruit's peel() method from the previous example doesn't force a change in Apple's interface and therefore needn't break Example2's code.
Here's how the changed code would look:
class Peel {

private int peelCount;

public Peel(int peelCount) {
this.peelCount = peelCount;
}

public int getPeelCount() {

return peelCount;
}
//...
}

class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public Peel peel() {

System.out.println("Peeling is appealing.");
return new Peel(1);
}
}

// Apple must be changed to accomodate
// the change to Fruit
class Apple {

private Fruit fruit = new Fruit();

public int peel() {

Peel peel = fruit.peel();
return peel.getPeelCount();
}
}

// This old implementation of Example2
// still works fine.
class Example1 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}

This example illustrates that the ripple effect caused by changing a back-end class stops (or at least can stop) at the front-end class. Although Apple's peel() method had to be updated to accommodate the change to Fruit, Example2 required no changes.
Comparing composition and inheritance
So how exactly do composition and inheritance compare? Here are several points of comparison:
• It is easier to change the interface of a back-end class (composition) than a superclass (inheritance). As the previous example illustrated, a change to the interface of a back-end class necessitates a change to the front-end class implementation, but not necessarily the front-end interface. Code that depends only on the front-end interface still works, so long as the front-end interface remains the same. By contrast, a change to a superclass's interface can not only ripple down the inheritance hierarchy to subclasses, but can also ripple out to code that uses just the subclass's interface.
• It is easier to change the interface of a front-end class (composition) than a subclass (inheritance). Just as superclasses can be fragile, subclasses can be rigid. You can't just change a subclass's interface without making sure the subclass's new interface is compatible with that of its supertypes. For example, you can't add to a subclass a method with the same signature but a different return type as a method inherited from a superclass. Composition, on the other hand, allows you to change the interface of a front-end class without affecting back-end classes.
• Composition allows you to delay the creation of back-end objects until (and unless) they are needed, as well as changing the back-end objects dynamically throughout the lifetime of the front-end object. With inheritance, you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass.
• It is easier to add new subclasses (inheritance) than it is to add new front-end classes (composition), because inheritance comes with polymorphism. If you have a bit of code that relies only on a superclass interface, that code can work with a new subclass without change. This is not true of composition, unless you use composition with interfaces. Used together, composition and interfaces make a very powerful design tool. I'll talk about this approach in next month's Design Techniques article.
• The explicit method-invocation forwarding (or delegation) approach of composition will often have a performance cost as compared to inheritance's single invocation of an inherited superclass method implementation. I say "often" here because the performance really depends on many factors, including how the JVM optimizes the program as it executes it.
• With both composition and inheritance, changing the implementation (not the interface) of any class is easy. The ripple effect of implementation changes remain inside the same class.
Choosing between composition and inheritance
So how do all these comparisons between composition and inheritance help you in your designs? Here are a few guidelines that reflect how I tend to select between composition and inheritance.
Make sure inheritance models the is-a relationship My main guiding philosophy is that inheritance should be used only when a subclass is-a superclass. In the example above, an Apple likely is-a Fruit, so I would be inclined to use inheritance.
An important question to ask yourself when you think you have an is-a relationship is whether that is-a relationship will be constant throughout the lifetime of the application and, with luck, the lifecycle of the code. For example, you might think that an Employee is-a Person, when really Employee represents a role that a Person plays part of the time. What if the person becomes unemployed? What if the person is both an Employee and a Supervisor? Such impermanent is-a relationships should usually be modelled with composition.
Don't use inheritance just to get code reuse If all you really want is to reuse code and there is no is-a relationship in sight, use composition.
Don't use inheritance just to get at polymorphism If all you really want is polymorphism, but there is no natural is-a relationship, use composition with interfaces.

6.a) What is object serialization? How is the concept linked to object-persistence? How does a persistent programming language help in object-oriented databases? [6]
Serialization is a way of flattening, pickling, sizzling, serializing, or freeze-drying Objects so that they can be stored on disk, and later read back and reconstituted, with all the links between Objects intact Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time .
When you serialize an object, you create a string representation of it. Anything that can be serialized can be unserialized. So, by serializing an object and storing the result somewhere (a file, database, memory, etc) you can later access the string and unserialize it to recreate the object.
Persistent programming languages – extend object-oriented programming language to deal with databases by adding concepts such as persistence and collections. Persistent Programming languages allow objects to be created and stored in a database, and used directly from a programming
July-2006 [18]

1.c) While using object oriented analysis multiple inheritance in type hierarchy occurs when a certain subtype T is a subtype of one or more than one types and hence inherits the function of one or more than one super type. State whether the sentence is true or false. Justify your answer. [4]
Multiple inheritance in a type hierarchy occurs when a certain subtype T is a subtype of two (or more) types and hence inherits the functions (attributes and methods) of both supertypes.
multiple inheritance, which allows a subtype to have multiplesupertypes
For example, we may create a subtype ENGINEERING_MANAGER that is a subtype of both MANAGER and ENGINEER. This leads to the creation of a type lattice rather than a type hierarchy. Consider the following type definitions
type Person abstract supertypes: Object
operations: String social_security (P: Person) String name (P: Person)
end type
type Employee supertypes: Person
operations: Department dept (E: Employee) Money salary (E: Employee)
end type
In this example, type Employee is declared to be a subtype of type Person.In the Core Object Model this implies that

1. all instances of type Employee are also instances of type Person,and so an Employee object can be used wherever a Person object is expected.
2. Employee inherits the name and social_security operations from Person.
Furthermore, Person is declared to be an abstract type and so it cannothave any direct instances.
9 Substitutability means being able to substitutean object of some type S when an object of type T is expected, where Tis a supertype of S, while guaranteeing that that the substituted objectwill support the same operations as specified by the supertype T.
10 Whether Ops(S) is a superset of Ops(T) or thetwo are disjoint sets is an implementation issue and does not affect theCore semantics.
g) What is persistent programming language? How do they make object persistent? [4]
Persistent data: data that continue to exist even after the program that created it has terminated.
A persistent programming language is a programming language extended with constructs to handle persistent data. It distinguishes with embedded SQL in at least two ways:
In a persistent program language, query language is fully integrated with the host language and both share the same type system. Any format changes required in databases are carried out transparently.
Comparison with Embedded SQL where (1) host and DML have different type systems, code conversion operates outside of OO type system, and hence has a higher chance of having undetected errors; (2) format conversion takes a substantial amount of code.
Using Embedded SQL, a programmer is responsible for writing explicit code to fetch data into memory or store data back to the database.
In a persistent program language, a programmer can manipulate persistent data without having to write such code explicitly.
Drawbacks: (1) Powerful but easy to make programming errors that damage the database; (2) harder to do automatic high-level optimization; and (3) do not support declarative querying well.
Several approaches have been proposed to make the objects persistent.
persistence by class. Declare class to be persistent: all objects of the class are then persistent objects. Simple, not flexible since it is often useful to have both transient and persistent objects in a single class. In many OODB systems, declaring a class to be persistent is interpreted as ``persistable'' -- objects in the class potentially can be made persistent.
persistence by creation. Introduce new syntax to create persistent objects.
persistence by marking. Mark an object persistent after it is created (and before the program terminates).
persistence by reference. One or more objects are explicitly declared as (root) persistent objects. All other objects are persistent iff they are referred, directly or indirectly, from a root persistent object. It is easy to make the entire data structure persistent by merely declaring the root of the structure as persistent, but is expensive to follow the chains in detection for a database system.
2.b) What is the importance of checkpoints in the database management system? How checkpoints are used in the system log file of database management system? [4]

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.