You are on page 1of 42

CSE219MidtermReviewMaterial

Software Development Cycle


__________________________________________________________________________

Whichpropertiesmakeasoftwaresystemhighquality?
correctness,efficiency,easeofuse,reliability/robustness,maintainability,modifiability,
extensibilityandscalability.

MemorizetheSoftwareDevelopmentLifecyclechart

Otherstepstoconsider:SoftwareIntegration,SoftwareMaintenance
SoftwareMaintenance:followsdeployment,monitoringandupdatingdeployedsoftware
UpdatedSoftwareDevelopmentLifecycle:
1) RequirementAnalysis
2) Design
3) EvalueDesign
4) Code
5) Test,Debug,&ProfileComponents
6) Integrate
7) Test,Debug,&ProfileWholeProgram
8) Deploy
9) Maintain
*Notethattherearemanyvariationtothesesteps*

Whatisaframework?

Frameworkismanyclassesworkingtogetherthatcooperatetogethertobuildnew
applicationsandotherframeworks.Frameworkdevelopersmustexplainhowtousethem
throughAPI,commentingandtutorials.

Revision Control
__________________________________________________________________________

Revisioncontrol(alsoknownasversioncontrol,sourcecontrol,andsourcecode
management)isthemanagementofchangestodocuments,computerprograms,largeweb
sites,andothercollectionsofinformation.Helpskeepahistoryofchangesforindividualsand
teamstoshareanddistributecommonsourcecode.

VersionControlsystemServices
BackupandRestore,Synchronization,shorttermundo,Longtermundo,TrackChanges,
TrackOwnership,Sandboxing,Branchingandmerging.

Backupandrestorefilesaresavedastheyareedited.Onecanjumptoanymomentintime.
Synchronizationletsdeveloperssharefilesandstayuptodatewiththelatestversioneven
whiledevelopersareworkingsimultaneously.
ShorttermUndoallowstogobacktothelastknowngoodversioninthedatabase.
LongtermUndoforparticularlybadmistakestogobacklikeayearintimetofixabug.
TrackChanges,asfilesareupdatedyoucanleavecommentsastowhythechange
occurred.Thismakesiteasytoseehowafileisevolvingovertime,andwhy.Developers
shoulddocumentalmosteverychangetosourcecode.
TrackOwnership,aVCStagseverychangewiththenameofthepersonwhomadeit,
date/timeofchange.
Sandboxing,Insuranceagainstyourself,youcanmaketemporarychangesinanisolated
areaandtestandworkoutthekinksbeforecheckinginyourchanges
BranchingandMerging,Alargersandbox,youcanbranchacopyofyourcodeintoa
separateareaandmodifyitinisolation.Trackingchangesseparately.Lateryoucanmerge
yourworkbackintothecommonarea.

SetupTerms
Repository(repo):Thedatabasestoringthefiles.
Server:Thecomputerstoringtherepository
Client:Thecomputerconnectingtotherepository
WorkingSet/WorkingCopy:Yourlocaldirectoryoffiles,whereyoumakechanges.
Trunk/Main:Theprimarylocationforcodeintherepository,mainlineinatreeofcode.

BasicActions
Add:putafileintotherepositoryforthefirsttimetobegintrackingitwithversioncontrol
Revision:Whatversionafileison
Head:thelatestrevisionintherepository
Checkout:Downloadafilefromtherepository
Checkin:Uploadafiletotherepository(ifitchanged)
CheckinMessage:Ashortmessagedescribingwhatwaschanged
Changelog/History:Alistofchangesmadetoafilesinceitwascreated
Update/Sync:Synchronizeyourfileswiththelatestfromtherepository,thisletsyougrabthe
latestrevisionsofallfiles.
Revert:Throwawayyourlocalchangesandreloadthelatestversionfromtherepository.

AdvancedActions
Merge:Applythechangesfromonefiletoanother,tobringituptodate.Wecanmerge
featuresfromonebranchintoanother.
Conflict:Whenpendingchangestoafilecontradicteachother,bothchangescannotbe
applied.
Resolve:Fixingthechangesthatcontradicteachotherandcheckinginthecorrectversion.
Locking:Takingcontrolofafilesonobodyelsecanedititunityouunlockit.
BreakingtheLock:Forciblyunlockingafilesoyoucaneditit.
Checkoutforedit:Checkingoutaneditableversionofafile

TypesofVCSs
RCS:RevisionControlSystem,deadasastandalonesystem
CVS:ConcurrentVersionSystem,dyingnow.
Subversion:KillingCVS,opensourceunderApacheLicense.
Distributed/Decentralizedrevisioncontrol:GitandMercurial.Theyallowtheusertokeeptrack
ofsoftwarerevisionsandalsoallowmanydeveloperstoworkonaprojectfromdifferent
networks.
GNUBazaar
BitKeeper

GITCommonOperations
Settingupagitrepository
gitinit:initializesanewGitrepository.(firstcommandthatneedstobecalled)
gitclone?location:createsacopyofanexistingGitrepository.
gitadd?file:moveschangesfromtheworkingdirectorytothestagingarea.
gitcommit:takesthestagedsnapshotandcommitsittotheprojecthistory
gitpull:downloadsabranchfromaremoterepository,thenimmediatelymergesitintothe
currentbranch.
gitpush:movesalocalbranchtoanotherrepository.

_______________________________________________________________________

Graphical User Interfaces JavaFX GUI Basics


_________________________________________________________________
HowdoGUIswork?Theysimplyloopandrespondtoevents.
AGUIFrameworkprovidesreadymadevisible,interactive,
customizablecomponentsthatyouwouldntwanttohaveto
codeyourownwindow.

BasicStructureofJavaFX
javafx.application.ApplicationistheentrypointforJavaFX
applications.JavaFXcreatesanapplicationthreadfor
runningtheapplicationstartmethod,processinginput
events,andrunninganimationtimelines.
Overridethestart(stage)method!
javafx.stage.StageisthetoplevelJavaFXcontainer,the
primarystageisconstructedbytheplatform.
javafx.scene.Sceneclassisthecontainerforallcontentin
ascenegraph.
javafx.scene.Nodeisthebaseclassforscenegraphnodes

BindingProperty:enablesatargetobjecttobeboundtoasourceobject.Ifthevalueinthe
souceobjectchanges,thetargetpropertyisalsochangedautomatically.thetargetobjectis
simplycalledabindingobjectorabindingproperty.

**AGUIautomaticallykeepsitsdisplaysynchronizedwiththeapplicationsunderlyingdata:
abindingobservesitslistofdependenciesforchanges,andthenupdatesitselfautomatically
afterachangehasbeendetected**
/*TheStackPanelayoutpaneplacesallofthenodeswithinasinglestackwitheachnew
nodeaddedontopofthepreviousnode.Thislayoutmodelprovidesaneasywaytooverlay
textonashapeorimageandtooverlapcommonshapestocreateacomplexshape.*/
JavaFXExternalCSSstylefile:
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm())
LayoutPanes:JavaFXprovidesmanytypesofpanesfororganizingnodesinacontainer.


