Docsity

Qualidade de código, Notas de estudo de Informática

Pré-visualização parcial do texto

Baixe Qualidade de código e outras Notas de estudo em PDF para Informática, somente na Docsity!

Pontif´ıcia Universidade Cat´olica de Minas Gerais Bacharelado em Ciˆencia da Computa¸c˜ao Algoritmos e Estruturas de Dados II Prof. Fabio Tirelo

Qualidade de C´odigo

Tipos Abstratos de Dados

Ultima atualiza¸^ ´ c˜ao: 20 de Julho de 2005

Qualidade de C´odigo

Fatores M´ınimos de Qualidade

  • Funcionamento;
  • Eficiˆencia de tempo e espa¸co;
  • Coment´arios, indenta¸c˜ao, escolha de identificadores, etc;

Modularidade

  • M´odulo: artefato de programa¸c˜ao que pode ser desenvolvido e compilado separadamente de outras partes do programa.
  • Encapsula¸c˜ao: esconder detalhes da implementa¸c˜ao reve- lando somente uma pequena interface de uso.
  • Coes˜ao: for¸ca relativa de um m´odulo.
  • Acoplamento: n´ıvel de inter-dependˆencia entre os m´odulos de um programa.

Abstra¸c˜ao: ato de descartar o que ´e acidental, detalhe ou pr´oprio do modo de resolver, concentrando-se no que ´e relevante, es- sencial, ou pr´oprio de uma especifica¸c˜ao.

  • Abstra¸c˜ao de express˜oes;
  • Abstra¸c˜ao de comandos;
  • Abstra¸c˜ao de declara¸c˜oes de vari´aveis (dados);
  • Abstra¸c˜ao de declara¸c˜oes de tipos.

Estrutura de Dados I

import aed2.Util;

// ´Indice da tabela ´e o n´umero de matr´ıcula public class TabelaAlunos { private int maxMatric; private String alunos []; public TabelaAlunos(int nd) { Util. valida (nd > 0, ”N´umero de d´ıgitos inv´alido ”); int nPos = (int) (Math.pow(10, nd) + 0.5); alunos = new String[nPos]; maxMatric = nPos − 1; } public void adicionaAluno(int matr, String nome) { Util. valida (matr >= 0 && matr < maxMatric, ”N´umero de matr´ıcula inv´alido!”); alunos [matr] = nome; } public String obtemAluno(int matr) { Util. valida (matr >= 0 && matr < maxMatric, ”N´umero de matr´ıcula inv´alido!”); return alunos[matr]; } }

Estrutura de Dados II

class Aluno { public int matr; public String nome; public Aluno(int mat, String n) { matr = mat; nome = n; } }

import aed2.Util; // Vetor de pares ( matr´ıcula ,nome) public class TabelaAlunos { private int nElem; private Aluno alunos []; public TabelaAlunos(int tam) { nElem = 0; alunos = new Aluno[tam]; } public void adicionaAluno(int matr, String nome) { ... } public String obtemAluno(int matr) { ... } }

Estrutura de Dados III

// Vetor de pares ( matr´ıcula ,nome), ordenado por matr´ıcula

// Realiza inser¸c˜ao ordenada no vetor public void adicionaAluno(int matr, String nome) {

Util. valida (matr > 0, ”Matr´ıcula inv´alida ”); Util. valida (nElem < alunos.length, ”Ultrapassou tamanho do vetor”);

int cont = nElem − 1; while (cont >= 0 && alunos[cont].matr > matr) { alunos [cont+1] = alunos[cont]; cont++; }

alunos [cont] = new Aluno(matr, nome); nElem++;

}

Estrutura de Dados III...

// Realiza pesquisa bin´aria no vetor public String obtemAluno(int matr) {

Util. valida (matr > 0, ”Matr´ıcula inv´alida ”);

boolean encontrado = false; int inf = 0, sup = nElem − 1, meio = (nElem − 1)/2;

while (! encontrado && inf <= sup) {

meio = (inf + sup)/2; if (alunos [meio].matr == matr) encontrado = true; else if (alunos [meio].matr < matr) inf = meio + 1; else sup = meio − 1;

}

if (encontrado) return alunos[meio].nome; else return null;

}

TAD Pilha

Defini¸c˜ao: Uma Pilha ´e um conjunto de elementos no qual o ´unico elemento acess´ıvel ´e o elemento inserido h´a menos tempo, denominado topo.

Ao se retirar um elemento de uma pilha, retira-se sempre o elemento do topo.

Opera¸c˜oes:

  • Stack-Empty(S): Verifica se a pilha est´a vazia.
  • Push(S, x): Insere x no topo da pilha S;
  • Pop(S): Retira o elemento do topo de S;

Implementa¸c˜ao como vetor de tamanho fixo:

  • Pilha com no m´aximo n elementos: vetor S[1.. n];
  • H´a um atributo top[S] que define o ´ındice do topo;
  • Elementos nas posi¸c˜oes S[1.. top[S]]

Opera¸c˜oes do TAD Pilha

