Apresentação em tema: "Curso de Requisitos Módulo 02: UML e Orientação a Objetos"— Transcrição da apresentação:
1Curso de Requisitos Módulo 02: UML e Orientação a Objetos Conceitos Básicos de UML e Orientação a Objetos
2O que é um Modelo? Um modelo é uma simplificação da realidade Pode ser um modelo detalhadoPode ser um modelo mais genéricoUm bom modelo apresenta os itens mais importantes e abstrai os itens menos relevantesUm modelo pode enfatizar a representação estrutural (organização do sistema) ou comportamental (dinâmica do sistema)
3Por que modelar? Nos ajuda a visualizar o sistema que queremos Nos permite especificar a estrutura e o comportamento do sistemaNos fornece um template que nos guia na construção do sistemaPermite documentar as decisões técnicas
4A importância da modelagem Os sistemas hoje são mais complexos do que podemos entender. Por isto, modelamosE quanto mais complexos e caros os sistemas, mais obrigatório se torna modelar, para assim diminuir complexidade e testar conceitos em modelos que se construídos antes seriam caros
5Comunicação não Ambígua Você pode utilizar técnicas de diagramação fornecidas pela UML para comunicar decisões técnicas de forma clara, não ambíguaExistem ferramentas automatizadas para criar estes diagramas UMLUm exemplo é o JUDE, uma ferramenta Open-source para modelar com UML
6UML – Unifield Modeling Language É uma linguagem padrão da indústria para visualizar, especificar, construir e documentar os artefatos de sistemaA UML é independente de tecnologia e define uma linguagem gráfica para apresentar modelos, assim como a semântica para cada elemento gráficoA UML melhora a comunicação entre os membros da equipe
7A linguagem dos diagramas Os vários tipos de diagrama são necessários para representar as diferentes visões do sistemaDiagramasde ClassesDiagramas deCasos de UsoDiagramas deObjetosDiagramas EstáticosDiagramas deSequênciaDiagramas deColaboraçãoDiagramas deComponenteModelosDiagramas deDeploymentDiagramasde EstadoDiagramas deAtividadeDiagramas Dinâmicos
8Os quatro princípios da modelagem Princípio 01: A escolha do modelo é importanteDepende da visão que se quer modelar (comportamento ou estrutura?)Princípio 02: Os níveis de precisão podem variarDepende de quem é o consumidor do modelo (para o cliente, um modelo de alto nível, para o desenvolvedor um mais detalhado)Princípio 03: Os melhores modelos estão conectados com a realidadePrincípio 04: Um único modelo não é suficientePelo menos dois modelos são necessários, um para comportamento (diagrama de sequência) e outro para estrutura (diagrama de classes)
9Principais diagramas utilizados pelo Analista de Requisitos Diagrama de Casos de UsoEstabelece o escopo do sistema e todos os seus possíveis usos pelos usuários (atores)Diagrama de AtividadesRepresenta o fluxo de atividades que ocorrem em um caso de uso em resposta às requisições do atorDiagrama de ClassesModela quais classes participam da realização do caso de uso (estrutural)Diagrama de SequênciaModela qual é o comportamento das classes para atender ao ator do caso de uso (comportamento)
10Orientação a objetosPara entendermos melhor como modelar, precisamos entender os conceitos básicos de orientação a objetosA UML se baseia na Orientação a ObjetosA Orientação a Objetos possibilita representar a realidade nos modelos UMLA Orientação a Objetos permite abstrair itens e tornar relevantes outros itens
11O que é um Objeto?Os objetos permitem representar coisas do mundo real, como:Entidade Física: pessoas, carros, documentosConceitos: processo químico, algoritmosEntidade de Software: Collections, TelasTodos objetos tem 2 componentes-chave:Atributos, que definem o estado do objetoOperações, que definem o comportamento do objetoEntidade físicaEntidade ConceitualEntidade de software
12Um objeto tem estadoO estado de um objeto é uma das condições possíveis em que um objeto pode estarO estado normalmente muda com o passar do tempoRepresentados por atributos e seus valores para cada objeto
13Um objeto possui comportamento O comportamento de um objeto é representado pelas operações que o mesmo possuiO comportamento é a forma com que a aplicação se comporta em sua interação com o usuário
14Um objeto tem identidade Cada objeto tem uma identidade única, mesmo que seus estados tenham valores idênticos
15Princípios da Orientação a Objetos AbstraçãoEncapsulamentoModularidadeHierarquia
16O que é abstração?Uma abstração é modelar o que é mais importante e suprimir ou ignorar detalhes pouco importantes, diminuindo a complexidadeA abstração captura a essência de algoUm carro é um exemplo de abstração para um “um veículo movido a motor que transporta pessoas de um local a outro local”.Abstrações dependem do contexto da modelagem (se um sistema de locadora, de recursos humanos, etc)
17O que encapsulamento?Propriedades e comportamentos são encapsulados em objetos e acessados através de uma interfaceUm exemplo de encapsulamento é um acelerador de carro. O motorista não precisa conhecer quais os cabos, componentes e tecnologia envolvidas, apenas apertar a interface “pedal do acelerador”.Uma tela não precisa conhecer como um objeto de cadastro de alunos funciona, apenas chama a operação inserirAluno(dados), passando os dados de cadastro do aluno
18Benefícios do Encapsulamento O encapsulamento melhora a manutenção e a torna menos cara.Ao passar um valor para um método, o estado interno de um componente e seu comportamento interno é alterado, sem que os outros objetos tenham conhecimentoA complexidade fica isolada dentro do objeto, e as demais classes somente utilizam seus serviços
19O que é modularidade?Modularidade ajuda a gerenciar complexidade, dividindo algo que é complexo dentro de peças gerenciáveis
20O que é Hierarquia?O uso de Hierarquia ajuda a organizar elementos, tornando fácil reconhecer similaridades e diferenças
21O que é uma Classe?É uma abstração de características comuns a um conjunto de objetosServe como template para criar objetosUma classe possui propriedades e operações
25Generalização e Herança Generalização é o relacionamento entre classes em que uma classe compartilha sua estrutura e comportamento com uma ou mais classes
27Um Modelo de Caso de Uso é essencialmente Texto The most important part of the use-case model is the text. Many people misinterpret the word “modeling” and believe that use cases are solely about drawing figures and arrows.O SistemaVolta pelo Modelo de CSU- Navegue pelos textos- Liste todos os atores- Liste todos os casos de usoAtor 1Use case 1Ator 2Use case 2Use case 3Ator 3The use-case model consists of both diagrams and text. The diagrams give a visual overview of the system. The text gives descriptions of the actors and the use cases.Use cases involve writing text. Drawing the pictures is only a small part of the effort. Typically, more than 80 percent of all effort during requirements capture is to write the textual description of what happens in each use case, the non-functional requirements, and rules. The description of what happens is called the flow of events.Activity diagrams (previously known as flow charts) are another useful tool you can use to describe a use case. It is quite common to use an activity diagram to describe complex flows of events. When using activity diagrams, it is advisable to use swimlanes to represent each actor and the system. Without swimlanes, the activities float in a “semantic emptiness” and quickly become meaningless.The following diagram is an example from a Withdraw Cash use case for an ATM.Especificação CSU 1- Descrição breve- Fluxo de eventosEspecif. CSU 2- Descrição Breve- Fluxo de eventosEspec. CSU 3- Descrição breve- Fluxo de eventos
28Elementos relevantes da Modelagem These are informal definitions of the two major modeling elements in use- case modeling of system requirements. Go through the definitions briefly.AtorAlguém ou alguma coisa externa, que tem o papel de interagir com o sistemaCaso de UsoRepresenta alguma coisa de valor que o sistema fornece para os seus atoresAtorCaso de UsoAn actor represents a role that interacts with the system.A use case describes a sequence of interactions between actors and the system that occur when an actor uses the system to achieve a certain business goal.A use case describes:The system, its environment, and the relationship between them.How things outside the system interact with the system.The desired behavior for the system.Use cases are containers for contextually related requirements of the system under development. They are containers because they group all requirements related to achieving a particular goal into a single story of how that is achieved.A use case is shown as an ellipse containing the name of the use case. An optional presentation is to place the use case name under the ellipse.Use Case
29O que é um Caso de Uso? Nome do Caso de Uso Animation:The slide starts with the ellipse and its label. One mouse click starts the animation, and then it is automatic. The use case definition is “built” with each phrase appearing in blue then fading to yellow as you move to the next piece.Emphasize the importance of each of the key phrases in the definition of a use case.Nome do Caso de UsoUm Casode UsoDefine a seqüência de açõesRealizado pelo sistemaA use case describes a set of possible executions of the system. It describes a complete flow through the system until the resulting value is achieved for some actor.“Sequence of actions”: Atomic activities, decisions, and requests. Each action is performed fully or not at all.“Performed by a system”: The actions performed by the system are the functional requirements.“Observable result of value”: Make sure that the use case results in an observable value. Why would anybody use the system if it does not achieve a result of value? If nobody receives value from the use case, then the use case is probably too small. It needs to be combined with other use cases to provide a complete set of steps for achieving some goal for an actor.“To an actor”: Decide which particular actor receives the value and helps avoid use cases that are too large. If more than one actor receives value from a use case, it might indicate that the use case is too big; it tries to do too much for too many actors. For example, in the Course Registration System, there could be just one use case, called “Operate the Registration System.” It would achieve a variety of results for a variety of actors. It would be so big that it is hard to understand. It needs to be broken into smaller use cases. Use cases that do not deliver something of value are too small and usually describe individual functions of the system. These use cases do not make sense on their own and must be avoided.Often the sequence of interactions in a use case involves several actors. But one actor receives the result of value. The actor receiving the value is sometimes called the primary actor. The actor receiving the value is usually, but not necessarily, the one who initiated the use case.Que produz um resultado de valorPara um ator.
30O Caso de Uso contêm os Requisitos de Software Use cases contain functional software requirements.Cada caso de usoDescreve ações no sistema que entrega algo de valor para um ator.Apresenta a funcionalidade do sistema usada pelo atorModela o diálogo entre sistema e ator.É um fluxo de eventos completo e significativo dos eventos da perspectiva de um ator em particularUse cases contain the detailed functional software requirements. Every time a use case says, “The system …,” is a detailed requirement of what the system must do.Also, remember the definition: “A sequence of actions performed by a system that yields a measurable result of value for a particular actor.”
31Benefícios dos Casos de Uso Start by emphasizing the key concepts of use-case modeling.Emphasize the ways the use cases help facilitate agreement (see student notes).Optional class exercise (initiated by instructor): The exercise involves whispering the rhyme: ‘twas Christmas time at Santa’s place, the sleigh was stacked with loot. “You can’t go out,” cried Mrs. Claus. “I’ve gone and shrunk your suit!”’Each person whispers the rhyme to the person next to them until it goes round the room. The last person repeats the rhyme back, and it is usually very wrong.The message or key point:Every time you rewrite a requirement, something is lost or added. Unlike more traditional forms of requirements capture, use cases do not require any form of translation in order to make them useful to all stakeholders. Use cases reduce the possibility of errors creeping into your requirements. Use cases feed directly into all facets of system development.The funniest answer I’ve seen is: “Santa Claus and Mrs. Claus going down a luge. Mrs. Claus is wearing a skirt and it keeps getting caught in the rails. Ken is there, also.”Dá um contexto para os requisitos.Coloca os requisitos do sistema em seqüência lógicaIlustra porque o sistema é necessário.Ajuda a verificar se todos requisitos foram atendidos.São fáceis de entender.Usa terminologia que clientes e usuários utilizam.Fala de estórias concretas de uso do sistemaVerifique o entendimento dos stakeholdersFacilita o acordo entre os clientes.Facilita reuso: teste, documentação, e projeto.Do you have any problems in these areas with your current requirement process?Use cases are a way to organize requirements from a user perspective. All the requirements for a user to accomplish a particular task are gathered together in a single use case. The use-case model is the collection of all the individual use cases.Advantages of use-case modeling include:Use cases show why the system is needed. Use cases show what goals the users can accomplish by using the system.System requirements are placed in context. Each requirement is part of a logical sequence of actions to accomplish a goal of a user.Use cases are easy to understand. The model expresses requirements from a user perspective and in the user’s own vocabulary. The model shows how users think of the system and what the system should do. Traditional forms of requirements capture need some translation to make them useable to different stakeholder types. When you translate something, information is often lost or misinterpreted. Use cases require no such translation and therefore provide a more consistent and reliable form of requirement capture.The model is a means to communicate requirements between customers and developers to make sure that the system we build is what the customer wants.Use-case modeling is the best tool (so far) to capture requirements and put them in context.
32Ciclo de Vida de Casos de Uso Fechar MatrículasDescobertoDescrição Breve: Este caso de uso permite ao Digitador fechar o processo de matrículas. Ofertas de curso que não possuírem alunos serão canceladas. O sistema de Cobrança é notificado com todos os dados de matrícula para assim efetuar as devidas cobranças.Descreva brevementeResumo do Fechar Matrículas-Fluxo de EventosPasso-a-PassoRabiscadoIn all but the most trivial of systems, use cases are not written in one sitting. As with any iterative process, a use case evolves from the spark of an idea to a fully described description of how your system behaves.Initially you “discover” a use case. This is done when you identify and name the goal that the actor is trying to achieve. A use case is discovered once you have named it.Immediately after discovering a use case (usually while you are discussing the name), you create a brief description of the use case. A brief description describes the goal in two or three sentences. For example, the Close Registration Use Case’s brief description is: This use case allows a Registrar to close the registration process. Course offerings that do not have enough students are cancelled. The Billing System is notified for each student in each course offering that is not cancelled, so the student can be billed for the course offering.The next stage of evolution is to outline the use case. This can be a bulleted list of just the basic flow. You may also choose to identify identify (not outline) possible alternate flows. This enables you to identify scenarios and also gain an understanding of the possible size and complexity of the use case.Finally, you fully describe the use case. This is done iteratively. You identify particular flows for development in an iteration and then fully describe and implement just those flows. You then identify flows for subsequent iterations and fully describe and implement those during that iteration. At the end of the project, you have all of your use cases fully described.Prioritization of flows is done during the Manage the Scope of the System workflow detail.Totalmente DescritoFechar Matrículas Especificação de Caso de Uso- Fluxo de Eventos detalhadoRequisitos EspeciaisCondições Pré/Pós
33? Definir Atores: Foco nos papéis Um ator representa um papel que um humano, hardware, ou outro sistema desempenha em relação ao sistema.Os nomes de ator devem representar claramente seu papel.The difference between an actor and an individual system user is that an actor represents a particular class of user rather than an actual user. Several users can play the same role, meaning they can be the same actor. In that case, each user constitutes an instance of the actor.However, in some situations, only one person plays the role modeled by an actor. For example, there may be only one individual playing the role of system administrator for a rather small system.?
34Jodie: É um aluno de Ciências. Atores e PapéisIn an online Course Registration System at a local college, Charlie is a professor.Charlie also takes courses at First Community College of Centerville. When he is enrolling in courses on the Course Registration system, he is taking on the role of the Student actor.Point out that a notable exception to the naming rule is when the actor is an external system, Then the actor name is usually the system name.Charlie: Está empregado como professor de matemática e é aluno de Economia.Jodie: É um aluno de Ciências.Matricular em CursoCharlie e Jodie agem como estudantes.Actors are roles. It is important to get away from thinking of actors as persons. In most situations, many different people can play the role of a particular actor. In the Course Registration example, there are many people who are students.At First Community College of Centerville, Charlie is a Professor. Charlie also takes courses at First Community College of Centerville. When he is enrolling in courses on the Course Registration system, he is taking on the role of the Student actor.Jodie is studying as a science undergraduate. She also takes on the role of a Student actor when using the system.The difference between an actor and a system user is that the actor represents a particular type of user rather than an actual user. Several users can play the same role, which means they are all instances of the same actor. Each user playing that role is an instance of the actor.In this example, Charlie and Jodie are students using a course registration system. When they are using the system to register for a course, each person is an instance of the Student actor.EstudanteProfessorSubmeter gradesCharlie também age como Professor.
35Comunicação-Associação Um canal de comunicação entre um ator e um Caso de Uso.Uma linha é usada para representar uma associação de comunicação.Uma flecha indica quem inicia cada interação.Uma linha se flecha indica que o caso de uso ou o ator podem iniciar a interação.This slide describes the relationship between actors and use cases. This relationship is indicated in a use-case diagram by a line or an arrow. An arrow is used to indicate who initiated the interaction.Go over the concepts briefly here, but illustrate them on the next few slides.Actors and use cases are both classifiers in the UML. The rules governing the use of an association are the same for all classifiers, for example, classes.The next slide describes the different uses of the arrow heads.Ator 1Caso de UsoRelationships between actors and use cases are called communicates-associations. A communicates-association between an actor and a use case indicates that they interact: the actor participates in and communicates with the system containing the use case.A communicates-association is represented on UML diagrams as a solid line. The line can be adorned with an arrow head. The line and arrow represent a two-way dialog between the actor and the system. If an arrow head is present, then only the “thing” at the tail of the association can initiate communication. No arrowhead means that either end can initiate communication (not that both ends do initiate communication).In the example above, Actor 1 always initiates communication with the system. The system may respond to messages from Actor 1, but can never send an unsolicited message to Actor 1. For the second association, the system always initiates communication with Actor 2. Actor 2 may respond to messages from the system, but can never send an unsolicited message to the system. For the third association, Actor 3 or the system may initiate the dialog.For more details, refer to the UML 1.3 Spec. Part 2 – Foundation, 2.5 – Core.Ator 2Ator 3
36Convenções das setas e linhas Use this slide to explain the different use of the arrowheads. See the student notes for details.The point to emphasize is that arrowheads can help clarify important characteristics of the actors.No arrowhead does not mean that either end does initiate communication. It means that either end can initiate communication.If you have two arrows pointing towards a use case, you can increase clarity by adding an «initiates» stereotype to the association between the use case and the actor that starts the use case. You should then describe the semantics of the «initiates» stereotype in your use-case modeling guidelines.Point out that the class examples and sample solutions follow the top form of the notation. It is up to the class if they want to use the top or bottom form during the exercises.Ask: Which form would they prefer to use during this class?Tell the students you will document their choice in the use-case-modeling guidelines and they should conform to that standard for the remainder of the class.Sensor passivoSupervisorMonitorar AlarmesSensor ativoSensor híbridoThe above is an example use case in a fire alarm monitoring system. The Supervisor is the person who administers the system and starts the monitoring.A passive sensor is a smoke detector that requires the system to ask for its status. An active sensor is a smoke detector that automatically sends its status to the system every 60 seconds. A hybrid sensor is a smoke detector that sends its status every 60 seconds, but it can also receive status requests from the system. In this system, if the system does not hear from it in 75 seconds then the system asks the sensor for its status.Observe how the top example conveys important characteristics of the actors surrounding the system. The information describing who starts the use case would be contained in the use-case description. For example: “This use case starts when the Supervisor activates the alarm monitoring.”The bottom example only shows the actor that starts the use case. This means the way the actors communicate with the system is relegated to the description of the actor. But this form is usually more palatable for non-UML savvy stakeholders.Arrowheads are optional in UML, only use them if they help to clarify the diagrams. Whatever standard you adopt, it should be clearly specified in Use-Case-Modeling Guidelines for the project. The Golden Rule for use-case-model guidelines: to effectively communicate the requirements to ALL stakeholders.Note: It is the exception to see two navigation arrows pointing towards a use case. Most of the time you have one arrow pointing in and the rest pointing out. The top example is present to reinforce that the navigation arrow is about indicating who initiates each interaction, not who obtains the goal or who initiates the use case.Sensor passivoSensor híbridoSensor ativoSupervisorMonitorar Alarmes
37Cada Associação de Comunicação é o Diálogo completo O estudante acessa o sistema.O sistema autentica o usuário.Estudante requisita dados do curso.Emphasize that the use- case diagram is intended only to show the actors, use cases, and the relationships between them. But the relationships are spelled out in detail in the descriptions of use cases.Matricular em CursoEstudanteSistema de Cadastro de CursosA communicates-association is a two-way dialog. The relationship between an actor and a use case is represented on the diagram by a single line or arrow, but the single line or arrow represents a whole dialog. For example, the relationship between the Student actor and the Register for Courses use case might include the whole dialog shown on the left side of this slide. The relationship between the Register for Courses use case and the Course Catalog System actor might include the whole dialog shown on the right side of this slide.The dialogs are recorded in the Flows of Events in the use-case specification.Sistema apresenta a lista de cursos.Estudante seleciona curso.Sistema apresenta a agenda do curso.O sistema transmite a requisição.O sistema retorna os dados do curso.
38Um cenário de uma instância de Caso de Uso Matricular em CursoWe’ve touched on the term “scenario” before, but this slide gives an example. Explain the two scenarios for the same use case. Mention that there are dozens of other scenarios for this use case. Ask for a few more examples of scenarios for the Register for Courses use case.See student notes for additional points to emphasize.Sistema de Cadastro de CursosEstudanteCenário 1Autenticar no sistema.Aprova o login.Digitar o assunto.Obter lista de cursos.Apresentar lista de cursos.Selecionar Cursos.Confirmar Disponibilidade.Mostrar grade final.Cenário 2Autenticar no sistema.Aprova o login.Digitar o assunto.Assunto inválido.Entra novamente assunto.Obter lista de cursos.Apresentar lista de cursos.Selecionar Cursos.Confirmar Disponibilidade.Mostrar grade final.A use-case instance describes one particular path through the flows of events described in a use case. It is a specific sequence of actions that illustrates the behavior of the system. This is also called a scenario. In the example here, the sketch of Scenario 1 for the Register for Courses use case shows a Student interacting with the Course Registration System and successfully enrolling in a course the first time. Scenario 2 shows a Student interacting with the Course Registration System and entering an invalid subject; that student must re-enter the subject before successfully getting the course list.A use case defines a set of related scenarios. A use case represents all the possible sequences that might happen until the resulting value is achieved or until the system terminates the attempt. The Register for Courses use case represents both of these sequences, and all the other possible sequences of interactions that may occur when a Student tries to enroll in a course.Users and stakeholders can often identify the sequence of actions they want to perform to obtain a result. Asking stakeholders for the sequence of actions they perform is a good way to start identifying the steps in a use case.
39Diagrama de Caso de Uso Máquina de Auto Atendimento (ATM) Sacar Fundos Animation: One click starts the animation and adds the arrows.Review the sample use-case model depicted in this diagram. Ask the students to describe how the system is used. Then start the animation to make the arrow heads appear.Note: The Cashier empties the deposited funds and uses another banking system to reconcile the amount in the envelope against the amount entered by the Bank Customer when they deposited the funds. In the case of an ATM that is not located in a bank, it is not possible to deposit funds using the ATM.Ask the students if they think the diagram is now clearer. Hopefully the answer should be “yes.”Sacar FundosTransferir FundosClienteBancoConsórcio deBancosDepositar FundosA use-case model shows what the system is supposed to do (use cases), the system's surroundings (actors), and the relationship between actors and use cases.The use-case diagram is a graphical description of the use-case model. Can you tell at a glance what users can do with an ATM?What do you think the priorities for the use cases above would be? The diagram already helps to determine these priorities; without the first one we do not have an ATM, so we better get it right, (e.g. during elaboration); other use cases like deposit funds are nice to have, but would also have quite an architectural impact.It is also useful to distinguish between primary use case and secondary use cases: Primary use cases support the customers/actors and business. Secondary use cases we get, because we decided on a particular technical solution and thus have to specify "extra" functionality to run this technical solution; thus, Maintain ATM, Print logs, Start, Stop, Backup the System, etc are required. These could be also be organized in a separate diagram.Coletar DepósitosCaixaManutençãoManter ATM
40Exemplo: Sistema de Matrículas Demonstrate how use-case modeling might begin:Write the title “Course Registration System” on easel paper. Then draw an oval and label it “Register for Courses” on the board. Explain that this is the beginning of the Course Registration System use-case model. Ask students who would be the actor. Draw and label an actor, “Student.”Draw the second actor, the Course Catalog System. Explain that, in our example system, the course catalog is maintained by a separate system. The Course Registration System calls on the Course Catalog System for information about course descriptions, prerequisites, and so on.Once this is clear, tell students that we are using an online Course Registration System as the example for practice in this module. Students develop this example as they go through the module.Finally, direct students to the section in the Student Workbook that contains the Course Registration Artifacts. Spend five minutes walking through them with the students. The purpose of looking at it now is to give students an idea of what they will be developing before they get started.Sistema de MatrículasEstudanteMatricular em CursoSistema de Registrode CursosOutro caso de usoAtor XThe use-case diagram shown here is a graphic description of the use-case model for an online Course Registration System. It shows two of the actors (Student and Course Catalog System) and one use case (Register for Courses) that they participate in.The diagram is incomplete. You use the online course registration system as a case study in this module. You develop the use-case model for this example as we go through the module.Take some time to look at the use-case model for an online Course Registration System in the Student Workbook. This example gives you an idea of what a use-case model looks like before you begin to develop one.The use-case model for an online Course Registration System in the Student Workbook is incomplete. It contains only enough artifacts for the purpose of this module: Introduction to Use-Case Modeling. A larger, much more fully developed case study is presented later in the course.Ator YCaso de Uso 3
41Como deve ser o nome do caso de uso? Indicar o significado ou objetivo do CSU.Usa a forma ativa; começar com verbo.Imagine uma lista de tarefas.Exemplos de variação:Matricular em cursosMatriculando em cursosConfirmar MatrículaMatrícula em CursoUsar Sistema de MatrículaPoint out the ambiguity of some of these names, for example, “Acknowledge Registration”. Who is doing the acknowledging? The customer? The Online System?The best answer here would probably be “Register for Courses.” But is this really what is happening? (Perhaps from the customer’s perspective.)What about “Registering for Courses”? This is in passive voice.Try to seed some discussion in this area. It is a good idea for each company to have a standard of naming use cases.Emphasize that the name should reinforce the goal of the use case.The main thing is to BE CONSISTENT.One point you may like to note is that the value or goal may not always be tangible. Sometimes the value may not even be to the actor initiating the use case. Instead it may be to another actor in another use case.The UML states that the “observable result of value” part of the definition is something you should strive for to help you identify good use cases, but it is not a rule.Each use case should have a name that indicates what is achieved by its interactions with the actor(s).A good rule of thumb (but not dictated by any standard) is to attach the actor’s name (of the primary actor) at the beginning of the use-case name to see if it makes a meaningful sentence. For example, does it make sense to say “The student registers for a course?” Does it make sense to say, “The student takes a course?”Another approach is to ask, “Why does the actor want to use the system?”Be focused on identifying the goal that is trying to be attained by using the system.Que variações tem maior significado para o usuário? Quais não tem?Que nome de caso de uso você escolhe? Por que?
42Passos para criar o Modelo de Casos de Uso Procurar atores e casos de uso.Identifique e descreva brevemente os atores.Identifique e descreva brevemente casos de usos.Escreva os casos de uso.Desenhe todos os casos de uso.Priorize os fluxos de casos de uso.Detalhe os fluxos por ordem de prioridade.Review the process for developing use-case models. Tell students that each of these activities is covered in more detail in subsequent slides.Creating a use-case model involves putting the pieces you have learned together. First, the actors and the use cases are found by using the requirements of customers and potential users as vital information. As they are discovered, the use cases and the actors are identified and illustrated in a use-case diagram. Next, the steps in a use case are outlined to get a sketch of the flow.The actor's name must clearly denote the actor's role. Make sure there is little risk at a future stage of confusing one actor's name with another.Define each actor by writing a brief description that includes the actor's area of responsibility and what the actor needs the system for. Because actors represent things outside the system, you need not describe them in detail.Each use case should have a name that indicates what is achieved by its interactions with the actor(s). The name may have to be several words to be understood. No two use cases can have the same name.Define each use case by writing a brief description of it. As you write the description, refer to the glossary and, if you need to, define new terms.When the actors and use cases have been found, each use case is described in detail. These descriptions show how the system interacts with the actors and what the system does in each individual case. In an iterative development environment, you select a set of use case flows to be detailed in each iteration. These are prioritized in such a way that technical risk is mitigated early and the customer gets important functionality before less important functionality.
43Procure Atores Quem está operando (interagindo com o sistema)? Explain each system to be built. In the system on top, a registrar is interacting with the Registration System.Ask: Who is the actor? (The answer is “The registrar.”)Ask: Is the student an actor? (The answer is “No” because the student is not interacting with the system.)In the system on the bottom, a student is interacting with the Registrar System.Ask: Who is the actor? (The answer is “The student.”)Ask: What functionality is different between the Registration System and the Online Registration System?EstudanteDigitadorSistema de MatrículasO sistema nunca digita no sistema; o digitador faz isto.Ou, você está construíndo uma aplicação web?To identify the actors for a system, the simplest question to ask is: “Who is doing the actual interaction?” The actor is the one who is interacting with the system.What if a person is using a speech recognition system? Then the actor is the one talking with the system.Sistema de Matrícula Online(www.college.edu)Estudante
44Identifique atores Quem/o que usa o sistema? Point out that this is an important page. Suggest that the students put a sticky note on it so they can find it easily when they want to identify actors.Remind students that an actor is a role. For a human actor, you should usually be able to name several different people who can act as a specific actor. Try to avoid an actor called “User,” rather try to figure out the role of that particular user.One way to do this is to think of the actor in the context of the business that the system is supporting.Quem/o que usa o sistema?Quem/o que obtêm informação do sistema?Quem/o que fornece informação para o cliente?Onde na empresa o sistema é usado?Quem/o que suporta ou mantêm o sistema?Quais outros sistemas usam o sistema?Here are some questions that may be used to help identify the actors in the system.To fully understand the system's purpose, you must know who or what the system is for, that is, who or what use it. Different user types are represented as actors.An actor is any person or any thing that is outside the system and that exchanges data with the system. An actor can either give information, receive information, or give and receive information.Actor is a role, not a particular person or thing. The name of the actor should represent, as clearly as possible, the actor’s role. Make sure that there is little risk of confusing one actor’s name with another at a future stage of the work. Also, try to avoid an actor called “User,” rather try to figure out the role of that particular user.In most instances, some person or some other system does something to trigger the start of the use case. If a use case in your system is initiated at a certain time, for example, at the end of the day or the end of the month, this can be modeled with a special actor, such as the “scheduler” or “time.” “Scheduler,” as opposed to “time,” is a useful name for such an actor because scheduler may be human or non-human. “Time” leaves an element of design in your use case model.
45Descrição de um ator Nome Estudante Descrição Breve Uma pessoa que se registra para um curso.Relacionamentoscom os casos deusoEmphasize that the actor name is a label that can be used to refer to it throughout the model. The brief description should clarify any ambiguity that the name might suggest.Matricular em CursoThis is the information used to describe each actor. Some of the information contained in the brief description is:What or whom the actor represents.Why the actor is needed.What interests the actor has in the system.Some information about the actors is also shown on use-case diagrams. The use-case diagrams show the name of the actor and the actor’s relationships with use cases.EstudanteCaminhar peloCaso de Uso
46Checkpoints para Atores Open up RUP and run through the complete list of checkpoints.Você encontrou todos atores? Você modelou todos os papéis do sistema em atores?O ator está envolvido com pelo menos um caso de uso?Você poderia identificar pelo menos duas pessoas que realizam o papel do ator?Alguns atores desempenham funções semelhantes em relação ao sistema? Se sim, colocá-los em um único ator.The above list of actor checkpoints is a summary of the list in the Rational Unified Process.
47Identificar Casos de Uso By searching for a goal instead of a task, you are forced to take a step back and look for the larger context.You are more likely to avoid functional decomposition when searching for the goal or by being goal-oriented when identifying your use cases.Quais objetivos desejo alcançar utilizando o sistema?Objetivo 1Identifying the use cases is the next step in developing your use-case model, once the actors have been identified. Use cases describe what an actor wants a system to do that provides some value to the actor. Use this process to identify the use cases for each actor.AtorObjetivo 2
48Identifique os Casos de Uso This is an important slide because it gives questions for identifying use cases. Suggest that the students mark this slide (tick the corner or place a sticky note) for easy access later.Emphasize that the use cases are the goals of some actor. What does the actor want to accomplish with the help of the system?In addition to the list of questions on the slide, mention other use cases not to forget (see Student Notes):System startupSystem terminationSystem maintenanceAutomatically schedule eventsQuais são os objetivos de cada ator?Porque o ator quer utilizar o sistema?O ator irá criar, guardar, mudar, remover, ou ler dados no sistema? Se sim, porque?O ator precisa informar ao sistema sobre mudanças ou eventos externos?O ator precisará ser informado sobre certas circunstâncias do sistema?O sistema atende ao négocio com o comportamento correto?Here are some questions that are useful to help you find the use cases in your system. The best way to find use cases is to consider what each actor requires of the system. Go through all the actors and identify the particular needs of each actor.When you have made your first list of use cases, verify that all required functionality has been treated. Do not forget special use cases for system startup, termination, or maintenance. Also, do not forget to include use cases for automatically scheduled events. For example, a time-initiated job may run the payroll at midnight on the last day of each month. Use cases that concern automatically scheduled events are usually initiated by a special actor: the scheduler.Try to keep all use cases at approximately the same level of importance. The notion of use-case levels as popularized by some authors is not recommended. It can lead to a functionally decomposed system.The above questions can help get the right granularity (refer also to the definition of a use case). Ask yourself:Would you ever want to perform a particular activity as an end result in itself?Are there any activities that should be kept together so you can review, modify, test, and document them together?Is the use case too complex? If it is, you may want to split it (a use-case report significantly longer than 10 pages may be a candidate).Give each use case a name that indicates what an instance of the use case does. The name may have to consist of several words to be clearly understood.Does it deliver something of value to multiple actors? If so, it may be too large.
49Descrição do Caso de Uso Nome Matricular em cursoDescrição Breve O estudante seleciona os cursos que deseja para o próximo semeste. Uma grade dos cursos primários e alternativos são gerados.Relacionamentocom atoresOn an easel paper, start making a list of the use- case properties so you can refer to them throughout the course. These are the use-case properties that are included in the Use- Case Model. Further properties of the use case are specified in the Use- Case Specification.Note: Some students may have had some exposure to use cases prior to taking this course. Do not get bogged down in a discussion about structuring relationships at this time. This comes later.This is the information used to describe the use case in the use-case model:Name: The name of the use case.Brief Description: A brief description of the purpose of the use case.Relationships: The relationships (communicates-associations, include, extend and generalization) in which the use case participates.Some information about the use cases is also shown on use-case diagrams in the Use-Case Model. The use-case diagrams show the name of the use case and the relationships with actors.Matricular em cursoEstudante
50Checkpoints para Casos de Uso Open up RUP and run through the complete list of checkpoints.O modelo de caso de uso apresenta o comportamento do sistema; com ele é fácil de entender o que o sistema ao revisar o modelo.Todos os casos de uso foram identificados; o caso de uso conta com todos os comportamentos esperados pelo ator com o qual interage.Todas as características estão mapeadas para pelo menos um caso de uso.O modelo de caso de uso não contêm comportamento supérfulo; todos os casos de uso podem ser justificados ao rastreá-los de volta para os requisitos funcionais.Todos os casos de uso CRUD são removidos.Create, Retrieve, Update, DeleteCheckpoints (continued from slide)Do the use cases have unique, intuitive, and explanatory names so that they cannot be mixed up at a later stage? If not, change their names.Do customers and users alike understand the names and descriptions of the use cases?Does the brief description give a true picture of the use case?Is each use case involved with at least one actor?Do any use cases have very similar behaviors or flows of events?The list of use-case checkpoints is a summary of the list in the Rational Unified Process.A CRUD use case is a Create, Read, Update or Delete use case. Data management use cases like these are another form of function decomposition. Managing the data like this is usually part of some higher goal (typically maintenance of information), and they should be combined into a single use case.For example, instead of having four use cases: “Add Customer”, “Delete Customer”, Update Customer Information”, and “View Customer Details”. You could have a single use case named: “Maintain Customer Details”.
51Decomposição funcional If we allow use cases to be used to model functional decomposition, we are no longer gathering requirements but architecting the system. We have other techniques to do this that are far better than use cases. Also, our use cases is no longer the focus of Project Management, User Interface Design, System Understanding, Functional Test, User Documentation, and so on. So you have "helped" the Designers (if you are lucky… but with poor requirements) at the expense of everything else that is great about Use Cases.É a quebra do problema em partes menores, isoladas.As partes juntas fornecem a funcionalidade do sistema.Muitas vezes não fazem sentido se isoladas.Casos de uso:Não há decomposição funcional.Mantêm a funcionalidade junta para descrever o uso completo do sistema.Fornecer o contexto.Humans deal with complex problems by breaking them up into small manageable pieces. The solutions to these pieces are then assembled to provide a complete solution to the original problem. When applied to computer science, this is called functional decomposition.This microscopic approach means that the requirements for these pieces lose their context. The greater the number of smaller pieces you have, the greater the number of interfaces you need between these pieces and the greater the potential for misfit.Use cases allow you to capture your requirements in a macroscopic form. They still contain the same level of detail as functional decomposition, but the requirements are put into context with each other and thus provide a technique that enables you to develop requirements that are more likely to be understood by your stakeholders as well as enabling you to deliver end-to-end functionality of the system.
52Decomposição Funcional Processar TransaçãoInserir CartãoConsórcio BancárioEntrar PINSelecionar Conta DestinoSelecionar Transferênciade FundosClienteEntrar QuantidadeThe diagram is an example of functional decomposition. The use cases look like a laundry list of steps that the actor performs instead of goals the actor is trying to achieve. In order to withdraw cash from the system, the actor needs to perform these use cases in a particular order. There is no way to show this required sequence.One of the biggest advantages of use cases over functional decomposition is that the requirements in the use cases have context. In the example, the requirements lose their context and their implementation becomes more difficult.What is often not realized about functional decomposition is that the pain is not felt during the requirements gathering activities. Instead it is felt by the implementers and testers of the system. This is because the implementers do not see the relationship between the requirements and testers that are testing use cases end up writing more test cases.The problems caused by this approach are:The requirements have no context, so they are harder to understand.Stakeholders have to read and cross-reference more isolated pieces of information, resulting in a more fragmented development and implementation experience.The goals of the actor are ambiguous.Implementers cannot see the relationship between the requirements.Testers have to write more test scripts (one per use case). These test scripts are “partial tests” because there is no end-to-end description of what the system must do.Selecionar Conta OrigemSelecionar SaqueSelecionar Saldo da Conta
53Evite Decomposição Funcional SintomasCasos de uso pequenosMuitos casos de usoCasos de uso sem resultado realNomes com operações de baixo nível“Operação” + “objeto”“Função” + “dados”Exemplo: “Inserir Cartão”Dificuldade de entender o contexto geralSee student notes.Point out that the RUP checkpoints can help guide you through identification of good use cases. This is covered on the next slide.Ações CorretivasProcure um contexto maior“Porque está construíndo o sistema?”Coloque-se no papel do usuário“O que o usuário quer obter?”“Qual objetivo o caso de uso deve satisfazer?”“Qual valor o caso de uso adiciona?”“Qual é a história do caso de uso?”Use cases are not functional decomposition. You want to avoid functional decomposition. Use cases describe the complete use of the system to achieve a goal.“Small” names are usually a symptom of too small use cases, tiny things that are operations. Nobody understands what the system can do for them by reading a lot of small, tiny bits that are not in context or in order.From a requirements analyst’s point of view, functional decomposition may not appear to be a serious problem. Problems with functional decomposition manifest themselves later in the lifecycle, particularly in the project schedule.If you have a functional decomposition, there will be more use cases to analyze, resulting in more code. More code means more bugs.A functional decomposition may also affect your testing team, resulting in more test cases.The sum of these means that your project takes longer.
54Decomposição Funcional: Um exemplo corrigido Sacar FundosTransferir FundosConsórcio BancárioClienteThe example above is a corrected example of the functionally decomposed use-case diagram seen previously. The benefits of this approach over the former are:The requirements are in context so they are easier to understand.The goals of the actor are clearly visible.All of the requirements related to the three goals are contained in the same use-case specification.Implementers see the relationship between the requirements.Testers can write fewer test cases.Depositar Fundos
55Sistema de Matrícula em Curso Evoluir o Caso de UsoAnimation: Starts automatically.The animation shows the progression of use-case modeling.Use-case diagrams to use- case outlining to use-case detailing. Use cases are documented in a use-case specification.Where do use cases and use-case specifications fit in the process?Take a look at the artifacts for the Course Registration project.Matricularem CursoSistema de Matrícula em CursoEstudante+ Descrição BreveMatricular Online em Curso+ Fluxo de eventos rabiscadoPassos de alto nívelEspecificação de Caso de Usodo Matricular para Curso+ Fluxo de Eventos detalhadoPasso a Passo+ Requisitos Especiais+ Condições Pré/PósThis module exposed you to use cases and use-case terminology. There are two more steps in creating your use-case model. After identifying the use cases, you should outline them to get a rough idea of what the system will do. Once the use cases have been outlined and everyone agrees that the general idea is correct, you progressively detail each use case until you develop a complete description of what the system must do.You’ll work more with use cases in the next few days when creating artifacts for the class project.The Register for Courses diagram, outline, and specification are located in the case study section of the Student workbook.
56Casos de Uso e o RUP ? Analisar o Problema Entender Necessidades do With the intro to use cases, we have:Terms and concepts of use-casesExposure to creating use case diagramsNow what?How do we implement use cases in RM?In Module 4, start RM activities with the class project.What is the problem?Who are the stakeholders?Analisar o ProblemaEntender Necessidades doStakeholderDefinir o SistemaUse-Case Spec.(outline)Gerenciar o EscopoIt is important to understand that use cases are only one tool in your armory for effective requirements management. Use cases are developed progressively over the course of a project, and there are many activities in the requirements management discipline that help you find the information that you want to capture in the use case model.This module has given you a brief introduction to give you a flavor for what use cases are. The remaining modules show you how to effectively manage your requirements and where in the process you work with use cases.Especificaçãode Caso de Uso(detalhada)Refinar o SistemaGerenciar Mudanças de Requisito