Event Programming
_________________________________________________________________
Foreachcontrol(button,combobox,etc.)wedefineaneventhandlerthatissimplyan
eventlistener.
AneventsourceisaGUIcontrolsuchasJButton,JComboBox,etc.Itcanregister
differenttypesoflisteners(handlers).
Whentheuserinteractswithacontrol(source):
aneventobjectisconstructed
theeventobjectissenttoallregisteredlistenerobjects
thelistenerobject(handler)respondsasyoudefineditto
YoucustomizetheresponseofaneventhandlerthroughInheritanceand
Polymorphism.
KindsofEventandListenerObjects
Differenteventsourcescanproducedifferentkindsofevents
ActionEvent(sentbyJButtonandothercomponents)
MouseEvent(sentbyJpanelandothercomponents)
Differentlistenerobjectsimplementdifferentrequiredmethodsfrominterfaces
ActionListener(actionPerformed)
MouseListener(mouseClicked,mouseEntered,mouseExited)
GUIDesignPattern
1)declareallGUIcontrolsasinstancevariables
2)Constructandarrange(layout)controls
3)Defineanclassforeachtypeofeventtobeyourlistener
4)Declareoneinstanceofeachhandlerasinstancevariables
5)Constructyourhandlerobjectsandgivethemwhattheyneed
6)RegisteryourhandlerswithyourGUIcontrols
ActionListenerInterface
Singlemethodintheinterface
publicvoidactionPerformed(ActionEvente)
TheActionEventclasshasmethodstogetinformationabouttheevent
publicObjectgetSource()
publicStringgetACtionCommand()
EventHandlingSummary
Specifyaclasstoimplementalistenerinterface,implementsActionListener
Codethatimplementsthemethodsofthelistenerinterface,publicvoid
actionPerformed(ActionEvente){..}
Codethatregistersalistenerobjectonaneventsource
cutButton.addACtionLister(this)

Internet Web Pages, HTML and Java Swing


_________________________________________________________________

<html><Thisisthehtmltageveryhtmlpagehasone
<h1>heading,<p>paragraphtag
<h1id=header_id_1><youcanidentifytags
<tableborder=3>
<tr>
<td>..</td>
<td>..</td>
<td>..</td>
</tr>
</table>

HTMLwithJavaSwing

JButtonb1=newJButton("<html><b><u>T</u>wo</b><br>lines</html>")

b3=newJButton("<html><center><b><u>E</u>nable</b><br>"
+"<fontcolor=#ffffdd>middlebutton</font>",
rightButtonIcon)

LoadafileintoaHTMLDocumentobjectby
1)parsingthefile2)loadtheStringintoaeditorPane,3)thensetthetextofthepannel:
myEditorPane.setText(htmlText)

gettheHTMLDocumentfromthepannel:
doc=(HTMLDocument)test.myEditorPane.getDocument()
getHTMLelements:headerElement=doc.getElement("header_id_1")
setnewHTMLhtmlInnerString="<spanstyle=\"color:red\">thisish1</span>"
setthenewHTMLcodeinSWING:doc.setInnerHTML(headerElement,htmlInnerString)

Threads
_________________________________________________________________

WeusethreadsthatwedefinetomultitaskanduseathreadschedulethattheJVM
providesforus.
todefineyourownthreadsExtendjava.lang.Thread
youmakeyourthreadsrunnablei.e.startthem.Javasthreadschedulerdecidesthe
order.
newstate,notyetstartedthreadobject,notyetknowntothreadschedulernot
runnableasofyet
Newtorunnabletransition
Constructedthreadisstarted,callstartmethodonit,therecanbeseveral
threadsinthisstate.
RunnabletoBlockedTransition
Runnablethreadmadeunrunnable
callsleepmethodonitforXmillisecondsdirectlyorwithalockmethod
Cannotbescheduled
Again,theremaybemanythreadsinthisstate
Blockedtorunnabletransition
Unrunnablethreadmaderunnable
sleeptimeexpiresandisnotrenewed.unlockmethodensuresthis.
Canbescheduled
RunnabletoDeadtransition
Runmethodcompletes,cannotberescheduled.AdeadthreadisDead.
CallisAlivetotakeapulse.

start()
makesthethreadrunnable,callstherunmethod.Threadclassmethodalready
doesthis,ifyourclassextendsThreadyoudonthavetodefinestart.
run()
exectuedwhenathreadisstarted(withthemethodstart())
run()iswherethethreadworkisdone
theThreadsuperclassrunmethoddoesnothing
ifyourclassextendsThreadyoumustdefinerun()tospecifywhat
workyourthreadwilldo.
AnInterruptedExceptionisthrownwhenathreadiswaiting,sleeping,orotherwise
occupied,andthethreadisinterrupted,eitherbeforeorduringtheactivity.
Runnableinterface
has1method:run()
Alternativethreadingapproach:useimplementsRunnableANDdefinerun()
Staticyield()methodtemporarilyreleasestimeforotherthreads.
Sleep(longmillis)methodputsthethreadtosleepforthespecifiedtimeinmillis.
isAlive()
returnstrueifitisintheReady,Blocked,orRunningstate
returnsfalseifathreadisnewandhasnotstartedofitisfinishedinterrupt()
Theinterrupt()methodinterruptsathreadinthefollowingway:Ifathreadis
currentlyintheReadyorRunningstate,itsinterruptedflagissetifathreadis
currentlyblocked,itisawakenedandenterstheReadystate,andan
java.io.InterruptedExceptionisthrown.
TheisInterrupt()methodtestswhetherthethreadisinterrupted.
ThreadPriority
eachthreadisassignedadefaultpriorityofThread.NORM_PRIORITY
youcanresetthepriorityusingsetPriority(intpriority)
TomakeourframemultithreadedweimplementRunnable
GUIeventhandlingandpaintingcodeexecutesineventdispatchthread
Thisensuresthateacheventhandlerfinishesexecutingbeforethenextoneexecutes
andthepaintingisntinterruptedbyevents.
Killingathread
dontusestopmethod,letathreadkillitselfusingyourowninstancevariable
bymakingitaloopcontrolforrun
Forcountingusethreadorjava.util.Timerinstancetodothecounting
TimerTaskclass,weuseruntooverridetheworkdonebythethreadthatexecutesit.

Stacks vs Heap
_________________________________________________________________

Stack
Managedautomatically.
Stackvariablesonlyexistwhilethefunctionthatcreatedthem,isrunning
Heap
notmanagedautomaticallyforyou
youmustallocatethememoryontheheapyourself
doesnothavesizerestrictionsunlikethestack
variablescanbeaccessedglobally

Object Oriented Programming


