A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

Programação Pragmática

Apresentações semelhantes


Apresentação em tema: "Programação Pragmática"— Transcrição da apresentação:

1 Programação Pragmática
Kleber Silva, 11/10/2005

2 Agenda Conceitos O Programador Pragmático Uma Abordagem Pragmática
As Ferramentas Básicas A Paranóia Pragmática Dobre ou Quebre Antes da Implementação... Testes Conclusões

3 Conceitos Criada por Andrew Hunt e David Thomas em 1999
Indica boas práticas de programação e alerta para as maiores armadilhas na área de desenvolvimento de software Principalmente voltada para o programador e para a equipe de programação

4 O Programador Pragmático
Adoção Cedo/Adaptação Rápida – Tem um traquejo para tecnologias e técnicas, e adora experimentar. Quando lhe é dado algo novo, pega com facilidade e integra com o resto de seu conhecimento. Sua confiança nasce da experiência. Inquisitivo – Tende a fazer perguntas. Isso está legal, como você fez? Você teve problemas com esta biblioteca? Pensador Crítico – Raramente aceita as coisas de pronto sem primeiro averiguar os fatos. Realista – Tenta entender a natureza oculta de cada problema enfrentado. Isso permite um “feeling” sobre o quão difícil as coisas são, ou quanto tempo vai se levar. Pau pra Toda a Obra. Esforça-se ao máximo para ter familiaridade com uma grande gama de tecnologias e ambientes, trabalha para acompanhar novos desenvolvimentos. Capaz de se mover para áreas novas, embora com foco especialista.

5 O Programador Pragmático
Dica 1: Preocupe-se com suas habilidades (expertise); Dica 2: Pense no seu trabalho; Dica 3: Dê opções, não venha com desculpas esfarrapadas (the cat ate my source code); Dica 4: Não viva com janelas quebradas; Dica 1: Não adianta se envolver com software se não for para fazê-lo bem feito. Dica 2: Nunca no modo de piloto automático. Critique o que faz real-time. Dica 3: When you do accept the responsibility for an outcome, you should expect to be held accountable for it. When you make a mistake (as we all do) or na error in judgment, admit it honestly and try to offer options. Dica 4 – Software Entropy. Software Rot. Janelas quebradas = design ruim, decisões tronchas, código pobre. Conserte logo que descobrir.

6 O Programador Pragmático
Dica 5: Seja um catalisador de mudanças A Sopa de Pedra Traçando um paralelo com o desenvolvimento de um projeto, muitas vezes nos defrontamos com portas fechadas quando tentamos um solução pra atacar a construção do produto. Pessoal, orçamento tudo pode complicar. Maravilhe as pessoas de forma que eles contribuam sem sentir para a realização de uma obra.

7 O Programador Pragmático
Dica 6: Lembre-se do contexto global O Sapo Cozido Note that the frog's problem is different from the broken windows issue discussed in Section 2. In the Broken Window Theory, people lose the will to fight entropy because they perceive that no one else cares. The frog just doesn't notice the change. Don't be like the frog. Keep an eye on the big picture. Constantly review what's happening around you, not just what you personally are doing.

8 O Programador Pragmático
Dica 7: Faça da qualidade um ponto importante nos requisitos Good Enough Software Striving to better, oft we mar what´s well. King Lear 1.4 Look at the manufacturers of the software tools and operating systems that you use. Can you find any evidence that these companies are comfortable shipping software they know is not perfect? As a user, would you rather (1) wait for them to get all the bugs out, (2) have complex software and accept some bugs, or (3) opt for simpler software with fewer defects?

9 O Programador Pragmático
Dica 8: Invista regularmente em seu portfólio de conhecimento Aprenda pelo menos uma nova linguagem a cada ano Leia um livro técnico a cada 4 meses Leia livros não técnicos também Participe em grupos de usuários locais Experimente diferentes ambientes Fique atualizado Antene-se Read a technical book each quarter. Bookstores are full of technical books on interesting topics related to your current project. Once you're in the habit, read a book a month. After you've mastered the technologies you're currently using, branch out and study some that don't relate to your project. Read nontechnical books, too. It is important to remember that computers are used by people—people whose needs you are trying to satisfy. Don't forget the human side of the equation. Stay current. Subscribe to trade magazines and other journals (see page 262 for recommendations). Choose some that cover technology different from that of your current project. Get wired. Want to know the ins and outs of a new language or other technology? Newsgroups are a great way to find out what experiences other people are having with it, the particular jargon they use, and so on. Surf the Web for papers, commercial sites, and any other sources of information you can find.

10 O Programador Pragmático
Dica 9: Analise com visão crítica o que você lê e o que você ouve Dica 10: É tanto o que você diz quanto a forma como diz Dica 9: Never underestimate the power of commercialism. Just because a Web search engine lists a hit first doesn't mean that it's the best match; the content provider can pay to get top billing.

