Docsity

HND Level 5 Unit 20 Advanced Programming Assignment, Papers of Programming Paradigms

Partial preview of the text

Download HND Level 5 Unit 20 Advanced Programming Assignment and more Papers Programming Paradigms in PDF only on Docsity!

UNIT 20

ADVANCED PROGRAMMING

ASSIGNMENT

Contents

  • P1 Characteristics of object-oriented paradigms
    • Class
    • Object..................................................................................................................................................
    • Encapsulation
    • Inheritance
    • Polymorphism
    • Abstraction
    • Abstract Class.....................................................................................................................................
    • Interface
  • P2 UML class diagram
  • P4 Design Pattern
    • Uses of design patterns
    • Types of design patterns
  • M1, M4, D2, D3 Selected Design Patterns
    • Factory Method Pattern
    • Decorator Pattern
  • D1 Relationship between object-oriented paradigms and design patterns
  • D4 Range of design patterns
  • References

Object Object is one of the most important notions in OOP. An object is an independent component created in a class which is made up of states and behaviors to make a specific sort of data usable. For example, in a company, the company as the whole is the class and the employees are the objects. Object can be defined as:

  • A real-world entity
  • A runtime entity
  • An instance of class
  • Both tangible and intangible item that we can visualize Real-life examples Cat – a cat can be referred as an object because it has states ( name, breed, age, size, color ) and behaviors ( eat, sleep, sit, run, meow ). Car – a car also has states ( type, color, model, manufacture date ) and behaviors ( go forward, reverse, turn left/right, accelerate ). Student – students have states ( name, age, ID, gender, weight, height, religion ) and behaviors ( eat, sleep, learn, shower, study ).

How to create objects

In the picture above, three objects for students are created and data are assigned to the parameters in the class.

Encapsulation Encapsulation is one of the fundamental concepts of OOP. It can be defined as a procedure to wrap data and methods under a single unit called class. It is a process of binding the codes and the data it controls together. Encapsulation can also be used as restriction to protect the data from being easily accessible by the code from outside. For example, in a capsule, several types of medicines are mixed together. The most significant benefit of encapsulation is data security since it prevents the unwanted access of data from outsiders. In addition, it lowers the number of human errors and make the program more understandable. In encapsulation, data and parameters from a class can be hidden from other existing classes and it can only be seen by the ones who are given access to it. Since the classes are hidden in encapsulation, sometimes it is also referred as data-hiding. To use encapsulation in the program, the user has to declare all the variables in the class a private. After that, they need to write public setter and getter methods inside the class to set and get the data from the variables. By utilizing setter and getter methods, we can either create read-only or write-only classes as required. Encapsulation also provides you with control over the data inside the objects. Let’s say we want to make the value of Age field between 1 and 30 only, we can write condition for it inside the setter method. Encapsulated class is also easy to create since most IDE provide easy ways to use setter and getter methods.

Encapsulation example

In the first picture above, private variables are created inside the class called ‘Student’. After that, setter and getter methods are used to assign condition to ID field and Age field. In the second picture, as you can see since no setter or getter method is used for Name field, data cannot be entered.

Polymorphism The word polymorphism means many shapes and is a combination of two Greek words: poly and morphs. In programming, polymorphism is one of the concepts in OOP which allow us to refine a single action is multiple ways whether by modifying how an action is performed or altering the components that are needed to perform that action. There are two types of methods in polymorphism, which are:

  • Run time polymorphism
  • Compile time polymorphism With the help of polymorphism, the developers can reuse the codes written, thereby saving time and costs. Many data types can also be stored by using only one variable and thus, allowing for easier debugging of codes. Method Overloading Method Overloading occurs when a class has many methods with the same name but distinct variables. If we only need to execute one action, having the methods with the same name improves the readability of the code. Method overloading used in compile time polymorphism. Method Overriding Method overriding occurs when the same method is declared in child class along with its parent class. To explain it simply, when the child class has the same methods with its parent class, method overriding occurs. Method overriding is used when we need to use the same features from its parent class. Method overriding is used in runtime polymorphism. Abstraction Abstraction is the procedure of obscuring execution details from the user and displaying only functionality. To explain it simply, only the necessities are presented to the users while internals details are hidden. For example, when the user sends SMS to someone, they can only see the textbox to type and send the text while the data transfer process and delivery process are hidden from the user. Therefore, abstraction allows the user to only concentrate on what the object can do rather than how it does it. The main benefits of using abstraction is that it multiple related classes can be grouped together as siblings which can reduce the complexity of the design and implementation of the program. There are two ways to use abstraction in programming, which are:
  • Abstract class
  • Interface Abstract Class An abstract class is a superclass which does not allow user to instantiate it and is used to declare or specify general properties of a program. It cannot be used to create an object and attempting to do so will result in compiler error. To create an abstract class, an abstract keyword is needed and it can contain both abstract or non-abstract methods along with constructors and static methods. Subclasses which are extended from an abstract class will have all the properties of the abstract class as well as subclass-specific properties. In an abstract class, the characteristic of the class and methods are declared. Thus, it defines the entire interface.