_________________________________________________________________
text/codesegment
containsexecutableinstructions
GlobalSegment
datathatisreservedatcompiletime,containsglobalvariablesandstatic
variablesthatareinitializedbytheprogrammer.
datasegmentisreadwrite,sincethevaluesofthevariablescanbealteredat
runtime.
Stacksegment
temporaryvariablesdeclaredinsidemethods,methodarguments.Removed
frommemorywhenamethodreturns.
Heapsegment
fordynamicdata(wheneveryouusenew)
dataforconstructedobjects

>>>>>>
Javahasautomaticmemorymanagement
Asuserswemustknowhowtowriteoutprograms:
Callbyvalue:
thevalueiscopiedfromarguments(actualparametersintoreal
parameters)
Thereferencevariables(classinstances)containtheaddressofthe
objectontheheap.
Types
javaisstronglytypedlanguage,compiledcodeisguaranteedtobetypesafe
exceptforclasscasting
Typeabstraction
Thecomparableinterfaceprovidesastandardmeansforcommunicationwih
yetunknowntypesofobjectsusingcompareTo
ApparentvsActualType
Apparenttype
thetypeanobjectwasdeclaredas.Thecompilercaresabouthistype
Actualtype
typeanobjectwasconstructedas.theJVMcaresaboutthistype.
Personp=newStudent()
Apparent(left)Actual(Right)
declaredconstucted<<typeofvariable
compilerJVM<<whocares
Apparentvs.Actual
Apparentdatatypeofanobject,determineswhatmethodsmaybecalled
Actualdatatypedetermineswheretheimplementationofacalledmethodis
defined
JVMlooksfirstinactualtypeandworksitswayup.
Dynamicbinding
Dynamicbinding:isacomputerprogrammingmechanisminwhichthemethod
beingcalleduponanobjectislookedupbynameatruntime.
Callbyvalue
Javamethodsalwaysusecallbyvalue:
methodargumentsarecopiedwhensent
thisincludesobjectids
Interfaces
specifyabstractmethods
methodheaderswithnobodies
publicinterfaceEventHandler<Textendsevent>{
publicvoidhandle(Tevent)}
AclassimplementsEventHandlermustdefinehandle
elseasyntaxerror
SojavaFXknowntocallyoureventhandlershandle

AbstractClasses
canspecifyabstractandconcretemethods
An abstract method is that method which have only the initialization of
the method. only method name and its parameters. An abstract method
is in the abstract class with the "abstract" keyword.
While a concrete method is those method which is with the
implementation. means with definition.
Any class that extends an abstract class:
guarantees it will define all abstract methods
Interfaces/Abstract classes & Polymorphism
Objects can have an apparent type of
A concrete class
An interface
An abstract class
Objects can never have the actual type of an interface or abstract
class.
Interfaces/Abstract classes & Polymorphism

INTERFACES ABSTRACT CONCRETE CLASSES

HAVE INSTANCE VARIABLES Y Y

HAVE STATIC VARIABLES Y Y

HAVE STATIC FINAL CONSTANTS Y Y Y

HAVE CONSTRUCTORS Y Y

HAVE ABSTRACT METHODS Y Y

HAVE CONCRETE METHODS Y Y

CAN BE CONSTRUCTED Y

Staticsvs.NonStatic
Staticmethodsandvariablesarescopedtoaclass
onestaticvariableforallobjectstoshare
Nonstatic(object)methodsandvariablesarescopedtoasingleobject.
eachobjectsownsitsnonstaticmethodsandvariables.
Canastaticmethod
directlycallanonstaticmethodinthesameclasswiththe.NO
directlycallastaticmethodinthesameclass?Yes
directlyreferenceanonstaticvariableinthesameclass?No
directlyreferenceastaticvariableinthesameclass?True

