Tải bản đầy đủ - 0 (trang)
Chapter 5. Designing a Desktop Application

Chapter 5. Designing a Desktop Application

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

applications.Justlikeapersonmayknowthemeaningofalot

ofwordsandhowtoplacethosewordsintosentences,and

evenhowtounderstandwhatothersmeanwhentheyuse

words,itisnotnecessarilytruethatthesamepersoncanuse

thatunderstandingtoconstructapersuasiveargumenton

behalfofanyparticularcause.IcanreadaShakespeareplay

butIcannotwriteone.

Partofthetaskathand,then,istohelptogetyoustarted

writingapplicationsinREALbasicratherthanwritinglinesof

code.Therearesomestandardapproachesanddesignpatterns

thatcomputerprogrammershavedevelopedthatcanhelpto

provideaframeworkyoucanusetowritebetterprograms.One

sucharchitectureiscalledModel-View-Controller(MVC)anditis

oftenusedwhendevelopingapplicationswithgraphicaluser

interfaces.

IhaveusedthebasicelementsoftheModel-View-Controller

architectureinthedesignoftheRSSReaderapplication.Inthis

chapter,then,IwillwalkthroughthecodeoftheRSSReader

applicationandshowyouhowIchosetoimplementMVCusing

REALbasic.Itismyhopethatthiswillprovideyouwitha

practical,hands-onfeelforonewaytoapproachthechallenge

ofcreatinganapplication.Itisbynomeanstheonlyway,noris

itnecessarilythebestway,butitiscertainlyagoodwaytogo

aboutitanditcanserveasastartingpointforyou,especiallyif

youarenewtoprogramming.

Iwillalsodescribethefewremaininglanguageelementsthat

makeuptheREALbasicprogramminglanguagethatIhaveyet

todiscuss,whichincludesMenuHandlersandExceptions.



IntegratedDevelopmentEnvironment

AnumberofnewfeaturesinREALbasic2005areworth

touchingon,andthereareafewfeaturesIhaveyettodiscuss.

BecausethischaptermakessuchheavyuseoftheIDE,Ido

wanttospendamomentandtouchonafewpointsofinterest.



IDEMenuItems

Firstoff,I'dliketofamiliarizeyouwithafewofthemore

importantfeaturesofREALbasicthatareaccessiblethrough

variousMenuItemsortoolbars.TheIDEhaschanged

considerablyandhasaddedafewnewfeaturesthatyouwill

findveryhelpful.Althoughsomepeoplewhoarefamiliarwith

theoldwayofusingREALbasicmaybegrudgesomeofthe

changes,Ifindithardtounderstandwhybecausetheuser

interfaceofREALbasic2005is,inthevastmajorityofinstances,

exceedinglybetterthanpreviousversions,especiallyifyouare

aWindowsdeveloper.



File,NewProject

AtthetopofthelistisNewProject.Everyprogramyouwrite

inREALbasiciscalledaproject.Aprojectwillbesavedonthe

filesystemasasinglefile(withafewexceptions)andwill

containallthecode,graphics,andsoonrequiredbyyour

applicationtocompileandrun.Bynow,thisisnothingnewto

you.

However,oneofthebestnewfeaturesisthatyoucannowopen

morethanoneprojectatatime.PriortoREALbasic2005,you

couldn'tdothis,andtherearelotsoftimeswhenitis

convenienttolookatcodeinoneapplicationwhileyou're



writingcodeinanother.Nowyoucanevencutandpastecode

fromoneapplicationtothenext.



File,NewWindow

TheNewWindowMenuItemduplicatesthecurrentWindow,

soyoucannowhavetwoWindowsopenforthesameproject.

Again,thisisasimple,butgreatlyappreciated,newfeaturein

thelatestIDE.



File,Import/Export

Youcanimportandexportspecificclassesandmodulessothat

youcansharethemamongapplications.Normallywhenyou

exportaclass,youareexportingacopyofit,sothatwhen

anotherapplicationofyoursimportstheclassandmodifiesit,

theoriginalisnotmodified.Thismaybeexactlywhatyouwant

todo,sothatyoucanavoidbreakingotherprogramsthat

alreadywork.Thedownsidetothisisthatyoucaneasilyendup

withlotsofdifferentversionsofclassesandmodulesthatare

difficulttokeeptrackof.

Externalitemsareasolutiontothis.Whenyouimportanta