Example (Abstraction using polymorphism)

Output: In the example above, an abstract class called Animal is created and sell() method is created inside the class. After that, two sub classes of Animal class, Dog and Cat are created. In the main method of the program, objects are added to each class and methods are invoked. For the result, you can see that even though the same method has been called for both objects. The results are different, this process is called polymorphism. And the users cannot see how this program works and they can only see the output so it is called abstraction. Interface In OOP, interface is defined as a blueprint of a class which is used to specify the properties of the class. Interface is a fully abstract class which can have both static contents and abstract methods and are used to group the related methods with vacant bodies. With interface abstraction can be achieved along with multiple inheritance. To achieve interface method in Java, interface keyword has to be used when creating the class. Similar to abstract classes, objects or constructors cannot be created in interface classes too. In addition, the interface methods do not have a body and it is provided by implement class. Interface can be used to have security for the programs especially when you don’t want certain processes and details to be seen by the users.

Example (Interface with OOP)

Output: In the example above, a normal class named Animal is created. Unlike Java, when you want to make the Animal class an interface in Dart, you have to write another class and use ‘implements’ keyword. As shown in the pictures two classes named Dog and Cat are created. When using interface, you have to override all the methods and parameters created in the interface method or else there will be errors. If you are creating a program and want to override all the methods and variables, you can use interface to make sure in order to not miss anything.

Benefits of using UML class diagram are:

  • Regardless of the level of complexities associated with the classes and data, it aids in the creation of more accurate and detailed data models.
  • It facilitates a better and clearer grasp of the overall system and concepts associated with the process.
  • Allows a person to create a visual depiction of the general needs and requirements of a system, which can then be used to distribute any type of business-related information.
  • aids in the production of superior chart detailing for improved final results in the comprehension of the possibilities involved in the system
  • Allows people to decide what type of implantation procedures are needed in the system to achieve better results. Example The example above shows a class diagram of a part of an order system of a program. Firstly, two classes ‘Customer’ and ‘Order’ are created and the relationship between them is represented as one- to-many since a customer can have several orders but one order cannot have multiple customers. Next, two subclasses derived from Order class is created. The subclasses are ‘SpecialOrder’ and ‘NormalOrder’. Since the sub classes are inheriting the features from their super class, inheritance notation is used. In addition to inheriting all the features, the subclasses also have their own methods like deliver() and receive().

Project’s UML Class Diagram

production and representation. In addition, allows you more control over the construction process and enables you to alter an object's internal structure. Factory Method Pattern Factory Method pattern is a creational design pattern that serves as an interface for creating objects in a parent class while allowing child classes to change the type of objects created. This design pattern helps developers to understand more about how to code for the interface instead of only implementation. It also eliminates the need for client code to instantiate actual implementation classes, therefore making the code to be more resilient, less connected and extensible. Factory patterns also provides abstraction between client and implementation classes. Prototype Pattern Prototype is a design pattern that allows users to replicate existing objects without having to make the code rely on the classes. This pattern can be used when classes are created at run time and it eliminates the requirement of creating sub classes therefore reducing the amount classes that needs to be created. It also can be used when the cost of creation of an object is high or complicated therefore, concealing and the complexity of object creation. Singleton Pattern Singleton pattern is a creational design pattern that can limit the number of times a class can be instantiated and ensures that only one instance of the class exists on the Java virtual servers. The contrast between a regular class and a singleton class is that a regular class has a constructor, whereas a singleton class has a getInstance() method. To create a singleton class, developers must convert the constructor as private and add a static function that returns the object type of the singleton class. Singleton design pattern could be helpful in areas where generating a class instance is time- consuming, such as when importing a large amount of data from outside sources. The pattern also comes in handy when you need to use the same object repeatedly throughout your code. When a caching layer is required, singleton might be employed — the singleton class is able to inspect and handle the cache on each instance request. Figure 4.1 Class diagram of Singleton Design Pattern

