appendix
appendix
design principles are similar to the design patterns implementing the methods which our class
doesn't nced.
concept. (b) Deal with bugs.
The only ditterence between the Design Principle (c) Implement changes without confusing co
and Deslgn Pattern is that the Design Principles dependencies.
are more generalized and abstract where as the (ii) Liskov Substitution Principle
(LSP):
desien pattern contains much more practical LSP is another design principle that stands for
advice and concrete. The design patterns are Liskov Substitution Principle. The LSP states that
related to the entie class problems, not just the derived class should be able to substitute the
generalized coding practices. base classes without changing our code.
Desiga Principles in Java The LSP is closely related to the SRP and ISP,
There are some of the most important Design So, violation of either SRP or ISP can bea
Principles which are as follows: violation (or become) of the LSP.
) SOLID Principles: The reason for violation in LSP because ifa cass
) SRP performs more than one function, subclasses
() LSP extending it are less likely to implement those
(ü) ISP two or more functionalities meaningfully.
(iv) Open'Closed Principle (iüi) Iaterace Segregation Priaciple (1SP:
(v) DIP ISP is another design principk that stands for
() Other Principles: Interface Segregation Principle. This principke
) DRY Principles states that the client should never be restrictcd to
() KISS Principle dependent on the interfaces that are not using in
(üi) Composition Over Inheritance Principle their entirety.
the
Let's understand all the principles one by one: This means that the interfae shoud have
() sOLID Principles: minimal set of methds rquird to ensure
functionality and be limited to ni e
Single Responsibility Principle (SRP):
SRP is design principle that stands for the Single functicnality.
Kesponsibility Principle. The SRP principle say s For example:
N
two intertae, we dni
that in one class, there should never be If we create a Burger
aus
implement the addChees) methd
functionalities. only one cheese isn't available for every Burger r
Te class should only have one and n iu N
reason to be changed. When there is nore
than Let's assume that al!burS
burer interta nte
one reasOn have sauce and detine that
Ie responsibility, there is more than
tollow ing na
to change that class at the same pont.
DRAION PATTERNS(B Teçh, VBEM. CAË NU)
Now, lets implement the Burger interface in doslyn prlnelple that gomgs In
wlalon that the
Vegtarian Buryer and Choese lurger classe. solid prlnelplew. Thls prlnciple
be closct
public clas Vegctarian Burger implements Burger methods And objocts or classos Ahould
modlflcatlon,
lor modifieatlon but open for
that wo
public void addTomatoAndCabbagc) In slmple words, thls prinelple say#
System.out.println("Adding Tomato and Cabbage whould have to Imploment our modules and
vegiables"% clasNos wth the polble uture updato in mind.
By doing that, our modules and élassos wll havo
a)verride
agenerle doslgn, and In ordor to oxtend tholr
public void addSaucc() !
bohavior, we would not neod to change tho clas
System.out.printin("Adding vauce in vcgetarian
itself.
Burger");
Wo can create now fields or nethods but in such
aOverride Away that we don't noed to nodiy the old code,
public void bake() { delete alroady croatod lelds, and rewrite the
System.out.println("Baking t vegctarian lBurger"); created mnethods.
The Open/Close principle is mainly used to provent
regrossion and ensure backward conpatibilty.
public class Chcescl3urger implemcntsBurger { () Dependency Inverslon Princlplo (DIP):
public void addCheese() { Another most Inportant design principle is DIP,
System.out.printin("Adding cheese in Burger"); i.o, Depondency Inversion Principle. This principle
states that the low and high lovels are decoupled
Override 8o that the changes in low-level modules dont
public void addSaucc() {
System.out.printIn("Adding saucc in Checse
require rework of high-level modules.
The high-levcl and low-lovel modules should not
Burger");
be dependent on cach other. They slhoud be
@Override dependent on the absraction, such as interlaces.
public void bake() { The Dependency lnvcrsion Principle also stales
System.out.printIn("Baking the Cheesc Burger"): that the dotails should be dependent on the
abstraction, not abstraction should be dejendent
on thedetails.
The VagitarianlBurger has Cabbage und T'omato, (I1) Other Principles:
whereas the CheesclBurger has checsc but nceds (U) Don'tRepeat Yoursclf Principle (DRY}
to be bakod and saucc that is defined in the interfacc. The DRY Iinciple stands for the Don't Repeat
If the adJChcese() and addlomatoandCabbage() Yoursclf Principle. It is one of the commn
methods were locatcd in the Burger interface,
principles or all programning languagts.
A-3
BD
DESIGN PATTERNS (B.Tech. V
within a system, cach piccc of SEM. CSE-NU)
DRY principle say Violations
as
of the DRY
principles arc refcrred to
logic should have single unambiguous WET solutions. WET is an
reprcscntation. following things: abbrcviation for thc
Let'stake an
examplc of the DRY principle Write cvcrything twicc
public class Animal We enjoy typing
public void catFood) { Write every time
System.out.printIn("Eat Food"): Waste everyone's twicc.
These violations are not always bad
becausc
repetitions are sometimes advisable to makc code
less inter-depcndent, more readable,
nublicclass Dog extends Animal inherently
dissimilar classes, etc.
public void woof() { (ü) Keep It Simple and Stupid Principle (KISS):
Svstem.out.println("Dog Woof! "):
Kiss Principle is another designing principle that
stands for Keep It Simple and Stupid Principle.
This principle is just a reminder to keep our code
public class Cat extends Animal readable and simple for humans. If several use
public void meow(){ cases are handled by the method, we necd to split
System.out.println("Cat Meow!"); them into smaller functions.
The KISS principle states that for most cascs, the
stack call should not severely affect our program's
Both Dog and Cat speak differently, but they perforinance until the efficiency is not extremely
need to cat food. The common functionality in important.
both of them is Eating food so, we can put this On the other hand, the lengthy and unreadable
common functionality into the parent class, i.e., methods will be very difficult for human
Animals, and then we can extend that parent class programmers to maintain and find bugs.
in the child class, i.e., Dog and Cat. The violation of the DRY principle can be done
Now, each class can focus on its own unique by ourselves because if we have a method that
logic, so there is no need to implement the same performs more than one task, we cannot call that
functionality in both classes. method to perform one of them. So, we will
Dog obj l = new Dog): create another method for that.
obj l .catFood); (ii) Composition Over Inberitance Principle:
Principle is
objl.woof(): . The Composition Over Inheritance
This
Cat obj2 = new Cat(); another important design principle in Java.
and
obj2.catFood0; principle helps us to implement flexible
maintainable code in Java.
obj2.meow(): The principle states that
we should havc to
Atter compile and run the above code, we will extending the
sce the following output: implement interfaces rather than
inheritance when
Output: classes. We implement the
all the functionalities.
Eat food The class need to implement substitute for our
used as a
Cat Meow! The child class can be
way, we use Composition
Eat food parent class. In the same
implement some specilic
Dog Woof! when the class nceds to
functionalities.
Violation of the DRY Principle VBD
DESIGN PATTERNS
A-4
Step 4:
Use the
Step 2: Studentontroller methods to
Create View. demonstrate MVC design pattern usage.
StudentView.java
public class StudentView {
MVCPatternDemojava
public claNs MVCPatterndemo {
public statie void main(Stringll args) {
public void printStudentDetails(String
studentName, String studcntRollNo){ I/teteln student rocord based on his roll no
System.out.println("Student: "); trom the database
A-7
D
Sudent model retrivcStudentl'rom DESIGN PATTERNS (B.Tech. V
(iü) SEM. CSENU)
Data Aceess ()bject
Databasc(): Data Acccss Objcct Conerete Clas:
ICreate avicw : to wrile student details on above interface. ThisConcrcte
class is
Class implemcnts
consolc data from a data source responsible to get
which can be datahas
StudentVicw vicw = ncw StudcntVicw(): xml or any other storagc
S1udentController controller = ncw Student (iti) Modcl Objcct or Va[ue mechanism.
Objeet:
Controller(model, vicw); Model Objcct or Value Objcct is simpk POO
controller.updateVicw(); containing ge/sct methods to store data retricved
using DAO class.
l/update model data Implementation of DAO Pattern:
controller.sctStudentName("John"); We are going to create a Student objcct acting as
controller.updateView(); a Model or Value Object. StudentDao is Data
Acccss Objcct Interface. StudentDaolmpl is
private static Student retrivcStudentFrom concrete class implementing Data Acces Object
Databasc(0{ Iterfacc. DaoPatternDemo, our demo class, wil1
Student student = new Student(); use StudentDao to demonstrate the use of Data
Access Object pattem.
student.setName("Robert"); ccntertacoN
@Overridc
Step 2:
Crcate Data Access Objcct Interface.
public void updateStudent(Student student) {
students.gct(student.getRolINo()).setName
StudcntDao.java (studcnt.get Namc():
import java.util.List; System.out.printin("Student: Roll No" + student
public interface StudentDao { -getRollNo() +", updated in the database"):
public List<Student> getAlIStudents():
public Student getStudent(int rollNo);
public void updateStudent(Student student); Step 4:
public void deleteStudent(Student student); Use the StudentDao to demonstrate Data Acccss
Object patern usage.
Step 3: DaoPatternDemo.java
Create concrete class implementing above interface. public class DaoPattern Demo{
StudentDaolmpl.java public static void main(String[l args) {
import java.util.ArrayList; StudentDao student Dao = new Student
import java.util.List; Daolmpl():
public class StudentDaolmpl implements llprint allstudents
StudentDao { for (Student student : studentDao.get
I/Mist is working as a database AllStudents())
List<Student> students; System.out.printin("Student: (RollNo :"+
public StudentDaolmpl(){ student.getRollNo()+ ", Name: " +
students = new ArrayList<Student>(); student.getName() + " ]"):
Student student = new Student("Robert",0);
Student student2 = new Student("John", 1); llupdate student
students.add(student l ); Student student =studentDao.getAlIStudcnts()
students.add(student2); -ge(0);
student.setName("Michacl"):
@Override
public voiddeleteStudent(Student student) {
studentDao.updateStudent(student):
lget the student
students.remove(student.getRollNo()); student Dao.getStudent(0);:
System.out.println("Student: Roll No " System.out.printin("Student: [RollNo: "+
student.getRollNo() +", deleted from database"); student.getRollNo)+", Name:
M+ student.getName() +"T}
lIretrive list of students from the database
@Override
VBD
A-9
DESIGN PATTERNS (B.Tech. V
SEM. CSE-NU)
Step5:
Verify the output.
TransferObjcctPatternDemo,
acting as a'client here
our demo class, is
Robert 1 and will use
StudentBO
Student: [RollNo : 0, Name: and Student to
demonstrate Transfer Object
John ]
Student: [RollNo : 1, Name : Design Pattern.
database
Student: RollNo 0, updated in the StudentBO
Student: [RollNo :0, Name : Michael ]
Uses
TransferPatternDemo
TRANSFER OBJECT DESIGNTPATTERN +getAlIStudents(): List
+updateStudentl() : void +main() :void
+deleteStudent(): void
os Write in detail about Transfer Object Design +addStudent(): void
Pattern.
Pattern:
Ans. Transfer Object Design
uses
Step 2: TransferObjcaPanernDemo,zua
Create Business Object. public class TransferObjoctPxeIDen
StudentB0.java putlic static void main(Sring] rgs)
import java.util.ArrayList, StudentB0 studctßusincss(io =T
import java.util.List; SzudertR0:
public class StudentBO {
IMist is working as a database print al students
List<StudentV0> students; for (Studcn:\O studenn :StudenRsnS
public StudentBO(){
students = new ArrayList<StudentVO>(0: Svstem uLprintn(Szudent RolNo
StudentVO studentl=new Student VO studentgRollNa0+Nne:
("Robert".0); + studentgetNme(+
StudentVO student2 = new Student VO
("John",1 ); Iupdate stadet
students.add(studentl); StudentVOstadet = sodoBshe
students.add(student2); Ooject getAIStodeta)
student setName("Michaci"
public void deleteStudent(StudentVO student) { studentBusinessObioctupdne
students.remove(student-getRollNo0); Sodcandortt
System.out.printn("Student: Roll No " + I/get the student
student.getRolINo() +", stadent = stadentBasinessObjecg
dçleted from database"): Sodc(
System.ouLprintin("Stodent RaNo:"+
lIretrive ist of students from the database stodent.geRoNo - " Namc:
public List<StudentVO> getAllStudents() { + stadertgNno)- n
return students;
Step 3:
Use the StudentBO to demonstrate Transfer
Object Design Pattern.