oop basics

71
OOP Basics

Upload: hayden

Post on 24-Feb-2016

37 views

Category:

Documents


0 download

DESCRIPTION

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.) - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: OOP Basics

OOP Basics

Page 2: OOP Basics

• 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.

Classes: Theory

Page 3: OOP Basics

• 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.

A Class is a Data Type

Page 4: OOP Basics

• Variables• Properties• Constructor• ToString• Subs• Functions• Enumerations

Classes: Parts

Page 5: OOP Basics

• 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:

Class Variables

Page 6: OOP Basics

• 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:

Using “.” to access properties

• 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.

Page 7: OOP Basics

• 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.

Properties

Page 8: OOP Basics

• 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.

Properties

Page 9: OOP Basics

• 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:

Properties--Format

Page 10: OOP Basics

• 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.

Properties--Details

Page 11: OOP Basics

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

Set

Page 12: OOP Basics

• 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 Constructor “New”

• 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.

Page 13: OOP Basics

• Looking at the Student class in the handout, you will notice:

1. Classes generally have lots of lines of code.2. Much of that code is repetitive and easy to

write,3. So easy, in fact, that it could be automated!4. That’s assignment 3.

Classes: Lots of Easy Code

Page 14: OOP Basics

• 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”.

Some correspondences

Page 15: OOP Basics

• “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.

More Correspondences

Page 16: OOP Basics

• 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.

And What About Relationships?

Page 17: OOP Basics

• 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!

So, if databases and OOP are the same, why do we have to learn OOP?

Page 18: OOP Basics

• 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!

Why OOP?

Page 19: OOP Basics

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)

Page 20: OOP Basics

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)

Page 21: OOP Basics

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)

Page 22: OOP Basics

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)

Page 23: OOP Basics

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)

Page 24: OOP Basics

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)

Page 25: OOP Basics

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)

Page 26: OOP Basics

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)

Page 27: OOP Basics

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)

Page 28: OOP Basics

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)

Page 29: OOP Basics

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)

Page 30: OOP Basics

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)

Page 31: OOP Basics

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.

Page 32: OOP Basics

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)

Page 33: OOP Basics

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)

Page 34: OOP Basics

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)

Page 35: OOP Basics

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.

Page 36: OOP Basics

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)

Page 37: OOP Basics

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)

Page 38: OOP Basics

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.

Page 39: OOP Basics

39

The Marching Band Program

• Demonstration of the Marching Band program.

Page 40: OOP Basics

40

• 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.

Concept to Code

Page 41: OOP Basics

41

1. Abstraction2. Inheritance3. Encapsulation4. Polymorphism

• I will explain what these mean, and show how these are used in the Marching Band program.

The Four Elements of OOP

Page 42: OOP Basics

42

• 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.

Abstraction

Page 43: OOP Basics

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.

Page 44: OOP Basics

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.

Page 45: OOP Basics

45

• 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.

Inheritance

Page 46: OOP Basics

46

• 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.

Inheritance

Page 47: OOP Basics

47

• 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.

Inheritance

Page 48: OOP Basics

48

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

or two.

Inheritance

Page 49: OOP Basics

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.

Page 50: OOP Basics

50Doonesbury, August 16, 2009

Page 51: OOP Basics

51

Micromanaging• The cartoon highlights something called “micromanagement”.• A company that is micro-managed keeps all authority at the top

level.• The opposite of micromanaging is delegating: trusting

subordinates to make decisions.• In programming, micromanaging involves creating one big

subroutine which does everything.• Delegating means creating objects capable of handling some

things on their own.• For the cartoon, you could imagine a Dealer class, where each

dealer is empowered to make certain decisions on his/her own.

Page 52: OOP Basics

52

Micromanaging the Marching Band

• All of the movements of the band members in the program could be coded at the highest level.

• A single subroutine could respond to the Turn Right button, and it would erase all of the band members and redraw them, one-by-one, in their new orientation.

• There would be huge amounts of code in frmBand, and the other two classes wouldn’t exist.

• This would be very difficult to debug, or to expand upon.

Page 53: OOP Basics

53

Band Camp!• As I said a couple of slides ago, the opposite of micromanaging is

delegating.• The key to successful delegation is training—if the subordinates know

what they’re doing, you can give them high-level orders (“Build 10000 Volts”, “Build a new factory”) and trust that it will happen.

• By training the band members to respond to standard commands, we don’t have to write detailed code at the higher levels of the program.

• We carry this a step further by adding a second level of management—the Rank. The band director doesn’t give any commands directly to band members; the commands go to the rank (or rank leader) who converts them to appropriate commands for each member in the rank.

Page 54: OOP Basics

54

The OOP Pyramid

• A good OOP program typically has its code in a sort of pyramid: there is a lot of code at the lowest levels (training the workers), and little code at the top (the CEO just barks out a few orders).

• In the band program, the BandMember class has 157 lines of code (including comments); the Rank class has 94, and the top-level frmBand class has 76 lines.

Page 55: OOP Basics

55

What happened to Encapsulation?• This whole delegation thing is related to encapsulation.• It’s very hard to find a simple definition of encapsulation, at

least one that really means what encapsulation means.• Here’s my definition: Encapsulation is clearly separating the

part of an object that is accessible from the outside, called its “interface”, from the inner workings of that object, called its “implementation.”

• An object with a small interface and large implementation is empowered: an object that can be delegated to. It knows how to do a lot on its own.

Page 56: OOP Basics

56

Interface

• The Interface of a VB Class consists of all of its Public– Properties– Procedures (Subs and Functions)– Events– Enumerations

