Tải bản đầy đủ - 0 (trang)
Hour 17. Designing Objects Using Classes

Hour 17. Designing Objects Using Classes

Tải bản đầy đủ - 0trang

Hour17.DesigningObjectsUsingClasses

You learned about what makes an object an object in Hour 3,

"Understanding Objects and Collections." Since that hour,

you've learned how to manipulate objects such as forms and

controls.Therealpowerofleveragingobjectscomesfrombeing

able to design and implement custom objects of your own

design.Inthishour,you'lllearnhowtocreateyourownobjects

by using classes (in contrast to using static methods). You'll

learn how to define the template for an object and how to

createyourowncustompropertiesandmethods.

Thehighlightsofthishourincludethefollowing:

Encapsulatingdataandcodeusingclasses

Comparing instance member classes with static member

classes

Constructorsanddestructors

Creatinganobjectinterface

Exposingobjectattributesasproperties

Exposingmethods

Instantiatingobjectsfromclasses

Bindinganobjectreferencetoavariable

Understandingobjectlifetime

Releasingobjectreferences



There is simply no way to become an expert on



programmingclassesinasinglehour.However,when

you've finished with this hour, you'll have a working

knowledge of creating classes and deriving custom

objectsfromthoseclasses;considerthishouraprimer

onobject-orientedprogramming.Istronglyencourage

you to seek other texts that focus on object-oriented

programming after you feel comfortable with the

materialpresentedthroughoutthisbook.







Top











UnderstandingClasses

Classes enable you to develop applications using objectorientedprogramming(OOP)techniques(recallthatIdiscussed

OOP briefly in Hour 3). Classes are templates that define

objects. Although you may not have known it, you have been

programming with classes throughout this book. When you

create a new form in a C# project, you are actually creating a

class that defines a form; forms instantiated at runtime are

derived from the class. Using objects derived from predefined

classes, such as a C# Form class, is just the start of enjoying

the benefits of object-oriented programming—to truly realize

thebenefitsofOOP,youmustcreateyourownclasses.

The philosophy of programming with classes is considerably

different from that of "traditional" programming. Proper classprogramming techniques can make your programs better, both

in structure and in reliability. Class programming forces you to

consider the logistics of your code and data more thoroughly,

causing you to create more reusable and extensible objectbasedcode.



EncapsulatingDataandCodeUsingClasses

Anobject derived from a class is an encapsulation of data and

code; that is, the object comprises its code and all the data it

uses. For example, suppose that you need to keep track of

employeesinanorganizationandthatyouneedtostoremany

ofpiecesofinformationforeachemployee,suchasName,Date

Hired, and Title. In addition, suppose you need methods for

adding and removing employees, and you want all this

informationandfunctionalityavailabletomanyfunctionswithin



your application. You could use static methods to manipulate

thedata.However,thiswouldmostlikelyrequiremanyvariable

arrays,aswellascodetomanagethearrays.



A better approach is to encapsulate all the employee

data and functionality (adding and deleting routines

and so forth) into a single, reusable object.

Encapsulation is the process of integrating data and

code into one entity—an object. Your application, as

wellasexternalapplications,couldthenworkwiththe

employee data through a consistent interface—the

Employee object's interface (An interface is a set of

exposedfunctionality—essentially,coderoutines.)

Creatingobjectsforuseoutsideofyourapplicationis

beyond the scope of this book. The techniques you'll

learn in this hour, however, are directly applicable to

creatingexternallycreatableobjects.

Theencapsulationofdataandcodeisthekeydetailofclasses.

By encapsulating the data and the routines to manipulate the

dataintoasingleobjectbywayofaclass,youfreeapplication

code that needs to manipulate the data from the intricacies of

data maintenance. For example, suppose company policy has

changedsothatwhenanewemployeeisaddedtothesystem,

aspecialtaxrecordneedstobegeneratedandaformneedsto

be printed. If the data and code routines weren't encapsulated

in a common object but were written in various places

throughout your code, you would need to modify each and

every module that contained code to create a new employee

record.Byusingaclasstocreateanobject,youneedtochange

onlythecodeinonelocation:withintheobject.Aslongasyou



don't modify the interface of the object (discussed shortly), all

the routines that use the object to create a new employee will

instantlyhavethepolicychangeineffect.



ComparingInstanceMemberswithStaticMembers

You learned in Hour 11, "Creating and Calling Methods," that

C# does not support global methods, but supports only class

methods. By creating static methods, you create methods that

can be accessed from anywhere in the project through the

class.

Instance methods are similar to static methods in how they

appear in the C# design environment and in the way in which

youwritecodewithinthem.However,thebehaviorofclassesat

runtimediffersgreatlyfromthatofstaticmembers.Withstatic

members,allstaticdataissharedbyallmembersoftheclass.

In addition, there are never multiple instances of the static

class data. With instance member classes, objects are

instantiatedfromaclassandeachobjectreceivesitsownsetof

data. Static methods are accessed through the class, whereas

nonstaticmethods(alsocalledinstancemethods)areaccessed

throughinstancesoftheclass.



Instance methods differ from static methods in more

ways than just in how their data behaves. When you

defineastaticmethod,itisinstantlyavailabletoother

classes within your application. However, instant

member classes aren't immediately available in code.

Classes are templates for objects. At runtime, your

codedoesn'tinteractwiththecodeintheclassperse,

butitinstantiatesobjectsderivedfromtheclass.Each

object acts as its own class "module" and thus it has

its own set of data. When classes are exposed



externally to other applications, the application

containing the class's code is called the server.

Applications that create and use instances of objects

arecalledclients.Whenyouuseinstancesofclassesin

the application that contains those classes, the

applicationitselfactsasbothaclientandaserver.In

thishour,I'llrefertothecodeinstantiatinganobject