classormoduleintoyourapplication,theeasiestwaytodoso

istodragitintoREALbasicfromthedesktop.Ifyouholddown

theCommand+Option(orControl+AltforWindows)keyswhile

doingso,youwillimportthemasExternalitems,whichmeans

thattheyarestoredoutsideoftheREALbasicprojectfile.

Whenyouexportanitem,youhavethesameoptionsthatyou

havewhensavingaprojectfile:youcanexportitasanative

REALbasicfile,oryoucanexportitinXMLformat.My

recommendationistouseREALbasic'sXMLformatwhenever

possible,forthefollowingreasons.



Whenusingexternalitems,youneedtobecautiousbecause

whenyouchangecodeinoneproject,youarechangingcodein

alltheotherprojectsthatsharethiscode,whichmeansyoucan

easilybreaksomething.IfyouexportREALbasicitemsinthe

XMLformat,youcanmoreeasilymanagethosefilesusing

versioncontrolsoftwaresuchasCVSorSubversion.Because

versioncontrolsoftwareletsyoutrackthechangesthathave

beenmadetoafile,youcanuseittoreviewwhichchanges

havebeenmadetothecodeinyourapplicationthathave

causedittostopworking.Youcaneitherfixtheproblemorroll

backthefiletothepreviousversion.

Ifyouchoosenottouseexternalitems,onepotentialsolution

istoassignaversionnumbertoeachclass.Youcanestablisha

constantcalledVersion,oramethodthatreturnstheversionof

thisclass.Whenyouimportitintoyournextproject,besureto

incrementthenumberifyoumakeanychangestoit.(Notethat

thiswillchangetheversionnumberinallprojectsthatusethe

classifyouareusingexternalitems.That'sokay,butyoumay

wanttohaveyourapplicationtestfortheclassnumberfirst.If

it'snotarecognizedversion,youcanbenotifiedthatithas

beenchangedinadifferentapplication.)



ProjectMenu

UndertheProjectmenu,youalsohavetheoptionof

encryptingtheselectedclass.Thisisforthosewhowantto

distributeclassesorgroupsofclasses,butnotrevealthesource

code.

FollowingtheEncryptitemareseveralselectionsformanaging

theplacementofcontrolsonpages.Controlsarelayeredonto

aWindow,sotheArrangeMenuItemletsyoumanagewhich

layersindividualcontrolsareon.Alignhelpsyoualignyour

controlssothattheylineupproperly.TheFindMenuItemis

yourentryintoREALbasic'spowerfulFindandReplacefeatures,



whichIdiscussseparately.



View,EditorOnly

UndertheViewmenuaremostofthenewfeatures(with

respecttotheIDE).ThefirstselectionsaysEditorOnly.Ifyou

selectthis,themaintoolbarandthebookmarktoolbarwill

disappearandyouwillbeleftwiththetabsforyourproject.

Thisgetssomeoftheclutteroutofthewayandletsyoufocus

moreonwhatyouaredoing.

OneimportantdesignfeatureofREALbasic'sIDEistheuseof

Toolbarsthereareseveralofthemwithintheapplication,and

theyareallcustomizable.Here'salistofwhat'savailablefor

eachtoolbar.



MainToolbar

Bydefault,theMainToolbarcontainsthefollowingitems:

Back,Forward,Run,Build,AddBookmark,Location,Search.

Inaddition,youhavetheoptionofaddingthefollowingitems:

NewProject,Open,Save,SaveAs,Print,Home,BuildSettings,

Stop,Cut,Copy,Paste,Delete,Undo,Redo,andLanguage

Reference.



TheEditorToolbar

TheEditorToolbarvariesaccordingtowhichtabyouhave

selected.Forexample,iftheProjecttabisselected,youwill

havetheProjectToolbar.Thesecontext-sensitiveToolbars

areasfollows.



ProjectToolbar

Default:AddWindow,AddClass,AddModule,Add

Folder

Optional:Encrypt

CodeEditorToolbar(wheneditingaclass)

Default:EditMode,AddMethod,AddProperty,Add

MenuHandler,AddConstant,AddEventDefinition,Add

Note,Comment

MenubarToolbar

Default:ViewMode,AddMenu,AddMenuItem,Add

Separator,AddSubmenu,ConvertToMenu

WindowToolbar(EditCodeMode)

Default:EditMode,AddMethod,AddProperty,Add