• The VB keyword Public is used to identify which properties, procedures, events and enumerations are available to the outside world.

Page 57: OOP Basics

57

BandMember Interface• Public Property Location• Public Property Dir• Public Property StepSize• Public Sub New (the constructor)• Public Sub StepForward• Public Sub TurnLeft• Public Sub TurnRight• Public Sub TurnAround• Public Sub Draw• Public Enumeration Direction (North, South, East, West)

Page 58: OOP Basics

58

Implementation• Everything else in the BandMember class (that isn’t part of the

Interface) is called its implementation.• The Interface lets the world know what the class can do;• The Implementation is how it does it.• You can change the implementation all you want if you don’t change the

interface.• If the class still responds to the same requests, it will work with any

program designed to use it—even if you change the implementation (without introducing bugs, that is!)

• You could recode the Draw routine to display a white “S” on a green background, or a gray “O” on a crimson background, and the Rank and frmBand classes would still function (albeit reluctantly!).

• Here it is in the sample solution:

Page 59: OOP Basics

59

That Definition Again?

• Encapsulation is clearly separating the part of an object that is accessible from the outside, called its “interface”, from the inner workings of that object, called its “implementation.”

• By separating the interface from the implementation, we can modify (improve) the implementation, and the class will still work with other classes that use it (like Rank).

Page 60: OOP Basics

60

Polymorphism

• Polymorphism refers to treating things of different types in the same way.

• In VB, it is sometimes related to inheritance: You can treat a Student object in many of the same ways as you can treat a Person object. (The Student Class would inherit from the Person Class).

• It can also be related to shared interfaces: things of different types which share certain properties or behaviors. (Birds and Planes can both fly, for example.)

Page 61: OOP Basics

61

The Timers• The animation that you see in the program comes

from a Timer control.• A Timer control is an event generator. At regularly-

scheduled intervals, it generates Tick events.• You write code to respond to the Tick events, just

as you would to a button click. (If you double-click on the Timer control, VB will create the framework of the sub for you.)

Page 62: OOP Basics

62

Timer Properties

• Timers only have two important properties:– Interval: The time in milliseconds between ticks.

To have the Timer tick every second, set the Interval property to 1000. This can be done in the properties window or in code.

– Enabled: Timers are turned on by setting their Enabled property to True. (Who wouldn’t be?)

Page 63: OOP Basics

63

The Object Structure

• The band is made up of ranks, which are in turn made up of band members. In VB terms, a rank is a collection of band members, and the band is a collection of ranks.

• The hierarchy could have one level added—musical section (trumpets, percussion, etc.) However, for modeling just the marching, this is unimportant.

• The object structure reflects a “part of” hierarchy.

Page 64: OOP Basics

64

The Class Structure

• There is no real class structure in this program; no inheritance is involved.

• There is a BandMember class and a Rank class.• There could be a Band class, but the whole

program serves that purpose here.

Page 65: OOP Basics

65

Could the Class Structure Be More Complex?

• Depending on how much of the band’s operation we want to model, a more complex class structure is certainly possible.

• BandMember could inherit from a Student class, which inherits from a Person class.

• The Band class could inherit from a StudentOrganization class, or perhaps from a MusicalGroup class.

• Remember: class structure reflects an “is a” hierarchy. A band is a student organization; a band is a musical group.

• Could band inherit from both? Not in VB—it doesn’t support multiple inheritance.

Page 66: OOP Basics

66

The Architecture of a System

• From the reading (p. 16): Collectively, we speak of the class and object structures of a system as its architecture.

Page 67: OOP Basics

67

A Class is a Program

• To me, the simplest way to think of a class is as a program in itself.

• The typical computer program takes input from the user, performs some tasks, and produces some sort of output of interest to the user (displayed on screen, saved to file, printed out).

• A class does the same thing, except the “user” may be another program or class, and the input and output may simply be values passed back and forth between objects of the classes.

Page 68: OOP Basics

68

OOP = Divide and Conquer• OOP provides a framework for you to break a large programming

task into smaller, more manageable pieces.• Unlike structured programming, where the large program is

broken into subroutines (procedures), OOP breaks the program into classes, which contain both procedures AND data.

• This enables classes to be self-contained subprograms that can be encapsulated, tested individually, and reused.

• In the marching band program, the BandMember class is really just a mini-program modeling the behavior of an individual band member. Each band member we create from this class (an “instance” or “object”) keeps track of its own data, and can respond to instructions.

Page 69: OOP Basics

69

Stable Intermediate Forms• My favorite section in the reading assignment (p. 14)• Complex systems will evolve from simple systems much more

rapidly if there are stable intermediate forms than if there are not.

• 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.

• As systems evolve, objects that were once considered complex become the primitive objects on which more complex systems are built.

Page 70: OOP Basics

70

Stable Intermediate Forms

• In the marching band program, both the BandMember class and the Rank class are stable intermediate forms.

• For some simple routines, the program displays certain aspects of a marching band in a vaguely realistic way.

• Band members are able to go forward, stop, turn left, turn right, and turn around.

• Ranks are able to perform maneuvers by telling various members to perform various combinations of those actions.

Page 71: OOP Basics

71

Stable Intermediate Forms• Expanding the program from these working, stable

intermediate forms will not be hard.• We can create new capabilities for the band members—

move more realistically, look more like real band members, play notes, dance.

• We can expand on the rank class both by designing new maneuvers for the existing band members, or incorporating the members’ new capabilities into new rank capabilities—play a song or dance a routine.

• Doing this incrementally, building on something that works, allows us to get immediate feedback on the new code.