11 Uma Abordagem Pragmática
Os males da duplicação Dica 11: DRY – Don´t Repeat YourSelf Duplicação Imposta Múltiplas Representações de Informações (Uso de MetaDados) Documentação no Código Documentação e Código Issues de Linguagem- i.e. headers do C, C++ Duplicação por desatenção Ex: Documentação no Código - Programmers are taught to comment their code: good code has lots of comments. Unfortunately, they are never taught why code needs comments: bad code requires lots of comments. Issues de Linguagem - Many languages impose considerable duplication in the source. Often this comes about when the language separates a module's interface from its implementation. C and C++ have header files that duplicate the names and type information of exported variables, functions, and (for C++) classes class Line { public: Point start; Point end; double length; }; class Line { public: Point start; Point end; double length() { return start.distanceTo(end); } }; ou

12 Uma Abordagem Pragmática
Os males da duplicação (continuação) Dica 11: DRY – Don´t Repeat YourSelf Duplicação por Impaciência “Shortcuts make for long delays” Duplicação Interdesenvolvedores Dica 12: Facilite o Reuso Duplicação Por Impaciência - You may well save some seconds now, but at the potential loss of hours later. Think about the issues surrounding the Y2K fiasco. Many were caused by the laziness of developers not parameterizing the size of date fields or implementing centralized libraries of date services. Interdeveloper Duplication - We heard firsthand of a U.S. state whose governmental computer systems were surveyed for Y2K compliance. The audit turned up more than 10,000 programs, each containing its own version of Social Security number validation.

13 Uma Abordagem Pragmática
Ortogonalidade Tipo de independência ou desacoplamento

14 Uma Abordagem Pragmá- tica
Sistemas Não Ortogonais

15 Uma Abordagem Pragmática
Ortogonalidade Dica 13: Elimine o efeito entre coisas não relacionadas Produz ganhos de produtividade Facilita o Reuso Reduz Risco Aplicável a equipes de projeto Design Toolkits e ferramentas Design = Most developers are familiar with the need to design orthogonal systems, although they may use words such as modular, component-based, and layered to describe the process. ToolKits & Ferramentas = If a class were made remotely accessible using RMI, every call to a remote method in that class could potentially throw an exception, which means that a naive implementation would require us to handle the exception whenever our remote classes were used. Using RMI here is clearly not orthogonal: code calling our remote classes should not have to be aware of their locations. The alternative—using CORBA—did not impose that restriction: we could write code that was unaware of our classes' locations. When you bring in a toolkit (or even a library from other members of your team), ask yourself whether it imposes changes on your code that shouldn't be there. If an object persistence scheme is transparent, then it's orthogonal. If it requires you to create or access objects in a special way, then it's not. Keeping such details isolated from your code has the added benefit of making it easier to change vendors in the future.

16 Uma Abordagem Pragmática
Ortogonalidade Código Mantenha desacoplado Evite dados globais Evite funções similares Teste É facilitado Documentação Separação conteúdo e apresentação Evite funções similares = fatorar o algoritmo central. Se tem funções similares é sinal de falha estrutural.

17 Uma Abordagem Pragmática
Reversibilidade Tudo muda Dica 14: Não há decisões finais (irredutíveis) Arquitetura Flexível Time for a little quantum mechanics with Schrödinger's cat. Suppose you have a cat in a closed box, along with a radioactive particle. The particle has exactly a 50% chance of fissioning into two. If it does, the cat will be killed. If it doesn't, the cat will be okay. So, is the cat dead or alive? According to Schrödinger, the correct answer is both. Every time a sub-nuclear reaction takes place that has two possible outcomes, the universe is cloned. In one, the event occurred, in the other it didn't. The cat's alive in one universe, dead in another. Only when you open the box do you know which universe you are in. But think of code evolution along the same lines as a box full of Schrödinger's cats: every decision results in a different version of the future. How many possible futures can your code support? Which ones are more likely? How hard will it be to support them when the time comes? Dare you open the box? O gato de Schrodinger

18 Uma Abordagem Pragmática
Tracer Bullet Usado para construção de algo novo: i.e. tecnologias, técnicas, linguagens e algoritmos Dica 15: Use Tracer Bullets para encontrar o alvo Abordagem incremental Abordagem Incremental = Tracer development is consistent with the idea that a project is never finished: there will always be changes required and functions to add. It is an incremental approach.

19 Uma Abordagem Pragmática
Tracer Bullet Vantagens Os usuários conseguem ver algo funcionando cedo Os desenvolvedores constroem uma estrutura para trabalhar Você tem uma plataforma de integração Você tem algo para demonstrar Você tem um maior sentimento de progresso Tracer Bullets vs Prototype Dica 16: Use Protótipos para aprender. Tracer Bullets vs. Prototype - You could prototype a user interface for your end users in a GUI tool. You code only enough to make the interface responsive to user actions. Once they've agreed to the layout, you might throw it away and recode it, this time with the business logic behind it, using the target language. Tracer Bullets = archictetural skeleton (cria-se um framework)