Example Implementation There are many ways to create Singleton method in Dart, below is an example by using Eager Loading. In the picture above, a singleton class is created. After that in that class, a static, private variable called ‘instance’ is created. In flutter, instead of getInstance() method a ‘get instance’ getter is replaced. Another void method with print function is also created inside the Singleton class to see the results easily. In order to see if Singleton works, a main method is created and the method inside the Singleton method is called.

Structural

Structural design patterns describe how to implement classes and objects together to form larger structures with new functionalities that are both flexible and efficient. Inheritance is used to construct interfaces in structural class-creation patterns. The most essential characteristic of these patterns is that they make it easier to operate and develop applications by making it simple to understand entity dependencies and it is easier to develop programs with independent class libraries using these patterns. Below are some of the well-known design patterns used for structural design patterns: Bridge Pattern Bridge pattern is a structural design pattern that allows developers to divide a large class or a group of closely related classes into two different hierarchies—abstraction and implementation—that can be developed separately. This design pattern allows the implementation and the interface to be separated and allows the client to be unaware of implementation specifics. In addition, it also enhances the extensibility. Decorator Pattern Decorator pattern is a structural pattern that enables developers to apply additional behaviors to objects by enclosing them in a unique wrapper objects that keep the behaviors. This pattern provides more developer with more options since they can assign methods and functions to objects in a transparent and dynamic way without impacting other objects. Since the modifications are done by creating new classes, the object's extensibility is also increased. Proxy Pattern Proxy is a structural pattern which enables users to provide a replacement or a standby for another object. A proxy manages access to the original object, letting users to do something before or after the request reaches the original object. Security is one of the benefits of this pattern. It can prevent the repetition of objects that are large and memory consuming. As a result, the application's performance improves. By installing a local code proxy (stub) on the client system and then connecting the server via the remote code, the remote proxy assures security.

test if the pattern works, in the main method, a new dog object and cat object is created, along with new adapter object. As shown in the last pic, when the meow() method from adapter method is called, instead of showing “Meow”, “Bark” is shown instead which means the adapter is working perfectly.

Behavioral

Behavioral design patterns are used in software engineering to identify and understand about the common patterns of communication between objects. Therefore, it enhances the flexibility of the communication carried out. Below are some of the well-known design patterns used for behavioral design patterns: Chain of responsibility Pattern A behavioral design pattern called Chain of Responsibility allows developers to transmit requests across the chain of handlers. When a request is received, each handler determines whether to process it or send it on to the following handler in the chain. One of the benefits of using this pattern is that to lessen the degree of coupling, it will be requested that the transmitter and receiver be decoupled. Object is also simplified since the chain structure does not need to be known by the object. This pattern also increases the flexibility of the responsibilities assigned to the objects. Command Pattern Command pattern is a behavioral pattern which transforms a request into a stand-alone object while keeping all of its information. You can send requests as method arguments, delay or queue a request's implementation, and provide undoable operations with this transformation. The classes the can invoke operations are decouples from the object that knows how to carry out the operations. This pattern also provides a queue mechanism that enables developers to create a series of commands. Using extensions to insert new commands is made more simple and does not require the existing code to be modified. Observer Pattern Observe pattern is a behavioral pattern that allows developers to specify a subscription mechanism for numerous objects to be notified of any events that occur on the object they're observing. This pattern adheres to the loose coupling concept between objects that can communicate with one another, allowing data to be sent to other objects without having to make any changes to subject or observer classes. In this pattern, the observers can be can be inserted or withdrawn anytime. State Pattern State pattern can be categorized as a behavioral design pattern that enables an object to change its behavior in response to the changes in its internal state. It appears as if it were the object's class that has changed. This pattern reduces conditional complication by removing the need for if and switch declarations in objects with unique behavior needs for different state transitions. It's fairly simple to transform the diagram into the State design pattern's types and methods if you can define the object's state using a finite state machine diagram. Template Method Pattern The skeleton of an operation's algorithm is defined by the template pattern. It is a behavioral pattern that provides the structure or template of an algorithm for users to use and implement without having to modify the structure of the algorithm. Subclasses can use this design pattern to rebuild specific sections of an algorithm without affecting the overall structure of the algorithm.

