1 / 71

OOP Basics

OOP Basics. Classes: Theory. In a database, entities are represented by tables. In an object-oriented program, entities are represented by Classes. Like a table, a class is a template—a framework for storing information about real things. (“Real” being a relative term here.)

hayden
Télécharger la présentation

OOP Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. OOP Basics

  2. Classes: Theory • In a database, entities are represented by tables. • In an object-oriented program, entities are represented by Classes. • Like a table, a class is a template—a framework for storing information about real things. (“Real” being a relative term here.) • In a database, the “real” things are the records—the rows in the table. • In an OOP program, the “real” things are called objects.

  3. A Class is a Data Type • OOP is a powerful way to divide a programming problem into manageable parts. • When you create a Class, you are creating a new data type. • Objects of this data type will have all of the attributes and abilities that you design into the Class. • Designing good classes that encapsulate the attributes and abilities of an entity can make programming complex problems much simpler. • In effect, by creating classes you are extending the Visual Basic language.

  4. Classes: Parts • Variables • Properties • Constructor • ToString • Subs • Functions • Enumerations

  5. Class Variables • Visual Basic allows you to design Classes in many different ways. • Good object-oriented programming (OOP) is more restrictive—there are things that you can do in VB that you should not do, according to OOP principles. • For starters, in good OOP class variables should be declared private, like this:

  6. Using “.” to access properties • Classes are used for many things. One of the most basic is to group data together: putting all of the properties of an object into the same variable. • You access the properties of an object by using a period. For example, this code creates a new Label object: • The next line of code assigns a string to the Label’s Text property. Note that we access L’s text property with a period. • The period is also used to access procedures, as we’ll see later.

  7. Properties • In a database, the attributes of an entity are represented by fields (columns) in a table. • In an OOP program, attributes are represented by properties in a Class. • A property is a means of encapsulation: a way of accessing an object’s data in a controlled fashion.

  8. Properties • Properties are the “gatekeepers” for the variables. • Properties provide a controlled way for the outside world (those parts of a program that are not part of the Class) to access the variables. • Properties do not store data by themselves. • Variables store the data; properties control the access.

  9. Properties--Format • In OOP, a Public Property is typically associated with a private variable. • The variable stores the data, while the property provides controlled access to it. • Here is the basic format:

  10. Properties--Details • Note that the variable and the property have the same data type. • The property has a descriptive name, while its associated variable has the same name, but with a small “m” in front of it. (The “m” stands for “member variable”.) • The Get portion of the property returns the variable, while the Set portion sets the variable equal to “value”. • I’ll explain later what all of this means; for now, I just want you to know what a property and its associated variable look like in VB code.

  11. Set • The Set portion of a property is frequently used to validate data.

  12. The Constructor “New” • An important part of any Class is the constructor—a subroutine called “New”. • For this assignment, we will use the constructor simply for assigning initial values to properties. • Here’s the code for the constructor in the Student class: • The items inside the parentheses,pFirstName, etc., are called parameters. • Parameter names can be any valid identifier; however, using a convention like the small “p” makes the code easier to understand. • Parameter variables are assigned values when the Sub is “called” by other code in the program.

  13. Classes: Lots of Easy Code • Looking at the Student class in the handout, you will notice: • Classes generally have lots of lines of code. • Much of that code is repetitive and easy to write, • So easy, in fact, that it could be automated! • That’s assignment 3.

  14. Some correspondences • ENTITIES are represented by tables in a database; they are represented by “classes” in OOP. • ATTRIBUTES are represented by fields (columns); in OOP, they become “properties” or “variables”. • TUPLES are records (rows) in database tables; in OOP, they are called “objects.” • Identifiers are represented by keys in databases; they become “variable names” or “references” in OOP. • And lookup tables are represented in OOP by “enumerations”.

  15. More Correspondences • “INSERT INTO” corresponds to the constructor of a class, “New”. “INSERT INTO” creates rows; “New” creates objects. • A selected set of records, such as the result set from a query like “SELECT * FROM Elements WHERE GROUP = 0”, can be represented by one of several types of “collections” in OOP. (Where it would be called a collection of objects.) • Super types and sub types correspond to parent classes and child classes (or sometimes referred to as classes and subclasses). Creating subclasses from a parent class is termed “inheritance” in OOP.

  16. And What About Relationships? • These actually get more complicated in OOP. • OOP relationships include: • “is a”: This could be one-to-one or one-to-many, but “is a” means an inheritance relationship: a robin “is a” bird, a commercial customer “is a customer.” • “has a” or “has some”: This is generally represented by a property—either a single-valued property, or some sort of collection. Again, could be one-to-one or one-to-many. • “acts like”: This is generally represented by something called an “interface”. • More on this later.

  17. So, if databases and OOP are the same, why do we have to learn OOP? • Silly question. They’re not the same—they’re similar. • And while a database table shares some features with a class in OOP, a class contains features that database tables don’t. • Namely, classes don’t just store data; they know what to do with it!

  18. Why OOP? • A tough question. Would probably take me about 30 pages to answer it. • Those pages are your reading assignment for this week: the “Intro to OOP” PDF file in Resources/Required Reading. • Basically, OOP appears to be the best way to deal with software complexity. • We learned about databases using example tables with only a few records, but the techniques are applicable to tables with millions of records. • Similarly, we will develop OOP programs simple enough that they could be created using other programming methods. But you wouldn’t learn OOP that way!

  19. Key Quotes from the Reading • The more complex the system, the more open it is to total breakdown. (p. 3) • We can reason about how a computer works only because we can decompose it into parts that we can study separately. (4)

  20. Complexity and Abstraction • Not only are complex systems hierarchic, but the levels of this hierarchy represent different levels of abstraction, each built upon the other, and each understandable by itself. At each level of abstraction, we find a collection of devices that collaborate to provide services to higher layers. We choose a given level of abstraction to suit our particular needs. (4)

  21. Interactions • As with the structure of a computer, the parts of a plant form a hierarchy, and each level of this hierarchy embodies its own complexity. All parts at the same level of abstraction interact in well-defined ways. For example, at the highest level of abstraction, roots are responsible for absorbing water and minerals from the soil. Roots interact with stems, which transport these raw materials up to the leaves. The leaves in turn use the water and minerals provided by the stems to produce food through photosynthesis. (5)

  22. Separation of Concerns • There is a clear separation of concerns among the parts at different levels of abstraction. (5) • We find separate parts that act as independent agents, each of which exhibits some fairly complex behavior, and each of which contributes to many higher-level functions. Only through the mutual cooperation of meaningful collections of these agents do we see the higher-level functionality of a plant. The science of complexity calls this emergent behavior: The behavior of the whole is greater than the sum of its parts. (6)

  23. Complex Systems • Some software systems are not complex. These are the largely forgettable applications that are specified, constructed, maintained, and used by the same person, usually the amateur programmer or the professional developer working in isolation. (7) • We are much more interested in the challenges of developing what we will call industrial-strength software. (8) • Software systems such as these tend to have a long life span, and over time, many users come to depend on their proper functioning. (8)

  24. Inherently Complex • The distinguishing characteristic of industrial-strength software is that it is intensely difficult, if not impossible, for the individual developer to comprehend all the subtleties of its design. Stated in blunt terms, the complexity of such systems exceeds the human intellectual capacity. (8) • Software is Inherently Complex. (8) • Inescapable complexity, in which we find a myriad of competing, perhaps even contradictory, requirements. (8)

  25. System Requirements • Users generally find it very hard to give precise expression to their needs in a form that developers can understand. In some cases, users may have only vague ideas of what they want in a software system. (9) • Actually, even if users had perfect knowledge of their needs, we currently have few instruments for precisely capturing these requirements. The common way to express requirements is with large volumes of text, occasionally accompanied by a few drawings. Such documents are difficult to comprehend, are open to varying interpretations, and too often contain elements that are designs rather than essential requirements. (9)

  26. Changing Requirements • A further complication is that the requirements of a software system often change during its development, largely because the very existence of a software development project alters the rules of the problem. Seeing early products, such as design documents and prototypes, and then using a system once it is installed and operational are forcing functions that lead users to better understand and articulate their real needs. At the same time, this process helps developers master the problem domain, enabling them to ask better questions that illuminate the dark corners of a system’s desired behavior. (9) • Planned or not, systems tend to evolve over time. (10)

  27. Illusion of Simplicity • The fundamental task of the software development team is to engineer the illusion of simplicity—to shield users from this vast and often arbitrary external complexity. (10)

  28. Team Effort • Today, it is not unusual to find delivered systems whose size is measured in hundreds of thousands or even millions of lines of code (and all of that in a high-order programming language, as well). No one person can ever understand such a system completely. (10) • This amount of work demands that we use a team of developers, and ideally we use as small a team as possible. (10) • Having more developers means more complex communication and hence more difficult coordination. (10)

  29. The Five Attributes of a Complex System • Hierarchic Structure • Many complex systems have a … hierarchic structure … enabling us to understand, describe, and even ‘see’ such systems and their parts. • Relative Primitives • What is primitive for one observer may be at a much higher level of abstraction for another. (13)

  30. The Five Attributes of a Complex System (3 and 4) • Separation of Concerns • The difference between intra- and intercomponent interactions provides a clear separation of concerns among the various parts of a system, making it possible to study each part in relative isolation. (14) • Common Patterns • Hierarchic systems are usually composed of only a few different kinds of subsystems in various combinations and arrangements. (14)

  31. The Five Attributes of a Complex System (5) • Stable Intermediate Forms • A complex system that works is invariably found to have evolved from a simple system that worked…A complex system designed from scratch never works and cannot be patched up to make it work. You have to start over, beginning with a working simple system. (14) • As systems evolve, objects that were once considered complex become the primitive objects on which more complex systems are built.

  32. The Canonical Form of a Complex System • An aircraft may be studied by decomposing it into its propulsion system, flight-control system, and so on. This decomposition represents a structural, or “part of” hierarchy. (15) • A jet engine represents a generalization of the properties common to every kind of jet engine; a turbofan engine is simply a specialized kind of jet engine, with properties that distinguish it, for example, from ramjet engines. (15) • This second hierarchy represents an “is a” hierarchy. In our experience, we have found it essential to view a system from both perspectives, studying its “is a” hierarchy as well as its “part of” hierarchy. For reasons that will become clear in the next chapter, we call these hierarchies the class structure and the object structure of the system, respectively. (15)

  33. Canonical Form • All complex systems take on the same (canonical) form. Collectively, we speak of the class and object structures of a system as its architecture. (16) • The class structure and the object structure are not completely independent; rather, each object in the object structure represents a specific instance of some class. (16)

  34. Canonical Form • There are usually many more objects than classes of objects within a complex system. By showing the “part of” as well as the “is a” hierarchy, we explicitly expose the redundancy of the system under consideration. (16) • Our experience is that the most successful complex software systems are those whose designs explicitly encompass well-engineered class and object structures and embody the five attributes of complex systems described in the previous section. (17)

  35. The Role of Decomposition • Two common programming approaches to decomposing a complex system: • Algorithmic Decomposition • The program is organized at the highest level around processes and sub-processes (Subroutines calling subroutines). • Object-Oriented Decomposition • The program is organized at the highest level around abstractions of entities, emphasizing the agents that either cause action or are the subjects on which these operations act.

  36. Object-Oriented Decomposition • We must start decomposing a system either by algorithms or by objects and then use the resulting structure as the framework for expressing the other perspective. Our experience leads us to apply the object-oriented view first because this approach is better at helping us organize the inherent complexity of software systems. (23) • Object-oriented decomposition yields smaller systems through the reuse of common mechanisms, thus providing an important economy of expression. Object-oriented systems are also more resilient to change and thus better able to evolve over time because their design is based on stable intermediate forms. Indeed, object-oriented decomposition greatly reduces the risk of building complex software systems because they are designed to evolve incrementally from smaller systems in which we already have confidence. Furthermore, object-oriented decomposition directly addresses the inherent complexity of software by helping us make intelligent decisions regarding the separation of concerns in a large state space. (23)

  37. The Role of Abstraction • Unable to master the entirety of a complex object, we choose to ignore its inessential details, dealing instead with the generalized, idealized model of the object. (23)

  38. The Role of Hierarchy • The object structure is important because it illustrates how different objects collaborate with one another through patterns of interaction that we call mechanisms. The class structure is equally important because it highlights common structure and behavior within a system.

  39. The Marching Band Program • Demonstration of the Marching Band program.

  40. Concept to Code • In OOP, we represent the different entities in our project with different classes. • Both Rank and Band could be considered “mechanisms” as described in the reading: collections of lower-order objects working together.

  41. The Four Elements of OOP • Abstraction • Inheritance • Encapsulation • Polymorphism • I will explain what these mean, and show how these are used in the Marching Band program.

  42. Abstraction • Abstraction means representing something by the characteristics that matter to you, and ignoring everything else. • In the band program, the band members are represented as blue squares with yellow M’s on them. • We have abstracted out all other features of real band members, these features not being required to show the patterns made on the field.

  43. Abstraction • It’s not just the appearance of the BandMembers that has been abstracted. • Our BandMembers only have the properties and abilities needed for them to march in our virtual marching band.

  44. Abstraction • From being complex human beings who take classes, play music, eat, sleep, etc., we have abstracted our BandMembers down to just the properties and behaviors needed for our program.

  45. Inheritance • There is no obvious use of inheritance in this project; none of the three classes in the solution explorer inherits from any of the others. • However, there is some code hidden in the background (we’ll see it in a future lecture) that inherits the frmBand class from VB’s built-in Form class. • All forms that you design in VB.NET inherit from the built-in Form class. This gives them all of the properties and features of a form—a boundary, a caption (Text property), the ability to contain controls like buttons and textboxes.

  46. Inheritance • Inheritance is the OOP equivalent of a supertype/subtype relationship in a database. • The subclass has all of the properties of the parent class, plus some. • While inheritance is critical to the success of large-scale programs worked on by multiple programs, • I don’t use it a lot in the programs I write myself, because • Inheriting from a class that I wrote is functionally the same as just copying all of the code, and • Typically, I don’t need a whole “is-a” hierarchy in my programs.

  47. Inheritance • For your assignments and project, you will probably find the best way to use inheritance is not to inherit from classes you have written, but • To inherit from built-in VB classes, with controls being the most useful. • This is because you can’t copy the code for the built-in classes; Microsoft won’t allow you to. • However, you can inherit from one of their classes and add properties, procedures, or other features to it, while keeping all of the features Microsoft built into the parent class.

  48. Inheritance • That’s all I’ll say about inheritance right now. • We’ll look at inheriting from controls in a week or two.

  49. Encapsulation • Encapsulation we’ll use a lot; it’s a key feature of OOP that’s very useful in programs of the scale we write in this course. • It’s sometimes called “data hiding”, because one of the aspects of encapsulation is to protect an object’s data from unwarranted interference from higher levels in the program. • It could be considered to be the avoidance of micromanaging.

  50. Doonesbury, August 16, 2009

More Related