20 Uma Abordagem Pragmática
Linguagens do Domínio Dica 17: Programe perto do Domínio do Problema Estimativas Dica 18: Estime para evitar surpresas Qual o grau de acurácia necessário? Estimativas de Cronograma de Projeto “The normal rules of estimating can break down in the face of the complexities and vagaries of a sizable application development. We find that often the only way to determine the timetable for a project is by gaining experience on that same project.”, The Pragmatic Programmer Dica 19: Itere o cronograma com o código Linguagens do Domínio = use "AB123" is not a format. known formats are ABC123, XYZ43B, PDQB, and 42. ao invés de Syntax error: undeclared identifier Grau de Acurácia: If your grandmother asks when you will arrive, she's probably wondering whether to make you lunch or dinner. On the other hand, a diver trapped underwater and running out of air is probably interested in an answer down to the second. What's the value of p?

21 As Ferramentas Básicas
Dica 20: Mantenha o Conhecimento em Plain Text Dica 21: Use o poder dos Command Shells Dica 22: Use bem um único editor Dica 23: Sempre use Controle de Versão de Código Fonte Dica 24: Fixe-se no problema, não nos culpados Dica 25: Não entre em pânico Dica 26: o "select" não está “buggado” Dica 27: Não assuma – prove Dica 28: Aprenda uma Linguagem de Manipulação Plain Text = With plain text, we give ourselves the ability to manipulate knowledge, both manually and programmatically, using virtually every tool at our disposal. Não entre em pânico = If your first reaction on witnessing a bug or seeing a bug report is "that's impossible," you are plainly wrong Não assuma – prove = That's why, when faced with a "surprising" failure, you must realize that one or more of your assumptions is wrong. Don't gloss over a routine or piece of code involved in the bug because you "know" it works. Prove it. Prove it in this context, with this data, with these boundary conditions. Aprenda uma linguagem de manipulação- i.e. Python, TCL, awk e sed do Unix.

22 As Ferramentas Básicas
Geradores de Código Passivo – Uma única vez Ativo – Toma uma representação e converte em código. Quando a representação muda, novo código é gerado Dica 29: Escreva código que escreva código

23 A Paranóia Pragmática Dica 30: Você não pode escrever software perfeito O Programador Pragmático desconfia de si próprio. Dica 31: Design with Contracts (DBC) Précondições Póscondições Invariantes de classe Dica 32: Crash Early Dica 33: Se não pode acontecer. Use Assertions pra garantir que não vai. Dica 34: Use exceções para casos excepcionais Dica 35: Termine o que você começou. (C++ new, delete) Crash Early - However, the basic principle stays the same—when your code discovers that something that was supposed to be impossible just happened, your program is no longer viable. Anything it does from this point forward becomes suspect, so terminate it as soon as possible. A dead program normally does a lot less damage than a crippled one.

24 Dobre ou Quebre Desacoplamento e a Lei de Demeter
Dica 36: Minimize o acoplamento entre módulos Spies, dissidents, revolutionaries, and such are often organized into small groups of people called cells. Although individuals in each cell may know each other, they have no knowledge of those in other cells. If one cell is discovered, no amount of truth serum will reveal the names of others outside the cell. Eliminating interactions between cells protects everyone. We feel that this is a good principle to apply to coding as well. Organize your code into cells (modules) and limit the interaction between them. If one module then gets compromised and has to be replaced, the other modules should be able to carry on.

25 Dobre ou Quebre Design para concorrência, para serviços
Separar Views de Modelos (MVC) Programação por coincidência Refactoring Com uso de ferramentas (automático) Wizards Não use se você não entende o código produzido!! Design para testes Foco em testes

26 Antes da Implementação...
Levantamento de Requisitos Trabalhe com o usuário para pensar como ele Dicionário de dados em reuniões com usuários Especificação de mini-linguagem Use Cases Documentação formal ou informal? Poucos detalhes Template para caso de uso - Cockburn

27 Template 1. CHARACTERISTIC INFORMATION Goal in context Scope Level
Preconditions Success end condition Failed end condition Primary actor Trigger

28 Template 2. MAIN SUCCESS SCENARIO 3. EXTENSIONS 4.VARIATIONS
5. SCHEDULE 6. OPEN ISSUES

29 Template 8.RELATED INFORMATION Priority Performance target Frequency
Superordinate use case Subordinate use cases Channel to primary actor Secondary actor Channel to secondary actor

30 Template

31 Testes Unitários Integração Validação e Verificação
Dados Regressão Testes de Performance Testes de Usabilidade Teste os testes!!! Cause bugs

32 Conclusão Não é só teoria, e sim uma abordagem da experiência que normalmente dá certo na área de desenvolvimento; Serve não somente para os programadores, mas também para a gerência dos projetos que se beneficia do conhecimento do que se deve fazer e do que deve ser evitado Promove um ganho de produtividade aos desenvolvedores Promove um maior nível de formalidade no levantamento de requisitos através do uso de templates específicos Metodologia com enfoque nos testes e no design.

33 Referências Andrew Hunt, David Thomas, The Pragmatic Programmer, Addison-Wesley, 2000

34 Dúvidas ???


Carregar ppt "Programação Pragmática"

Apresentações semelhantes


Anúncios Google