MenuHandler,AddConstant,AddEventDefinition,Add

Note,Comment

WindowToolbar(EditLayoutMode)

Default:EditMode,ShowControlOrder,Forward,Front,

Backward,Back,andAlign

Option:AddBindandListBinds



History



REALbasicnowtracksyourHistory.Thisworksjustlikethe

historydoesonyourwebbrowserandhelpsyoutogobackto

recentlymodifieditems.Thereisnothingexceptionalhere.



Bookmarks

Thisisaconvenienceaddedthatallowsyoutobookmark

sectionsofyourprojectthatyouwillreturntooften.Thisis

helpfulwhenyouhavemultiplewindowsopen,andsoon.



Help

IamnotcertainthatitisaccuratetosaythatREALbasichasan

improvedhelpsystem.Itisprobablymoreaccuratetosaythat

atthistime,REALbasichaslaidthefoundationforanimproved

helpsystem.TherearesomenewitemsundertheHelpmenu

tobeawareof.First,ifyouaddanyplug-instoyourproject,

youwillbeabletoaccesstheirdocumentationunderthismenu.

Thereisalsoanewlanguagereferencewhich,atthetimeof

thiswriting,wasintheprocessofbeingrewritten.Althoughit

hasitsfairshareofproblems,thenewlanguagereferenceis

writteninHTML,issearchable,andhasthepromiseofbeing

muchimproved.Onewordofwarning,however:partsofitare

outdatedandotherpartsarejustplainwrong.Hopefully,this

bookwillhelpoffsetthatissue,andtherearealsoalotofonline

resourcesthatyoucanreferto,includingaREALbasic

documentationWiki.RatherthanputtingURLsthatmight

changeatsomepointinthefutureintothisbook,Ihave

includedlinkstothematthefollowingsite:

http://realbasicbook.com/.



Preferences



ThenewIDEalsooffersmorecontrolinthewayofpreferences.

WhenyouselectPreferencesfromthepreferencemenu(or

Options),aWindowwillbedisplayedthatlooksmoreorless

likeatypicalpreferenceswindow.Ontheleftisacolumnof

iconsthatrepresentthepreferencesyoucanchange.Selectone

andtherightsideoftheWindowdisplaysthespecificvalues

thatcanbeupdated.



CodeEditor

IfyouselectCodeEditor(whichisselectedbydefault),you'll

havetheopportunitytochangethedefaultfontREALbasicuses

inthecodeeditor,aswellashowlargethefontshouldbe

displayed.There'sevenahandyalphabetlistingbelowsothat

youcanseewhatitwilllookthat.

Belowthatisthesecondoptionthatallowsyoutocontrol

syntaxhighlighting.Youcanadjustthemtosuityourown

personalfancy.

YoualsohavetheoptionofhavingREALbasicapplythe

standardcasewhenusingAutocomplete.Autocompleteisatool

availableinthecodeeditorthattriestodetectwhatyouare

typing;whenitthinksitknows,anellipsisappears(threelittle

dots...).Whenthatshowsup,youcanpresstheTabkeyanda

menuwillpopupwithalltheoptions.Thiscomesinhandy

whenyouarereferringtoREALbasicclassesorfunctionsand

you'renotsurewhatthenameofthepropertyormethodis

thatyouwanttocall.ByusingAutocomplete,you'reprovideda

listfromwhichyoucanchoosetherestofthestatement.

That'salongexplanation,butthepointofitwastoexplain

whatitmeanstoapplystandardcasetoAutocomplete.

Generallyspeaking,REALbasicdoesn'tcareaboutcase.Youcan

refertoobjectsinuppercaseorlowercaseandREALbasicwill

acceptitregardless.Whatthisfeaturedoesismakesurethat



thecodeisinthe"Standard"caseifyouuseAutocomplete.

REALbasiccapitalizesthefirstletterinmostclasses,modules,

andmethods.Ifthenameisthecombinationoftwowords,like

ListBoxorEditField,thefirstcharacterofeachwordis

capitalized.Namesofclasseshavetobeoneword,butthey

oftenmakemoresenseifyouaremoredescriptive.Byjoininga

fewwordstogetherandcapitalizingthefirstletterofeachword,

youmakeyourcodemuchmorelegible.



WindowEditor

YoucansetfontattributesfortheWindowEditoraswell.

Controlsaretheuser-interfaceelementsyouseeonany