Cananonstaticmethod
directlycallanonstaticmethodinthesameclasswiththe.Yes
directlycallastaticmethodinthesameclass?Yes
directlyreferenceanonstaticvariableinthesameclass?Yes
directlyreferenceastaticvariableinthesameclass?Yes
Inheritance
whenaclassisinherited,itgetsthemembers(fields,methods,andnested
classes)fromitssuperclassbutnotConstructors.Buttheconstructorofthe
superclasscanbeinvokedfromthesubclass.
AbstractClass
Anabstractclassisaclassthatisdeclaredabstractitmayormaynotinclude
abstractmethods.Abstractclassescannotbeinstantiated,buttheycanbe
subclassed.
Anabstractmethodisamethodthatisdeclaredwithoutanimplementation
(withoutbraces,andfollowedbyasemicolon),likethis
abstractvoidmoveTo(doubledeltaX,doubledeltaY)
Ifaclassincludesabstractmethods,thentheclassitselfmustbedeclared
abstract.
Whenanabstractclassissubclassed,thesubclassusuallyprovides
implementationsforalloftheabstractmethodsinitsparentclass.
WhatisanInterface?
Aninterfaceisagroupofrelatedmethodswithemptybodies
Abicycle'sbehavior,ifspecifiedasaninterface,mightappearasfollows:
interfaceBicycle{

//wheelrevolutionsperminute
voidchangeCadence(intnewValue)

voidchangeGear(intnewValue)

voidspeedUp(intincrement)

voidapplyBrakes(intdecrement)
}
Toimplementthisinterfaceaparticularclassmustimplementit
classACMEBicycleimplementsBicycle{
Implementinganinterfaceallowsaclasstobecomemoreformalaboutthebehaviorit
promisestoprovide.Interfacesformacontractbetweentheclassandtheoutsideworld,
andthiscontractisenforcedatbuildtimebythecompiler.Ifyourclassclaimstoimplement
aninterface,allmethodsdefinedbythatinterfacemustappearinitssourcecodebeforethe
classwillsuccessfullycompile.
Method overloading in Java occurs when two or more methods in the same class have the
exact same name but different parameters (remember that method parameters accept values
passed into the method).
Method overloading in Java occurs when two or more methods in the same class have the
exact
same
name
but

different parameters (remember that method parameters accept values passed into the
method).
Overriding methods is completely different from overloading methods. If a derived class
requires a different definition for an inherited method, then that method can be redefined in
the derived class.
Modifiers Accessibilities ^^

Binary I/O
_________________________________________________________________
Atextfileconsistsofasequenceofcharactersandabinaryfileconsistsofa
sequenceofbits.
BinaryI/Odoesnotrequireconversions:whenyouwriteabytetoafile,theoriginal
byteiscopiedintothefile,andwhenyoureadabytefromafile,theexactbyteinthe
fileisreturned.
TheSerializableInterface
notallobjectscanbewrittentoanoutputstream
Objectsthatcanbewrittentoanobjectstreamissaidtobeserializable.a
serializableobjectisaninstanceofthejava.io.Serializableinterface(sothe
classofaserializableobjectmustimplementSerializable).
theSerializableinterfaceisamarkerinterface:hasnomethods,soyou
donotneedtoaddadditionalcodeinyourclassthatimplements
Serializable.
TransientKeyword
youcantellJVMtoignorecertaindatafieldswhenwritingtoobjectstream.
RandomAccessFileclassallowsafiletobereadfromandwritetoatrandom
locations
Arandomaccessfileconsistsofasequenceofbytesandthereisaspecialmarker
calledfilepointerthatispositionedatoneofthesebytes

PROPERTIES OF HIGH QUALITY SOFTWARE


_________________________________________________________________
Correctness:doestheprogramperformitsintendedfunction
Efficiency:wiselychooseyourdatastructuresandalgorithms
Easeofuse:easyguiforuser,appealingandforivingofusermistakes
Reliability/Robustness:doesittakeoferrors
Feedback:providefeedbacktoendusersdueto:badinput,missingfiles,etc.
Flexibility:tellswhenthingsgowrong
Reusability:codecanbeusedforanotherproject
Extensibility:caniteasilybeextended
Scalability:increasingsizeofproblemorsizeofusers

GENERICS
_________________________________________________________________

Itisbettertogetacompilingwarningthanaruntimeerror!
Genericsisthecapabilitytoparameterizetypes,basicallytellingwhattypeofthingsto
store.Forexampleastackobjectforholdingstrings.
Benefitofgenericsistoenableerrorstobedetectedatcompiletimeratherthen
runtime.
ifyouattempttousetheclassormethodwithanincompatibleobject,acompileerror
occurs.
Advantage:NoCastingNeeded
Backwardcompatibility:atechnologyisbackwardcompatibleifitcanworkwith
inputgeneratedforanoldertechnology
Forwardcompatibilityimpliesthatolddevicesallowinputformatsofnewdevicesto
run(withoutsupportingthenewfeatures).

POST MIDTERM MATERIAL


_________________________________________________________________

Test Driven Development (Design to Test)


_________________________________________________________________

Bottom-Up Development:

All modules used by module M are implemented and tested


before M is implemented. Requires the use of drivers.
Canplacelessofaloadonsystemresources.
Canleadtoearliercompletionofusefulsubsystems.

Top-Down Development:

AllmodulesthatusemoduleMareimplementedandtestedbeforeMisimplemented
Modulesthemselveswillprobablyusebottomupdevelopment
Canleadtoearliercompletionofusefulsubsystems.

The Development Strategy:


Shouldbedefinedexplicitlybeforeimplementationbegins
shouldbeprimarilytopdown,withbottomupusedmainlyformodulesthatareeasier
toimplementthantosimulate
Advantagesoftopdownoutweighbottomup
simplifiessystemintegrationandtest
makesitpossibletoproduceusefulpartialversionofthesystem
allowscriticalhighleveldesignerrorstobecaughtearly
Bottomupdevelopmentmaybeusedforeachmodule

What is design to test?


approachtoimplementation
designmodularclassesandmethods
beforecoding
determinewhatneedstobetested
designtestcasesforthoseimportantmethods
testincrementally,asyouimplementyoursolution

Dont design to fail


Thingstoavoid
codingwithoutadesign
notplanningonhowadesignwillbetested
creatinglargeamountsofuntestedcode
codingverylargemethods
lackofmodularitycandoomandimplementation

Testing vs. Debugging


Testing
aprocessofrunningaprogramonasetoftestcasesandcomparingtheactual
resultswithexpectedresults
Verification
aformalorinformalargumentthataprogramworksasintendedforallpossible
inputs
Validation
aprocessdesignedtoincreaseconfidencethataprogramworksasintended
Defensiveprogramming
writingprogramsinawaydesignedtoeasetheprocessofvalidationand
debugging.

Kinds of Testing
UnitTesting
testeachmoduleinaprogramseparately.
IntegrationTesting
Testinterfacesbetweenmodules
muchmoredifficultthanunittesting
RegressionTesting
Testprogramsaftermodificationstoensurecorrectbehavioroftheorignal
programispreserved.
Systemtesting
testoverallsystembehavior

Aspects of Testing
Howdowegeneratetestcases?
Exhaustive
considerallpossiblecombinationsofinputs
Sampled
Asmallbutrepresentativesubsetofallinputcombinations
Blackboxtesting:testcasesgeneratedfromprogram
specificationsandnotdependentontheimplementation
Glassboxtesting:testcasesgeneratedfromprogramscode
Blackboxtesting
itisthebestplacetostartwhenattemptingtotestaprogramthoroughly
testcasesbasedonprogramsspecifications,notonitsimplementation
testcasesarenotaffectedby:
invalidassumptionsmadebytheprogrammer
Implementationchanges
Testcasescanbegeneratedbyanindependentagent,unfamiliarwith
theimplementation.
Testcasesshouldcoverallpaths(notallcases)throughthe
specification,includingexceptions.

Boundary Conditions
isaninputthatisoneawayfromproducingadifferentbehaviorintheprogramcode
suchcheckscatch2commontypesoferrors:
logicalerrors,inwhichapathtohandleaspecialcasepresentedbya
boundaryconditionisomitted
Failuretocheckforconditionalsthatmaycausetheunderlyinglanguageor
hardwaresystemtoraiseanexception(ex:arithmeticoverlow)

Glass-box testing
Blackboxtestingisgenerallynotenough.
ForGlassboxtesting,thecodeofaprogrambeingtestedistakenintoaccount
Pathcompleteness
testcasesaregeneratedtoexerciseeachpaththroughaprogram.
maybeinsufficienttocatchallerrors
canbeusedeffectivelyonlyforaprogramfragmentthatcontainsareasonable
numberofpathstotest.

JUnit
Unittestframeworkforjavaprograms.
Thetestclasshasasetoftestmethods
publicvoidtestX()whereXisthemethodtobetested
Thetestmethodsuseassertionstoperformthetests,ex:
Assert.assertEquals(x,y)
Assert.assertTrue(c)

Building unit tests with JUnit


Initializeanyinstancevariablesnecessaryfortestinginthetestobject
Definetestsforemptiness,equality,boundaryconditions,
Definetestsuites,ifnecessary,togrouptets.
UserAssertmethodstoperformtests

Notes on Static Import


Staticimportisafeatureintroducedinathejavaprogramminglanguagethatallows
members(fieldsandmethods)definedinaclassaspublicstatictobeusedinJava
codewithoutspecifyingtheclassinwhichthefieldisdefined.

Notes on Assertions
Anassertionisajavastatementthatenablesyoutoassertanassumptionaboutyour
program
Anassertioncontainsabooleanexpressionthatshouldbetrueduringprogram
execution
Assertionscanbeusedtoassureprogramcorrectnessandavoidlogicerrors.

Declaring Assertions
AnassertionisdeclaredusingthenewJavakeywordassertasfollows
assertassertionsOR
assertassertion:detailMessage
WhereassertionisaBooleanexpressionanddetailMessageisaprimitivetypeoran
Objectvalue.

Executing Assertions
Whenanassertionstatementisexecuted,Javaevaluatestheassertion.
Ifitisfalse,anAssertionErrorwillbethrown.
Ithasanoargconstructoroftypeint,long,float,double,boolean,charand
Object.
AssertionErrorisasubclassofError,whenanassertionbecomesfalse,the
programdisplaysamessageontheconsoleandexits.

Running Programs with Assertions


Bydefault,theassertionsaredisableatruntime.Toenableit,usetheswitch
enableassertions,oreaforshort.
Assertionscanbeselectivelyenableordisabledatclasslevelorpackagelevel
thedisableswitchisdisableassertionsordaforshort.

Using Exception Handling or Assertions


Assertionshouldnotbeusedtoreplaceexceptionhandling.
Exceptionhandlingdealswithunusualcircumstancesduringprogram
execution.
Assertionsaretoassurethecorrectnessoftheprogram.
Exceptionhandlingaddressesrobustnessandassertionaddresses
correctness.
Assertionsareusedforinternalconsistencyandvaliditychecks.
Assertionsarecheckedatruntimeandcanbeturnedonoroffatstarttime.
Donotuseassertionsforargumentcheckinginpublicmethods
Userassertionstoreaffirmassumptions.

Notes from, class notes, liang, derek banas and


from http://sourcemaking.com/design_patterns
Structural Design Patterns
_________________________________________________________________

Design patterns that ease the design by identifying a simple way


to realize relationships between entities.
Decorator Pattern: adds additional functionality to a class at
runtime where subclassing would result in an exponential
rise of new classes.
Adapter pattern: adapts one interface for a class into one
that a client expects.
Facade pattern: creates a simplified interface of an existing
interface to ease usage for common tasks.
Flyweight pattern: a high quantity of objects share a
common properties object to save space.
Bridge pattern: decouples an abstraction from its
implementation so that the two can vary independently.

The Decorator Pattern


_________________________________________________________________

attaches additional responsibilities to an object


dynamically.
exampledecoratinganobject.
Decoratorsprovideaflexiblealternativetosubclassingforextendingfunctionalityby
wrappinganobject.
Worksontheprinciplethatclassesshouldbeopentoextensionbutclosedto
modification.
Thegoalistoallowclassestobeeasilyextendedtoincorporatenewbehaviorwithout
modifyingexistingcode.
Bydoingsowegetdesignsthatareresilienttochangeandflexibleenoughtotakeon
newfunctionalitytomeetchangingrequirements.

NotesfromDerekBanas
addschangesdynamically
Decoratordesignpatternsimplifiescodebecauseyouaddfunctionalityusingmany
simpleclassesratherthanrewritingoldcodeyoucanextendwithnewcode.
Wewanttobeabletowritenewcodetoaddfunctionalityinsteadofmodifyingold
code.


AboveWemakeapizzainterface,wemakeaconcreteclassofthemostbasicpizza.
ThenitgoestotempPizzawhichisthendecoratedbytheToppingDecorator
accordingly.
PizzabasicPizza=newTomatoSauce(newMozzarella(newPlainPizza()))
Soinsteadofmakinginfinitesubclasseswecanjusthavedecoratorswherewewrite
newcodebywritingnewclassestoincorporatenewbehaviorwithoutmodifying
existingcode.

The Adapter Pattern( 2 plug to 3 plug outlet)


_________________________________________________________________
Allows2incompatibleinterfacetowork
Usedwhentheclientexpectsa(target)interface
Theadapterclassallowstheuseoftheavailableinterfaceandthethetargetinterface
anyclasscanworktogetheraslongastheadaptersolvestheissuethatallclasses
mustimplementeverymethoddefinedbythesharedinterface.

^^^eachtimeanyEnermyAttackermethodiscalled,itcallsthecorrectversionwithin
EnemyRobotthusactinglikeanadapter.
Thispatternisusedwhenyouwanttotranslateoneinterfaceofaclassintoanotherinterface.Now,
itmakessensethatthese2interfacesarecompatibleotherwisethepatternmaynotmakesense.
Toaccomplishthis,allyouneedtodoisbridgethedifferencesusingouroldfriendcomposition
again.
Existingsystemusesadriverviaaninterface.
Newhardwareusesadifferentinterface
adaptercanadaptdifferences
ExistingsystemHASAOldInteface
AdapterimplementsOldInterfaceandHASANewInterface
ExistingsystemcallsOldInterfacemethodsonadapter,adapterforwardsthemtoNewInterface
implementations.

The Facade Pattern


_________________________________________________________________
Whenyoucreateasimplifiedinterfacethatperformsmanyotheractionsbehindthe
scenes.
TheFacadepatternbasicallysaysthatyoushouldsimplifyyourmethodssothatmuchofwhatis
doneisinthebackground.Intechnicaltermsyoushoulddecoupletheclientfromthesub
componentsneededtoperformanoperation.
Providesaunifiedinterfacetoasetofinterfacesinasubsystem.
Thefacadedefinesahigherlevelinterfacethatmakesthesubsytemeasiertouse.

Employstheprincipleofleastknowledge
FromLiang,TheFacadepatternprovidesaunifiedinterfacetoasetofinterfacesina
subsystem.Facadedefinesahigherlevelinterfacethatmakesthesubsystemeasier
touse.BeforeapplyingtheFacadepattern,asubsystemmaylookliketheonein
Figure6(a)wherethecomponentsareaccessedbymany500clients.Applyingthe
Facadepattern,youcancreateaunifiedinterfacecalledFacade,asshowninFigure
6(b),wheretheclientsaccessthecomponentsinthesubsystemthroughtheFacade.

The Flyweight Pattern


_________________________________________________________________

Usedwhenyouneedtocreatealargelargenumberofsimilarobjects
toreducememoryusageyoushareObjectsthataresimilarinsomewayratherthan
creatingnewones
theycanallbecontrolledidentically.
IntrinsicState:Color,whatiscommonamongobjects
ExtrinsicState:Size,Whatvariesbetweenobjects
Flyweightisbeneficialbecauseitreducesthenumberofobjectinstancesatruntime,
savingmemory.Italsocentralizesstateformanyvirtualobjectsintoasinglelocation.
Onceyouhaveimplementedit,single,logicalinstancesoftheclasswillnotbeableto
behaveindependentlyfromtheotherinstances.
Mustbeimmutable
Dependonanassociatedtable
mapsidenticalinstancestothesingleobjectthatrepresentsallofthem

The Bridge Pattern


_________________________________________________________________

Separatesanobjectsinterfacefromitsimplementation
FromLiang
TheBridgepatternallowsyoutovarytheimplementationandtheabstraction
byplacingthetwoinseparateclasshierarchies.
Scenario
youarewritingthecodeforanewergonomicanduserfriendlyremotecontrol
forTVs.
therewillbelotsofimplementationsoneforeachmodelofTVusean
abstraction(interface)
youknowtherewillbemanychangesovertimetothespecificationneedsto
accommodatechanges
Solution?Abstracttheabstraction.
Benefits
Abstractionandimplementationcanbeextendedindependently
Changestotheconcreteabstractionclassesdonotaffecttheclient.

Creational Design Patterns


_________________________________________________________________

Factory, Singleton, Builder and Prototype.

The Factory Pattern


_________________________________________________________________

Factoriesmakestuff,factoryclassesmakeobjects.
Factoryclassesemployconstructors
Whyusefactorypattern?
Factorypatternpreventsmisuse
hidesconstruction
provideapiconvenience
onestopshopforgettinganobjectofafamilytype
Whatobjectsdofactoriesmake?
commonancestor
sameapparenttype
differentactualtype
FactorypatternAdvantages
programusingfactorydesignpatternneverneedstoknowabouttheactual
class/type.
simplifiesuseforprogrammer
fewerclassestolearn

FromLiang
Thefactorymethodpatterndefinesanabstractmethodforcreatinganobject,
butletsubclassesdecidewhichclasstoinstantiate.Factorymethodletsa
classdeferinstantiationtosubclasses.
Example
BorderFactory.createXXXBordermethods
returnapparenttypeofinterfaceBorder
returnactualtypesofBevelBorder,EtchedBorder,etc

The implementation is really simple


The client needs a product, but instead of creating it directly using the new
operator, it asks the factory object for a new product, providing the information
about the type of object it needs.
The factory instantiates a new concrete product and then returns to the client
the newly created product(casted to abstract product class).
The client uses the products as abstract products without being aware about
their concrete implementation.

The Singleton Pattern


_________________________________________________________________

FromLiang,Thesingletonpatterndeclaresaclassthatcanbeusedtoinstantiatea
uniqueinstance.Occasionally,itisdesirabletorestrictinstantiationofaclassto
exactlyoneobject.Forexample,theremaybemanyprintersinasystem,butthere
shouldbeonlyoneprinterspooler.
So,yousystemshouldensurethatonlyoneprinterspoolerobjectiscreated
Thesingletonpatterncanbeimplementedbycreatingaclasswithaprivate
constructorandastaticconstantthatreferencesaninstanceoftheclass.
Singletonshouldbeconsideredonlyifallthreeofthefollowingcriteriaaresatisfied:
ownershipofthesingleinstancecannotbereasonablyassigned
LazyInitializationisdesirable
Globalaccessisnototherwiseprovidedfor
Example
TheSingletonpatternensuresthataclasshasonlyoneinstanceandprovides
aglobalpointofaccesstothatinstance.Itisnamedafterthesingletonset,
whichisdefinedtobeasetcontainingoneelement.TheofficeofthePresident
oftheUnitedStatesisaSingleton.TheUnitedStatesConstitutionspecifiesthe
meansbywhichapresidentiselected,limitsthetermofoffice,anddefinesthe
orderofsuccession.Asaresult,therecanbeatmostoneactivepresidentat
anygiventime.Regardlessofthepersonalidentityoftheactivepresident,the
title,"ThePresidentoftheUnitedStates"isaglobalpointofaccessthat
identifiesthepersonintheoffice.

The Builder Pattern


_________________________________________________________________

Allowsconstructioninsteps,goodforcomplexobjectconstruction.
Examplescenario,buildavacationplannerforathemepark
Guestscanchooseahotel,tickets,events,etc.
guestsmaywantzerotomanyofeach
createaplannertoencapsulateallthisinformation
FromDerekBanas
Builderpatternisapatternusedtobuildanobjectmadeupfromotherobjects
whenyouwantthecreationofthesepartstobeindependentofthemainobject
hidethecreationofthepartsfromtheclientsobotharenotdependent
builderknowsthespecificsandnobodyelsedoes

Example
TheBuilderpatternseparatestheconstructionofacomplexobjectfromits
representationsothatthesameconstructionprocesscancreatedifferent
representations.Thispatternisusedbyfastfoodrestaurantstoconstruct
children'smeals.Children'smealstypicallyconsistofamainitem,asideitem,
adrink,andatoy(e.g.,ahamburger,fries,Coke,andtoydinosaur).Notethat
therecanbevariationinthecontentofthechildren'smeal,buttheconstruction
processisthesame.Whetheracustomerordersahamburger,cheeseburger,
orchicken,theprocessisthesame.Theemployeeatthecounterdirectsthe
crewtoassembleamainitem,sideitem,andtoy.Theseitemsarethenplaced
inabag.Thedrinkisplacedinacupandremainsoutsideofthebag.This
sameprocessisusedatcompetingrestaurants.


Builderreturnstheproductasafinalstepafterbuildingitinparts.

The Prototype Pattern


_________________________________________________________________
Creatingnewobjects(instances)bycloning(copying)otherobjects
allowsforaddingofanysubclassinstanceofaknownsuperclassatruntime
whentherearenumerouspotentialclassesthatyouwanttoonlyuseifneededat
runtime
Reducestheneedforcreatingsubclasses
Example


Helpsuseasilycreatenewobjectsthroughcloning,thenewobjectswouldinfacthave
differentaddressstoredinmemory.
theprototypespecifiesthekindofobjectstobecreated.
Toenableanobjecttobecloned,theclassmustimplementtheCloneableinterface
andoverridetheclone()method.
PrototypeBenefits
hidesthecomplexitiesofmakingnewinstancesfromtheclient
providestheoptionfortheclienttogenerateobjectswhosetypeisnotknown
Insomeinstancescopyinganobjectismoreefficientthancreatinganew
object.
PrototypeUsesandDrawbacks
Prototypeshouldbeconsideredwhenasystemmustcreatenewobjectsof
manytypesinacomplexclasshierarchy
Adrawbacktousingtheprototypeisthatmakingacopyofanobjectcan
sometimesbecomplicated.

Behavioral Design Pattern


_________________________________________________________________

Designpatternsthatidentifycommoncommunicationspatternsbetweenobjectsand
realizethesepatterns.
Theyincreasetheflexibilityincarryingoutcommunication

1. Strategypattern:algorithmscanbeselectedonthefly
2. Templatemethodpattern:describestheprogramskeletonofaprogram
3. Observerpattern:objectsregistertoobserveaneventthatmayberaisedbyanother
object.
4. Commandpattern:commandobjectsencapsulateanactionanditsparameters
5. Iteratorpattern:iteratorsareusedtoaccesstheelementsofanaggregateobject
sequentiallywithoutexposingitsunderlyingrepresentation
6. Statepattern:acleanwayforanobjecttopartiallychangeitstypeatruntime.

Strategy Design Pattern


_________________________________________________________________

Definesafamilyofalgorithms,encapsulateeachone,andmakethem
interchangeable.Strategyletsthealgorithmvaryindependentlyfromtheclientsthat
useit.
Capturetheabstractioninaninterface,buryimplementationdetailsinderivedclasses.
Example:AStrategydefinesasetofalgorithmsthatcanbeusedinterchangeably.
ModesoftransportationtoanairportisanexampleofaStrategy.Severaloptionsexist
suchasdrivingone'sowncar,takingataxi,anairportshuttle,acitybus,ora
limousineservice.Forsomeairports,subwaysandhelicoptersarealsoavailableasa
modeoftransportationtotheairport.Anyofthesemodesoftransportationwillgeta
travelertotheairport,andtheycanbeusedinterchangeably.Thetravelermustchose
theStrategybasedontradeoffsbetweencost,convenience,andtime.


Template Method Design Pattern
_________________________________________________________________

Atemplateforanalgorithm
Definestheskeletonofanalgorithminamethod,deferringsomestepstosubclasses.
Letssubclassesredefinecertainstepsofanalgorithmwithoutchangingthe
algorithmsstructure.
Example

Whats a hook
_________________________________________________________________

Atypeofaconcretemethod
Declaredintheabstractclass
onlygivenanemptyordefaultimplementation
Givessubclassestheabilitytohookintothealgorithmatvariouspoints,iftheywish.
Asubclassisalsofreetoignorethehook.

Strategy vs. Template Method


_________________________________________________________________

Strategy
subclassesdecidehowtoimplementstepsinalgorithm
Templatemethod
encapsulateinterchangeablebehaviorsandusedelegationtodecidewhich
behaviortouse

Observer Design Pattern


_________________________________________________________________

Definesaonetomanydependencybetweenobjectssothatwhenoneobjectchanges
state,allitsdependentsarenotifiedandupdatedautomatically.
FromLiang,Theobserverpatterndefinesadependencyrelationshipbetweenan
Object(calledsubject)anditsdependentobjects(calledobservers).Whenthesubject
objectchangesitsstate,alltheobserversobjectsarenotified.
WeseethisinourGUI
example,TheObserverdefinesaonetomanyrelationshipsothatwhenoneobject
changesstate,theothersarenotifiedandupdatedautomatically.Someauctions
demonstratethispattern.Eachbidderpossessesanumberedpaddlethatisusedto
indicateabid.Theauctioneerstartsthebidding,and"observes"whenapaddleis
raisedtoacceptthebid.Theacceptanceofthebidchangesthebidpricewhichis
broadcasttoallofthebiddersintheformofanewbid.


MVC employs the observer pattern
_________________________________________________________________

Model
notifiesviewswhensomethinginterestinghappens
View/Observer
Visualrepresentation
viewsattachthemselvestomodelinordertobenotified
Controller
eventhandler
listenersthatareattachedtoviewinordertobenotifiedofuserinteraction
MVCInteraction
controllerupdatesmodel
modeltellsviewthatdatahaschanged
viewredrawn

Command Design Pattern


_________________________________________________________________

Encapsulatearequestasanobject,therebylettingyouparameterizeclientswith
differentrequests,queueorlogrequests,andsupportundoableoperations.
Anobjectorientedcallback
TheCommandpatternallowsrequeststobeencapsulatedasobjects,thereby
allowingclientstobeparameterizedwithdifferentrequests.The"check"atadineris
anexampleofaCommandpattern.Thewaiterorwaitresstakesanorderorcommand
fromacustomerandencapsulatesthatorderbywritingitonthecheck.Theorderis
thenqueuedforashortordercook.Notethatthepadof"checks"usedbyeachwaiter
isnotdependentonthemenu,andthereforetheycansupportcommandstocook
manydifferentitems.

Iterator Design Pattern


_________________________________________________________________

SequentiallyaccesstheelementsofaCollection
Providesaunifiedwayfortraversingandprocessingtheelementsinanaggregate
objectsuchasanarray,set,list,andmapwithoutexposingitsunderlying
representation.
Aniteratorisaseparateobjectthatcontainsthemethodforretrievingandprocessing
theelementsintheaggregateobject.
Iteratorsarecommonlydefinedusinganinterface.
TheIteratorprovideswaystoaccesselementsofanaggregateobjectsequentially
withoutexposingtheunderlyingstructureoftheobject.Filesareaggregateobjects.In
officesettingswhereaccesstofilesismadethroughadministrativeorsecretarialstaff,
theIteratorpatternisdemonstratedwiththesecretaryactingastheIterator.Several
televisioncomedyskitshavebeendevelopedaroundthepremiseofanexecutive
tryingtounderstandthesecretary'sfilingsystem.Totheexecutive,thefilingsystemis
confusingandillogical,butthesecretaryisabletoaccessfilesquicklyandefficiently.
Onearlytelevisionsets,adialwasusedtochangechannels.Whenchannelsurfing,
theviewerwasrequiredtomovethedialthrougheachchannelposition,regardlessof
whetherornotthatchannelhadreception.Onmoderntelevisionsets,anextand
previousbuttonareused.Whentheviewerselectsthe"next"button,thenexttuned
channelwillbedisplayed.Considerwatchingtelevisioninahotelroominastrange
city.Whensurfingthroughchannels,thechannelnumberisnotimportant,butthe
programmingis.Iftheprogrammingononechannelisnotofinterest,theviewercan
requestthenextchannel,withoutknowingitsnumber.

State Design Pattern


_________________________________________________________________

Statepatternallowsanobjecttoalteritsbehaviorwhenitsinternalstatechanges.The
objectwillappeartochangeitsclass.Theobjectrepresentsastate.Itisautomatically
changedtoanewstateobjectwhenthestatechanges.
Thestatepatternstructurecanbeoutlinedasshowbelow


Thestatepatternusesobjectstorepresentstates.
Example,The State pattern allows an object to change its behavior
when its internal state changes. This pattern can be observed in a
vending machine. Vending machines have states based on the
inventory, amount of currency deposited, the ability to make change,
the item selected, etc. When currency is deposited and a selection is
made, a vending machine will either deliver a product and no
change, deliver a product and change, deliver no product due to
insufficient currency on deposit, or deliver no product due to
inventory depletion.

Code Profiling
__________________________________________________________________________
Programsshould
solveaproblemcorrectly,bereadable,beflexibleforfuturemodifications,be
fastandbelean(usetheleastamountofmemorynecessary).
Hardwarebecomesfasterandmorecapable,butdataismore.
programefficiencyisstillanissue
softwareexpectationscontinuetoincrease
Whennottooptimize(makethebestormosteffectiveuseof)
Onlyoptimizewhennecessary
Whynotjustberesponsibleandalwaysoptimize?
Optimizationisagoodwaytointroducebugs
sometechniquesdecreasetheportabilityofyourcode
youcanexpendalotofeffortforlittleornotresults
optimizationmakesthecodelessreadable!
increasescomplexityandthedifficultyofdebugging
optimizationcanbehardtodoproperly
optimizationisamovingtarget
Sowhatisoptimizing?
Modifyingasystemtoimproveitsperformance
WhydoesDonaldKnuthhateit?
becausealltheoptimizationintheworldcanneverreplacethewiseselection
ofproperdatastructuresandtheproperuseofefficientalgorithms.
Optimizationoptions
Designforspeed:selectyourdatastructuresandalgorithmswisely
Useacodeprofiler
userautomaticoptimizers
Implementlowlevelcodeoptimizations
Intheprocessofdesigningaprogram:
Identifyoperationsneededineachclassbeforechoosingyourdata
structures
pickadatastructurethatcanbeusedtoperformsuchoperations
efficiently
Selectasolidalgorithmthatfitstheproblemandthedata:BigO
notation
ProgramHotSpots
Whenthechoiceofbestdatastructureofalgorithmisnotclearatdesigntime:
usethesimplestdatastructureoralgorithm,collectdataabouttheimpactof
thedatastructureofalgorithmontheoverallspeedoftheprogram.
Identifytheportionofthecodethattakesthemosttimeormemory
Replacethatsection,ifpossiblewithabetterstructureofalgorithm.

Whatsaprofile?
Aprofilerisaprogramthatcantacktheperformanceofanotherprogramby
checkinginformationcollectedwhilethecodeisexecuting:
canusuallytracktimeusedorfrequencyofuseofcode(random
samplingwithaparllelthread)
theentireapplicationorjustselectmethods
Typesofprofiling
CPUperformanceprofiling
memoryprofiling
Threadsprofiling
memoryleakprofiling
CollectingperformancedatausingHProf
Generateprofiledataonsampleruns
javaclassicXrunhprofDriver
javaclassicXrunhprof:cpu=samplesDriver
Analyzetheprofiledatatofind
hotspotswithrespecttotime
mostfrequentlyusedmethods
mosttimeconsumingmethods
bottlenecks
hotspotswithrespecttospace(memory)
mostfrequentlyusedportionsofdatastructures
AdditionalOptimizationtools
Compileralreadyperformmanyoptimizations
javacO,thejavaoptimizer
Optimizescompiledcodebyliningstatic,finalandprivatemethods.
Inliningamethodcallinsertsthecodeforthemethoddirectlyintothe
codemakingthemethodcall
Eliminatestheoverheadofthemethodcall
forasmallmethodthisoverheadcanrepresentasignificant
percentageofitsexecutiontime
Onlyprivate,static,orfinalmethodsareeligibleforinling
Synchronizedmethodswontbeinlined
Thecompilerwillonlyinlinesmallmethods
MachineCode
javaccompilesjavaprogramstothemachinecodefortheJVM
directlycallingthiscodecanimproveprogramperformance
javapctodumpouttheJVMinstructionsgeneratedbytheJavacompiler
gccStodumpassemblyinstructionsgeneratedbytheCcompiler
JNI
JavaNativelanguageInterface
Standardprogramminginterfaceforwritingjavanativemethodsand
embeddingtheJavavirtualmachineintonativeapplications
LookupTables
Precomputedvaluesofsomecomputationthatyouknowyouwillperform
duringruntime
simplycomputeallpossiblevaluesatstartupthenrunthegame
OptimizationGuidelines
DoNOThandoptimizeyourcode:
Ifitunnecessarilysacrificesreadability,OR
ifitunnecessarilysacrificesmaintainability
Ifanoptimizationisnecessary,thinkdatastructuresandalgorithmsfirst
Manycommoncodeoptimizationsaredonebythecompiler
Don'toveroptimize

Annotations
__________________________________________________________________________
Featuresofsomelanguages
programmerconveniences
Usefulincheckinginheritance
alternatedevelopmentmodes
@Override
RememberJUnit?
@Before,@After,@Test
@isJavasnotationforthestartofanannotation
like@authorforjavadoc
Whatarethey?
metadata,providedataaboutaprogram
Whatareannotationsusedfor?
Informationforthecompilertodetecterrorandtosuppresswarnings.
Compiletimeanddeploymenttimeprocessing
forIDEsandothertools
generatecode,XMLfiles,etc.
Runtimeprocessing
someannotationsareusedatruntime
Annotationscanhavefieldnamesanddata
@author(name=bob,date=3/27/2003)
Wherecanannotationsbeused?
Declarationsofclasses,fields,methods,etc.
JavaSE8alsohastypeannoations:
Classinstancecreationexpressions:
new@InternedMyObject()
Typecast:myString=(@NonNullString)str
implementsclause:
classUnmodifiableList<T>implements@ReadonlyList<@readonly
T>{.....}
Thrownexceptiondeclaration
voidmonitorTemperature()throws@CriticalTemperatureException{..}
Whydowecareaboutannotations?
Toolslovetousethem
JUnit,Javadoc,Webrelatedtools
Annotationstypes
Thepredefinedannoationtypesdefinedinjava.langare@Deprecated,
@Override,and@SuppressWarnings
@Deprecatedannotationindicatesthatthemarkedelementis
deprecatedandshouldnolongebeused.
DeclaringanAnnotationType
@interfaceClassPreamble{
Stringauthor()
Stringdate()
intcurrentRevision()default1
String[]reviewers().}
Aftertheannotationtypeisdefined,youcanuseannotationsofthat
type
@ClassPreamble(reviewers={Alice,bob}
DeclaringanAnnotationType
Tomaketheinformationin@ClassPreambleappearin
javadocgenerateddocumentation,whenyoudefinetheannotation
Reflection
Apowerfulprogrammingfeature
requirestheabilitytoexamineormodifytheruntimebehaviorof
applicationsrunningintheJavaVirtualMachine.
Dynamicallyexamineclassesandobjects
shouldbeusedonlybydeveloperswhohaveastronggraspofthe
fundamentalofthelanguage.
Callmethodsatruntimethatyoudidnotknowexistedatcompiletime
Atruntime:askaclasswhatmethodithas,calloneofthosemethods
ReflectionUses
Extensibilityfeatures
dynamicallyuseclassesnotknownatcompiletime,plugins,
addons,etc.completeflexibility.
Reflection
ItallstartswiththeClassclass:
Everyobjectinjavaisamemberofaclass.
getClass()methodinheritedfromObject
example,Classc=Hello.getClass()
itcouldthrowClassNotFoundException
othermethodsinclude
getSuperclass
getDeclaredClasses
Fields
Hasatypeandvalue
TypeisaClass
get/setdataviaget/setmethods
Otherusefulclasses
method
constructor
DrawbacksofReflection
PerformanceOverhead
dynamictyperesolutionisexpensive
certainjavavirtualmachineoptimizationsskipped
shouldbeavoidedinhotspots
SecurityRestrictions
ExposeofInternals.

You might also like