Stack-Empty(S)

1 if top[S] = 0 2 then return true 3 else return false

Push(S, x)

1 top[S] ← top[S] + 1 2 S[top[S]] ← x

Pop(S)

1 if Stack-Empty(S) 2 then error “underflow” 3 else top[S] ← top[S] − 1 4 return S[top[S] + 1]

Exemplo de Uso da Abstra¸c˜ao

Clonagem:

public static Stack p2p n(Stack S) { Stack result = new Stack(), aux = new Stack(); while (! S.empty()) aux.push(S.pop()); while (! aux.empty()) { int val = aux.pop(); S.push(val ); result .push(val ); } return result ; }

Clonagem Invertida:

public static Stack p2p i(Stack S) { Stack result = new Stack(), aux = new Stack(); while (! S.empty()) { int val = S.pop(); aux.push(val ); result .push(val ); } while (! aux.empty()) S.push(aux.pop()); return result ; }

Implementa¸c˜ao do TAD Pilha – Vers˜ao II

Implementa¸c˜ao utilizando vetores flex´ıveis public class Stack { private static final int DEFAULT SIZE = 10; private int store [], top; public Stack(int maxElements) { store = new int[maxElements + 1]; } public Stack() { this(DEFAULT SIZE); } public boolean empty() { return top == 0; } public void push(int element) { if (top == store.length − 1) grow(); store [++top] = element; } private void grow() { int oldstore [] = store; store = new int[2 ∗ oldstore. length ]; for (int i = 0; i < oldstore. length ; i++) store [ i ] = oldstore [ i ]; } public int pop() { Util. valida (! empty(), ”UNDERFLOW”); return store [top−−]; } }

Aplica¸c˜ao: Soma de N´umeros Grandes

public class SomaNumerosGrandes { public static void main(String [] args) { Stack stk1 = strToStack(”6897890123456”); Stack stk2 = strToStack(”5897890123456”); Stack stkRes = soma(stk1, stk2); System.out. println (stackToStr(stkRes )); } private static String stackToStr(Stack stkRes) { String res = ””; while (! stkRes.empty()) res += stkRes.pop(); return res; } private static Stack soma(Stack stk1, Stack stk2) { Stack result = new Stack(); int vaium = 0; while (! stk1 .empty() ||! stk2 .empty()) { int val1 = stk1.empty()? 0 : stk1 .pop(); int val2 = stk2.empty()? 0 : stk2 .pop(); int res = val1 + val2 + vaium; result .push(res % 10); vaium = res / 10; } if (vaium > 0) result .push(vaium); return result ; } private static Stack strToStack( String strNum) { Stack stkNum = new Stack(strNum.length()); for (int i = 0; i < strNum.length(); i++) stkNum.push(strNum.charAt(i) − ’0’); return stkNum; } }

Aplica¸c˜ao: Sa´ıda de um Labirinto

Considere um labirinto armazenado em um arquivo texto da seguinte maneira:

11 11 11 11 x x x x x x x x x x x x x x x x x x x x x x x x x x..... x x x x x x x x. x... x x x E x x x E. x..... x x x x x x x x x x x x x x x x. x x x x x x x x x x... x x x x x x x x. x x x x x x x x x x x x x x. x x x x M x x x x x M x. x x x x x x... x x x x x x x x x x x x x x x x x x x x x x x x

Legenda:

  • M representa a posi¸c˜ao do rato;
  • E representa a posi¸c˜ao de sa´ıda do labirinto;
  • x representa um muro.

O objetivo ´e fazer com que o rato encontre a sa´ıda.

Aplica¸c˜ao: Sa´ıda de um Labirinto...

public class Position { private int row, column; public Position (int row, int column) { this .row = row; this.column = column; } public int getColumn() { return column; } public void setColumn(int column) { this .column = column; } public int getRow() { return row; } public void setRow(int row) { this .row = row; } public String toString () { return ”(” + row + ”,” + column + ”)”; } }

public class MazeProgram { public static void main(String [] args) throws FileNotFoundException, IOException { Maze maze = new Maze(”teste.txt”); maze.findExitPath (); } }

Aplica¸c˜ao: Sa´ıda de um Labirinto...

public class Maze { // Constantes private static final char MOUSE = ’M’; private static final char EXIT = ’E’; private static final char FREE = ’ ’; private static final char VISITED = ’.’; private static final char WALL = ’x’; // Atributos da classe private char mazeTable [][]; private Position aux [][], posMouse, posExit; private int nRows, nColumns; // Construtor public Maze(String fileName) throws FileNotFoundException, IOException { ... } // M´etodo da interface : p´ublico public void findExitPath () { ... } // M´etodos auxiliares : privados private void readPosition (int row, String strRow, int column) { ... } private void allocMazeTable(String strSize ) { ... } private void showPath() { ... } private void showMazeTable() { ... } private void clearMazeTable() { ... } private void pushUnvisited(Stack s , Position p, int row, int col ) { ... } private void markMouseAndExit() { ... } private void markPath() { ... } }