This behavioral design pattern is one of the most straightforward to comprehend and apply. In framework development, this design pattern is often employed. This also aids in the avoidance of code duplication. Example Implementation The example above shows an order process of a store. The customers can either buy from online or buy at the store but the process of either ways will be the same. First, the customer will select items to buy and then they will have to make payment. After making payment, they can either choose to gift wrap the items or not and then the items they ordered will be delivered or given to them. For this process, first an abstract class named ‘Template’ is created which has algorithm skeleton. As shown in the picture, processOrder() is a method containing all of the processing steps. Next, two subclasses named ‘OnlineOrder’ and ‘StoreOrder’ is created, extending from the Template class so they both have same processing steps. In the main method, both subclasses are called and the output is shown. As it can be seen, eventhough both classes have the same process steps, the outputs are not the same as the methods created in the Template method are overridden and the operations are performed differently depending on the class. Figure 4.2 Class diagram of simple Template Method Design Pattern Output:

parameters, a method with a same is of the class is created and the name of the parameters are written with ‘this’ keyword in order to identify the parameter variable. Next, inside the same EmployeeData class, a method named ‘calculate’ is created in which the monthly salary of each employee will be calculated. If the employee gets full attendance that month, they will get 20000 bonus. If they are punctual everyday when coming to work, they will get 10000 bonus and depending on the number years they have been working for the company, they will get 50000 bonus for each year they have worked for. The amount of salary gotten from the calculation is then returned in order to that result in another class. After that interface class creation is done, five more subclasses named according to the type of position that exists in the company are created. These five classes inherit all parameters and methods from its parent, ‘EmployeeData’ class and all the methods and parameters are overridden. The new subclasses are created in order to calculate employee salary depending on their position at work. Next, a class named ‘Factory’ is created to apply factory method design pattern to the project. Inside this class, a new method named ‘getEmp’ is created. This method will be used to accept input from another class and check if that input matches the condition set in this method. When the position entered matches ‘Manager’, a new ‘Manager’ will be created and returned. After that the returned data will be used for other purpose in another class. The same apply to the other positions entered and the subclasses created. When someone wants to change the amount of bonus an employee get they just have to go and change at calculate() method in ‘EmployeeData’ class. And if they want to add more methods which depends on employee position, they can just add it in ‘EmployeeData’ class and initiate it from Factory method.

The picture on the right shows how the factory class is created and used in another class. The position is input into the method and the according to the input, the class related is called back and the amount of the salary will be calculated for specific employee with the calculate method. If there is another function created and wants to use it, the developer can just change the method called in that class.

UML Class Diagram

In the class diagram above for factory method design pattern, firstly, a class where the data of the employees will be kept is created and is named ‘EmployeeData’ inside the class, parameter for name of the employee, gender, NRC, email, department, position, number of years the employee has been working at the company and the salary is created. As for the method, ‘calculate’ method is created where the monthly salary of the employee will be calculated and bonus will be given accordingly. After that, another class named ‘DataAccess’ which has aggregation relationship with ‘EmployeeData’ is created and inside that class, a list where employee objects will be kept is created and the methods for getting employee data from that list, adding employee data to the list, searching of employee from that list, counting numbers of employees in each department, calculating the total amount of monthly salary the certain employee gets, amount of attendance bonus, punctuality bonus and yearly bonus will also be calculated. After that, five subclasses implementing the ‘EmployeeData’ class is created and all the parameters and methods are overridden. Then, ‘Factory’ class is created and inside this class there is ‘getEmp’ method and depending on the type of employee position added to this method and the subclass related will be used. Next, a class named ‘EmpAtt’ is created and this is where is factory class will be called from and used. Inside the class, parameters and method related to the employees are created. Since EmpAtt is a stateful widget, the build method is also created.