Chapter 3: From Procedural to Object-Oriented (OO) PDF

Document Details

SecureLesNabis775

Uploaded by SecureLesNabis775

Badji Mokhtar University - Annaba

2024

Dr. Sarra Namane

Tags

object-oriented programming procedural programming programming paradigms computer science

Summary

This document is a chapter on object-oriented and procedural programming. It details a lesson on core programming concepts from introductory computer science, possibly for a second-year engineering class at Badji Mokhtar University, Annaba.

Full Transcript

Chapter 3: From Procedural to Object- Oriented (OO) Dr. Sarra Namane Department of Computer Science Badji Mokhtar University, Annaba Class: 2nd Year Engineering Year: 2024/2025 Introduction Programming paradigms represent fundam...

Chapter 3: From Procedural to Object- Oriented (OO) Dr. Sarra Namane Department of Computer Science Badji Mokhtar University, Annaba Class: 2nd Year Engineering Year: 2024/2025 Introduction Programming paradigms represent fundamental and coherent approaches to the design and structuring of computer programs. Each paradigm defines a set of principles, styles, and concepts that guide how developers write, organize, and understand source code. 3 What is a programming paradigm? A programming paradigm is a model or a consistent approach that defines how computer programs are designed, structured, and executed. 4 What is procedural programming? Procedural programming, exemplified by languages such as C, Pascal, and others, consists of a sequence of instructions, often grouped into functions, that are executed by a machine. The purpose of these instructions is to act on data in order to produce a specific effect. Dissociation between data and functions Data accessible and modifiable Sequential execution order System evolution and maintenance difficulties Difficulty in code reuse Open access to data Code redundancy 5 What is object-oriented programming? Object-oriented programming (OOP) is a programming style that organizes code using 'objects' that represent real-world entities. These objects have associated characteristics and actions. Object 2 Object 1 Objects communicate through messages Object 3 6 The principles of object- The advantages of object- oriented programming oriented programming Modularity Productivity Flexibility Security Scalability Code reuse 7 Object-Oriented Objective: The Adventures of OO Adding Methods to a Class: Transforms the class from a data container to an active object. Methods are the only way to access or modify the object's state. Each object should have an interface, similar to a user manual. History of Object-Oriented Programming (OOP): OOP is not new; the first major OO language, Simula, was created in 1966. Experienced programmers might view recent developments as reworked ideas. 8 Object-Oriented Objective: The Adventures of OO (2) Innovation in Programming: Similar to fields like philosophy and jazz, not all eras are equally innovative. The 1950s and 60s were particularly groundbreaking for computing. Prevalence of OOP: OOP is becoming more common compared to procedural programming. Knowledge of OOP concepts can enhance job prospects. Illustration of Differences: Practical differences between procedural and OO approaches will be shown through a small ecosystem simulation. 9 An example of a simple ecosystem simulation in Java In this Java programming exercise, we’ll simulate a forest ecosystem with trees, animals, and a river. Here’s how the simulation works: 1. Animal Movement: - Animals can move towards a river, a tree, or away from other animals. The animal's movement depends on which object it detects first within its sensing range. 10 An example of a simple ecosystem simulation in Java (2) - Each animal has a sensing range that determines which objects it can detect. If an object is within this range, the animal will move towards or away from it based on its needs. 2. Tree Behavior: - Trees provide food and shelter. When an animal is close to a tree, it will interact with the tree (e.g., eat fruits or find shelter). - Trees slowly grow over time, increasing their size and resource availability. 11 An example of a simple ecosystem simulation in Java (3) 3. River Behavior: - The river provides water for animals. When animals come into contact with the river, they replenish their energy. - The river's water level decreases slightly over time due to evaporation, visually represented by a shrinking water area. 4. Interactions: - Animals gain energy from interacting with trees or drinking water from the river. - The growth of trees and the evaporation of the river occur gradually over time. - Animals might change their behavior based on their energy levels (e.g., seek water more urgently if low on energy). 12 Ecosystem Simulation What functions do all the objects need to perform here? First, both animals (such as deer and wolves) need to move. We will start by thinking about and coding the movement of these animals together. It is important to handle them together even though they are different entities. For both the deer and the wolf, each animal must first locate a target. The "movement" function will rely on a new function called "detection," which is relevant to all objects. Objects need to detect each other: the wolf searches for the deer, the deer looks for plants and avoids the wolf, and both look for water. Detection is done using a vision system, a procedural block with two similar functions that will be applied to each animal and will operate only during detection. 13 Ecosystem Simulation (2) A second major function involves resource gathering for the deer and the wolf. This function will again affect all objects, as the resource gathering varies depending on the encountered resource. For instance, when the deer encounters a plant, it eats it, and the plant’s size decreases. When the wolf encounters the deer, it eats the deer, which then disappears from the screen. The third major function is the temporal evolution of resources, where plants grow and water evaporates. The main program will consist of all the objects in the ecosystem and three major procedures: "movement," "resource gathering," and "resource evolution." The "movement" procedure will call a new detection procedure for objects. 14 Procedural Programming Procedural programming involves collective access and global manipulation of objects, within a few large functional modules that interrelate with each other. In contrast, object-oriented programming relies on a large number of objects that pass the baton to each other for executing the specific functions assigned to them. ❑ All objects are created and stored in memory from the start. ❑ Objects are treated as a global set of data affected by large procedural modules. ❑ In procedural programming, the program is broken down into major functions or procedures. ❑ The code is organized by dividing it into its main functions. ❑ Objects are accessed and managed globally within large functional modules. ❑ Unlike object-oriented programming, where many objects work together to perform specific tasks. 15 Procedural Design In procedural design, movement involves all objects, while detection involves pairs of objects. Resource gathering also applies to all objects, whereas resource evolution affects only two objects. This example shows how procedural practice breaks down the problem into large, nested functions that cover most of the data. In procedural programming, modularity and evolution come from these interconnected functions. However, it’s harder to create a natural decomposition of the problem into relatively independent modules. 16 Object-Oriented Design In object-oriented practice, the focus is on identifying the key elements in the forest ecosystem and turning them into classes that group their structural and behavioral characteristics. These elements are defined by what they do, not just their structure. Classes guide the modular construction of the software. In this case, the elements are the trees, animals, river, and plants. Each element has specific attributes and functions. ✓ Trees: Grow and can change in size. ✓ River: Changes in volume over time due to evaporation or rain. ✓ Animals: Move around, interact with other objects, drink water, and eat plants. For example, deer can eat plants and drink from the river, while wolves can hunt deer and drink from the river. Each class has interactions with other classes, and methods are linked to these objects. 17 Impacts of Object-Oriented Approach Element-Based Design: - Software design is based on major elements (trees, animals, river, plants) rather than activities. - This approach feels more natural and intuitive, similar to how we view the ecosystem. Maintenance and Updates: - In procedural programming, changes in an element’s description may require updating the entire codebase. - In object-oriented programming, changes to an element’s structure, like the river class, typically only require updating the related methods, making maintenance easier. 18 Functional Dependence vs. Software Independence Functional Dependence This refers to the way different classes (or objects) in an OO program interact with and rely on each other to function correctly. For example, if you have two classes, one representing a `Forest` and another representing `Animals`, the `Forest` class might depend on the `Animals` class to populate itself with creatures. These dependencies are necessary for the program to execute properly because the objects need to communicate and collaborate to perform tasks. 19 Functional Dependence vs. Software Independence (2) Software Independence Despite the functional dependence during execution, when developing an OO program, efforts are made to keep the classes as independent as possible. This means that the code for each class is written in such a way that it can be developed, tested, and maintained separately from other classes. This independence makes it easier to manage the software because: - Different programmers can work on different classes without interfering with each other. - The code becomes more stable, as changes in one class are less likely to affect others. - The classes can be reused in other programs or contexts. - The software is easier to evolve, as new features can be added with minimal impact on existing code. 20 Functional Dependence vs. Software Independence (3) In summary, while classes in an OO program need to work together (functional dependence), the goal during development is to write the code so that these classes are as independent as possible, which helps in managing, maintaining, and extending the software. While the execution of an object-oriented (OO) program primarily relies on interactions between dependent classes, everything is syntactically implemented during software development to maintain significant independence between these classes. This independence during development promotes both the distribution of tasks among programmers and the stability of the code during maintenance, reuse in different contexts, and its evolution. 21 Inheritance and Polymorphism in OOP Inheritance allows a new class (called a subclass) to inherit properties and behaviors (like variables and methods) from an existing class (called a superclass). This helps in reducing code duplication and organizing the code logically. For example, in the forest ecosystem simulation, you might have a general superclass called `Animal`. Specific animals like `Deer` and `Wolf` could inherit common traits (like the ability to move) from this `Animal` class. 22 Inheritance and Polymorphism in OOP (2) Polymorphism allows objects of different classes to be treated as objects of a common superclass. It also allows methods to behave differently based on the object that is calling them. In our example, if `Deer` and `Wolf` are both subclasses of `Animal`, you could write a method that works for any `Animal` without worrying about whether it's a deer or a wolf. Inheritance and Polymorphism will be fully explored in a later chapter, using the forest ecosystem as an example. 23 Class Collaboration in Pairs In object-oriented programming, classes often work in pairs, sending messages to each other. This method encourages breaking down the program into smaller, independent parts, which makes it easier to assign different modules to different programmers and reduces the impact of changes in one part on the others. This approach aligns with how we naturally perceive and separate objects in the world. 24 Example of Class Collaboration Forest Ecosystem Example: Classes : Deer: Represents a deer in the forest. It has methods like `move()`, `eatPlant()`, and `drinkWater()`. Wolf: Represents a wolf in the forest. It has methods like `huntDeer()`, `move()`, and `drinkWater()`. Plant: Represents plants that deer eat. It has methods like `grow()` and `decreaseQuantity()`. Water: Represents water sources in the forest. It has methods like `evaporate()` and `decreaseQuantity()`. 25 Examples of Class Collaboration (2) Class Collaboration: ❑ The `Wolf` class collaborates with the `Deer` class by calling `huntDeer()` when a wolf targets a deer. The `huntDeer()` method may involve interactions such as the wolf chasing and catching the deer, leading to the deer’s removal from the ecosystem. ❑ The `Deer` class collaborates with the `Plant` class by calling `eatPlant()`. This method will reduce the quantity of the plant and provide the deer with energy. ❑ Both `Wolf` and `Deer` classes collaborate with the `Water` class. When they call `drinkWater()`, the water quantity decreases. 26 OO vs. Procedural Performance It's incorrect to claim that object-oriented programs perform better in terms of resource consumption (like CPU time and memory) compared to procedural programs doing the same tasks. OO programs often use more memory (due to the proliferation of objects spread throughout memory) and take more time to execute (because the system has to find objects and methods in memory, translate methods into executable form at the last moment, and deal with things like garbage collection). The real savings in time and resources come during development and maintenance, as OO programming makes it easier for programmers to manage and evolve their code. OO simply prioritizes programmer time over machine time, which we believe is the right approach. 27 Learning activity Why OO Programs Use More Memory and CPU? 1. Memory Usage Object Proliferation: In OO programs, each class instance (object) occupies memory. As more objects are created, they collectively consume more memory. For example, in a large forest ecosystem simulation, thousands of `Deer`, `Wolf`, `Plant`, and `Water` objects might be instantiated, each taking up memory. Instance Variables: Every object stores its own data (instance variables). If you have many objects, this leads to a significant increase in memory consumption compared to a procedural approach where data might be shared more directly between functions. 28 Learning activity (2) 2.CPU Usage Dynamic Method Dispatch: In OO languages like Java, when a method is called on an object, the program must determine at runtime which specific method implementation to execute, especially with inheritance and polymorphism. This dynamic method dispatch adds extra CPU cycles. Garbage Collection: OO programs often create and destroy many objects. Java’s garbage collector has to run periodically to clean up unused objects, which consumes CPU resources. Memory Access Patterns: In OO programs, objects may be spread out in memory, leading to poor cache locality. This means that accessing data from different objects can cause more CPU cache misses, slowing 29 down the program. QCM 1. What is the primary focus of procedural programming? - A) Identifying actors in a problem and their behaviors - B) Decomposing the problem into large, interrelated functions - C) Creating classes with shared behaviors - D) Encapsulating data and functions within objects 2. Which of the following best describes polymorphism in OOP? - A) It allows objects of different classes to be treated as objects of a common superclass. - B) It prevents objects from sharing methods with other objects. - C) It requires that all classes have the same number of methods. - D) It eliminates the need for class inheritance. 30 References BERSINI, Hugues. La programmation orientée objet. Editions Eyrolles. 2010. Head First Java, Second Edition, By Kathy Sierra, Bert Bates, O'Reilly Media. Programmer en JAVA, 4ème édition, Deitel et Deitel, Les éditions Reynal Goulet. http://java.sun.com Le Programmeur JAVA 2, Lemay L, Campus Press. Au cœur de Java 2 Volume I - Notions fondamentales, Horstmann et Cornell, The Sun Microsystems Press Java Series. Programmer en Java, Claude Delannoy, Eyrolles. 31

Use Quizgecko on...
Browser
Browser