Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
ShubaNarasimhan
h0352854
JavaProgrammingPractical,WS2005/2006
BusinessInformationTechnology
Dr.MichaelHahsler
Contents
1ProblemDescription...
Page
2
2ProblemAnalysis,DesignandImplementation.
2.1 AnalysisFlowChart....
2.2 UMLUsecases.....
2.3 ClassDiagramsandDescriptions..
2.4 SequenceDiagrams....
16
InstallationandUse....
18
Maintenance...
29
Conclusion..
30
Bibliography....
31
ProblemDescription
Concept
Theconceptofthisprojectistocreateaprogrammethatallowsindividualstocreateandmaintainastock
portfoliocomposedofsharesfromavirtualstockmarketwithoutanyfinancialcommitment.Thisexercisein
tradingsharesoverasimulatedstockmarketisintendedtoprovidepracticeforbeginnersinterestedinstock
markets.
Goal
Thegoalofthisprojectistocreateandimplementastocktradinggame,whichsuccessfullysimulatesasimple
portfoliomanagerandiscapableofthefollowingfunctions:
Displayingastockmarketthatcontinuouslyupdatesitsdisplaydata(socalledChristmastree
application)
Openingandmaintainingaportfoliothataccuratelytrackschangesinthemarket
Buildingaportfoliofromachoiceofdifferentshares
Investinginshares
Sellingshares
Increasing/decreasingavailablebalance
Calculatingprofit/loss
Moreover,acomprehensivegraphicaluserinterface(GUI)isintendedtoprovideoptimaldisplayofdatawhilealso
simplifyingcommunicationbetweentheuserandthesoftware.
ProposedSolution
Inordertoformulateanappropriatesolutionthatwouldrealisetheaboveconcept,itisvitaltoconsiderthetime
framewithinwhichtheprojectistobefinished,whichinthiscaseisapproximately12weeks.
Hence,forthesakeofmaintainingsimplicity,theprogrammeistobeinitiallyimplementedasasingleperiod
modelwiththepossibilityofonlyoneuser.Thiscouldlaterbeextendedtoaccommodateadditional
functionalities.
TheprojectiscreatedandimplementedinJavaalongguidelinesprovidedbyObjectOrientedProgramming
(OOP).
2
ProblemAnalysis,DesignandImplementation
2.1
Inordertounderstandthespecificrequirementsofsuchaprogramme,asimpleflowchart
demonstratingthethoughtprocessofauserwascreated:
2.2
Thischartwasconsequentlyusedtodeterminetheusecasestobeimplementedinthisproject:
2.2
UseCaseDescriptions
UseCaseName
Personincharge
Priority
Set/Changeavailablebudget
PreConditions
JREhasbeeninstalledtorunprogramme
Programmeisactivated
Anewportfolioisbeingorhasbeencreated
Portfolioframeisopen
Stockmarketdisplayisopen
UserclicksthebuttonCreatePortfolio,AddBalanceorWithdrawBalance
PostConditions
Trigger
Nonfunctional
Boundaryconditions
NormalFlow
Error
Result
Notes
Unclarifiedpoints
UseCaseName
Personincharge
Priority
Openprogramme>createnewportfolio>specifybalancetostartwith>open
portfolio>addorwithdrawbalancebyclickingtherespectivebuttons
Userdoesnotsupplyanumbervariableasamount
Userwishestowithdrawmorethanhisaccountbalance
BalanceupdatedaccordinglyORerrormessagedisplayed
NOTE:Negativebalancenotpermitted
Viewsharesavailablefortrade
PreConditions
PostConditions
Trigger
Nonfunctional
Boundaryconditions
NormalFlow
Error
Result
JREhasbeeninstalledtorunprogramme
Programmeisactivated
Stockmarketframeisopen
Stockmarketframeisopen
Useropensapplication
Openapplication>stockmarketdisplaywithalistofallavailablesharesis
opened>Usermaximises/minimiseswindow
Applicationisnotstartedproperly
Internalerrorinobtainingdisplaydata
Allsharesavailablefortradearedisplayedinatablealongwiththeir
pricesanddeltas
Notes
Unclarifiedpoints
UseCaseName
Personincharge
Priority
Buyshares(Tradeshares)
PreConditions
JREhasbeeninstalledtorunprogramme
Programmeisactivated
Anewportfoliohasbeencreated
Positiveportfoliobalance
Applicationisopen
Tradedoesnotreduceportfoliobalancebelowzero
UserclicksBuybuttononportfolioframe
PostConditions
Trigger
Nonfunctional
Boundaryconditions
NormalFlow
Error
Result
Notes
Unclarifiedpoints
Openapplication>createnewportfolio>clicktheBuybutton>alistdialog
with all shares available for purchase is shown > choose share > specify
quantity (number) > click SET button > portfolio table appended to display
purchase>displayedportfoliodetailsupdatedtoreflectpurchase
Userdoesnotfeedinanintegervariableasquantity
Portfoliobalanceiszero
Tradewouldreduceportfoliobalancebelowzero
Portfoliotabledisplayspurchasemade
Displayedportfoliodetailsupdatedtoreflectpurchase
ORerrormessagedisplayed
NOTE:Negativebalancenotpermitted
UseCaseName
Personincharge
Priority
Sellshares(Tradeshares)
PreConditions
JREhasbeeninstalledtorunprogramme
Programmeisactivated
Anewportfoliohasbeencreated
Portfoliocontainsoneormoreofthesharetobesold
Applicationisopen
Tradedoesnotreducequantityofshareheldinportfoliotobelowzero
UserclicksSellbuttononportfolioframe
PostConditions
Trigger
Nonfunctional
Boundaryconditions
NormalFlow
Error
Result
Notes
Unclarifiedpoints
Openapplication>createnewportfolio>addsharestoportfolio>clicktheSell
button>alistdialogwithallsharesavailableforsaleisshown>chooseshare>
specify quantity (number) > click SET button > portfolio table appended to
displaysale>displayedportfoliodetailsupdatedtoreflectsale
Userdoesnotfeedinanintegervariableasquantity
Quantityofsharewishedtobesoldequalsorislessthanzero
Tradewouldreducequantityofshareheldinportfoliotobelowzero
Portfoliotabledisplayssalemade
Displayedportfoliodetailsupdatedtoreflectsale
ORerrormessagedisplayed
NOTE:Shortsellingnotpermitted
UseCaseName
Personincharge
Priority
Viewportfolioposition
PreConditions
JREhasbeeninstalledtorunprogramme
Programmeisactivated
Anewportfoliohasbeencreated
Applicationisopen
Useropensanewportfolio(ClicksCreatePortfolio)
PostConditions
Trigger
Nonfunctional
Boundaryconditions
NormalFlow
Error
Result
Notes
Unclarifiedpoints
2.3
Openapplication>createnewportfoliowithstartingbalance>(add/withdraw
balanceORchangeportfoliocompositionORstockpriceschange)>displayed
portfoliopositiondetailsupdatedtoreflectchanges
Portfolioframenotopenedaccordingtoinstructions
Openedportfolioframedisplaysportfoliopositiondetails
ClassDiagramsandDescriptions
PackageStockTrade:
ClassDescriptionsforPackageStockTrade
Thispackagecontainsthefollowingclassesthatimplementthemarketandportfoliostructurebehindthescenes
oftheGUI:
StockMarket(Stringname):Aninstanceofthisclassisastockmarketwhereallthestocksarestoredina
map.Ithasthefollowingfunctionsthatarecritical(usedbyGUItodisplayatableofallavailablestocks):
voidadd(Stockstock):addsstocktostockList
voiddelete(Stockstock):deletesstockfromstockList
StockgetStock(StringstockKey):searchesandreturnsastockfromstockList
HashMapgetStockList():returnsstockList
Stock(Stringkey,Stringname,doubleprice):Aninstanceofthestockclassrepresentsasinglestock
identifiedbyauniquestockkey,whichisthenstoredinastockmarket.Thisclassstoresallinformation
concerningaparticularstock(pricehistory,whichisalistofspotpricesovertime,name,key,delta).The
followingfunctionsareofparticularimportance:
doublegetPrice():returnsthecurrentstockprice
voidsetPrice(doubleprice):setsthepriceforthecurrentdatewhileaddingtheoldpricetopriceHistory
voidupdate(doubledelta):analternativetosetPrice(),thismethodchangesthecurrentpricebyagiven
delta
SpotPricegetSpotPrice():returnsthecurrentSpotPriceforfurthercalculations
GregorianCalendargetDate():returnsthecurrentdate
SpotPrice(doubleprice,Datedate):Thisclasscanonlybeinstantiatedbyastock.Aninstanceofthisclass
hasadateandapriceandisdependantonastockforitsexistence.Ithasthreeconstructorstoallow
flexibility.AnypricechangeundertakenbytheStockclasschangesthepriceinacertainspotprice(ata
givendate).ItsgetPrice()andgetDate()methodsareusedbythecorrespondingmethodsintheclassStock.
MyPortfolio(Stringname,doublebalance):Thisistheheartoftheapplicationandcontainsallfunctionsthat
allowtheusertobuyandsellshares,todepositorwithdrawmoneyandtocalculatethecurrentvalueand
costofauserportfolio.Aninstanceofthisclasshasamapofpositions(indifferentstocks)identifiedbythe
stockkey.Apurchaseorsaleofshareswouldcausethecompositionofthismaptochange.However,
positionsarenevercompletelyeliminatedfromthismap.Evenafterallunitsofastockhavebeensold,the
positionpersistswithaquantityvalueofzero.Theportfolioalsocontainsamapofallitscurrentvalues
(PortfolioValue),whichcouldthenbeusedtocreateatimeseriesgraphofthedevelopmentofitsvalue.
Someofitsmostimportantmethodsareexplained:
Positionbuy(HashMapstockList,Stringkey,intqty):buysthegivenqtyofthesharefortheportfolioand
returnstheresultingposition
Positionsell(HashMapstockList,Stringkey,intqty):sellsthegivenqtyofthesharefortheportfolioand
returnstheresultingposition
voiddeposit(doublebal):increasesportfoliobalancebythegivenamount
voidwithdraw(doublebal):decreasesportfoliobalancebythegivenamount
Position:Thisclasscanonlybeinstantiatedbyaportfolioanddependsontheportfolioforitsexistence.Itis
importanttonotethatonepositioncanonlypointtoonestock(andviceversa).Hence,whennewunitsofan
alreadypurchasedstockarebought,therespectivepositionisupdatedinsteadofcreatinganewposition.A
positionhasalistoftransactions,whichstoresalltransactionsundertakenfortheparticularstockit
represents.Anycurrentvalue/costcalculationsundertakenbytheportfolioaggregatesvaluesthatare
calculatedinitspositions.Ithasfollowingfunctionsthatareofimportance:
doublecurrentValue():returnsthecurrentvalueofaposition
voidupdate(intqty,intid):updatesthecostofapositionandisusedbythebuyandsellmethodsof
MyPortfolio
voidaddTransaction(Transactiontransaction):addsatransactiontoitstransactionlist,whichisthen
usedbytheupdatemethod.
PortfolioValue:AsubclassofSpotPrice,ithassimilarfunctions.Itstoresthecurrentportfoliovalueforagiven
date.Ithasnootherfunctionsandservessolelytobestoredinalist,whichchartsthedevelopmentofthe
portfoliovalue.
Transaction:AlsoasubclassofSpotPrice,atransactionstoresthestockkey,quantitybought/soldofthe
particularstock,andthespotpriceatthemomentofsale/purchase.Itisvitaltothewholestructuresinceany
reductioninportfoliocostrequiresthisinformationinordertobeimplemented.
PackageGUIStockTrade
Pleasenotethatthecomplexityoftheindividualclassespreventsallclassesfrombeingdisplayedindetail.
Moreover,theclassesserveonlytoimplementthemethodscontainedintheStockTradepackage(seeabove).
GUIStockTradeimportsthispackageinordertoaccessitsfunctions.
AdetailedviewofthemostimportantclassesintheGUIStockTradeisprovidedonthenextpage.
10
DetailedviewoftheclassesPortfolioTableSorter(portfoliotable),PortfolioFrame(portfoliowindow),
StockMarketDisplay(stockmarketwindow)andStockTableSorter(stockmarkettable):
OtherclassessuchasListDialogorTableSorterdonotserveanyfunctionalpurpose.Theyexistsolelyforthe
purposeofdecorationorforfeedingdataprovidedbytheuser.Amoredetaileddescriptionofallclassesisgiven
onthenextpage.
11
ClassDescriptionsforPackageGUIStockTrade:
Thispackagecontainsthefollowingclassesthatimplementtheuserinterface:
DisplayData:Thisclassimplementstherunnableinterface.Itinstantiatestherequiredstockmarketsand
providesthedataforthestockmarkettable(StockTableSorter).Italsoimplementsthethreadthatgenerates
randompricechangesobservedinthestocks.Inaddition,thisclasscontainsvarioushelpermethodssuch
asonethatprovidesafancyfont(providedbySunMicrosystems),onethatreturnsasortedarrayofkeysfor
agivenHashMapetc.Thisclassisinstantiatedonlyoncewhilecreatingthestockmarkettable.Mostofthe
methodsandvariablesinthisclassarestatic.
StockMarketDisplay:Thisisthefirstwindowtoconfronttheuserwhentheapplicationisrunandcontainsthe
mainmethodfortheapplication.Itinstantiatesallthecomponents(containers,buttons,dialogs)thatmakeup
thestockmarketinterfaceanddisplaysthestockmarkettable.Italsocreatesanewportfoliowindowwhen
theappropriateactionistaken.Boththestockmarketandtheportfolioarecreatedasinternalframesnested
inadesktopframe.
PortfolioFrame:PortfolioFrameisasubclassofJInternalFrame.ThisistheheartoftheGUIandisthesecond
windowtobecreated(whenusercreatesaportfolio).Accordingly,itismoreinvolvedthanthe
StockMarketDisplay.Itimplementsallfunctionsrequiredoftheportfolioandcreatesalltheassociated
components.Itsuppliestheinformationrequiredtocreatetheportfoliotable(PortfolioTableSorter)and
displaysit.Inaddition,itdisplaysthecurrentstatusoftheportfolio,allowstheusertobuyandsellstocks,to
depositorwithdrawmoneyandtoobtainstockmarkettips.
StockTableSorter:ThisisactuallyasubclassofJPanelthatcontainsatableusingacustomtablemodel.The
tablemodelimplementstherunnableinterfaceandobtainsitsdatafromDisplayData(thisistheonlyclass
thatinstantiatesDisplayData).Itrunsthethreadthatpublisheschangestostockpricesgeneratedbydisplay
data.
PortfolioTableSorter:AlmostidenticaltotheStockTableSorterwiththeonlyexceptionthatitsdataisprovided
bytheportfolioframe(i.e.,bytheuser).Itimplementsathreadthatreflectsthechangestakingplaceinthe
stocktableintheportfoliotable.
TableSorter:ThisclassisasubclassoftheAbstractTableModelandisprovidedbySunMicrosystems.Ithas
thesolepurposeofdecorationandisusedtosortthestockmarketandportfoliotables.Thisisdoneby
insertingatablesorterbetweenatableanditstablemodel.Thisapplicationusesthetablesortertoallow
theusertosortthestockmarketandportfoliotablesbyanychosencolumnparameter.
InputDialog:Thisclassallowstwotypesofinputdialoguestobecreated(withoneortwotextfields)
accordingtothespecifiedrequirements.Itsonlyfunctionistodeliverdatasuppliedbytheuser.Bothstock
marketandportfoliowindowsuseit.
ListDialog:AlmostidenticaltoInputDialogwiththeexceptionthatithasonetextfieldandonelistfromwhich
theuseristochooseanappropriateoption.Itisusedbytheportfolioframetoimplementitsbuyandsell
methods.
12
2.4
SequenceDiagrams(forthemethodsbuyandsellfromthepackageStockTrade;foradetailed
viewofboththediagramsseefilesSequenceDiagBuyandSequenceDiagSell)
voidbuy(HashMapstockList,StringstockKey,intqty)
13
voidsell(HashMapstockList,StringstockKey,intqty)
14
3InstallationandUse
15
TheinstallationanduseofthisapplicationonacomputerrequirestheJRE(1.4upwards)tobeinstalledonthis
computer.Theapplicationismadeavailableasa.jarfile,whichcanbedownloaded.Inordertorunthe
application,theuserneedstoopen/runjarfile.Thiscanbedoneby:
doubleclickingthefileiconinaWindowsoperatingsystem
orbyopeningacommandwindowandissuingthefollowingcommandline:
javajarportfolioManager.jar
Itisimportanttoaccessthefilefromthefolderinwhichitissaved.
Uponopening,thefollowingwindowisdisplayed.Thisisthestockmarket:
Tosortthestockmarkettable,clickanychosencolumnheader
16
Tocreateaportfolio,clicktheCreatePortfoliobutton.Enternameandthebalancetostartwithinthe
CreatePortfoliodialogbox:
Anewportfoliowindowiscreatedandtheusercanbegintransactinginshares:
17
Tobuyshares,clicktheBuySharebutton.Chooseashareandenterthenumberofsharesyouwishtobuy:
18
Uponpurchase,theportfoliotableaswellastheportfoliopositiondetailsareupdated:
19
Similarly,tosellshares,clicktheSellSharebutton.Chooseashareandenterthenumberofsharesyou
wishtosell:
20
Uponsale,theportfoliotableaswellastheportfoliopositiondetailsareupdated:
21
Toaddtoaccountbalance,clicktheAddBalancebutton.Enteramounttobeadded:
22
Upondeposit,theportfoliopositiondetailsareupdated:
23
Towithdrawmoney,clicktheWithdrawBalancebutton:
24
Uponwithdrawal,portfoliobalanceisupdatedinasimilarfashiontothedepositprocedure
Inordertoobtainmarkettips,clicktheMarketTipsbutton:
25
Toexitapplication,clicktheExitApplicationbuttonorclosewindow.
4Maintenance
Theapplicationasitcurrentlyexistsrequiresnoexplicitmaintenancesincechangesinpricesarerandomly
generatedanditsasingleperiodmodelforasingleuser.
However,shouldthisapplicationbedevelopedintoafullfledgedportfoliomanager,incorporatingalargernumber
ofstocksandrealtimesharedata,maintenancewouldbecomeanintegralpartoftheapplication.Following
pointsaretonotewhilefurtherdevelopingthismodel:
26
Duetothelargenumberofcollectionsandhencethelargevolumeofdatainthisapplication,itisimportant
toefficientlyorganisethedatarequiredtobedisplayedandupdatedinthetables.Thecurrentmodeldoes
notallowforlargevolumesofdatatobeupdatedquickly.Analternativewouldbetoassignhashcodesto
eachrowdatasothatspecificrowscanbeupdatedwithoutscanningthewholelist.
Itisimportanttorecognisewherethedataiscomingfrom.Ifitisbeingsourcedfromaninternetresource
(suchasthewebsiteofastockmarket),dataneedstobecheckedonaregularbasis.
Additionalfunctionssuchasmultiplestockmarketsandmultipleuserswouldaccordinglymultiplythe
maintenancerequired.
5Conclusion
Initially,theprojectwasconceivedtoprocessrealtimesharedata,providegraphsandimplementaSerializable
interfaceinordertosavepersonalsettings.However,theprojectwasscaleddowntoreflecttherealistictime
commitmentpossible(thetimetocompletionneededtobecompletedinapproximately140hours,assuming11
productivehoursaweeks)andpreventedmanyofthemoresophisticatedfunctionalitiesfrombeingimplemented.
Inspiteofthedownscaling,thetimetocompletionwasunderestimated
Noformalmodel(suchasCOCOMO)wasusedtoestimatethetimerequiredforprojectcompletion.Sinceno
finishedprojectcouldbeusedasanexample,estimatinglinesofcode(LOC)wouldhaveproventobevery
erroneous(thisisespeciallytrueoftheGUI).Hence,itisuncertainwhethersuchamodelwouldhavehelpedto
finishtheprojectontime.
Theprojectitselfwasimplementedasaniterativeprocessandwouldmostcloselyresemblethespiralmodel.
Thisismainlyduetothelearningcurveinvolved.
Implementingthecoremodel(analysis,designandimplementationforStockTrade)requiredonly50hourswhile
thetimeexpectedforitsimplementationwas60hours.
ImplementingtheGUI(analysis,designandimplementationforGUI)required80hours(i.e.,30hoursmorethan
expected).Thiswasmainlyduetothelackofexperiencewithuserinterfacesandhence,steeplearningcurve
involved(mostofthecodeisselfwritten).
27
Integrationandtestingwasfairlysimplegiventhattheprojectwasimplementedasaniterativeprocesswith
integrationandtestingtakingplaceaftereachstep.Accordingly,thefinalintegrationandtestingrequiredonly15
hours(5lessthanplanned).
Thedocumentationrequiredafurther20hours(expected:10hours).Thiswasmainlyduetoadministrative
problemswithdifferentdrawingtoolsandmodellingpackages.
Theprojectcanbesummedupasfollows:
Process
PackageStockTrade(Analysis,Design,
Implementation)
PackageGUI(Analysis,Design,
Implementation)
IntegrationandTesting
Documentation
Total
ExpectedTimein
Hours
60
IncurredTimeinHours
Difference
50
10
50
80
30
20
10
140
15
20
165
5
10
25
Hence,theprojectoverranby25hours;assuming11productivehoursaweek(12weeks)andhencearound1.6
hoursaday,theprojectrequiredaround16daysmorethanscheduled.Itshouldalsobenotedthatinspiteofthe
overrun,manyofthefunctionalitiesconceivedatthestartwerenotimplemented.Thisismainlyattributableto
lackoftimeandtherequiredexpertise.
6Bibliography
Hahsler,M:LectureslidesforIntroductiontoJavaProgramming,http://wwwai.wu
wien.ac.at/~hahsler/JAVA/
Hahsler,M:LectureslidesforJavaProgrammingPractical,
http://wwwai.wuwien.ac.at/~hahsler/JAVA_praktikum/
SunGUITutorial:http://java.sun.com/docs/books/tutorial/uiswing/
Stockmarketexample:http://www.java2s.com/ExampleCode/Swing
JFC/AnapplicationthatdisplaystockmarketdatainaJTable.htm
Violet,SandWalrath,K:ChristmasTreeApplications:HowtoCreateFrequentlyUpdatedJTablesthat
PerformWell,http://java.sun.com/products/jfc/tsc/articles/ChristmasTree/
ClassTableSorter(packageGUI)Source:http://java.sun.com/docs/books/tutorial
MethodgetAFont()inDisplayData(PackageGUI)Source:http://java.sun.com/docs/books/tutorial
28