derivedfromaclassasclientcode.

Begin by creating a new Windows Application titled Class

ProgrammingExample.Changethenameofthedefaultform

to fclsClassExample and set its Text property to Class

Example. Next, change the entry point of the project in the

method Main() to reference fclsClassExample instead of

Form1. Add a new class to the project by choosing Add Class

from the Project menu. Save the class with the name

clsMyClass.cs(seeFigure17.1).

Figure17.1.Classesareaddedtoaprojectthesameas

otherobjectfilesareadded.



ConstructorsandDestructors

Asyouopenyournewclassfile,you'llnoticethatC#

added the public class declaration and a method

called clsMyClass(). This is known as the class

constructor. A constructor has the same name as the

class,includesnoreturntype,andhasnoreturnvalue.

Aclassconstructoriscalledwheneveraclassobjectis

instantiated. Therefore, it's normally used for

initialization if some code needs to be executed

automatically when a class is instantiated. If a

constructorisn'tspecifiedinyourclassdefinition,the

Common Language Runtime (CLR) will provide a

defaultconstructor.



Objects consume system resources. The .NET

Framework (discussed in Hour 24, "The 10,000-Foot

View")hasabuilt-inmechanismtofreeresourcesused

by objects. This mechanism is called the Garbage

Collector Hour 24 as well). Essentially, the garbage

collectordetermineswhenanobjectisnolongerbeing

used and then destroys the object. When the garbage

collector destroys an object, it calls the object's

destructor method. If you aren't careful about how to

implement a destructor method, you can cause

problems.Irecommendthatyouseekabookdedicated

to object-oriented programming to learn more about

constructorsanddestructors.



CreatinganObjectInterface

Foranobjecttobecreatedfromaclass,theclassmustexpose

an interface. As I mentioned earlier, an interface is a set of

exposed functionality (essentially, code routines/methods).

Interfaces are the means by which client code communicates

with the object derived from the class. Some classes expose a

limitedinterface,whereassomeexposecomplexinterfaces.The

content and quantity of your class's interface is entirely up to

you.

Theinterfaceofaclassconsistsofoneormoreofthefollowing

members:

Properties

Methods

Events



Forexample,assumethatyouarecreatinganEmployeeobject

(that is, a class used to derive employee objects). You must

first decide how you want client code to interact with your

object. You'll want to consider both the data contained within

theobjectandthefunctionstheobjectcanperform.Youmight

wantclientcodetobeabletoretrievethenameofanemployee

and other information such as sex, age, and the date of hire.

For client code to get these values from the object, the object

mustexposeaninterfacememberforeachoftheitems.Recall

from Hour 3 that values exposed by an object are called

properties. Therefore, each piece of data discussed here would

havetobeexposedasapropertyoftheEmployeeobject.

In addition to properties, you can expose functions—such as a

Delete or AddNew function. These functions may be simple in

nature or very complex. The Delete function of the Employee

object, for example, might be quite complex. It would need to

perform all the actions necessary to delete an employee,

including such things as removing the employee from an

assigned department, notifying accounting to remove the

employee from the payroll, notifying security to revoke the

employee's security access, and so on. Publicly exposed

functions of an object, as you should remember from Hour 3,

arecalledmethods.

Propertiesandmethodsarethemostcommonlyusedinterface

members. Although designing properties and methods may be

new to you, by now using them isn't; you've been using

properties and methods in almost every hour so far. Here,

you'regoingtolearnthetechniquesforcreatingpropertiesand

methodsforyourownobjects.

For even more interaction between the client and the object,

you can expose custom events. Custom object events are

similar to the events of a form or a text box. However, with

customeventsyouhavecompletecontroloverthefollowing:

Thenameoftheevent



Theparameterspassedtotheevent

Whentheeventoccurs



EventsinC#arebasedondelegates.Creatingcustom

eventsiscomplicated,andI'llbecoveringonlycustom

propertiesandmethodsinthishour.

Properties, methods, and events together make up an object's

interface. This interface acts as a contract between the client

applicationandtheobject.Anyandallcommunicationbetween

the client and the object must transpire through this interface

(seeFigure17.2).

Figure17.2.Clientsinteractwithanobjectviathe

object'sinterface.



The technical details of the interaction between the client and

the object by way of the interface are, mercifully, handled by

C#.Yourresponsibilityistodefinetheproperties,methods,and

events of an object so that its interface is logical, consistent,

and exposes all the functionality a client needs to use the

object.



ExposingObjectAttributesasProperties

Propertiesaretheattributesofobjects.Propertiescanbereadonly,ortheycanallowbothreadingandwritingoftheirvalues.

Forexample,youmaywanttoletaclientretrievethevalueofa

propertycontainingthepathofthecomponent,butnotletthe

clientchangeitbecauseyoucan'tchangethepathofarunning

component.

You can add properties to a class in two ways. The first is to

declare public variables. Any variable declared as public

instantly becomes a property of the class (technically, it's

referred to as a field). For example, suppose you have the

followingstatementintheDeclarationssectionofaclass:



publiclongQuantity;

Clients could read from and write to the property using code

suchasthefollowing:



objMyObject.Quantity=139;

This works, but significant limitations exist that make this

approachlessthandesirable:

Youcan'texecutecodewhenapropertyvaluechanges.For

example, what if you wanted to write the quantity change

toadatabase?Becausetheclientapplicationcanaccessthe

variable directly, you have no way of knowing when the

valueofthevariablechanges.

You can't prevent client code from changing a property,

becausetheclientcodeaccessesthevariabledirectly.

Perhaps the biggest problem is this: How do you control

data validation? For instance, how could you ensure that

Quantitywasneversettoanegativevalue?



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hour 17. Designing Objects Using Classes

Tải bản đầy đủ ngay(0 tr)

×