application,suchasPushButtons,EditFields,andsoon.AllI

willsayatthispointisthatcontrolscancontainothercontrols,

andthispreferenceitemletsyoudecidewhethertohighlight

theparentcontrolandwhatcoloryou'dlikethathighlighttobe.

I'drecommendkeepinghighlightingoftheparentcontrolon

becauseitcansometimesbedifficulttotellwhetheronecontrol

isembeddedinanother,orjustoverlappingit,andthiscan

provideyouwithimmediatefeedbackandsaveyoualotof

time.



BuildProcess

Afteryouhavebuilt(compiled)yourapplication,youhavethe

optionofbeingshownthelocationofthebuiltapplicationson

yourharddrive.TheMacintoshversionoftheIDEreferstothis

astheFinder,whichisequivalenttoWindowsExploreronthe

PC.

Asecondoptionistoshowmultiplecompileerrors.



Debugger

Thedebuggeristhetoolthathelpsyoutrackdownerrorswith

yourapplication.Youwillneedtogetintimatelyinvolvedwith

thedebuggereventually.REALbasichasanexcellentdebuggerit

isextremelyeasytouse.BecauseREALbasicallowsyouto

compileapplicationsforthreeplatforms,therearetimeswhen

youwillwanttobeabletodebugtheWindowsversionofyour

application,eventhoughyouarewritingthecodeonyour

Macintosh,orperhapstheotherwayaround.TheProfessional

EditionofREALbasicallowsyoutocompileapplicationsforall

platforms,buttheIDErunsonlyontheplatformyoupurchased

itfor.

Youcansetuptheinformationyouneedtobeabletodebug

appsrunningonothercomputershere.Seethesectiontitled

"Debugger"laterinthischapterformoreinformation.



Printing

Printingis...well...let'sjustsaythatthere'snotalotyoucando

withtheprintingfeaturesofREALbasic.Abouttheonlything

youcandoisdecidewhichfonttousewhenprintingyour

sourcecode.



FindandReplace

ThenewfindandreplaceWindowprovidesamuchbetterway

ofsearchingthroughyourcodethaninthepreviouseditionof

REALbasic.

Inthedefaultlayout,asearchboxappearsontheMain

Toolbar.Clickthemagnifyingglassicontonarrowyoursearch

totheentireproject,theitem,orthemethod.Itemmeansthe



currentlyactiveclassormodule.

AmorepowerfulinterfacecanbefoundundertheEditmenu.

GotoEdit,Find,Findandselect.Adialogboxappears,with

anEditFieldtoenteryoursearchcriteriaand,ifapplicable,a

fieldtoenterthereplacevalue.

Twonewfeaturesofnotearethatthesearchsavesrecent

searches,whichareaccessiblebyclickingtheBevelButton

decoratedwithastopwatchicon.NexttothatistheFavorites

BevelButton,signifiedwithahearticon.

Youcansearchforthewholeword,matchcase,oruseregular

expressions.Whenmatchingthewholeword,REALbasicwill

matchonlywhenacompletewordmatcheswhatissearched

for.Inotherwords,ifyousearchfortheword"for,"itwillmatch

only"for"andnot"ford."MatchingcasesmeansthatREALbasic

willpayattentiontouppercaseorlowercasewhenmatching

words,andwilltreat"mark"asdistinctfrom"Mark."

Afterthesearchtermisentered,youhavetheoptionoffinding

thefirstoccurrence,oroffindingalloccurrences.Theresultsof

theFindAllsearchwillappearinaSearchtabandwillbe

listedalongwithinformationaboutthetypeofmatch,thefully

qualifiednameofthememberinwhichthematchoccurred,and

thematchitself.AtthebottomofthislistisaReplacefield,

whichallowsyoutodoasearchandreplaceagainstthe

selectedmatcheditems.

IftheSearchResultstabisalreadyupandyousearchinthe

searchfieldintheMainToolbar,thesearchwilldefaulttoa

FindAllsearch.

Supposeyouhaveasinglemethodthatiscalledfromseveral

placesinyourcodeandyoudecidethatinsteadofonemethod,

youwanttwomethods.Youcansearchforthemethodname,

findingalloccurrencesofitsuse,andthenyoucanselectthe

onesyouwanttochangeandreplacetheoldnamewiththe



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

Chapter 5. Designing a Desktop Application

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

×