with certain severity levels, bugs submitted during a particular time range, or bugs in various statesnew, assigned, fixed, and so forth.The bug manager and release coordinator can also
Trang 1under-The Bug Hunter ExampleThe sections in this chapter explain different ways to characterize an application They discuss theprogram from the point of view of the users, architects, developers, and others.
To make the discussion easier, each section works with the same example: a hypothetical bugtracking application named Bug Hunter This application allows users to enter bug reports A bugmanager reviews each report and assigns it to an appropriate developer The developer reviewsthe bug, tries to reproduce it, fixes the bug (hopefully), and clears the bug A release coordinatorthen performs regression testing, revises the application and user documentation, and thenreleases a new version of the code
In some cases, the bug can follow a different path, looping back to a previous state For example,
if the assigned developer cannot reproduce the bug, it is sent back to the user for clarification Ifregression testing shows that the bug fix broke something, the bug is sent back to the developer forreevaluation
Throughout this process, users can view the status of a particular bug to see if it is new, underreview, assigned, under study, fixed, or released The user can generate reports showing informa-tion about bugs, selected and ordered in various ways, such as a particular bug, all bugs, bugs
Trang 2with certain severity levels, bugs submitted during a particular time range, or bugs in various states(new, assigned, fixed, and so forth).
The bug manager and release coordinator can also select reports that are not available to the users (such
as the code modules containing the bugs, the developers who wrote code containing bugs, and so forth)
Building an Object Model
Before you can start building an application, you must identify the classes that you will use Once theseclasses are defined, they will quickly become intertwined with the developers’ code Changing, remov-ing, or replacing them later becomes very difficult You may be able to add new properties and methods
to a class However, making large changes is time-consuming and likely to affect the existing code
To avoid needless drudgery and frustration, you should spend extra time at the beginning of the projectidentifying the major classes that you will use, spelling out their roles and responsibilities, and defining(at least in general terms) their properties, methods, and events
The following sections describe some methods you can use to pick classes for developers to use
Picking Candidate Classes
One way of picking candidate classes is to take a close look at the project’s written specification ordescription, and highlight all of the nouns in the text For now, focus on nouns that are objects, such asdocument, user, and report Skip concepts and activities, such as testing and evaluation The nouns youhave highlighted are the candidate classes
The following text is the description of the Bug Hunter application with the candidate nouns in bold:
This application allows users to enter bug reports A bug manager reviews each report and assigns
it to an appropriate developer The developer reviews the bug, tries to reproduce it, fixes the bug
(hopefully), and clears the bug A release coordinator then performs regression testing, revises the
application and user documentation, and then releases a new version of the code.
In some cases, the bug can follow a different path, looping back to a previous state For example, if the assigned developer cannot reproduce the bug, it is sent back to the user for clarification If regression testing shows that the bug fix broke something, the bug is sent back to the developer for reevaluation Throughout this process, users can view the status of a particular bug to see if it is new, under review, assigned, under study, fixed, or released The user can generate reports showing information about
bugs , selected and ordered in various ways, such as a particular bug, all bugs, bugs with certain
severity levels , bugs submitted during a particular time range, or bugs in various states (new,
assigned, fixed, and so forth).
The bug manager and release coordinator can also select reports that are not available to the users (such as the code modules containing the bugs, the developers who wrote code containing bugs, and
so forth).
Next, combine any duplicates and make a list Add comments, if necessary, to clarify a word’s meaning.For example, the word “something” is too vague to be useful by itself The following list shows the boldnouns from the previous text:
Trang 3❑ all bugs (report)
❑ application
❑ bug manager
❑ bug report
❑ bugs in various states (report)
❑ bugs submitted during a particular time range (report)
❑ bugs with selected severity levels (report)
❑ code modules containing the bugs (report)
❑ developer
❑ new version of the code
❑ particular bug (report)
❑ path (a bug report’s path through the states/statuses)
❑ release coordinator
❑ something (a piece of code broken by a bug fix)
❑ state (of a bug report)
❑ status (of a bug report)
❑ the developers who wrote code containing bugs (report)
❑ user documentation
Note that picking candidate classes in this way requires that you have a good specification If the cation is vague, it won’t include all of the nouns that you will need for the classes The specification is thestarting point for building a list of candidate classes, not the final story If something seems to be missing,take another look at the specification and see if it completely describes what the program needs to do
specifi-Converting Candidates into Classes
After you compile the initial candidate list, you must look over the items and decide which will makegood classes, and what interactions there are among them
This list contains some items that represent the same concepts The items “state” and “status” are reallythe same concept, so you can remove one of them Let’s remove “state.” Similarly, “bug” and “bugreport” represent the same idea, the data about a bug, so let’s remove “bug.”
Looking at the list, you can see a couple of general categories There are several different kinds of reports.There are also four kinds of people: user, bug manager, developer, and release coordinator You shouldpull these related objects out into groups Such groups of objects often indicate a close relationship, andmay be a sign of inheritance, composition, or other close coupling
Trang 4Think about the groups and decide whether these objects are the same type of thing at some level, orwhether they are just closely related In this example, user, bug manager, developer, and release coordi-nator are all the same sort of thing: people It’s even easier to see that all of the reports are types ofreports.
Because the objects are the same sort of thing, it probably makes sense to combine them by making theminherit from parent classes Study these items further and see how much they have in common becausethey are the same type of thing The people items all have characteristics of people: name, address,phone number, and so forth
Different people will also have different permissions for using application features For example, the bugmanager and release coordinator can make reports showing bugs by module or developer, whereas theusers cannot
The report items are less well-defined at this point, so it’s a bit more difficult to know what they have incommon Drawing on previous experience with other applications, however, you can guess that theywill all need methods for building the report, setting report parameters, saving the report into a file,printing, exporting the report for analysis in a spreadsheet and possibly other file formats, and so forth
Armed with this information, you can generalize the groups by pulling their common features into a
parent class, and making the items in the previous list child classes
Now, consider the remaining items and think about the types of roles they will play in the application.Decide whether the item represents a single piece of data, a more complex data structure with multiplefields, something that performs an action (or on which important actions are performed), or a combina-tion of these
You can model a single piece of data by using normal variables such as strings, integers, or arrays ofsimilar simple data types
You can implement a complex data structure in Visual Basic by using either a structure or a class Bothstructures and classes can provide methods, so you can use either to represent something that performsactions
The difference between a structure and a class in Visual Basic is mainly one of how the item is allocated.
A structure is allocated when it is declared, whereas a class is allocated when you use the Newkeyword For example, if you declare an array of 1,000 structures, Visual Basic allocates memory for them when it reaches the declaration If you allocate 1,000 class objects, Visual Basic only allocates memory for refer- ences to the objects, and doesn’t create the objects themselves until you initialize them individually by using the Newstatement There are also a few additional differences (such as the fact that structures
don’t have constructors) I usually use classes, at least partly because they can have constructors.
The “bug report” item contains information about a bug, so it represents a piece of data It is also a verycentral concept to the system: a user creates it, the bug manager assigns it, a developer works it, and therelease coordinator releases it It takes part in reports and requires user documentation The fact that thisitem plays a role in so many activities indicates that it is something special Let’s make it a class
In the earlier description of Bug Hunter, “application” refers to Bug Hunter in a fairly general way, and
it doesn’t really do anything specific At most, you could use it to represent application properties such
Trang 5as the version number, release date, and so forth Because this information changes rarely (only whennew versions are created) and because the “application” item doesn’t need to perform any action, let’stentatively remove it from the list The program will store application information such as version num-ber in the program’s properties and in the data describing a bug report.
I’ve seen many systems where object enthusiasts insist on creating objects for even small items such as this They would create an ApplicationInformationclass whose sole purpose is to load and save these few data values I prefer to initially keep these items simple and make them more elaborate later only if it proves absolutely necessary.
Similarly “new version of the code” refers to a new program build to fix a bug The new code itself isstored outside of the program in some sort of source code control system Though this is an importantpart of the Bug Hunter system as a whole, it’s not properly part of the code
The “user documentation” item also refers to something external to the program Updating the mentation is an important activity, but it’s not part of Bug Hunter Even if the program displays thedocumentation online, it is the release coordinator, not the program, that updates the documentation.You could add a property to the “bug report” object to record the version number of the documentationproduced in response to the bug, but even that may not be necessary It’s more common for the docu-mentation to include a revision history that will indicate that it was revised because of the bug
docu-The “path” item represents the path a bug report takes through the system as it is created, assigned,worked, and released Whether you need to keep this item depends on whether you really care about
the job’s path through the system or whether you just need to know that the job follows some path In
some applications it is important to know an object’s complete history
For example, if you are processing financial information, you may need to establish a chain of custody
so you know exactly who did what to the data and when In that case, you might want to implement
an audit trail system where the application saves a record every time the data is modified (and possiblyviewed)
For Bug Hunter, let’s assume that you just want to know that a bug report flows through the system andyou don’t need to remember all of the steps, so let’s remove “path” from the list
The “status” item represents a bug report’s current state in the system This item takes specific valuessuch as New, Assigned, and Released The “status” item is a single enumerated value that applies to abug report, so let’s make it a property of the “bug report” object In the Visual Basic code, let’s make thelist of possible values an enumerated type
Finally, the “something (a piece of code broken by a bug fix)” item represents the code that was fixed.This is another item that lies outside of Bug Hunter’s code However, the program’s description saysthat the bug manager should be able to generate reports showing bugs by module and bugs by devel-oper To provide those reports, the program must know where the bugs occurred and who created thebugs These are fairly simple data items, and the program won’t do anything with them other thanreport them, so let’s make these properties of the “bug report” item After fixing a bug, the developershould enter this information in the “bug report” data
Figure 4-1 shows the initial object model
Trang 6Figure 4-1: The initial object model contains objects extracted from the program’s description.
Adding Internal Classes
Sometimes an application’s object model needs additional classes that don’t correspond to the physicalobjects mentioned in the project description These classes provide features that the developers need tobuild as parts of the system, but they are often hidden from the users
Sometimes you may know that these classes are necessary from previous experience In a similar cation, you may have used a PriorityQueueclass that you think will be useful for keeping bug reportsordered by priority
appli-Other times you will discover that you need new classes as you develop the classes that you have alreadydefined You may discover that the Reportobject’s ExportToFilemethod would best be implemented
by a group of classes that can handle different export formats (such as tabbed text, comma-separatedvalue, Excel workbook, and others)
You may find additional classes when you apply design patterns to the application’s design view-controller, facade, adapter, and other design patterns add new classes to the design
Model-It’s often useful to look at the places where the application interacts with the outside world to identifynew classes That includes places that read or write files, such as the ExportToFilemethod mentionedearlier It also includes places where the application must read or send email, upload or download filesfrom the Internet, print reports, send faxes, interact with Windows or other applications, and interactwith different components of your application
BugReportStatus FixedInVersion BugInModule BugWrittenBy Description ReportedBy Etc.
ReportNew() Parameters SaveToFile() ExportToFile() Print() Etc.
PersonName Address Phone Privileges Etc.
BugManagerDeveloper
ReleaseCoordinatorUser
ReportBySeverity
ReportByModuleReportByDeveloperReportSpecificBug
ReportAllReportByStatus
ReportByDate
Trang 7Adding Database Classes
A particularly common interaction is with a database Many programs read and write data in a database,and they can use classes to make that easier Higher-level classes can act as factories for reading andwriting certain other kinds of objects For example, a DbPersonFactoryclass might have methods thatcan build and save Personobjects in the database A database-level class might provide methods forinserting, updating, querying, and deleting data Higher-level classes could use its methods instead ofaccessing the database directly
Separation between the day-to-day development classes and the database is important so that developers don’t need to remember the details of the database’s structure and the particular database engine’s access methods For example, Access and Oracle databases delimit dates differently The database classes should hide this from higher-level classes.
However, I’ve worked on several applications where developers got carried away and added too many extra layers of classes trying to increase the separation between the developers and the database That made tracing a piece of data through the system almost impossible I’ve seen code that climbed through
30 or 35 layers of call stack involving dozens of objects to retrieve a relatively simple piece of data This
is not only inefficient, but it’s also incredibly hard to debug.
Use classes for separation, but strive for broad, shallow object hierarchies, instead of very long inheritance chains or deep stacks of method calls.
Often, the tables in a database map naturally to classes within the program Perform a quick study of theprogram’s data needs and design a preliminary database Now see if any of the tables should correspond
to classes
Tables that are related in the database often correspond to classes that are related in a similar way BugHunter will probably need a BugReportstable to store information about bugs and a Peopletable tostore information about people
There are two one-to-many relationships between the BugReportstable and the Peopletable becauseeach BugReportsrecord will contain references to the Userwho created the report and the Developer
who is assigned to it These are one-to-many relationships because each BugReportsrecord refers to asingle creating user and assigned developer, while each user or developer can be associated with anynumber of BugReportsrecords
You will probably want to model this relationship by giving the BugReportclass references to the sponding Userand Developerobjects
corre-Studying Different Design Views
It has been repeatedly shown that the longer it takes to find a bug in an application, the more difficult it
is to fix Design decisions are particularly important, because you make them near the beginning of theproject and because they have such wide-ranging consequences A big mistake in the initial design canmake the entire project fail
One of the easiest ways to make big design mistakes is to not understand the application thoroughly Ifyou don’t understand the customers’ needs, you can’t design classes to satisfy them If you don’t under-stand the application’s internal needs, you can’t design the classes that it needs to get the job done
Trang 8To gain the best possible understanding of the system, you should look at the application from as manypoints of view as possible Some of the different views you should consider include the following:
❑ Object View — Perform an object-oriented analysis to define likely classes to represent the
physi-cal objects in the system Group and combine objects, build an inheritance hierarchy, refine theobjects, and so forth
❑ GUI View — Sketch out a rough user-interface design Then think about the types of data the
program will need to support that interface Often, the items displayed on the screen matchunderlying classes Chapter 5, “User-Interface Design,” has more to say about designing theapplication’s user interface
❑ Data View — Identify the data that the system needs Decide where the data should reside: in
classes, global variables, or someplace else Design the database if you need one and see if thetables in the database naturally map to classes
❑ Document View — In many applications, the users work on some sort of document In Bug
Hunter, the central document is a bug report Often these documents correspond to classes.Mentally follow the documents through the system and identify the entities that interact withthem In Bug Hunter, these are the different kinds of people and reports Often, these entitiesshould also be implemented as classes
❑ Case View — Step through the use cases that you and the users have defined for the application.
See if the classes you have defined contain all of the necessary ingredients to handle the usecases Look for new nouns in the use cases that might make good classes
The Universal Modeling Language (UML), described later in this chapter, can help you characterize thedetails of different aspects of the application’s design and behavior It gives you a representation thatyou and the other application designers can use to study the design meaningfully Later, it can givedevelopers guidance so they share a common vision of how the system should work
UML also gives you several new views from which to examine the system, so even if you are the soledesigner and developer on the project, you may get some benefit from using UML
Improving the Classes
For years, object-oriented developers have focused on three important characteristics of object-orientedlanguages: encapsulation, polymorphism, and inheritance These three principles make classes morepowerful and easier to use with fewer chances for errors
Unfortunately, many focus so tightly on those three principles that they forget the purpose behind thedogma By keeping in mind the reasons why those three concepts are useful, you can generalize themand apply similar principles to higher-level design tasks Most experienced developers understand that
a well-designed class should provide encapsulation, polymorphism, and inheritance It’s less clear howyou can apply the underlying concepts to improve the design of higher-level entities such as applicationsystems and subsystems
The following sections describe encapsulation, polymorphism, and inheritance They also extract theunderlying ideas and explain how you can apply them to the application’s higher-level organization
Trang 9Encapsulation is the idea that a class should wrap up its implementation details in a tight little package.
The class provides an interface (properties, methods, and events) that lets other parts of the programinteract with the class’s objects, but it keeps the details about how it does its job a closely held secret
Many programmers justify encapsulation by saying that it makes the rest of the program less dependent
on the class’s code If you later need to change the way the class works, you will not need to modify therest of the program to work with the new code
For example, suppose an Invoiceclass looks up a customer’s data and the list of items that customer haspurchased, adds up the items’ prices, and prints an invoice The main program can create an Invoice
object and call its MakeInvoicemethod to make and print an invoice
Now, suppose the company decides to create a new Preferred Customer program that gives any customer
a 10 percent across-the-board discount on every order after the customer has purchased $10,000 worth ofgoods You need to modify the Invoiceclass so it checks the value of the customer’s previous orders Ifthe customer has placed $10,000 worth of orders, the Invoiceclass applies the 10 percent discount andprints the invoice
Because the Invoiceclass encapsulates the invoice generation and printing process, you don’t need
to change the rest of the application The main program still creates an Invoiceobject and calls its
hidden from the main program
You can also think of the ability to change one part of the application without messing up another part
as loose coupling The different systems are related, but loosely enough that changes to one don’t
neces-sarily require changes to the others Although developers think of encapsulation as a class-level concept,loose coupling applies equally to all levels of the project Keeping the user interface, report generation,invoicing, inventory, and other major systems as loosely coupled as possible means changes to one areless likely to require changes to the others
A second part to encapsulation that is sometimes overlooked is the simple fact that it hides informationabout the class’s internals This is such an integral part of encapsulation that encapsulation is sometimes
called information hiding.
Even if hiding the class’s internals didn’t promote loose coupling, it would still have a large benefit fordevelopers because it allows them to use the class without worrying about what’s going on beneath thesurface, thus reducing the developer’s cognitive load The developer can use the class and assume that
it works
This may seem like the smaller of encapsulation’s two effects, but it can have a big impact, particularly
if you apply the idea to the higher levels of the application design If the report generation system hidesits internal details from developers, those developers can work on their own pieces of code, calling thereport generation system as needed, without worrying about how it works
On a large project where different teams implement the application’s various systems, keeping the tems as independent as possible is absolutely crucial You must allow the teams to work separately toget their pieces of the application done as quickly as possible Information hiding allows members ofone system’s team do their jobs without needing to consult with the members of the other teams
Trang 10sys-One really strong way to promote loose coupling is to build parts of the application as dynamic link
libraries (DLLs), components, and controls Most developers have the sense that classes in these kinds of modules are separate entities That makes them less likely to try to break the class’s encapsulation than they might be if the class was simply another class in the same code base Putting the class in a separate code library adds a “barrier to messing around” with the code.
Of course, if it’s harder to modify the library’s code, then you’d better spend some extra time up front to ensure that the library can handle all of the requests that the developers will need to make of it The extra work at the beginning will be more than repaid by the additional isolation you get between the applica-
tion’s systems.
To summarize, encapsulation really includes two concepts: loose coupling and information hiding Both
of these are beneficial when you build a class, but they are also useful at the higher levels of applicationdesign
Hide as many of the details as possible within a class Provide public access to the bare essentials thatother code needs to get the job done If it later turns out that a piece of vital information that is hiddenwithin the class must be exposed, you can add it later It’s better to start out too restrictive and loosenaccess than it is to start too loose and create dependencies that will be hard to implement, debug, andmaintain
Polymorphism and Inheritance
Encapsulation, polymorphism, and inheritance are the three main characteristics of object-oriented gramming As the previous section explains, you can maximize encapsulation in your classes and system-level design to make the application easier to build, debug, and maintain
pro-Polymorphism and inheritance, however, are more descriptions of objects, rather than advice on how touse them
Polymorphism means the ability to use one object as if it were another type of object In particular, it means
that the code should be able to treat an object as if it had the type of its ancestor classes You should beable to treat a Userobject as if it were a Personbecause Useris a child class of Person Useris a type of
Person, so a Useris actually also a Person Note that the reverse is not true: a Personis not necessarily atype of User
In practice, this means that you can pass a Userobject into a routine that expects a Person You can alsostore a Userobject in a variable that is a reference to a Person
Inheritance means that derived classes inherit the properties, methods, and events of their parent classes.
AUserobject has all of the features of a Personobject, possibly with some additional features The
Userclass may also modify some of the Personfeatures (for example, overriding or shadowing them).It’s hard to see how you would change a class’s definition to gain the most benefit from polymorphismand inheritance, much less how to apply those principles at a higher design level It helps to ask whythese capabilities are useful
Both polymorphism and inheritance provide forms of code reuse If a routine manipulates derivedclasses as if they belonged to the parent class, you don’t need to write separate routines to handle eachderived class If you write a routine to send email to a Personobject, you don’t need to write separateroutines to deal with User, BugManager, Developer, and ReleaseCoordinatorobjects
Trang 11Similarly, inheritance allows derived classes to reuse the code in their parent classes If the Personclassdefines Name, Address, and Phoneproperties, you don’t need to define those properties in the User,
To take the greatest advantage of polymorphism, design and later program with the highest-level, mostabstract object types that you can Suppose the application needs a piece of code that generates a reportlisting bugs by date created and then prints the report Rather than making the code work with a
ReportByDateobject, write it to work with a variable from the parent class Report Then you can reusethe code to work with other kinds of reports You may need to add some additional code to create thedifferent kinds of reports (or use a factory object to create the report without knowing what type it is),but the rest of the routine should be the same for each report type
To get the most out of inheritance, move functionality as high up the inheritance hierarchy as possible
If the derived classes all have similar functionality, move the functionality into the parent class Then thebenefits of inheritance follow automatically
These ideas of looking for ways to make code more general sometimes contradict the agile philosophy of implementing the simplest possible solution for the given situation without regard for code you will need to write later.
For example, if you need to sort a list that could contain up to three integers, a simple series of If Then
statements will suffice There’s no need to waste extra time writing a powerful routine that uses the bucketsort algorithm to sort huge numbers of values of arbitrary data types That version will be harder
to write, debug, and maintain, and would provide no additional advantage over the simpler solution.
Though the keep-it-simple philosophy is important for agile development (and actually applies to agile development, too), there’s no need to be intentionally stupid If you see an opportunity to make the code more flexible without a lot of extra effort, take it This is particularly important during the early stages of design where decisions will have far-reaching consequences.
non-When you write a subroutine or design a class, ask yourself if small changes would make it more general.Can you make the routine work with more generic ancestor objects? Can you move common features into
a parent class? Both of these will promote code reuse
UML
Universal Modeling Language (UML) is a design tool that developers can use to model a system’s behavior.
The idea is that a set of UML diagrams, use cases, and other depictions are to software engineers whatblueprints are to structural engineers and architects Once you have a UML representation of an applica-tion, you should be able to send that representation to all of the developers so that everyone has the sameview of how the system should behave With this common vision, the developers can then start imple-menting their separate pieces of the systems, confident that they are all working toward the same goal
In addition to providing a consistent model of the application’s behavior for the developers, some projectsuse UML to allow the users to help specify and understand the application Unfortunately, UML is notintuitively obvious It takes some training and practice to use UML effectively Few users have experiencewith UML, and training them in its use can be difficult and time-consuming Even after they understandthe ideas of UML, they may not have a good understanding of what the diagrams really mean If youhave sophisticated users that either already understand UML or who pick it up quickly, you can use UML
Trang 12to help ensure that the design implemented by the developers matches the expectations of the users asspecified by the diagrams If your users don’t have previous experience with UML, you might want tofocus only on the most intuitive diagrams: use case diagrams and activity diagrams.
In the projects I’ve worked on, we always tried to interact with the users in their own language We
used simple tools that they use regularly and that are comfortable for them, such as word processing
applications, spreadsheets, email, telephones, and face-to-face conversations We wanted them to focus
on their knowledge of the problem space and not get bogged down trying to learn UML or other opment tools We wanted the users to concentrate on what they wanted to happen, and let the develop- ers make software architecture decisions.
devel-The following sections describe the most common types of diagrams defined by UML devel-The intent ofthese sections is to give you an idea of what UML can do, not to be an exhaustive tutorial They describeonly relatively simple versions of the diagrams UML is a fairly complicated tool and includes many
detailed variations To really learn UML, see a book about the subject such as Professional UML with Visual Studio NET by Andrew Filev et al (Indianapolis: Wrox, 2002) or UML in Practice: The Art of Modeling Software Systems Demonstrated thorough Worked Examples and Solutions by Pascal Roques
(Indianapolis: John Wiley & Sons, 2004)
Use Case Diagrams
A use case is a script for an action that the users will perform with the system It describes the steps that auser will follow to perform some specific task When the application is finished, the users can run throughthe use cases to verify that the application can handle them all
The use cases for the bug reporting system describe how the users perform various actions For example,these would include the following:
❑ User enters a bug report
❑ Bug manager reviews a bug and assigns it to a developer
❑ Developer reproduces the bug, studies it, fixes it, and moves it into the “fixed” state
❑ Developer fails to reproduce the bug and returns it to the user for more information
❑ Developer reproduces the bug, studies it, discovers it should be better handled by anotherdeveloper, and returns it to the bug manager for reassignment
❑ Release coordinator tests the fix and releases a new executable and user documentation
❑ User generates a report giving a specific bug’s status
❑ User generates a report listing all bugs with a specific state (for example, “open”)
❑ User generates a report listing all bugs with a specific priority (for example, “high”)
❑ Bug manager generates a report showing all bugs by code module
❑ Bug manager generates a report showing total time spent clearing bugs in code by code module
An application such as this one could easily have several dozen use cases Depending on the numberand types of reports needed, it could have more than 100 use cases
Trang 13I’ve worked on projects with a wide variety of use case needs Some projects have only a couple of fairly straightforward use cases One of my most recent projects had only one use case, but it was extremely complex, involving about two dozen steps and close to 1,000 data entry fields Other projects I’ve worked on had more than 100 use cases.
A project’s complexity and flexibility determines the number of use cases In fact, the number of use cases you and the users can come up with is a reasonable first measure of how complex an application will be, although sometimes a fairly simple but powerful application can provide enough flexibility to handle a large number of use cases.
Typically, a use case is a script that explains what each of the actors in the scenario need to do It should specify what needs to be done, but not how it should be done The application’s design will determine
how the actors accomplish their tasks
For example, the use case for entering a new bug report might look like the following:
The purpose of the UML use case diagrams is to help you visualize how the system’s actors interact with the
use cases They also show how the use cases relate to each other by showing which actors perform the usecases For example, the “User enters a bug report” use case is related to the “User creates bug reports”use cases because the same actor performs them: the user
Use cases are drawn as ellipses Actors are drawn as stick figures Lines connect the actors to the usecases that they perform
To keep the use case diagrams simple, use cases are grouped into categories Instead of listing every sible user report use case, the diagram contains a single object representing the “generate basic reports”group of use cases
pos-The user enters data describing the bug including:
❑ Bug priority
❑ Date and time of bug
❑ Description of what the user was trying to do
❑ Description of actions the user took
❑ Description of what actually happened
❑ Error messages received
❑ Operating system and computer hardware
Trang 14Figure 4-2 shows a use case diagram for the Bug Hunter application.
Figure 4-2: Use case diagrams show the relationships between actors and use cases
The diagram also helps clarify who performs which actions for use cases that may not have been initiallyspelled out in the requirements In this example, the diagram shows that every actor can generate basicreports (bugs by severity, bugs by status), but only the bug manager and release coordinator can gener-ate advanced reports (bugs by module, bugs by developer)
From Figure 4-2, you can also see that some use cases are naturally grouped in a one-to-one mapping withcertain actors For example, only the developer performs the “Fix bug,” “Return bug,” and “Reassignbug” use cases, so you could group them into a larger category of “Developer cases.” Similarly you couldgroup the “Release fix” and “Reject fix” use cases into “Release coordinator cases.”
Use case diagrams can help the users understand the different roles the systems will define This exampledefines four roles: user, bug manager, developer, and release coordinator The use case diagram showswhich activities these actors will perform Often, you can use this as a basis for the application’s permis-
User
Bug Manager
Developer
ReleaseCoordinator
Enter bug report
Generateadvanced reports