<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fabricio Engeroff on Medium]]></title>
        <description><![CDATA[Stories by Fabricio Engeroff on Medium]]></description>
        <link>https://medium.com/@fa.engeroff1996?source=rss-3bca9844656e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WNTNGixFIOeFqstA</url>
            <title>Stories by Fabricio Engeroff on Medium</title>
            <link>https://medium.com/@fa.engeroff1996?source=rss-3bca9844656e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 05:09:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fa.engeroff1996/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Paradigmas de Linguagens de Programação — Parte 2]]></title>
            <link>https://medium.com/@fa.engeroff1996/paradigmas-de-linguagens-de-programa%C3%A7%C3%A3o-parte-2-853af03e6149?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/853af03e6149</guid>
            <category><![CDATA[linguagem-de-programação]]></category>
            <category><![CDATA[teste-de-software]]></category>
            <category><![CDATA[engenharia-de-software]]></category>
            <category><![CDATA[ciência-da-computação]]></category>
            <category><![CDATA[programação]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 10:21:19 GMT</pubDate>
            <atom:updated>2026-11-16T10:21:19.052Z</atom:updated>
            <content:encoded><![CDATA[<p>15 de nov. de 2026 · @Última Conversa</p><p>Você troca a ordem de duas linhas e o resultado muda de 6 pra 4. Dá 10% de desconto e o cliente paga o preço cheio. Digita quantidade -2 e a loja acaba devendo dinheiro pro cliente. Nenhum desses programas deu erro de compilação — todos rodaram liso, e todos estão errados.</p><p>Na parte 1 eu passei pelos fundamentos: o que faz uma linguagem ser boa, paradigmas, sintaxe e semântica, tipos, operadores, estruturas e sub-rotinas. Aqui eu foco no paradigma imperativo, o mais usado de todos: estado, ordem dos comandos, o primeiro programa em C, validação, estruturas de controle, funções e ponteiros. E o fio condutor continua sendo a compra: preço, quantidade e desconto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wh4D7TjoaHHimb86aRPu_Q.png" /></figure><h3>O paradigma imperativo — dar ordens, uma de cada vez</h3><p>Imperativo vem de imperar: dar as ordens. Cada passo é uma ordem, executada na sequência, e cada passo pode mudar os valores guardados na memória. O programa é uma lista de comandos, um depois do outro.</p><p>É o paradigma mais popular e a base de quase todas as linguagens — até porque ele é muito parecido com o funcionamento do próprio computador.</p><p>O mesmo cálculo em C e em Python:</p><pre>double preco = 30;<br>int quantidade = 4;<br>double media = preco / quantidade;   // cada instrução termina em ;</pre><pre>preco = 30<br>quantidade = 4<br>media = preco / quantidade   # sem ; e sem tipo declarado</pre><p>No C você declara o tipo de cada variável, e o ponto e vírgula avisa “a instrução acabou aqui”. No Python não precisa de nenhum dos dois: ele se organiza pela indentação, os espaços no começo da linha. A escrita muda, o jeito de pensar é o mesmo.</p><h3>Estado — a fotografia das variáveis</h3><p>Estado é a fotografia das variáveis num determinado momento da execução. Essa é a característica central do paradigma imperativo.</p><pre>int quantidade = 2;                     // estado: quantidade = 2<br>quantidade = quantidade + 1;            // estado: quantidade = 3<br>double preco = 19.90;                   // estado: quantidade = 3, preco = 19.90<br>double subtotal = preco * quantidade;   // estado: ..., subtotal = 59.70</pre><p>Se alguém pergunta “quanto vale a quantidade?”, a resposta é: depende da linha que você está olhando.</p><h3>O exemplo que derruba a matemática</h3><p>Na matemática, a ordem dos fatores não altera o produto. Na programação imperativa, a ordem dos comandos altera tudo. Começando com x = 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*OaOPtvZBv7i9qK5yZnmmiw.png" /></figure><p>Mesmos comandos, ordem diferente, resultado diferente. Isso acontece em qualquer linguagem imperativa. Num programa imperativo, você precisa acompanhar quem muda cada variável, quando e por quê.</p><h3>Paradigma, linguagem e implementação são coisas diferentes</h3><ul><li>Paradigma — o estilo de arquitetura, a forma de organizar a solução.</li><li>Linguagem — o material e as regras de construção: as palavras e símbolos que você pode usar.</li><li>Implementação — a ferramenta que transforma o código em algo que roda. No caso do C, o compilador GCC.</li></ul><p>Por isso compilador e interpretador não definem o paradigma: uma linguagem ser compilada não a torna imperativa, nem o contrário. Pelo mesmo motivo, usar int, double e char não torna um programa imperativo — isso são recursos da linguagem. O paradigma aparece na forma de organizar os comandos e as mudanças de estado.</p><h3>Do primeiro programa à compra — C na prática</h3><h3>O menor programa em C</h3><pre>#include &lt;stdio.h&gt;          // traz a biblioteca de entrada e saída</pre><pre>int main(void) {            // a porta de entrada do programa<br>    printf(&quot;Olá, turma\n&quot;); // escreve na tela<br>    return 0;               // encerra e avisa o sistema<br>}</pre><p>Compilando com GCC: suponha que o código está salvo em compra.c. No terminal:</p><pre>gcc -std=c17 -Wall -Wextra compra.c -o compra.exe<br>.\compra.exe</pre><ul><li>gcc — chama o compilador.</li><li>-std=c17 — diz qual versão do C usar.</li><li>-Wall -Wextra — ligam avisos que ajudam a achar problema no código.</li><li>compra.c — o arquivo a compilar.</li><li>-o compra.exe — o nome do executável gerado.</li></ul><p>Isso funciona se você tiver o GCC instalado. O .\compra.exe é no Windows; no Linux e no Mac, é ./compra.exe.</p><h3>O problema da compra com desconto</h3><p>O exemplo que atravessa a parte 2 inteira:</p><ol><li>Recebe três dados: preço unitário, quantidade e percentual de desconto.</li><li>Processa: calcula o subtotal, o valor do desconto (o abatimento) e o total.</li><li>Mostra o resultado.</li></ol><p>Na conta: 19,90 × 3 = 59,70. 10% disso é 5,97. Total a pagar: 53,73.</p><p>Antes de programar, o professor definiu as regras:</p><ul><li>O preço não pode ser negativo.</li><li>A quantidade é inteira e não pode ser negativa.</li><li>O desconto tem que estar entre 0 e 100%.</li></ul><p>Guarda essas regras: são elas que vão virar a verificação do código.</p><h3>Tipos em C e variáveis que nascem com lixo</h3><p>Na compra, só a quantidade é int, porque é unidade. Todo o resto é double.</p><p>O tamanho de cada tipo depende da implementação (compilador e sistema). Dá pra conferir com sizeof(int): em tabelas antigas o int aparece com 2 bytes, mas hoje geralmente são 4.</p><p>Declarar, inicializar e atribuir são três momentos diferentes:</p><pre>int quantidade;           // DECLARA: avisa que existe<br>quantidade = 3;           // ATRIBUI: coloca um valor<br>double preco = 19.90;     // DECLARA + INICIALIZA: tudo de uma vez<br>preco = 21.50;            // ATRIBUI: substitui o valor anterior<br>const int limite = 100;   // CONSTANTE: não pode receber outra atribuição</pre><p>O cuidado no C: uma variável declarada sem valor já ocupa um pedaço da memória, com o que estava lá antes. É como uma gaveta deixada por um inquilino anterior: você não sabe o que tem dentro. Por isso, sempre inicialize:</p><pre>int quantidade = 0;   // seguro</pre><p>Outras linguagens te protegem disso. No Java, usar uma variável local antes de atribuir dá erro de compilação. No Python, a variável só passa a existir quando recebe um valor. E o TypeScript avisa que você está usando antes de atribuir.</p><h3>Entrada e saída — scanf e printf</h3><pre>double preco, desconto;<br>int quantidade;</pre><pre>int lido = scanf(&quot;%lf %d %lf&quot;, &amp;preco, &amp;quantidade, &amp;desconto);<br>if (lido != 3) {<br>    printf(&quot;Entrada inválida\n&quot;);<br>    return 1;<br>}<br>printf(&quot;Preço: R$ %.2f | Quantidade: %d\n&quot;, preco, quantidade);</pre><ul><li>scanf — pensa nele como o programa pedindo pro usuário digitar naquele lugar. Ele devolve quantos valores conseguiu ler.</li><li>%lf espera um double; %d espera um int.</li><li>&amp; passa o endereço da variável na memória, pra que o scanf consiga guardar o valor lá. Se o &amp; te confundiu, segura: ele volta na parte de ponteiros.</li><li>%.2f no printf mostra o número com duas casas decimais.</li></ul><h3>Calcular, guardar, comparar e mostrar não são a mesma coisa</h3><p>Considere que x vale 2 antes de cada linha:</p><p>São quatro operações parecidas, com efeitos diferentes:</p><ul><li>Calcular — produz um valor, mas não guarda nada.</li><li>Atribuir — é a única que muda o estado.</li><li>Comparar — só produz verdadeiro ou falso.</li><li>Mostrar — exibe algo visível, mas não altera a variável.</li></ul><h3>Validação, armadilhas e testes — onde o erro lógico se esconde</h3><h3>Validar a entrada em dois níveis</h3><ol><li>A leitura deu certo? O scanf conseguiu ler os valores de entrada?</li><li>Os valores fazem sentido? O usuário digitou algo que o programa leu, mas que quebra as regras — tipo um desconto de 110%.</li></ol><pre>if (scanf(&quot;%lf %d %lf&quot;, &amp;preco, &amp;quantidade, &amp;desconto) != 3) {<br>    printf(&quot;Entrada inválida\n&quot;);<br>    return 1;<br>}<br>if (preco &lt; 0 || quantidade &lt; 0 || desconto &lt; 0 || desconto &gt; 100) {<br>    printf(&quot;Valores fora da faixa\n&quot;);<br>    return 1;<br>}</pre><p>Repara no OU: ele só é falso se todas as condições forem falsas. Ou seja, o programa só passa se nenhum valor estiver errado.</p><h3>A armadilha da divisão inteira</h3><p>Esse erro é comum em C e em Java. Olha só:</p><pre>double preco = 200.0;<br>int desconto = 10;<br>double fracao = desconto / 100;              // 0.0 — errado<br>double precoFinal = preco - preco * fracao;<br>System.out.println(precoFinal);              // 200.0 — o cliente não ganhou desconto</pre><p>Por quê? O Java não olha pra quem vai receber o resultado (o double). Ele olha pra conta: int ÷ int dá int. 10 ÷ 100 = 0, e só depois esse 0 é guardado no double, virando 0.0.</p><p>O certo seria:</p><pre>double fracao1 = desconto / 100.0;         // 0.1<br>double fracao2 = (double) desconto / 100;  // 0.1<br>double fracao3 = desconto * 0.01;          // 0.1</pre><p>O Java e o C olham os operandos, não a variável que recebe. É a coerção da parte 1 — só que aqui nenhum dos dois lados é decimal pra puxar o outro.</p><p>Dica importante: encha o programa de printf, ou use o debug, pra ver os resultados intermediários em sequência. Assim você enxerga exatamente onde o valor desandou.</p><h3>Duas formas de calcular o desconto</h3><p>Em etapas:</p><pre>double subtotal = preco * quantidade;<br>double abatimento = subtotal * (desconto / 100.0);<br>double total = subtotal - abatimento;</pre><p>Direta:</p><pre>double total = preco * quantidade * (1.0 - desconto / 100.0);</pre><p>A primeira guarda os valores intermediários, então fica mais fácil de conferir — vale quando memória não é preocupação. A segunda é mais curta, mas mais difícil de ajustar.</p><h3>O balanço do paradigma imperativo</h3><p>A conta da compra mostra o paradigma inteiro:</p><ol><li>Estado — preço, quantidade, subtotal e total são informações disponíveis num momento específico.</li><li>Atribuições — os resultados intermediários atualizam o estado.</li><li>Sequência de dependências — o abatimento depende do subtotal, e o total depende dos dois. Existe uma ordem obrigatória.</li><li>Controle explícito — os if decidem se o programa continua ou para.</li><li>Efeitos observáveis — os printf exibem o resultado ou as mensagens de erro.</li></ol><p>A vantagem: dá pra acompanhar cada passo. O preço: você precisa cuidar de quem modifica cada variável, quando e por quê.</p><p>O fluxo: ler → validar → está na faixa? → calcular → mostrar.</p><h3>Imperativo, estruturado e procedural</h3><ul><li>Imperativo — a ideia geral: comandos que mudam o estado.</li><li>Estruturado — a organização do fluxo usando só três estruturas: sequência, seleção (if, switch) e repetição (for, while, do-while).</li><li>Procedural — a divisão do problema em sub-rotinas, ou seja, em funções, cada uma com sua responsabilidade.</li></ul><p>A programação estruturada é uma forma de organizar o imperativo. E organizar em funções não deixa de ser imperativo: os comandos continuam lá, só distribuídos em partes menores.</p><h3>Estruturas de controle — escolher o caminho e repetir</h3><p>Novo problema: em vez de uma compra, agora são três subtotais guardados num vetor: 59,70, 20,00 e 22,00. Aplica 10% de desconto em cada um e soma tudo. As etapas:</p><ol><li>Validar o desconto de 0 a 100 — seleção.</li><li>Percorrer o vetor — repetição.</li><li>Aplicar o desconto em cada valor — função.</li><li>Acumular e mostrar o total — sequência.</li></ol><h3>if/else — escolhendo o caminho</h3><pre>if (desconto &gt;= 0 &amp;&amp; desconto &lt;= 100) {<br>    printf(&quot;Percentual válido\n&quot;);<br>} else {<br>    printf(&quot;Percentual inválido\n&quot;);<br>}</pre><p>Como é um &amp;&amp;, as duas condições precisam ser verdadeiras:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*4CEcxyEerCahSVtngElEBQ.png" /></figure><p>Atenção: trocar o &amp;&amp; por || muda tudo. Com ||, o 110 passa como válido, porque basta ser maior ou igual a zero. E dá pra encadear mais caminhos com if / else if / else.</p><h3>switch/case — pra quando as opções são fixas</h3><p>É como um menu: você escolhe entre valores específicos.</p><pre>switch (opcao) {<br>    case 1:                        // cada case é um valor possível<br>        printf(&quot;Resumo\n&quot;);<br>        break;                     // o break obriga a parar ali<br>    case 2:<br>        printf(&quot;Detalhes\n&quot;);<br>        break;<br>    default:                       // pega qualquer valor que não está na lista<br>        printf(&quot;Opção inválida\n&quot;);<br>}</pre><p>Sem o break, o programa continua e executa o case de baixo também. O default funciona como o “senão”. Tem gente que sente falta dessa estrutura no Python: ele passou anos sem ela e só ganhou o match na versão 3.10.</p><p>Resumindo:</p><ul><li>switch — quando a decisão é sobre uma variável com valores exatos (1, 2, 3).</li><li>if — quando são faixas, tipo entre 0 e 100.</li></ul><h3>for — quando você sabe quantas voltas vai dar</h3><pre>const valores: number[] = [59.70, 20.0, 22.0];<br>let soma = 0;<br>for (let i = 0; i &lt; valores.length; i++) {<br>  soma += valores[i];<br>}</pre><p>O cabeçalho do for tem três partes:</p><ol><li>let i = 0 — o início: o índice começa em zero.</li><li>i &lt; valores.length — a condição, testada a cada volta. Quando i chega no tamanho do vetor, o laço para.</li><li>i++ — o passo: soma 1 ao final de cada volta.</li></ol><p>A variável soma é acumuladora: a cada volta ela recebe mais um valor. É a prova viva do paradigma imperativo — o estado muda a cada repetição.</p><h3>while e do-while</h3><p>O while testa antes de entrar:</p><pre>int i = 0;                 // o início fica fora<br>double soma = 0.0;<br>while (i &lt; 3) {            // a condição<br>    soma += valores[i];<br>    i++;                   // o passo fica dentro<br>}</pre><p>A lógica é idêntica à do for; o que muda é a organização. No for, início, condição e passo ficam no cabeçalho. No while, o início vem antes do laço e o passo vai dentro do corpo. E se você esquecer o i++, a condição fica sempre verdadeira: loop infinito.</p><p>O do-while executa primeiro e testa depois. É perfeito pra pedir algo pro usuário: ele pergunta pelo menos uma vez antes de saber se a resposta serve.</p><pre>let desconto: number;<br>do {<br>  desconto = Number(prompt(&quot;Desconto (0 a 100): &quot;));<br>} while (desconto &lt; 0 || desconto &gt; 100);</pre><p>O laço repete enquanto o valor digitado estiver errado. O usuário digita 110: 110 &gt; 100 é verdadeiro, então a pergunta volta. Digita 10: as duas condições dão falso, o OU dá falso e o laço termina.</p><p>O jeito que eu guardei:</p><ul><li>while — o porteiro confere a lista antes de você entrar na festa.</li><li>do-while — o restaurante te serve primeiro e depois pergunta se você quer mais.</li></ul><h3>Qual laço escolher?</h3><ul><li>for — você sabe quantas vezes vai repetir. Ex: percorrer um vetor de 3 posições.</li><li>while — você não sabe quantas vezes, só sabe a condição de parar.</li><li>do-while — precisa executar uma vez antes de testar. Ex: pedir uma entrada.</li></ul><h3>Funções e ponteiros — dividir o problema e mexer na memória</h3><h3>Funções — protótipo, definição e chamada</h3><p>Função é escrever em um só lugar algo que resolve o problema, em vez de repetir em vários lugares. O exemplo do desconto, em Java:</p><pre>static double desconto(double valor, double percentual) {<br>    return valor * (1.0 - percentual / 100.0);<br>}</pre><p>Quem chama a função não precisa saber como ela calcula: só manda os dados e recebe a resposta. É como pedir um café no restaurante — o atendente faz na máquina e você recebe sem precisar saber mexer nela.</p><p>No C, a função tem três elementos:</p><pre>#include &lt;stdio.h&gt;</pre><pre>double desconto(double valor, double percentual);  // PROTÓTIPO: diz ao compilador como ela pode ser usada</pre><pre>int main(void) {<br>    double total = desconto(59.70, 10);             // CHAMADA: pede que ela execute<br>    printf(&quot;%.2f\n&quot;, total);                        // 53.73<br>    return 0;<br>}</pre><pre>double desconto(double valor, double percentual) { // DEFINIÇÃO: diz o que fazer<br>    return valor * (1.0 - percentual / 100.0);<br>}</pre><p>O protótipo é coisa do C — é a prototipação da parte 1. Java, Python e TypeScript não precisam dele.</p><h3>Retorno x efeito colateral</h3><ul><li>Retorno — o valor que a função devolve e que pode ser guardado numa variável.</li><li>Efeito colateral — qualquer coisa que a função muda fora dela: escrever na tela, alterar uma variável de fora, gravar um arquivo.</li></ul><p>Atenção: printf dentro de uma função não é retorno. Pensa numa prova: se alguém te entrega a nota numa folha, isso é retorno. Se alguém grita sua nota lá de longe, não é — é efeito colateral. Você ouviu, mas não tem a nota na mão pra fazer a conta.</p><p>Por isso, ao analisar uma função, olhe duas coisas: o que ela devolve e o que ela altera. E quando houver efeito colateral, documente, pro colega que pegar o código depois ficar ligado.</p><h3>Passagem por valor — a função recebe uma cópia</h3><pre>static void mudar(int q) {<br>    q = 9;<br>}</pre><pre>int quantidade = 3;<br>mudar(quantidade);   // quantidade continua 3</pre><ol><li>Antes da chamada, quantidade vale 3.</li><li>Na chamada, o valor 3 é copiado pro parâmetro q.</li><li>Dentro da função, q vira 9. Só a cópia mudou.</li><li>A função termina e q deixa de existir, porque é local.</li><li>quantidade continua valendo 3.</li></ol><p>No C, os argumentos são sempre passados por valor. É o jeito mais seguro: a função não consegue estragar os dados de quem chamou. Pensa num xerox: você entrega a cópia pro colega, ele pode riscar à vontade, e o seu original fica intacto.</p><p>Resumindo:</p><ul><li>Tipos primitivos (int, double, number) — você copia o valor. Entrega o xerox.</li><li>Objetos — você copia o endereço. Entrega a chave da casa.</li></ul><h3>O programa modular</h3><p>Juntando a aula, o problema dos três subtotais fica dividido em funções, cada uma com sua responsabilidade:</p><pre>// 1ª: recebe um valor e um percentual, devolve o valor com desconto<br>function aplicarDesconto(valor: number, percentual: number): number {<br>  return valor * (1.0 - percentual / 100.0);<br>}</pre><pre>// 2ª: percorre a lista, aplica o desconto em cada valor e soma tudo<br>function totalizar(valores: readonly number[], percentual: number): number {<br>  let soma = 0.0;<br>  for (let i = 0; i &lt; valores.length; i++) {<br>    soma += aplicarDesconto(valores[i], percentual);<br>  }<br>  return soma;<br>}</pre><pre>const valores: number[] = [59.70, 20.0, 22.0];<br>const total = totalizar(valores, 10.0);<br>console.log(`Total: R$ ${total.toFixed(2)}`);   // Total: R$ 91.53</pre><ul><li>percentual / 100.0 transforma 10 em 0.10, e 1.0–0.10 dá 0.90: a parte que sobra depois do desconto.</li><li>readonly é a trava: garante que totalizar não consiga alterar o vetor que recebeu.</li><li>soma é acumuladora: nasce fora do laço valendo zero e cresce a cada volta.</li></ul><h3>Ponteiros — guardando o endereço</h3><p>Um ponteiro guarda um endereço de memória, e esse endereço é onde a variável mora.</p><pre>int x = 4;<br>int *p = &amp;x;         // p guarda o endereço de x<br>*p = 9;              // vai até o endereço e coloca 9 lá<br>printf(&quot;%d\n&quot;, x);   // 9</pre><ul><li>&amp;x — o endereço de x.</li><li>int *p — p é um ponteiro pra um int.</li><li>*p — o conteúdo do lugar pra onde p aponta.</li></ul><p>Depois de *p = 9, o ponteiro continua guardando o mesmo endereço. O que mudou foi o conteúdo da casa. O ponteiro é uma forma de alterar outra variável indiretamente.</p><p>Obs: o * tem dois papéis, multiplicação e ponteiro. O &amp; também: endereço e E bit a bit. É a sobrecarga de operadores da parte 1.</p><p>Funções também podem receber uma cópia do endereço. Quando a função termina, o ponteiro local some, mas a alteração fica. Na prática, é assim que o C faz passagem por referência.</p><p>Quando usar? Quando a memória é pouca: em vez de criar variáveis auxiliares, você aponta direto pra variável que vai ser alterada.</p><p>Voltando ao xerox: em vez de entregar a cópia do documento, você entrega uma cópia da chave do seu armário. A chave é cópia, mas o armário é o verdadeiro.</p><p>Em Java, TypeScript e Python, os números simples são sempre copiados. Mas quando você passa uma lista ou um objeto, a função recebe um atalho pra ele, e as alterações feitas lá dentro aparecem do lado de fora.</p><h3>Trocar dois valores com ponteiro</h3><p>O clássico: x = 3, y = 8, e queremos inverter.</p><pre>void troca(int *a, int *b) {<br>    int temp = *a;   // guarda o valor de x (3)<br>    *a = *b;         // x recebe o valor de y (8)<br>    *b = temp;       // y recebe o valor guardado (3)<br>}</pre><pre>int main(void) {<br>    int x = 3, y = 8;<br>    troca(&amp;x, &amp;y);<br>    printf(&quot;%d %d\n&quot;, x, y);   // 8 3<br>    return 0;<br>}</pre><p>O temp é a variável que ajuda na troca: sem ela, quando x recebe 8, o 3 se perde e mistura tudo.</p><p>Passo a passo na memória:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*Tx8evh1aagaFaEoDlBmxvw.png" /></figure><p>Os ponteiros a e b nunca mudam. O que muda são os valores das casas.</p><p>No TypeScript, a mesma troca sai numa linha:</p><pre>let x = 3, y = 8;<br>[x, y] = [y, x];</pre><h3>O mesmo paradigma em outra linguagem</h3><p>Pra fechar, o mesmo código em Pascal. O objetivo não é aprender Pascal, e sim mostrar que o paradigma continua o mesmo — só a escrita muda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*AqiqvH49I-pozM7WH6BALg.png" /></figure><pre>double aplicarDesconto(double valor, double percentual) {<br>    return valor * (1.0 - percentual / 100.0);<br>}</pre><pre>function AplicarDesconto(valor, percentual: real): real;<br>begin<br>  AplicarDesconto := valor * (1.0 - percentual / 100.0);<br>end;</pre><p>As funções não definem o paradigma — elas existem em vários paradigmas. Aqui elas servem pra organizar uma solução que continua sendo imperativa. Todo programa estruturado é imperativo, mas nem todo programa imperativo é estruturado.</p><h3>Juntando tudo na compra — um programa, todos os conceitos</h3><p>O fio da parte 2 inteira foi a compra com desconto. Então vale juntar tudo num programa C só e ver onde cada conceito aparece.</p><pre>#include &lt;stdio.h&gt;</pre><pre>double aplicarDesconto(double valor, double percentual);   // protótipo</pre><pre>int main(void) {<br>    double valores[3] = {59.70, 20.0, 22.0};   // vetor de subtotais<br>    double desconto;</pre><pre>    if (scanf(&quot;%lf&quot;, &amp;desconto) != 1) {         // nível 1: a leitura deu certo?<br>        printf(&quot;Entrada inválida\n&quot;);<br>        return 1;<br>    }<br>    if (desconto &lt; 0 || desconto &gt; 100) {        // nível 2: o valor faz sentido?<br>        printf(&quot;Percentual fora da faixa\n&quot;);<br>        return 1;<br>    }</pre><pre>    double soma = 0.0;                          // acumuladora: nasce zerada<br>    for (int i = 0; i &lt; 3; i++) {               // repetição contada<br>        soma += aplicarDesconto(valores[i], desconto);   // chamada + muda o estado<br>    }</pre><pre>    printf(&quot;Total: R$ %.2f\n&quot;, soma);           // efeito observável<br>    return 0;<br>}</pre><pre>double aplicarDesconto(double valor, double percentual) {   // definição<br>    return valor * (1.0 - percentual / 100.0);<br>}</pre><p>Lendo de cima pra baixo:</p><ul><li>Protótipo — aplicarDesconto é anunciada antes do main e definida só no final. Sem o protótipo, o compilador reclamaria.</li><li>Tipos — valores e desconto são double porque entram na conta; o int fica com o índice, que só conta posições.</li><li>Validação em dois níveis — primeiro o scanf (a leitura deu certo?), depois a faixa (o valor faz sentido?).</li><li>Controle explícito — os if decidem se o programa continua ou para, e o return 1 avisa o sistema que deu erro.</li><li>Repetição — o for percorre as 3 posições do vetor.</li><li>Estado — soma nasce zerada e muda a cada volta. A fotografia vai mudando até o fim.</li><li>Função e passagem por valor — aplicarDesconto recebe cópias e devolve um valor, sem efeito colateral.</li><li>Divisão — o 100.0 garante conta decimal, mesmo se um dia o percentual virar int.</li><li>Efeito observável — o printf mostra o resultado: com 10% de desconto, Total: R$ 91.53.</li></ul><p>Três valores num vetor, e a parte 2 inteira está ali dentro.</p><h3>Fechando</h3><p>No imperativo, o programa é uma lista de ordens. E o computador cumpre cada uma, exatamente na ordem em que foram dadas — inclusive as erradas.</p><p>Pra quem testa software, isso muda o que procurar. O y que deu 4 em vez de 6, o 10 / 100 que virou zero, o -2 que fez a loja pagar o cliente: nenhum desses travou o programa, e o compilador ficou quieto. Quem pega esse tipo de erro é o teste de mesa, o caso de teste no limite e a pergunta que ninguém fez: “e se o usuário digitar isso?”</p><p>O computador não erra a ordem. Ele segue a sua.</p><p>Na parte 3, sigo com as próximas aulas da matéria.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=853af03e6149" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming Language Paradigms — Part 2]]></title>
            <link>https://medium.com/@fa.engeroff1996/programming-language-paradigms-part-2-f9bf25343025?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9bf25343025</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 10:21:11 GMT</pubDate>
            <atom:updated>2026-11-16T10:21:11.733Z</atom:updated>
            <content:encoded><![CDATA[<p>You swap the order of two lines and the result changes from 6 to 4. You give a 10% discount and the customer pays full price. You type a quantity of -2 and the store ends up owing the customer money. None of these programs threw a compile error — they all ran smoothly, and they’re all wrong.</p><p>In part 1 I covered the fundamentals: what makes a language good, paradigms, syntax and semantics, types, operators, structures and subroutines. Here I focus on the imperative paradigm, the most widely used of all: state, command order, the first program in C, validation, control structures, functions and pointers. And the thread running through it is still the purchase: price, quantity and discount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPFtuyZ2Zh5UxLPD1kcFcA.png" /></figure><h3>The imperative paradigm — giving orders, one at a time</h3><p>Imperative comes from the Latin for giving orders. Each step is an order, executed in sequence, and each step can change the values stored in memory. The program is a list of commands, one after another.</p><p>It’s the most popular paradigm and the foundation of almost every language — partly because it’s very close to how the computer itself works.</p><p>The same calculation in C and in Python:</p><pre>double price = 30;<br>int quantity = 4;<br>double average = price / quantity;   // every statement ends with ;</pre><pre>price = 30<br>quantity = 4<br>average = price / quantity   # no ; and no declared type</pre><p>In C you declare the type of every variable, and the semicolon says “this statement ends here”. Python needs neither: it organizes itself through indentation, the spaces at the start of the line. The writing changes, the way of thinking stays the same.</p><h3>State — a snapshot of the variables</h3><p>State is a snapshot of the variables at a given moment of execution. It’s the central feature of the imperative paradigm.</p><pre>int quantity = 2;                    // state: quantity = 2<br>quantity = quantity + 1;             // state: quantity = 3<br>double price = 19.90;                // state: quantity = 3, price = 19.90<br>double subtotal = price * quantity;  // state: ..., subtotal = 59.70</pre><p>If someone asks “what’s the value of quantity?”, the answer is: it depends on which line you’re looking at.</p><h3>The example that breaks math</h3><p>In math, changing the order of the factors doesn’t change the product. In imperative programming, changing the order of the commands changes everything. Starting with x = 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*6cITq4TwGItI6KFX3yUyjw.png" /></figure><p>Same commands, different order, different result. This happens in every imperative language. In an imperative program, you have to keep track of who changes each variable, when and why.</p><h3>Paradigm, language and implementation are different things</h3><ul><li>Paradigm — the architectural style, the way you organize the solution.</li><li>Language — the building material and rules: the words and symbols you’re allowed to use.</li><li>Implementation — the tool that turns the code into something that runs. For C, the GCC compiler.</li></ul><p>That’s why compilers and interpreters don’t define the paradigm: being compiled doesn’t make a language imperative, and vice versa. For the same reason, using int, double and char doesn’t make a program imperative — those are language features. The paradigm shows up in how you organize the commands and the state changes.</p><h3>From the first program to the purchase — C in practice</h3><h3>The smallest program in C</h3><pre>#include &lt;stdio.h&gt;          // brings in the input/output library</pre><pre>int main(void) {            // the program&#39;s entry point<br>    printf(&quot;Hello, class\n&quot;); // writes to the screen<br>    return 0;               // ends and tells the system<br>}</pre><p>Compiling with GCC: say the code is saved as purchase.c. In the terminal:</p><pre>gcc -std=c17 -Wall -Wextra purchase.c -o purchase.exe<br>.\purchase.exe</pre><ul><li>gcc — calls the compiler.</li><li>-std=c17 — says which version of C to use.</li><li>-Wall -Wextra — turn on warnings that help you find problems in the code.</li><li>purchase.c — the file to compile.</li><li>-o purchase.exe — the name of the generated executable.</li></ul><p>This works if you have GCC installed. The .\purchase.exe is for Windows; on Linux and Mac, it’s ./purchase.exe.</p><h3>The discount purchase problem</h3><p>The example that runs through all of part 2:</p><ol><li>Take three inputs: unit price, quantity and discount percentage.</li><li>Process: calculate the subtotal, the discount amount and the total.</li><li>Show the result.</li></ol><p>The math: 19.90 × 3 = 59.70. 10% of that is 5.97. Total to pay: 53.73.</p><p>Before writing any code, the professor set the rules:</p><ul><li>The price can’t be negative.</li><li>The quantity is a whole number and can’t be negative.</li><li>The discount has to be between 0 and 100%.</li></ul><p>Keep these rules in mind: they’re what will turn into checks in the code.</p><h3>Types in C and variables born with garbage</h3><p>In the purchase, only the quantity is an int, because it counts units. Everything else is a double.</p><p>The size of each type depends on the implementation (compiler and system). You can check it with sizeof(int): older tables show int as 2 bytes, but today it’s usually 4.</p><p>Declaring, initializing and assigning are three different moments:</p><pre>int quantity;            // DECLARE: says it exists<br>quantity = 3;            // ASSIGN: puts a value in it<br>double price = 19.90;    // DECLARE + INITIALIZE: all at once<br>price = 21.50;           // ASSIGN: replaces the previous value<br>const int limit = 100;   // CONSTANT: can&#39;t be assigned again</pre><p>The catch in C: a variable declared without a value already takes up a piece of memory, holding whatever was there before. It’s like a drawer left behind by a previous tenant: you don’t know what’s inside. So always initialize:</p><pre>int quantity = 0;   // safe</pre><p>Other languages protect you from this. In Java, using a local variable before assigning it is a compile error. In Python, a variable only exists once it gets a value. And TypeScript warns you when you use it before assigning.</p><h3>Input and output — scanf and printf</h3><pre>double price, discount;<br>int quantity;</pre><pre>int itemsRead = scanf(&quot;%lf %d %lf&quot;, &amp;price, &amp;quantity, &amp;discount);<br>if (itemsRead != 3) {<br>    printf(&quot;Invalid input\n&quot;);<br>    return 1;<br>}<br>printf(&quot;Price: $%.2f | Quantity: %d\n&quot;, price, quantity);</pre><ul><li>scanf — think of it as the program asking the user to type something right there. It returns how many values it managed to read.</li><li>%lf expects a double; %d expects an int.</li><li>&amp; passes the variable’s address in memory, so scanf can store the value there. If the &amp; confused you, hang on: it comes back in the pointers section.</li><li>%.2f in printf shows the number with two decimal places.</li></ul><h3>Calculating, storing, comparing and showing are not the same thing</h3><p>Assume x is 2 before each line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*ImOdzzPx0TnJDv9_NQ5sXw.png" /></figure><p>Four similar-looking operations, with different effects:</p><ul><li>Calculating — produces a value, but stores nothing.</li><li>Assigning — the only one that changes the state.</li><li>Comparing — only produces true or false.</li><li>Showing — displays something visible, but doesn’t change the variable.</li></ul><h3>Validation, traps and tests — where logic errors hide</h3><h3>Validating input on two levels</h3><ol><li>Did the read work? Did scanf manage to read the input values?</li><li>Do the values make sense? The user typed something the program could read, but it breaks the rules — like a 110% discount.</li></ol><pre>if (scanf(&quot;%lf %d %lf&quot;, &amp;price, &amp;quantity, &amp;discount) != 3) {<br>    printf(&quot;Invalid input\n&quot;);<br>    return 1;<br>}<br>if (price &lt; 0 || quantity &lt; 0 || discount &lt; 0 || discount &gt; 100) {<br>    printf(&quot;Values out of range\n&quot;);<br>    return 1;<br>}</pre><p>Notice the OR: it’s only false if every condition is false. In other words, the program only gets through if no value is wrong.</p><h3>The integer division trap</h3><p>This bug is common in C and Java. Look:</p><pre>double price = 200.0;<br>int discount = 10;<br>double fraction = discount / 100;              // 0.0 — wrong<br>double finalPrice = price - price * fraction;<br>System.out.println(finalPrice);                // 200.0 — the customer got no discount</pre><p>Why? Java doesn’t look at who receives the result (the double). It looks at the calculation: int ÷ int gives an int. 10 ÷ 100 = 0, and only then is that 0 stored in the double, becoming 0.0.</p><p>The right way:</p><pre>double fraction1 = discount / 100.0;         // 0.1<br>double fraction2 = (double) discount / 100;  // 0.1<br>double fraction3 = discount * 0.01;          // 0.1</pre><p>Java and C look at the operands, not at the variable receiving the result. It’s the coercion from part 1 — except here, neither side is a decimal to pull the other one along.</p><p>Key tip: fill the program with printf calls, or use the debugger, to see the intermediate results in sequence. That way you see exactly where the value went off track.</p><h3>Two ways to calculate the discount</h3><p>Step by step:</p><pre>double subtotal = price * quantity;<br>double discountAmount = subtotal * (discount / 100.0);<br>double total = subtotal - discountAmount;</pre><p>Direct:</p><pre>double total = price * quantity * (1.0 - discount / 100.0);</pre><p>The first one keeps the intermediate values, so it’s easier to check — good when memory isn’t a concern. The second is shorter, but harder to adjust.</p><h3>The balance of the imperative paradigm</h3><p>The purchase calculation shows the whole paradigm:</p><ol><li>State — price, quantity, subtotal and total are pieces of information available at a specific moment.</li><li>Assignments — the intermediate results update the state.</li><li>Chain of dependencies — the discount amount depends on the subtotal, and the total depends on both. There’s a mandatory order.</li><li>Explicit control — the if statements decide whether the program continues or stops.</li><li>Observable effects — the printf calls show the result or the error messages.</li></ol><p>The upside: you can follow every step. The cost: you have to keep track of who changes each variable, when and why.</p><p>The flow: read → validate → in range? → calculate → show.</p><h3>Imperative, structured and procedural</h3><ul><li>Imperative — the general idea: commands that change state.</li><li>Structured — organizing the flow with only three structures: sequence, selection (if, switch) and repetition (for, while, do-while).</li><li>Procedural — splitting the problem into subroutines, that is, functions, each with its own responsibility.</li></ul><p>Structured programming is a way of organizing imperative code. And organizing it into functions doesn’t make it any less imperative: the commands are all still there, just spread across smaller parts.</p><h3>Control structures — choosing the path and repeating</h3><p>New problem: instead of one purchase, there are now three subtotals stored in an array: 59.70, 20.00 and 22.00. Apply a 10% discount to each one and add them all up. The steps:</p><ol><li>Validate the discount from 0 to 100 — selection.</li><li>Go through the array — repetition.</li><li>Apply the discount to each value — function.</li><li>Accumulate and show the total — sequence.</li></ol><h3>if/else — choosing the path</h3><pre>if (discount &gt;= 0 &amp;&amp; discount &lt;= 100) {<br>    printf(&quot;Valid percentage\n&quot;);<br>} else {<br>    printf(&quot;Invalid percentage\n&quot;);<br>}</pre><p>Since it’s an &amp;&amp;, both conditions have to be true:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*LVDN6lTHhGgA3CIC_NPV-Q.png" /></figure><p>Heads up: swapping &amp;&amp; for || changes everything. With ||, 110 passes as valid, because being greater than or equal to zero is enough. And you can chain more paths with if / else if / else.</p><h3>switch/case — for when the options are fixed</h3><p>It’s like a menu: you pick from specific values.</p><pre>switch (option) {<br>    case 1:                        // each case is one possible value<br>        printf(&quot;Summary\n&quot;);<br>        break;                     // break forces it to stop there<br>    case 2:<br>        printf(&quot;Details\n&quot;);<br>        break;<br>    default:                       // catches any value not in the list<br>        printf(&quot;Invalid option\n&quot;);<br>}</pre><p>Without the break, the program keeps going and runs the case below as well. The default works like an “else”. Some people miss this structure in Python: it went years without it and only got match in version 3.10.</p><p>In short:</p><ul><li>switch — when the decision is about one variable with exact values (1, 2, 3).</li><li>if — when it’s about ranges, like between 0 and 100.</li></ul><h3>for — when you know how many laps it’ll run</h3><pre>const values: number[] = [59.70, 20.0, 22.0];<br>let sum = 0;<br>for (let i = 0; i &lt; values.length; i++) {<br>  sum += values[i];<br>}</pre><p>The for header has three parts:</p><ol><li>let i = 0 — the start: the index begins at zero.</li><li>i &lt; values.length — the condition, tested every lap. When i reaches the array’s length, the loop stops.</li><li>i++ — the step: adds 1 at the end of each lap.</li></ol><p>The variable sum is an accumulator: every lap, it takes in one more value. It’s living proof of the imperative paradigm — the state changes on every repetition.</p><h3>while and do-while</h3><p>while tests before going in:</p><pre>int i = 0;                 // the start stays outside<br>double sum = 0.0;<br>while (i &lt; 3) {            // the condition<br>    sum += values[i];<br>    i++;                   // the step goes inside<br>}</pre><p>The logic is identical to the for; what changes is the layout. In a for, start, condition and step all sit in the header. In a while, the start comes before the loop and the step goes inside the body. And if you forget the i++, the condition stays true forever: infinite loop.</p><p>do-while runs first and tests afterwards. It’s perfect for asking the user for something: it asks at least once before knowing whether the answer is any good.</p><pre>let discount: number;<br>do {<br>  discount = Number(prompt(&quot;Discount (0 to 100): &quot;));<br>} while (discount &lt; 0 || discount &gt; 100);</pre><p>The loop repeats while the typed value is wrong. The user types 110: 110 &gt; 100 is true, so the question comes back. They type 10: both conditions are false, the OR is false and the loop ends.</p><p>The way I remember it:</p><ul><li>while — the bouncer checks the list before you get into the party.</li><li>do-while — the restaurant serves you first and then asks if you want more.</li></ul><h3>Which loop to pick?</h3><ul><li>for — you know how many times it’ll repeat. E.g. going through an array with 3 positions.</li><li>while — you don’t know how many times, only the condition to stop.</li><li>do-while — it needs to run once before testing. E.g. asking for input.</li></ul><h3>Functions and pointers — splitting the problem and touching memory</h3><h3>Functions — prototype, definition and call</h3><p>A function is writing something that solves the problem in one single place, instead of repeating it in several places. The discount example, in Java:</p><pre>static double discount(double value, double percentage) {<br>    return value * (1.0 - percentage / 100.0);<br>}</pre><p>Whoever calls the function doesn’t need to know how it calculates: they just send the data and get the answer back. It’s like ordering a coffee at a restaurant — the server makes it on the machine and you get it without needing to know how to work the machine.</p><p>In C, a function has three elements:</p><pre>#include &lt;stdio.h&gt;</pre><pre>double discount(double value, double percentage);  // PROTOTYPE: tells the compiler how it can be used</pre><pre>int main(void) {<br>    double total = discount(59.70, 10);             // CALL: asks it to run<br>    printf(&quot;%.2f\n&quot;, total);                        // 53.73<br>    return 0;<br>}</pre><pre>double discount(double value, double percentage) { // DEFINITION: says what to do<br>    return value * (1.0 - percentage / 100.0);<br>}</pre><p>The prototype is a C thing — it’s the prototyping from part 1. Java, Python and TypeScript don’t need it.</p><h3>Return value vs side effect</h3><ul><li>Return value — the value the function hands back, which can be stored in a variable.</li><li>Side effect — anything the function changes outside itself: writing to the screen, changing an outside variable, saving a file.</li></ul><p>Heads up: a printf inside a function is not a return value. Think of an exam: if someone hands you your grade on a sheet of paper, that’s a return value. If someone yells your grade from across the room, it isn’t — it’s a side effect. You heard it, but you don’t have the grade in hand to do any math with it.</p><p>So when you analyze a function, look at two things: what it returns and what it changes. And when there’s a side effect, document it, so the colleague who picks up the code later is aware.</p><h3>Pass by value — the function gets a copy</h3><pre>static void change(int q) {<br>    q = 9;<br>}</pre><pre>int quantity = 3;<br>change(quantity);   // quantity is still 3</pre><ol><li>Before the call, quantity is 3.</li><li>On the call, the value 3 is copied into the parameter q.</li><li>Inside the function, q becomes 9. Only the copy changed.</li><li>The function ends and q stops existing, because it’s local.</li><li>quantity is still 3.</li></ol><p>In C, arguments are always passed by value. It’s the safest way: the function can’t mess up the caller’s data. Think of a photocopy: you hand the copy to a colleague, they can scribble all over it, and your original stays intact.</p><p>In short:</p><ul><li>Primitive types (int, double, number) — you copy the value. You hand over the photocopy.</li><li>Objects — you copy the address. You hand over the house key.</li></ul><h3>The modular program</h3><p>Putting the class together, the three-subtotals problem gets split into functions, each with its own responsibility:</p><pre>// 1st: takes a value and a percentage, returns the discounted value<br>function applyDiscount(value: number, percentage: number): number {<br>  return value * (1.0 - percentage / 100.0);<br>}</pre><pre>// 2nd: goes through the list, applies the discount to each value and adds them up<br>function totalize(values: readonly number[], percentage: number): number {<br>  let sum = 0.0;<br>  for (let i = 0; i &lt; values.length; i++) {<br>    sum += applyDiscount(values[i], percentage);<br>  }<br>  return sum;<br>}</pre><pre>const values: number[] = [59.70, 20.0, 22.0];<br>const total = totalize(values, 10.0);<br>console.log(`Total: $${total.toFixed(2)}`);   // Total: $91.53</pre><ul><li>percentage / 100.0 turns 10 into 0.10, and 1.0–0.10 gives 0.90: the part that’s left after the discount.</li><li>readonly is the lock: it guarantees totalize can’t change the array it received.</li><li>sum is an accumulator: it’s born outside the loop at zero and grows every lap.</li></ul><h3>Pointers — storing the address</h3><p>A pointer stores a memory address, and that address is where the variable lives.</p><pre>int x = 4;<br>int *p = &amp;x;         // p stores the address of x<br>*p = 9;              // goes to that address and puts 9 there<br>printf(&quot;%d\n&quot;, x);   // 9</pre><ul><li>&amp;x — the address of x.</li><li>int *p — p is a pointer to an int.</li><li>*p — the content of the place p points to.</li></ul><p>After *p = 9, the pointer still holds the same address. What changed was what’s inside the house. A pointer is a way to change another variable indirectly.</p><p>Note: * has two roles, multiplication and pointer. &amp; does too: address and bitwise AND. That’s the operator overloading from part 1.</p><p>Functions can also receive a copy of the address. When the function ends, the local pointer disappears, but the change stays. In practice, that’s how C does pass by reference.</p><p>When to use it? When memory is tight: instead of creating helper variables, you point straight at the variable that’s going to change.</p><p>Back to the photocopy: instead of handing over a copy of the document, you hand over a copy of your locker key. The key is a copy, but the locker is the real one.</p><p>In Java, TypeScript and Python, simple numbers are always copied. But when you pass a list or an object, the function gets a shortcut to it, and changes made inside show up outside.</p><h3>Swapping two values with pointers</h3><p>The classic: x = 3, y = 8, and we want to swap them.</p><pre>void swap(int *a, int *b) {<br>    int temp = *a;   // stores the value of x (3)<br>    *a = *b;         // x gets the value of y (8)<br>    *b = temp;       // y gets the stored value (3)<br>}</pre><pre>int main(void) {<br>    int x = 3, y = 8;<br>    swap(&amp;x, &amp;y);<br>    printf(&quot;%d %d\n&quot;, x, y);   // 8 3<br>    return 0;<br>}</pre><p>temp is the helper variable for the swap: without it, once x gets 8, the 3 is lost and everything gets mixed up.</p><p>Step by step in memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*XkwtYTnizdE7IAwhe0fhBQ.png" /></figure><p>The pointers a and b never change. What changes is the values inside the houses.</p><p>In TypeScript, the same swap fits in one line:</p><pre>let x = 3, y = 8;<br>[x, y] = [y, x];</pre><h3>Same paradigm, another language</h3><p>To wrap up, the same code in Pascal. The goal isn’t to learn Pascal, but to show that the paradigm stays the same — only the writing changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*wLhZjkRxw6vxrOwGH9vO6Q.png" /></figure><pre>double applyDiscount(double value, double percentage) {<br>    return value * (1.0 - percentage / 100.0);<br>}</pre><pre>function ApplyDiscount(value, percentage: real): real;<br>begin<br>  ApplyDiscount := value * (1.0 - percentage / 100.0);<br>end;</pre><p>Functions don’t define the paradigm — they exist in many paradigms. Here they’re used to organize a solution that’s still imperative. Every structured program is imperative, but not every imperative program is structured.</p><h3>Putting it all together in a purchase — one program, every concept</h3><p>The thread running through all of part 2 was the discount purchase. So it’s worth putting everything into a single C program and seeing where each concept shows up.</p><pre>#include &lt;stdio.h&gt;</pre><pre>double applyDiscount(double value, double percentage);   // prototype</pre><pre>int main(void) {<br>    double values[3] = {59.70, 20.0, 22.0};   // array of subtotals<br>    double discount;</pre><pre>    if (scanf(&quot;%lf&quot;, &amp;discount) != 1) {        // level 1: did the read work?<br>        printf(&quot;Invalid input\n&quot;);<br>        return 1;<br>    }<br>    if (discount &lt; 0 || discount &gt; 100) {       // level 2: does the value make sense?<br>        printf(&quot;Percentage out of range\n&quot;);<br>        return 1;<br>    }</pre><pre>    double sum = 0.0;                          // accumulator: born at zero<br>    for (int i = 0; i &lt; 3; i++) {              // counted repetition<br>        sum += applyDiscount(values[i], discount);   // call + changes the state<br>    }</pre><pre>    printf(&quot;Total: $%.2f\n&quot;, sum);             // observable effect<br>    return 0;<br>}</pre><pre>double applyDiscount(double value, double percentage) {   // definition<br>    return value * (1.0 - percentage / 100.0);<br>}</pre><p>Reading it top to bottom:</p><ul><li>Prototype — applyDiscount is announced before main and only defined at the end. Without the prototype, the compiler would complain.</li><li>Types — values and discount are doubles because they go into the math; the int is the index, which only counts positions.</li><li>Two-level validation — first scanf (did the read work?), then the range (does the value make sense?).</li><li>Explicit control — the if statements decide whether the program continues or stops, and return 1 tells the system something went wrong.</li><li>Repetition — the for goes through the array’s 3 positions.</li><li>State — sum starts at zero and changes every lap. The snapshot keeps changing until the end.</li><li>Function and pass by value — applyDiscount receives copies and returns a value, with no side effects.</li><li>Division — the 100.0 guarantees decimal math, even if the percentage becomes an int someday.</li><li>Observable effect — printf shows the result: with a 10% discount, Total: $91.53.</li></ul><p>Three values in an array, and pretty much all of part 2 is right there inside it.</p><h3>Closing</h3><p>In imperative programming, the program is a list of orders. And the computer carries out each one, exactly in the order it was given — including the wrong ones.</p><p>For anyone who tests software, this changes what you look for. The y that came out 4 instead of 6, the 10 / 100 that turned into zero, the -2 that made the store pay the customer: none of them crashed the program, and the compiler stayed quiet. What catches this kind of bug is the desk check, the test case at the edge, and the question nobody asked: “what if the user types this?”</p><p>The computer doesn’t get the order wrong. It follows yours.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9bf25343025" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PARADIGMAS DE LINGUAGENS DE PROGRAMAÇÃO— Parte 1]]></title>
            <link>https://medium.com/@fa.engeroff1996/paradigmas-de-linguagens-de-programa%C3%A7%C3%A3o-parte-1-ac4f94115815?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac4f94115815</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 10:22:36 GMT</pubDate>
            <atom:updated>2026-11-03T10:22:36.463Z</atom:updated>
            <content:encoded><![CDATA[<p>Você cadastra o produto com código 00127 e o sistema salva 127. Soma 0.1 com 0.2 e o resultado vem 0.30000000000000004. Converte a altura 1.78 pra inteiro e ela vira 1, não 2. Nenhum desses é bug de tela — é a linguagem fazendo exatamente o que foi programada pra fazer.</p><p>Entender como uma linguagem de programação funciona por dentro muda a forma de escrever código e, principalmente pra quem é de QA, muda a forma de testar. Aqui eu reúno o que aprendi na matéria de Linguagens de Programação esse semestre: o que faz uma linguagem ser boa, paradigmas, sintaxe e semântica, tipos, operadores, estruturas e sub-rotinas. No final, junto tudo num exemplo só: um carrinho de compra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4w1BulGfdFbZEyePM1BDQ.png" /></figure><h3>O que faz uma linguagem ser boa — os critérios</h3><p>Antes de escolher uma linguagem, vale entender o que pesa na avaliação dela. Não existe linguagem perfeita, existe a que equilibra melhor esses pontos pro problema que você tem.</p><p><strong>Simplicidade</strong> — quanto menos comandos e símbolos, mais simples é. Menos coisa pra decorar, menos jeito de errar.</p><p><strong>Ortogonalidade</strong> — a capacidade de construir qualquer coisa a partir de poucos elementos básicos (estruturas de controle, estruturas de dados e operadores), com nenhuma ou pouca exceção. Quanto menos exceção, menos surpresa.</p><p><strong>Tipos de dados</strong> — tipos bem definidos ajudam e reduzem o improviso. Ter um boolean de verdade é bem melhor que ficar representando verdadeiro e falso com 0 e 1.</p><p><strong>Verificação de tipos</strong> — parte dos erros é detectada ainda na escrita do código, como atribuir um texto a uma variável numérica. A outra parte só aparece quando executa.</p><p><strong>Projeto da sintaxe</strong> — palavras reservadas, símbolos e delimitadores de bloco afetam diretamente a simplicidade e a ortogonalidade.</p><p><strong>Suporte à abstração</strong> — de processo, quando você isola um trecho de código em um subprograma; e de dados, quando representa só o que é relevante de algo real.</p><p><strong>Expressividade</strong> — formas de abreviar sem perder clareza, como os operadores de incremento (++, +=) e a avaliação de expressões lógicas em que, se um lado já decide o resultado, o outro nem é avaliado.</p><p><strong>Tratamento de exceções</strong> — a capacidade de tratar possíveis erros sem derrubar o programa.</p><p><strong>Apelidos (aliases)</strong> — dois nomes acessando o mesmo dado na memória. Dá flexibilidade, mas reduz a confiabilidade: você altera por um nome e o outro muda junto.</p><p>Além disso, outros fatores entram na escolha: dificuldade de aprendizado, custo e desempenho de execução, facilidade de implementação — o JavaScript, por exemplo, roda direto no navegador sem precisar de recurso extra — e confiabilidade, principalmente em sistemas críticos.</p><p>E tem a <strong>otimização</strong>: o compilador usa técnicas que reduzem o tamanho do programa e aumentam a velocidade, sem você precisar mexer no código.</p><h3>Paradigmas — formas diferentes de pensar o mesmo problema</h3><p>Paradigma é a forma de programar. Cada linguagem nasce com um jeito principal de pensar: Java é orientada a objetos, Lisp é funcional, Prolog é lógica, SQL é declarativa e TypeScript é multiparadigma.</p><p><strong>Imperativo</strong> — variáveis, atribuições, condições e repetições. O ponto central é o <strong>estado</strong>: o conjunto de informações que muda durante a execução.</p><pre>total = 0<br>total = total + 2<br>total = total + 3   # estado agora é 5<br>print(total)</pre><p><strong>Orientado a objetos</strong> — a solução é montada com objetos, que juntam dado e operação. Um carrinho de compra tem itens (dados) e uma operação que soma o total.</p><p><strong>Funcional</strong> — composição de funções. Recebe uma coleção, transforma, filtra e combina. O lambda é um recurso funcional que o Java tem, mas isso não torna o Java funcional: ele continua sendo OO.</p><p><strong>Lógico</strong> — aqui você não descreve passos. Você conta o que sabe e depois pergunta. Fato: João é pai de Maria. Regra: o pai do pai é o avô. Aí você faz a consulta e a linguagem descobre a resposta sozinha.</p><p><strong>Declarativo</strong> — na prática é o SQL: você diz o que quer e o banco decide como buscar.</p><p><strong>Multiparadigma</strong> — deixa você programar em mais de um paradigma. O mesmo cálculo em Python, de dois jeitos:</p><pre># imperativo — descreve o passo a passo<br>total = 0<br>for valor in [2, 3, 4]:<br>    total += valor<br># total = 9</pre><pre># funcional — diz o que quer<br>total = sum([2, 3, 4])<br># total = 9</pre><p>O jeito que eu guardei:</p><ul><li><strong>OO</strong> — coisas: tenho objetos que têm dados e ações.</li><li><strong>Imperativo</strong> — passo a passo: faço isso, depois aquilo.</li><li><strong>Funcional</strong> — máquina: entra um dado, sai outro.</li><li><strong>Lógico</strong> — eu dou os fatos e as regras, faço a consulta e ele descobre.</li></ul><h3>Sintaxe e semântica — escrever certo e fazer sentido</h3><p><strong>Sintaxe</strong> é a regra de como os símbolos se organizam pra formar uma construção válida. É escrever frases bem formadas. <strong>Semântica</strong> é fazer essas frases terem sentido.</p><p>Dá pra pensar em português:</p><ul><li>“O gato bebe leite” — sintaxe ok, semântica ok.</li><li>“Gato o leite bebe” — sintaxe errada, nem dá pra entender.</li><li>“O leite bebe o gato” — sintaxe ok, semântica ruim.</li></ul><p>No Java é igual:</p><pre>int total = 2 + ;          // erro de sintaxe: falta o número depois do +<br>int total = quantidade + 3; // erro de semântica: quantidade não foi declarada</pre><p>A semântica organiza a gramática e deixa a sequência coordenada, na ordem certa, pra cumprir o objetivo. Erros semânticos clássicos: usar uma variável sem declarar, declarar fora da ordem, declarar duas vezes a mesma variável, colocar um comando fora do bloco.</p><p>E assim como livros antigos podem não ter tradução, linguagens antigas podem não ter atualização. Quando têm, geralmente vem como biblioteca nova, versão nova ou adoção de outro paradigma.</p><h3>Comando, instrução e aninhamento</h3><ul><li><strong>Comando</strong> — palavra reservada + seus parâmetros + os símbolos pra completar. Ex: print(total).</li><li><strong>Instrução</strong> — um comando simples ou uma instrução que agrupa outras, como as estruturas de controle (if, for, while). Dependendo do paradigma, pode ser funcional.</li><li><strong>Aninhamento</strong> — colocar uma instrução dentro de outra.</li></ul><pre>for (int i = 0; i &lt; 3; i++) {     // instrução agrupadora<br>    if (i == 1) {                 // aninhada dentro do for<br>        System.out.println(i);    // comando aninhado dentro do if<br>    }<br>}</pre><p>No funcional, o aninhamento aparece como encadeamento e funções dentro de funções:</p><pre>[0, 1, 2].filter(i =&gt; i == 1).forEach(i =&gt; console.log(i));<br>// .filter().forEach() = encadeamento<br>// cada i =&gt; ... é um lambda passado como argumento</pre><h3>Lexema x token — como o compilador enxerga sua linha</h3><p><strong>Lexema</strong> é exatamente a sequência que você digita. <strong>Token</strong> é a categoria a que esse lexema pertence. Pegando int total = 2 + 3; e lendo peça por peça:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*oDqYUANWmlcauGC8i7xGgw.png" /></figure><p>Traduzindo: declarei uma variável total do tipo inteiro que já começa com o resultado de 2 + 3, ou seja, 5.</p><p>Os nomes das categorias variam entre autores, mas o que importa é o conceito. Essa é a base da <strong>análise léxica</strong>, a primeira etapa quando o código passa pelo compilador.</p><p>E por que a palavra reservada importa tanto? Porque toda instrução tem uma como base. Sem ela, a análise sintática nem sabe como verificar o resto. Com a sintaxe correta, o compilador consegue montar os tokens na árvore sintática: delimitadores, operadores e identificadores.</p><h3>Gramática e BNF</h3><p>A <strong>gramática</strong> são as regras que compõem a linguagem. A <strong>BNF</strong> é o manual com essas regras e notações — é o que ajuda o compilador a ver se o código está escrito corretamente. Ela é uma <strong>metalinguagem</strong>: uma linguagem usada pra descrever outra linguagem.</p><p>Como ler uma regra BNF:</p><pre>&lt;assign&gt; -&gt; &lt;var&gt; = &lt;expression&gt;</pre><p>Uma atribuição é formada por uma variável, o símbolo = e uma expressão. O que está entre &lt; &gt; é algo genérico, ainda não preenchido.</p><h3>Delimitadores de bloco e propriedades</h3><p>O <strong>delimitador de bloco</strong> marca onde o bloco começa e termina: pode ser palavra (início/fim), símbolo ({ } no Java, C e TS) ou indentação, como no Python.</p><p>Duas propriedades que vêm direto da matemática:</p><ul><li><strong>Comutativa</strong> — troca a ordem dos dois lados e não muda nada: 3 * 2 = 2 * 3. Vale pra soma e multiplicação.</li><li><strong>Associativa</strong> — muda o agrupamento e não muda nada, desde que seja a mesma operação: 2 + (3 + 5) = (2 + 3) + 5.</li></ul><p>Resumo pra guardar:</p><ol><li>Sintaxe = bem escrito. Semântica = faz sentido.</li><li>Lexema = o que está escrito. Token = o que é.</li><li>BNF = manual de regras da linguagem.</li><li>Bloco = { } ou indentação.</li><li>Precedência = o que vai primeiro. Comutativa = troca de lado. Associativa = troca de agrupamento.</li></ol><h3>Tipos de erro — quanto mais tarde aparece, mais caro custa</h3><ul><li><strong>Sintático</strong> — mal escrito, estrutura quebrada.</li><li><strong>Semântico</strong> — a estrutura está certa, mas não faz sentido ou não combina.</li><li><strong>De execução</strong> — está tudo certo até rodar, e aí quebra.</li><li><strong>Lógico</strong> — roda sem o compilador reclamar, mas o resultado está errado.</li></ul><p>Quanto mais tarde o erro aparece, mais difícil e mais caro é corrigir. E o erro lógico é o mais perigoso de todos: o sistema funciona, só que não segue o fluxo correto. Ninguém percebe até o dado errado chegar em algum lugar que importa — e é exatamente aí que o teste faz diferença.</p><p>Aqui a ortogonalidade volta: pouca ortogonalidade significa muitas exceções, e muitas exceções significam erros que só aparecem rodando.</p><h3>Identificadores, variáveis e estado — dando nome e lugar pros dados</h3><h3>Identificadores</h3><p>Identificador é o nome que você dá pra variáveis, sub-rotinas e estruturas de dados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*6rgNtCPu9pzgkLGOxsFHpg.png" /></figure><p>Pra nomes compostos, usa preco_unitario. Atenção que a maioria das linguagens é <strong>case sensitive</strong>: total e Total são identificadores diferentes. E palavras reservadas (int, for, return, def) não servem como identificador. Tem casos específicos, como PHP e Ruby, que usam símbolos como $ e @ no começo do nome.</p><h3>Variável e memória</h3><p>Variável é um espaço reservado na memória, geralmente na RAM, que guarda um valor e pode ser alterado durante a execução.</p><p>Em linguagem de alto nível você não precisa saber o endereço desse espaço. Isso só aparece em linguagem de baixo nível, como C ou Assembly. No C existem os <strong>ponteiros</strong>, que apontam pra um lugar na memória e permitem acessar aquele mesmo espaço em outras partes do código. No Java isso aparece como referência, quando você cria um objeto com new.</p><p>Linguagens de baixo nível também deixam você definir o tamanho ocupado na memória. Antigamente a memória era pouca e cara, então isso fazia muita diferença. Hoje as linguagens modernas resolvem isso automaticamente.</p><h3>Mudança de estado</h3><pre>int quantidade = 3;          // declara e inicia<br>quantidade = quantidade + 2; // agora vale 5</pre><p>Em programação, = é o sinal de atribuição. Na segunda linha eu pego o valor 3 que já estava lá, somo 2 e guardo de volta. O lado direito usa o estado anterior e a atribuição atualiza — isso é característica da programação imperativa.</p><p>No C, você precisa atribuir um valor antes de ler a variável. Só declarar não vale.</p><h3>Literais e constantes</h3><p><strong>Literal</strong> é o valor escrito direto no código: 3, 0.10, &quot;caderno&quot;.</p><p><strong>Constante</strong> é um nome associado a um valor que não muda durante toda a execução. Já a variável comum tem vinculação dinâmica: o valor muda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*wqfp5hug0-3eOddN-a8tsA.png" /></figure><p>No Python a constante é só convenção: o nome em maiúscula está gritando “não mude”, mas a linguagem não impede.</p><h3>Tipos de dados — escolha pela finalidade, não pela aparência</h3><h3>Bits, bytes e tipos primitivos</h3><p>Todo dado é armazenado em bits. Um conjunto de 8 bits forma 1 byte, e essa é a base de tudo.</p><p>Os <strong>tipos primitivos</strong> são os básicos: inteiro, ponto flutuante (decimal), booleano e caractere — e em algumas linguagens, números complexos. A <strong>string</strong> é uma cadeia de caracteres; pode ser primitiva ou não, e pode ser estática (tamanho fixo) ou dinâmica. A <strong>expressão regular</strong> é um tipo especial de padrão que define exatamente quais caracteres serão aceitos — CEP, CNPJ, CPF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*plP-waIolc4pIUMA5oiOrQ.png" /></figure><h3>Escolha pela finalidade</h3><p>A pergunta certa na hora de escolher o tipo é: o que eu vou fazer com esse dado?</p><p>O código de produto 00127 parece número. Se você usar int, os zeros somem e ele vira 127. CPF e CEP também parecem números, mas só identificam — e muitos começam com zero.</p><p>O teste rápido: <strong>você faz conta com isso?</strong></p><ul><li><strong>Sim</strong> — preço, quantidade, idade → tipo numérico.</li><li><strong>Não</strong> — código, CEP, CPF → texto.</li></ul><h3>Limites de precisão — o erro do computador</h3><p>Até aqui falamos do erro do programador. Agora é o erro do computador. Pra ele, tudo é binário, e alguns decimais que parecem simples pra nós não cabem de forma exata em binário. Então ele guarda uma aproximação.</p><pre>0.1 + 0.2<br># 0.30000000000000004  → sobrou um restinho</pre><p>Isso importa em sistemas que exigem precisão: financeiro, cálculo científico, sistemas críticos.</p><h3>Tipagem estática x dinâmica</h3><p><strong>Estática</strong> — o tipo é declarado e checado antes de rodar, em tempo de compilação. Os erros são pegos cedo; a desvantagem é que precisa de mais código pra declarar.</p><p><strong>Dinâmica</strong> — os tipos são verificados em tempo de execução. A variável pode guardar qualquer tipo e o interpretador só descobre qual quando a linha executa. O desenvolvimento fica mais ágil e o código mais enxuto; a desvantagem é que os erros só aparecem rodando.</p><p>Detalhe importante: dinâmica não é ausência de tipo. Python tem tipo, só que ele está no objeto, não na variável.</p><h3>Tipagem forte x fraca</h3><p>Aqui a pergunta é: a linguagem aceita misturar os tipos?</p><pre>5 + &quot;2&quot;   # Python: TypeError — não soma número com texto</pre><pre>5 + &quot;2&quot;   // JavaScript: &quot;52&quot; — converte o 5 em texto e concatena</pre><p>Ou seja: Python é fortemente e dinamicamente tipado. JavaScript é fracamente tipado. O rótulo de forte ou fraca não dispensa o aprendizado de cada linguagem — umas são mais rígidas, outras convertem e são mais flexíveis.</p><p>Resumo:</p><ul><li><strong>Estática / dinâmica</strong> — quando o tipo é checado: na compilação ou na execução.</li><li><strong>Forte / fraca</strong> — o quanto a linguagem é rígida ao misturar tipos.</li></ul><h3>Conversão, coerção e perda de informação — quando o tipo muda</h3><p><strong>Conversão explícita (cast)</strong> é quando você pede a conversão de forma clara no código. Se tentar converter algo impossível, dá erro: int(&quot;três&quot;) quebra, porque letras não viram número. Um caso clássico no Python: o input() sempre devolve texto, mesmo que o usuário digite um número.</p><p>No C e no Java, o cast é escrito entre parênteses:</p><pre>double altura = 1.78;<br>int parte = (int) altura; // 1</pre><p>O cast não muda o valor original: altura continua 1.78. Quem recebe o valor truncado é parte.</p><p><strong>Coerção</strong> é quando a própria linguagem converte os dados pra expressão fazer sentido, sem você pedir.</p><pre>int quantidade = 3;<br>double preco = 19.90;<br>double subtotal = quantidade * preco;</pre><p>A multiplicação envolve int e double, então o C converte o 3 em 3.0 pra fazer a conta. A variável quantidade continua sendo int — a adaptação vale só pro cálculo. O tipo mais flexível predomina sobre o mais restrito.</p><p>Resumo: <strong>conversão</strong> é você pedindo. <strong>Coerção</strong> é a linguagem fazendo sozinha.</p><h3>Perda de informação</h3><p>Nem toda conversão preserva o valor original. Transformar decimal em inteiro descarta a parte fracionária.</p><p>Muita gente acha que converter 1.78 pra inteiro vai dar 2, porque está mais perto. Errado: a conversão <strong>trunca</strong>, joga uma parte fora. Se você quer arredondar de verdade, precisa usar uma função específica de matemática — math no Python, math.h no C, Math no TypeScript.</p><p>Isso é um trade-off: em alguns sistemas a perda é aceitável, em outros não.</p><h3>Operadores e expressões — a mesma conta nem sempre dá o mesmo resultado</h3><p>Uma <strong>expressão</strong> combina identificadores e operadores pra produzir um resultado.</p><ul><li><strong>Aritméticos</strong> — soma, subtração, multiplicação, tudo da matemática.</li><li><strong>Relacionais</strong> — comparam valores (&lt;, &lt;=, &gt;, &gt;=, ==, !=) e produzem verdadeiro ou falso.</li><li><strong>Lógicos</strong> — combinam condições: &amp;&amp;, ||, ! no C, Java e TS; and, or, not no Python.</li><li><strong>De atribuição</strong> — =, +=, -=, ++, --.</li></ul><p>Atenção: a mesma conta pode dar resultados diferentes dependendo da linguagem e dos tipos. No C, quantidade == 3 produz 1 (verdadeiro) ou 0 (falso). No Python, produz True ou False. Se você mistura isso sem perceber, o compilador não reclama — e a lógica equivocada pode demorar pra ser descoberta.</p><h3>Sobrecarga de operadores</h3><p>O mesmo operador pode ter mais de uma função dependendo do contexto. O + soma números, mas em várias linguagens também junta textos. O * no C multiplica, mas antes de um nome (*p) indica ponteiro.</p><h3>Atribuição x comparação</h3><ul><li>= <strong>atribuir</strong> — guarde esse valor nessa variável.</li><li>== <strong>comparar</strong> — esses dois valores são iguais?</li></ul><h3>Precedência e associatividade</h3><p><strong>Precedência</strong> é a ordem em que as operações são resolvidas, e segue a matemática:</p><pre>10 + 2 * 3     // 16 — multiplica primeiro, depois soma<br>(10 + 2) * 3   // 36 — parênteses primeiro: 12, depois multiplica</pre><p><strong>Associatividade</strong> decide o empate, quando as duas operações têm a mesma prioridade. A linguagem resolve da esquerda pra direita. Em (2 + 5) - 3 e 2 + (5 - 3) o resultado é 4 dos dois jeitos.</p><p>Quando entram comparações com “E” e “OU”, como idade &gt;= 18 E sexo == &quot;F&quot;, a ordem é:</p><ol><li>Primeiro as comparações, cada uma vira V ou F.</li><li>Depois o “E” junta esses dois resultados.</li></ol><p>Pra guardar: <strong>“E”</strong> só é verdade se os dois forem verdade. <strong>“OU”</strong> só é falso se os dois forem falsos. <strong>“NÃO”</strong> só inverte.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*Cm59zjdFEM8t9Q8TkGIt0w.png" /></figure><h3>Curto-circuito</h3><p>No E e no OU, se a primeira parte já decidiu o resultado, a linguagem nem avalia a segunda. O ganho prático é enorme, porque isso protege contra erros:</p><pre>if (quantidade != 0 &amp;&amp; total / quantidade &lt; 20) {<br>    // ...<br>}</pre><p>Se quantidade for zero, a primeira condição já é falsa e a divisão nem é executada — nada de divisão por zero. Por isso a ordem das condições importa: coloque primeiro a que protege a segunda.</p><h3>Estruturas de dados — agrupando o que tem relação</h3><p>Dá pra dividir em duas partes.</p><p><strong>Estrutura homogênea</strong> — tudo do mesmo tipo.</p><ul><li><strong>Vetor</strong> — lista de elementos acessada por um índice.</li><li><strong>Matriz</strong> — um vetor com mais de uma dimensão, como linhas e colunas, ou até mais. Uma matriz tridimensional, por exemplo, é percorrida com laços encadeados.</li></ul><p><strong>Estrutura heterogênea</strong> — tipos misturados.</p><ul><li><strong>Registro</strong> — um agrupador de dados de tipos diferentes que descrevem a mesma coisa, como um produto ou uma pessoa. Pode ser uma classe no Java, uma struct no C ou uma interface no TS. Cada dado dentro dele é um campo, ou atributo.</li></ul><p>Aqui o conceito conversa direto com banco de dados: um vetor de registros é uma tabela. Cada posição é um produto (uma linha) e cada campo é uma coluna. Nem todo paradigma usa registro, mas as linguagens de propósito geral usam bastante.</p><h3>Escopo e tempo de vida</h3><p><strong>Escopo</strong> diz de onde uma estrutura de dados pode ser acessada.</p><ul><li><strong>Global</strong> — declarada fora das sub-rotinas, pode ser vista em qualquer parte do código. Por isso mesmo pode ser alterada por engano.</li><li><strong>Local</strong> — declarada dentro da sub-rotina e só existe ali.</li></ul><p><strong>Tempo de vida</strong> acompanha o escopo. Uma estrutura local só ocupa memória enquanto a sub-rotina está executando. Quando ela termina, a memória é liberada e os dados se perdem — por isso a sub-rotina retorna um valor, pra não perder o resultado.</p><p>No C, até o código principal fica dentro de uma função, a main. Então as variáveis declaradas ali também são locais.</p><h3>Estruturas de controle — o programa não roda só de cima pra baixo</h3><p>Um programa não executa só linha após linha. Ele toma decisões e repete trechos de código — e é isso que as estruturas de controle fazem.</p><h3>Decisão</h3><p>Avalia uma condição lógica, verdadeira ou falsa, e executa um bloco ou outro. Ex: quantidade &gt; 0, quantidade &lt;= estoque.</p><ul><li><strong>Simples</strong> — executa um bloco se a condição for verdadeira.</li><li><strong>Composta</strong> — tem um segundo caminho, o else, pra quando for falsa.</li><li><strong>Encadeada (aninhada)</strong> — uma decisão dentro da outra: a de dentro só é avaliada se a anterior for verdadeira. Ex: só pergunta se a pessoa tem habilitação se ela for maior de idade.</li><li><strong>Múltipla (</strong><strong>switch / </strong><strong>match)</strong> — escolhe um bloco conforme o valor de uma variável: caso 1, caso 2, caso contrário.</li></ul><h3>Repetição</h3><p>Em vez de copiar o mesmo trecho várias vezes, você repete:</p><ul><li><strong>while (enquanto)</strong> — testa a condição antes de cada volta. Pode não executar nenhuma vez.</li><li><strong>do...while (repita enquanto)</strong> — executa o bloco e só depois testa. Garante pelo menos uma execução.</li><li><strong>for (para)</strong> — repetição contada, com número de voltas definido.</li></ul><p>Cuidado com o loop infinito: se a condição nunca vira falsa, o programa nunca sai dali.</p><h3>Sub-rotinas, parâmetros e bibliotecas — dividir pra conquistar</h3><p>Os sistemas ficaram complexos demais pra rodar tudo num bloco só. Daí surgiram as sub-rotinas, ou subprogramas: dividir um problema grande em partes pequenas e resolver cada uma separadamente.</p><p>Cada sub-rotina tem uma entrada. Quem chamou fica esperando enquanto ela executa, e o controle sempre volta pra quem chamou. Existem dois tipos:</p><ul><li><strong>Procedimento</strong> — executa uma tarefa e não devolve nada.</li><li><strong>Função</strong> — executa e devolve um valor.</li></ul><pre>function calculaTotal(preco: number, qtd: number, desconto: number): number {<br>  return preco * qtd * (1 - desconto);<br>}</pre><p>A estrutura sempre precisa de um <strong>cabeçalho</strong> (nome, parâmetros e tipo de retorno) e de um <strong>corpo</strong>. O retorno pode acontecer em mais de um ponto, dependendo das condições dentro da função.</p><h3>Parâmetros</h3><p>Parâmetros são os dados que a sub-rotina recebe. Eles existem pra que ela não precise acessar diretamente as variáveis de quem a chamou — o que seria inseguro.</p><ul><li><strong>Parâmetros formais</strong> — os que eu declaro no cabeçalho, com nome e tipo: preco, qtd, desconto.</li><li><strong>Parâmetros reais</strong> — os valores passados na chamada: calculaTotal(19.90, 3, 0.10).</li></ul><p>Eles são <strong>posicionais</strong>: a ordem na chamada precisa bater com a ordem do cabeçalho. E existem duas formas de passar os dados:</p><ul><li><strong>Por valor</strong> — a sub-rotina recebe uma cópia. O original não é afetado. É a forma mais segura.</li><li><strong>Por referência</strong> — a sub-rotina recebe um ponteiro pro original. Qualquer alteração ali muda o dado de verdade em quem chamou.</li></ul><h3>Prototipação</h3><p>Principalmente no C. O compilador lê o código de cima pra baixo: se uma função é usada antes de ser definida, ele reclama — igual a uma variável usada antes de ser declarada.</p><p>Quando as sub-rotinas dependem uma da outra (a 1 chama a 2, que chama a 3), às vezes é impossível ordenar tudo de forma que cada uma apareça antes de ser chamada. A solução é a <strong>prototipação</strong>: escrever só o cabeçalho da função no início do arquivo, avisando o compilador que ela existe, e deixar a implementação completa pra depois, na ordem que quiser.</p><h3>Bibliotecas e reuso</h3><p>Sub-rotinas também podem ficar em arquivos externos. Isso organiza o código e traz recursos prontos e já testados. Existem as bibliotecas padrão da linguagem — entrada e saída de dados, matemática, gráficos — e você também pode criar a sua pra reaproveitar código em outros projetos.</p><p>No C, ao incluir uma biblioteca, ela inteira é agregada ao programa. No Java, as bibliotecas (a API) são agregadas às classes, e dá pra importar só o necessário pra aquela classe ou problema.</p><h3>Juntando tudo na compra — um carrinho, todos os conceitos</h3><p>O exemplo que atravessou a matéria inteira foi o de uma compra: produto, quantidade, preço, desconto. Então vale juntar tudo num código só e ver onde cada conceito aparece.</p><pre>const DESCONTO = 0.10;                 // constante: não muda durante a execução</pre><pre>interface Produto {                    // registro: estrutura heterogênea<br>  codigo: string;                      // &quot;00127&quot; é texto — não se faz conta com ele<br>  nome: string;<br>  preco: number;                       // preço faz conta → numérico<br>  quantidade: number;<br>  estoque: number;<br>}</pre><pre>function calculaTotal(itens: Produto[]): number {     // função: cabeçalho com parâmetro e retorno<br>  let total = 0;                                      // variável local, estado inicial</pre><pre>  for (const item of itens) {                         // repetição<br>    if (item.quantidade &gt; 0 &amp;&amp; item.quantidade &lt;= item.estoque) { // decisão + curto-circuito<br>      total += item.preco * item.quantidade;          // expressão + atribuição: muda o estado<br>    }<br>  }</pre><pre>  return total * (1 - DESCONTO);                      // precedência: parênteses primeiro<br>}</pre><pre>const carrinho: Produto[] = [                         // vetor de registros = uma tabela<br>  { codigo: &quot;00127&quot;, nome: &quot;Caderno&quot;, preco: 19.90, quantidade: 3, estoque: 10 },<br>];</pre><pre>console.log(calculaTotal(carrinho));</pre><p>Lendo de cima pra baixo:</p><ul><li><strong>Tipos pela finalidade</strong> — codigo é string porque só identifica; se fosse number, o 00127 virava 127. preco e quantidade são numéricos porque entram na conta.</li><li><strong>Estrutura de dados</strong> — Produto é um registro; carrinho é um vetor de registros. Cada item é uma linha, cada campo é uma coluna.</li><li><strong>Sub-rotina</strong> — calculaTotal é uma função: recebe o carrinho por parâmetro, em vez de acessar uma variável global, e devolve um valor.</li><li><strong>Escopo e estado</strong> — total é local: nasce zerado, muda a cada volta do for e deixa de existir quando a função termina. Só o resultado sobrevive, pelo return.</li><li><strong>Curto-circuito</strong> — se a quantidade não for maior que zero, a comparação com o estoque nem é feita.</li><li><strong>Precisão numérica</strong> — 19.90 × 3 com desconto pode sair com um restinho no fim das casas decimais. Em sistema financeiro, isso se resolve trabalhando em centavos (inteiros) ou arredondando só na exibição.</li><li><strong>Tipagem</strong> — no TypeScript, se alguém passar quantidade: &quot;3&quot; como texto, o erro aparece antes de rodar. No JavaScript puro, &quot;3&quot; * 19.90 passaria por coerção sem ninguém perceber.</li></ul><p>Um carrinho de compra simples, e praticamente a matéria inteira está ali dentro.</p><h3>Fechando</h3><p>No começo, linguagem de programação parece só um monte de regra pra decorar. Mas cada regra existe por um motivo: o tipo protege o dado, o escopo protege a memória, o curto-circuito protege a conta, o parâmetro protege a variável de quem chamou.</p><p>Pra quem testa software, entender isso muda o olhar. O código 00127 que virou 127, o 0.1 + 0.2 que não deu 0.3, a altura 1.78 que virou 1 — nada disso é a linguagem errando. É a linguagem fazendo exatamente o que mandaram, e alguém não sabia o que estava mandando.</p><p>Antes de culpar a ferramenta, entenda como ela funciona. O bug quase sempre está na distância entre o que você escreveu e o que achou que escreveu.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac4f94115815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming Language Paradigms— Part 1]]></title>
            <link>https://medium.com/@fa.engeroff1996/programming-language-paradigms-part-1-97327b37efc9?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/97327b37efc9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 10:22:28 GMT</pubDate>
            <atom:updated>2026-11-03T10:22:28.621Z</atom:updated>
            <content:encoded><![CDATA[<p>You register a product with code 00127 and the system saves 127. You add 0.1 and 0.2 and the result comes out as 0.30000000000000004. You convert a height of 1.78 to an integer and it becomes 1, not 2. None of these are UI bugs — it’s the language doing exactly what it was programmed to do.</p><p>Understanding how a programming language works under the hood changes the way you write code and, especially for QA, changes the way you test. This is part 1 of a series on my Programming Languages course, covering the first two classes: what makes a language good, paradigms, syntax and semantics, types, operators, structures and subroutines. At the end, I put it all together in a single example: a shopping cart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITnax2lUbCYG1fHezIRDFA.png" /></figure><h3>What makes a language good — the criteria</h3><p>Before choosing a language, it’s worth understanding what weighs in its evaluation. There’s no perfect language — there’s the one that best balances these points for the problem you have.</p><p><strong>Simplicity</strong> — the fewer commands and symbols, the simpler it is. Less to memorize, fewer ways to get it wrong.</p><p><strong>Orthogonality</strong> — the ability to build anything from a few basic elements (control structures, data structures and operators), with no or few exceptions. Fewer exceptions, fewer surprises.</p><p><strong>Data types</strong> — well-defined types help and reduce improvisation. Having a real boolean is much better than representing true and false with 0 and 1.</p><p><strong>Type checking</strong> — part of the errors is caught while you’re still writing the code, like assigning text to a numeric variable. The other part only shows up when it runs.</p><p><strong>Syntax design</strong> — reserved words, symbols and block delimiters directly affect simplicity and orthogonality.</p><p><strong>Abstraction support</strong> — process abstraction, when you isolate a piece of code into a subprogram; and data abstraction, when you represent only what’s relevant about something real.</p><p><strong>Expressiveness</strong> — ways to shorten code without losing clarity, like increment operators (++, +=) and logical expressions where, if one side already decides the result, the other isn&#39;t even evaluated.</p><p><strong>Exception handling</strong> — the ability to handle possible errors without crashing the program.</p><p><strong>Aliases</strong> — two names accessing the same data in memory. It gives flexibility but reduces reliability: you change it through one name and the other changes too.</p><p>Other factors also weigh in: learning curve, execution cost and performance, ease of implementation — JavaScript, for example, runs straight in the browser without any extra resources — and reliability, especially in critical systems.</p><p>And there’s <strong>optimization</strong>: the compiler uses techniques that reduce the program’s size and increase its speed, without you having to touch the code.</p><h3>Paradigms — different ways to think about the same problem</h3><p>A paradigm is a way of programming. Each language is born with a main way of thinking: Java is object-oriented, Lisp is functional, Prolog is logic, SQL is declarative and TypeScript is multi-paradigm.</p><p><strong>Imperative</strong> — variables, assignments, conditions and loops. The central point is <strong>state</strong>: the set of information that changes during execution.</p><pre>total = 0<br>total = total + 2<br>total = total + 3   # state is now 5<br>print(total)</pre><p><strong>Object-oriented</strong> — the solution is built with objects, which bring data and operations together. A shopping cart has items (data) and an operation that adds up the total.</p><p><strong>Functional</strong> — function composition. It takes a collection, transforms it, filters it and combines it. Lambda is a functional feature Java has, but that doesn’t make Java functional: it’s still OO.</p><p><strong>Logic</strong> — here you don’t describe steps. You state what you know and then ask. Fact: John is Mary’s father. Rule: a father’s father is a grandfather. Then you run the query and the language figures out the answer on its own.</p><p><strong>Declarative</strong> — in practice it’s SQL: you say what you want and the database decides how to fetch it.</p><p><strong>Multi-paradigm</strong> — lets you program in more than one paradigm. The same calculation in Python, two ways:</p><pre># imperative — describes the step by step<br>total = 0<br>for value in [2, 3, 4]:<br>    total += value<br># total = 9</pre><pre># functional — says what it wants<br>total = sum([2, 3, 4])<br># total = 9</pre><p>The way I remember it:</p><ul><li><strong>OO</strong> — things: I have objects that have data and actions.</li><li><strong>Imperative</strong> — step by step: do this, then that.</li><li><strong>Functional</strong> — a machine: one piece of data goes in, another comes out.</li><li><strong>Logic</strong> — I give the facts and the rules, run the query and it figures it out.</li></ul><h3>Syntax and semantics — writing it right and making sense</h3><p><strong>Syntax</strong> is the rule for how symbols are arranged to form a valid construction. It’s writing well-formed sentences. <strong>Semantics</strong> is making those sentences mean something.</p><p>You can think of it in plain English:</p><ul><li>“The cat drinks milk” — syntax ok, semantics ok.</li><li>“Cat the milk drinks” — broken syntax, you can’t even understand it.</li><li>“The milk drinks the cat” — syntax ok, semantics wrong.</li></ul><p>In Java it’s the same:</p><pre>int total = 2 + ;          // syntax error: missing the number after +<br>int total = quantity + 3;  // semantic error: quantity was never declared</pre><p>Semantics organizes the grammar and keeps the sequence coordinated, in the right order, to reach the goal. Classic semantic errors: using a variable without declaring it, declaring things out of order, declaring the same variable twice, placing a command outside its block.</p><p>And just like old books may never get a translation, old languages may never get an update. When they do, it usually comes as a new library, a new version or the adoption of another paradigm.</p><h3>Command, statement and nesting</h3><ul><li><strong>Command</strong> — reserved word + its parameters + the symbols that complete it. E.g. print(total).</li><li><strong>Statement</strong> — a simple command or a statement that groups others, like control structures (if, for, while). Depending on the paradigm, it can be functional.</li><li><strong>Nesting</strong> — placing one statement inside another.</li></ul><pre>for (int i = 0; i &lt; 3; i++) {     // grouping statement<br>    if (i == 1) {                 // nested inside the for<br>        System.out.println(i);    // command nested inside the if<br>    }<br>}</pre><p>In functional style, nesting shows up as chaining and functions inside functions:</p><pre>[0, 1, 2].filter(i =&gt; i == 1).forEach(i =&gt; console.log(i));<br>// .filter().forEach() = chaining<br>// each i =&gt; ... is a lambda passed as an argument</pre><h3>Lexeme vs token — how the compiler sees your line</h3><p>A <strong>lexeme</strong> is exactly the sequence you type. A <strong>token</strong> is the category that lexeme belongs to. Taking int total = 2 + 3; and reading it piece by piece:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*LGCr1FIkbV7Np_bw_Uoqbw.png" /></figure><p>In plain words: I declared a variable total of type integer that already starts with the result of 2 + 3, which is 5.</p><p>Category names vary between authors, but what matters is the concept. This is the basis of <strong>lexical analysis</strong>, the first stage when code goes through the compiler.</p><p>And why does the reserved word matter so much? Because every statement has one at its base. Without it, syntax analysis doesn’t even know how to check the rest. With correct syntax, the compiler can arrange the tokens into the syntax tree: delimiters, operators and identifiers.</p><h3>Grammar and BNF</h3><p>The <strong>grammar</strong> is the set of rules that make up the language. <strong>BNF</strong> is the manual with those rules and notation — it’s what helps the compiler check whether the code is written correctly. It’s a <strong>metalanguage</strong>: a language used to describe another language.</p><p>How to read a BNF rule:</p><pre>&lt;assign&gt; -&gt; &lt;var&gt; = &lt;expression&gt;</pre><p>An assignment is made of a variable, the = symbol and an expression. Whatever is between &lt; &gt; is something generic, not filled in yet.</p><h3>Block delimiters and properties</h3><p>The <strong>block delimiter</strong> marks where a block starts and ends: it can be a word (begin/end), a symbol ({ } in Java, C and TS) or indentation, as in Python.</p><p>Two properties that come straight from math:</p><ul><li><strong>Commutative</strong> — swap the order of the two sides and nothing changes: 3 * 2 = 2 * 3. Works for addition and multiplication.</li><li><strong>Associative</strong> — change the grouping and nothing changes, as long as it’s the same operation: 2 + (3 + 5) = (2 + 3) + 5.</li></ul><p>Summary to keep:</p><ol><li>Syntax = well written. Semantics = makes sense.</li><li>Lexeme = what’s written. Token = what it is.</li><li>BNF = the language’s rulebook.</li><li>Block = { } or indentation.</li><li>Precedence = what goes first. Commutative = swap sides. Associative = swap grouping.</li></ol><h3>Error types — the later it shows up, the more it costs</h3><ul><li><strong>Syntax error</strong> — badly written, broken structure.</li><li><strong>Semantic error</strong> — the structure is right, but it doesn’t make sense or doesn’t fit.</li><li><strong>Runtime error</strong> — everything’s fine until it runs, and then it breaks.</li><li><strong>Logic error</strong> — it runs without the compiler complaining, but the result is wrong.</li></ul><p>The later an error shows up, the harder and more expensive it is to fix. And the logic error is the most dangerous of all: the system works, it just doesn’t follow the correct flow. Nobody notices until the wrong data lands somewhere that matters — and that’s exactly where testing makes the difference.</p><p>Orthogonality comes back here: low orthogonality means lots of exceptions, and lots of exceptions mean errors that only show up at runtime.</p><h3>Identifiers, variables and state — giving data a name and a place</h3><h3>Identifiers</h3><p>An identifier is the name you give to variables, subroutines and data structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*-YSpZEUXQ27We-aFdydnvw.png" /></figure><p>For compound names, use unit_price. Watch out: most languages are <strong>case sensitive</strong>, so total and Total are different identifiers. And reserved words (int, for, return, def) can&#39;t be used as identifiers. There are specific cases, like PHP and Ruby, that use symbols such as $ and @ at the start of the name.</p><h3>Variables and memory</h3><p>A variable is a reserved space in memory, usually in RAM, that holds a value and can be changed during execution.</p><p>In high-level languages you don’t need to know the address of that space. That only comes up in low-level languages, like C or Assembly. C has <strong>pointers</strong>, which point to a place in memory and let you access that same space from other parts of the code. In Java this shows up as references, when you create an object with new.</p><p>Low-level languages also let you define how much memory is used. Back in the day memory was scarce and expensive, so this made a big difference. Today, modern languages handle it automatically.</p><h3>State change</h3><pre>int quantity = 3;          // declares and initializes<br>quantity = quantity + 2;   // now it&#39;s 5</pre><p>In programming, = is the assignment sign. On the second line I take the 3 that was already there, add 2 and store it back. The right side uses the previous state and the assignment updates it — that&#39;s a feature of imperative programming.</p><p>In C, you need to assign a value before reading the variable. Just declaring it isn’t enough.</p><h3>Literals and constants</h3><p>A <strong>literal</strong> is a value written directly in the code: 3, 0.10, &quot;notebook&quot;.</p><p>A <strong>constant</strong> is a name tied to a value that doesn’t change during the whole execution. A regular variable, on the other hand, has dynamic binding: its value changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*ze-Y8Kadui48Cd8JKhdzBg.png" /></figure><p>In Python a constant is just a convention: the uppercase name is shouting “don’t change me”, but the language won’t stop you.</p><h3>Data types — choose by purpose, not by appearance</h3><h3>Bits, bytes and primitive types</h3><p>All data is stored in bits. A group of 8 bits makes 1 byte, and that’s the foundation of everything.</p><p><strong>Primitive types</strong> are the basic ones: integer, floating point (decimal), boolean and character — and in some languages, complex numbers. A <strong>string</strong> is a sequence of characters; it may or may not be primitive, and it can be static (fixed size) or dynamic. A <strong>regular expression</strong> is a special pattern that defines exactly which characters will be accepted — ZIP codes, phone numbers, ID numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*D8-HmI4NXaS8yV3IX9_VEg.png" /></figure><h3>Choose by purpose</h3><p>The right question when choosing a type is: what am I going to do with this data?</p><p>Product code 00127 looks like a number. If you use int, the zeros disappear and it becomes 127. ZIP codes and ID numbers also look like numbers, but they only identify — and many of them start with zero.</p><p>The quick test: <strong>do you do math with it?</strong></p><ul><li><strong>Yes</strong> — price, quantity, age → numeric type.</li><li><strong>No</strong> — code, ZIP code, ID number → text.</li></ul><h3>Numeric precision limits — the computer’s error</h3><p>So far we’ve talked about the programmer’s error. Now it’s the computer’s. To it, everything is binary, and some decimals that look simple to us don’t fit exactly in binary. So it stores an approximation.</p><pre>0.1 + 0.2<br># 0.30000000000000004  → a little leftover</pre><p>This matters in systems that demand precision: finance, scientific computing, critical systems.</p><h3>Static vs dynamic typing</h3><p><strong>Static</strong> — the type is declared and checked before running, at compile time. Errors are caught early; the downside is more code to declare things.</p><p><strong>Dynamic</strong> — types are checked at runtime. A variable can hold any type and the interpreter only finds out which when the line runs. Development is faster and the code leaner; the downside is that errors only show up at runtime.</p><p>Important detail: dynamic doesn’t mean no types. Python has types — they’re just on the object, not on the variable.</p><h3>Strong vs weak typing</h3><p>The question here is: does the language accept mixing types?</p><pre>5 + &quot;2&quot;   # Python: TypeError — can&#39;t add a number to text</pre><pre>5 + &quot;2&quot;   // JavaScript: &quot;52&quot; — turns 5 into text and concatenates</pre><p>In other words: Python is strongly and dynamically typed. JavaScript is weakly typed. The strong or weak label doesn’t replace learning each language — some are stricter, others convert and are more flexible.</p><p>Summary:</p><ul><li><strong>Static / dynamic</strong> — when the type is checked: at compile time or at runtime.</li><li><strong>Strong / weak</strong> — how strict the language is about mixing types.</li></ul><h3>Conversion, coercion and information loss — when the type changes</h3><p><strong>Explicit conversion (cast)</strong> is when you clearly ask for the conversion in the code. If you try to convert something impossible, it errors out: int(&quot;three&quot;) breaks, because letters don&#39;t turn into numbers. A classic case in Python: input() always returns text, even if the user types a number.</p><p>In C and Java, the cast is written in parentheses:</p><pre>double height = 1.78;<br>int part = (int) height; // 1</pre><p>The cast doesn’t change the original value: height is still 1.78. Whoever receives the truncated value is part.</p><p><strong>Coercion</strong> is when the language itself converts the data so the expression makes sense, without you asking.</p><pre>int quantity = 3;<br>double price = 19.90;<br>double subtotal = quantity * price;</pre><p>The multiplication involves an int and a double, so C converts 3 into 3.0 to do the math. The variable quantity is still an int — the adaptation only applies to the calculation. The more flexible type wins over the more restricted one.</p><p>Summary: <strong>conversion</strong> is you asking. <strong>Coercion</strong> is the language doing it on its own.</p><h3>Information loss</h3><p>Not every conversion keeps the original value. Turning a decimal into an integer throws away the fractional part.</p><p>A lot of people think converting 1.78 to an integer gives 2, because it’s closer. Wrong: conversion <strong>truncates</strong>, it throws a part away. If you really want to round, you need a specific math function — math in Python, math.h in C, Math in TypeScript.</p><p>It’s a trade-off: in some systems the loss is acceptable, in others it isn’t.</p><h3>Operators and expressions — the same math doesn’t always give the same result</h3><p>An <strong>expression</strong> combines identifiers and operators to produce a result.</p><ul><li><strong>Arithmetic</strong> — addition, subtraction, multiplication, everything from math.</li><li><strong>Relational</strong> — compare values (&lt;, &lt;=, &gt;, &gt;=, ==, !=) and produce true or false.</li><li><strong>Logical</strong> — combine conditions: &amp;&amp;, ||, ! in C, Java and TS; and, or, not in Python.</li><li><strong>Assignment</strong> — =, +=, -=, ++, --.</li></ul><p>Heads up: the same math can give different results depending on the language and the types. In C, quantity == 3 produces 1 (true) or 0 (false). In Python, it produces True or False. If you mix that up without noticing, the compiler won&#39;t complain — and the faulty logic can take a while to be found.</p><h3>Operator overloading</h3><p>The same operator can have more than one function depending on the context. + adds numbers, but in many languages it also joins text. * in C multiplies, but in front of a name (*p) it means a pointer.</p><h3>Assignment vs comparison</h3><ul><li>= <strong>assign</strong> — store this value in this variable.</li><li>== <strong>compare</strong> — are these two values equal?</li></ul><h3>Precedence and associativity</h3><p><strong>Precedence</strong> is the order in which operations are resolved, and it follows math:</p><pre>10 + 2 * 3     // 16 — multiply first, then add<br>(10 + 2) * 3   // 36 — parentheses first: 12, then multiply</pre><p><strong>Associativity</strong> breaks the tie when two operations have the same priority. The language resolves it left to right. In (2 + 5) - 3 and 2 + (5 - 3) the result is 4 either way.</p><p>When comparisons come in with AND and OR, like age &gt;= 18 AND gender == &quot;F&quot;, the order is:</p><ol><li>First the comparisons, each one becomes true or false.</li><li>Then AND combines those two results.</li></ol><p>To remember: <strong>AND</strong> is only true if both are true. <strong>OR</strong> is only false if both are false. <strong>NOT</strong> just flips it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*bl9uSR8wOJIZUuXW8BlcNA.png" /></figure><h3>Short-circuit evaluation</h3><p>With AND and OR, if the first part already decided the result, the language doesn’t even evaluate the second. The practical gain is huge, because it protects against errors:</p><pre>if (quantity != 0 &amp;&amp; total / quantity &lt; 20) {<br>    // ...<br>}</pre><p>If quantity is zero, the first condition is already false and the division never runs — no division by zero. That&#39;s why the order of conditions matters: put the one that protects the second one first.</p><h3>Data structures — grouping what belongs together</h3><p>You can split this into two parts.</p><p><strong>Homogeneous structure</strong> — everything of the same type.</p><ul><li><strong>Array</strong> — a list of elements accessed by an index.</li><li><strong>Matrix</strong> — an array with more than one dimension, like rows and columns, or even more. A three-dimensional matrix, for example, is traversed with nested loops.</li></ul><p><strong>Heterogeneous structure</strong> — mixed types.</p><ul><li><strong>Record</strong> — a grouping of data of different types that describe the same thing, like a product or a person. It can be a class in Java, a struct in C or an interface in TS. Each piece of data inside it is a field, or attribute.</li></ul><p>Here the concept connects straight to databases: an array of records is a table. Each position is a product (a row) and each field is a column. Not every paradigm uses records, but general-purpose languages use them a lot.</p><h3>Scope and lifetime</h3><p><strong>Scope</strong> tells you where a data structure can be accessed from.</p><ul><li><strong>Global</strong> — declared outside the subroutines, it can be seen from any part of the code. That’s exactly why it can be changed by mistake.</li><li><strong>Local</strong> — declared inside the subroutine and only exists there.</li></ul><p><strong>Lifetime</strong> follows scope. A local structure only takes up memory while the subroutine is running. When it ends, the memory is freed and the data is lost — that’s why the subroutine returns a value, so the result isn’t lost.</p><p>In C, even the main code lives inside a function, main. So the variables declared there are local too.</p><h3>Control structures — programs don’t just run top to bottom</h3><p>A program doesn’t just run line after line. It makes decisions and repeats chunks of code — and that’s what control structures do.</p><h3>Decision</h3><p>It evaluates a logical condition, true or false, and runs one block or another. E.g. quantity &gt; 0, quantity &lt;= stock.</p><ul><li><strong>Simple</strong> — runs a block if the condition is true.</li><li><strong>Compound</strong> — has a second path, the else, for when it&#39;s false.</li><li><strong>Nested</strong> — one decision inside another: the inner one is only evaluated if the outer one is true. E.g. only ask whether the person has a driver’s license if they’re of legal age.</li><li><strong>Multiple (</strong><strong>switch / </strong><strong>match)</strong> — picks a block based on a variable&#39;s value: case 1, case 2, default.</li></ul><h3>Repetition</h3><p>Instead of copying the same chunk over and over, you repeat it:</p><ul><li><strong>while</strong> — tests the condition before each round. It may never run at all.</li><li><strong>do...while</strong> — runs the block and only then tests. Guarantees at least one run.</li><li><strong>for</strong> — counted repetition, with a set number of rounds.</li></ul><p>Watch out for infinite loops: if the condition never becomes false, the program never gets out of there.</p><h3>Subroutines, parameters and libraries — divide and conquer</h3><p>Systems got too complex to run everything in a single block. That’s where subroutines, or subprograms, came in: split a big problem into small parts and solve each one separately.</p><p>Each subroutine has an entry point. Whoever called it waits while it runs, and control always goes back to the caller. There are two types:</p><ul><li><strong>Procedure</strong> — runs a task and returns nothing.</li><li><strong>Function</strong> — runs and returns a value.</li></ul><pre>function calculateTotal(price: number, qty: number, discount: number): number {<br>  return price * qty * (1 - discount);<br>}</pre><p>The structure always needs a <strong>header</strong> (name, parameters and return type) and a <strong>body</strong>. The return can happen at more than one point, depending on the conditions inside the function.</p><h3>Parameters</h3><p>Parameters are the data a subroutine receives. They exist so it doesn’t have to access the caller’s variables directly — which would be unsafe.</p><ul><li><strong>Formal parameters</strong> — the ones I declare in the header, with name and type: price, qty, discount.</li><li><strong>Actual parameters</strong> — the values passed in the call: calculateTotal(19.90, 3, 0.10).</li></ul><p>They’re <strong>positional</strong>: the order in the call has to match the order in the header. And there are two ways to pass data:</p><ul><li><strong>By value</strong> — the subroutine gets a copy. The original isn’t affected. It’s the safest way.</li><li><strong>By reference</strong> — the subroutine gets a pointer to the original. Any change there changes the real data in the caller.</li></ul><h3>Prototyping</h3><p>Mostly in C. The compiler reads the code top to bottom: if a function is used before it’s defined, it complains — just like a variable used before it’s declared.</p><p>When subroutines depend on each other (1 calls 2, which calls 3), sometimes it’s impossible to order them so each one appears before it’s called. The solution is <strong>prototyping</strong>: write only the function’s header at the top of the file, letting the compiler know it exists, and leave the full implementation for later, in whatever order you want.</p><h3>Libraries and reuse</h3><p>Subroutines can also live in external files. That keeps code organized and brings ready-made, already-tested features. There are the language’s standard libraries — data input and output, math, graphics — and you can also build your own to reuse code in other projects.</p><p>In C, when you include a library, the whole thing is added to the program. In Java, libraries (the API) are attached to classes, and you can import just what’s needed for that class or problem.</p><h3>Putting it all together in a purchase — one cart, every concept</h3><p>The example that ran through the whole course was a purchase: product, quantity, price, discount. So it’s worth putting everything into one piece of code and seeing where each concept shows up.</p><pre>const DISCOUNT = 0.10;                 // constant: doesn&#39;t change during execution</pre><pre>interface Product {                    // record: heterogeneous structure<br>  code: string;                        // &quot;00127&quot; is text — you don&#39;t do math with it<br>  name: string;<br>  price: number;                       // price goes into the math → numeric<br>  quantity: number;<br>  stock: number;<br>}</pre><pre>function calculateTotal(items: Product[]): number {   // function: header with parameter and return<br>  let total = 0;                                      // local variable, initial state</pre><pre>  for (const item of items) {                         // repetition<br>    if (item.quantity &gt; 0 &amp;&amp; item.quantity &lt;= item.stock) { // decision + short-circuit<br>      total += item.price * item.quantity;            // expression + assignment: changes state<br>    }<br>  }</pre><pre>  return total * (1 - DISCOUNT);                      // precedence: parentheses first<br>}</pre><pre>const cart: Product[] = [                             // array of records = a table<br>  { code: &quot;00127&quot;, name: &quot;Notebook&quot;, price: 19.90, quantity: 3, stock: 10 },<br>];</pre><pre>console.log(calculateTotal(cart));</pre><p>Reading it top to bottom:</p><ul><li><strong>Types by purpose</strong> — code is a string because it only identifies; as a number, 00127 would become 127. price and quantity are numeric because they go into the math.</li><li><strong>Data structure</strong> — Product is a record; cart is an array of records. Each item is a row, each field is a column.</li><li><strong>Subroutine</strong> — calculateTotal is a function: it gets the cart as a parameter, instead of reaching for a global variable, and returns a value.</li><li><strong>Scope and state</strong> — total is local: it starts at zero, changes on every round of the for and stops existing when the function ends. Only the result survives, through the return.</li><li><strong>Short-circuit</strong> — if the quantity isn’t greater than zero, the stock comparison never runs.</li><li><strong>Numeric precision</strong> — 19.90 × 3 with the discount can come out with a little leftover at the end of the decimals. In financial systems, you solve that by working in cents (integers) or rounding only for display.</li><li><strong>Typing</strong> — in TypeScript, if someone passes quantity: &quot;3&quot; as text, the error shows up before running. In plain JavaScript, &quot;3&quot; * 19.90 would slip through by coercion without anyone noticing.</li></ul><p>A simple shopping cart, and pretty much the whole course is right there inside it.</p><h3>Closing</h3><p>At first, a programming language looks like a pile of rules to memorize. But every rule exists for a reason: the type protects the data, scope protects memory, short-circuit protects the math, the parameter protects the caller’s variable.</p><p>For anyone who tests software, understanding this changes how you look at things. The 00127 code that became 127, the 0.1 + 0.2 that didn’t give 0.3, the 1.78 height that became 1 — none of that is the language getting it wrong. It’s the language doing exactly what it was told, and someone didn’t know what they were telling it.</p><p>Before blaming the tool, understand how it works. The bug is almost always in the gap between what you wrote and what you thought you wrote.</p><p>In part 2, I’ll move on to the next classes of the course.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97327b37efc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NoSQL in practice — what I learned in college]]></title>
            <link>https://medium.com/@fa.engeroff1996/nosql-in-practice-what-i-learned-in-college-ff3edaa870db?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff3edaa870db</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 12:12:51 GMT</pubDate>
            <atom:updated>2026-09-26T12:12:51.543Z</atom:updated>
            <content:encoded><![CDATA[<p>Databases moved beyond SQL a long time ago. Here’s what actually matters about each model and why each one exists.</p><p>NoSQL Big Data Database Software Engineering</p><p>Have you ever wondered why Netflix doesn’t use the same database as your company’s HR system? Or why Instagram can still show your feed even when the servers are under heavy load — even if the like count is slightly off?</p><p>The answer comes down to choosing the right database for each problem. And that’s exactly what I learned this semester.</p><h3>The problem that started it all — Big Data</h3><p>Before talking about databases, you need to understand why the traditional model started falling short. The scenario is simple: a hospital with an ICU. At the same time you have massive data volume — petabytes of exams, medical records, images — insane generation speed, a sensor measuring heart rate every single second, and total variety: medical record text, x-ray image, sensor reading, payment record. All at once. That’s Big Data.</p><p>The relational database was built for a more predictable world. When data is too varied, a rigid schema generates a flood of NULL fields and expensive JOINs that don’t scale. A CT scan alone generates hundreds of images at over 500KB each. Multiply that by thousands of patients and you’re already in petabyte territory. The JOIN on that structure starts getting heavy and the database can’t keep up.</p><p>That’s how the conversation about other database models grew — not to replace relational, but to solve what it was never built to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3hTi_y03Xr2REfFZDaNkA.png" /></figure><h3>Centralized vs distributed — the architecture choice</h3><p>Before NoSQL, there was only one path: the mainframe. One giant machine, everything centralized, vertical scaling. When you needed more capacity, you swapped it out for a bigger one. Rigid, expensive, hard to scale. Eventually there was no bigger machine to buy.</p><p>Distributed systems flipped that. Multiple computers connected together that look like a single system to whoever’s using it. Need to grow? Add another node to the cluster. No swapping anything out, no downtime, no losing what you already had. That’s horizontal scaling — and it’s exactly where NoSQL lives. You keep adding cheap commodity machines and the system grows with you.</p><h3>The CAP theorem — the trade-off nobody tells you about</h3><p>In any distributed system you can only guarantee two of three things at the same time: consistency, availability and partition tolerance. You’re always giving something up. The CAP theorem is basically that — there’s no perfect distributed system, there’s the right system for each scenario.</p><p>CP — consistency and partition tolerance. Data is always correct, but it might be slow. If the network goes down, the system stops rather than returning stale data. This is the banking system. You made a withdrawal, the balance has to be updated everywhere before any response goes out. Wrong balance data can cause serious damage — so it’s worth the delay to guarantee the data is right.</p><p>AP — availability and partition tolerance. System is always up, but data might be slightly out of date. When the network comes back, the nodes sync automatically. This is the social network and the news feed. It doesn’t matter if you see 100 likes on one server while another already shows 1000. Nobody is making a critical decision based on that. What matters is the system staying up.</p><p>The choice between CP and AP isn’t a technical one — it’s a business one. You need to understand what hurts more: wrong data or a system that’s down.</p><h3>Relational model — still irreplaceable</h3><p>SQL didn’t die, it just got neighbors. The relational model organizes data into tables with a rigid schema — all rows have the same fields, JOINs connect different tables. The normalization process eliminates redundancy but increases the number of tables, and more tables means more JOINs. JOIN is one of the most expensive operations that exists in a database.</p><p>When data is heterogeneous — each record with different fields — relational databases start generating floods of NULLs. Reserved space for information that will never exist. But when the data is predictable, structured, and needs full consistency, relational is still the best choice. Payments, invoices, financial transactions, inventory control — anything where getting it wrong is costly. Strong consistency, referential integrity, transaction control. No NoSQL replaces that.</p><h3>Key-Value — the simplest and fastest</h3><p>Key-Value operates on a hash table in RAM. One key, one value. No internal structure, no complex queries, no JOINs. You pass the key, you get the value back instantly. It’s the simplest model that exists — and that’s exactly why it’s the fastest.</p><p>The clearest example: the key is the user’s ID, the value is the R$500 in their shopping cart. The system stores that in memory cache. When the page loads, it doesn’t need to run a big database query, doesn’t need to build any SQL — it goes straight to cache and responds immediately. That’s what keeps the e-commerce cart responsive even with millions of simultaneous users. User sessions, cache, temporary data that needs millisecond response times.</p><h3>Document — schema flexibility</h3><p>Document-oriented databases eliminate the rigid fixed schema of SQL. Each document is a self-contained JSON — it holds both the attribute names and the values, so you don’t need an external data dictionary to understand what you’re reading. And each document in the same collection can have a completely different structure from the others.</p><p>The example that stuck: a blood test and an ECG from the same patient have completely different fields. In relational you’d need separate tables and a JOIN to build the full medical record. In MongoDB, each exam is a document with its own fields — no problem, no NULLs, no JOINs. A laptop has memory and processor. A t-shirt has size and color. Both sit in the same collection with no empty fields left over. Medical records, heterogeneous product catalogs, any data where each record looks different.</p><h3>Column family — Bigtable and HBase</h3><p>This was the model that tied my brain in knots at first, but the bakery analogy made it click. Google’s Bigtable is a multidimensional, ordered, sparse and distributed map. Data is addressed across four dimensions: the row key that identifies the row like a primary key, the column family which is a logical grouping of attributes, the column itself which can be created dynamically as needed, and the timestamp that keeps historical versions of the same cell.</p><p>The sparse part is what changes everything: if a field doesn’t exist for a record, it simply doesn’t take up space. No NULLs, no wasted bytes. And since row keys are kept in order, range searches are fast — you know exactly where to look without scanning everything.</p><p>HBase is the open source child of Bigtable, living inside the Hadoop ecosystem. Hadoop is the whole bakery, HBase is just the service counter. HDFS stores the data physically in blocks distributed across servers, with copies in two or three places at the same time. If one shelf falls, there’s another one with the same product. HBase sits on top of HDFS — it doesn’t store anything on its own, it just organizes the access. You come to the counter, ask for Rômulo’s file, HBase knows which shelf in the warehouse to look at.</p><h3>The bakery analogy that made it clear</h3><p>Picture Dona Zélia’s bakery. In the relational database she has a notebook with one column for each product she sells: bread, cake, coxinha, coffee, juice. Customers go in the rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*9WEWU2-CHfZRH9mJGZaHSg.png" /></figure><p>Half the notebook is null. Wasted space. And if she starts selling pasteis tomorrow? She has to redo the whole notebook just to add a new column.</p><p>In Bigtable she uses an index card for each customer. The name in bold at the top is the row key. The card has tabs on the side — one for breads, one for cakes, one for drinks — those are the column families. In each tab she only writes down what the customer actually bought. João never ordered cake? The cake tab on his card simply doesn’t exist. That’s sparse — a field that doesn’t exist takes up no space.</p><p>Each note has a date and time. In January João bought one bread, in March he started buying two. That’s the timestamp — Bigtable keeps the version history of the same cell, so you can know what the data looked like at any point in the past.</p><p>The bakery grew and opened three branches. The index cards were distributed by name range: branch 1 holds A-H, branch 2 I-P, branch 3 Q-Z. When someone asks for Rômulo, she goes straight to branch 3 without checking the others. Those are the cluster nodes, each one holding a range of keys. That’s what makes it possible to find data in petabytes without scanning everything.</p><h3>Time series — when time is the data</h3><p>Time series databases are different from everything you learn before them. The timestamp isn’t just an attribute you store to know when the data was created — it’s the reference point that gives meaning to everything else. Each sensor reading creates a point in time, and you don’t overwrite the previous one, you accumulate. Each minute is a new data point, independent of the last.</p><p>InfluxDB organizes this into measurements — what’s being measured, like heart rate or temperature — fields which are the actual numeric values collected, tags which are key-value pairs to filter quickly, like which hospital or which patient, and the timestamp with millisecond or nanosecond precision. With that you can compress minutes into hours, hours into days, and still answer: what was the patient’s heart rate in the ICU at 2:32pm on Tuesday? And fire an alert automatically when it goes over 90bpm. In an ICU environment, that difference of seconds can be the difference between acting in time or not.</p><h3>Graph — when the relationship matters more than the entity</h3><p>Graph databases solve a specific problem that relational handles poorly: when what you want to query isn’t the data itself, but the connections between data points. In relational that would turn into a massive chain of JOINs, slow and hard to maintain. In a graph database, relationships are stored explicitly as edges — they’re not calculated at query time, they’re already there.</p><p>The clearest case is contact tracing during the pandemic. Who was in the same place as the infected person, at the same time, in the last 14 days? In Neo4j that’s a simple query traversing the visit edges between people and locations. You can find indirect contacts two or three levels deep in seconds. In relational that would be a nightmare of nested JOINs. Recommendation systems work the same way — who bought X also bought Y, who watched A also watched B. The value is in the network of connections, not in the isolated data points.</p><h3>Polyglot persistence — the practical conclusion</h3><p>After understanding all these models, the conclusion is simple: no single database solves everything. A mature system uses several at the same time, each one where it does its best work. Key-value for user sessions and cart — maximum speed. Document for medical records and catalogs — schema flexibility. Time series for ICU sensors and wearables — timestamp as the central axis. Graph for contact tracing and recommendations — explicit relationships. Column family for high-volume images — sparse and distributed. Relational for payments and financial transactions — strong consistency.</p><p>That’s not architectural weakness. That’s engineering maturity. You don’t use a flathead screwdriver on a Phillips screw. The right tool for each job.</p><p>Before choosing the technology, understand the problem. What’s the nature of the data? How fast does it come in? How much does it vary between records? How will it be queried? The technology is the consequence. Understanding the problem is the cause.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff3edaa870db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NoSQL na prática — o que aprendi na faculdade]]></title>
            <link>https://medium.com/@fa.engeroff1996/nosql-na-pr%C3%A1tica-o-que-aprendi-na-faculdade-033e8ccc449d?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/033e8ccc449d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 12:11:48 GMT</pubDate>
            <atom:updated>2026-09-26T12:11:48.401Z</atom:updated>
            <content:encoded><![CDATA[<p>Bancos de dados foram além do SQL há muito tempo. Aqui está o que realmente importa entender sobre cada modelo e por que cada um existe.</p><p>NoSQL Big Data Banco de dados Engenharia de software</p><p>Você já se perguntou por que o Netflix não usa o mesmo banco de dados que o sistema de RH da sua empresa? Ou por que o Instagram consegue mostrar o feed mesmo quando os servidores estão sobrecarregados — mesmo que os números de curtida estejam levemente errados?</p><p>A resposta está na escolha do banco certo pra cada problema. E é isso que aprendi esse semestre.</p><h3>O problema que gerou tudo isso — Big Data</h3><p>Antes de falar de banco, precisa entender por que o modelo tradicional começou a não dar conta. O cenário é simples: hospital com UTI. Ao mesmo tempo você tem volume de dados gigante — petabytes de exames, prontuários, imagens — velocidade absurda de geração, sensor medindo batimento cardíaco a cada segundo, e variedade total: texto de prontuário, imagem de raio-x, número de sensor, registro de pagamento. Tudo junto, ao mesmo tempo. Isso é Big Data.</p><p>O banco relacional foi feito pra um mundo mais previsível. Quando o dado é variado demais, o esquema rígido gera uma maré de campos NULL e JOINs caros que não escalam. Uma tomografia gera centenas de imagens de mais de 500KB cada. Multiplica por milhares de pacientes e você chega em petabytes. O JOIN nessa estrutura começa a pesar e o banco não consegue mais crescer rápido o suficiente.</p><p>Foi assim que a discussão sobre outros modelos de banco de dados foi crescendo — não pra substituir o relacional, mas pra resolver o que ele não foi feito pra resolver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3hTi_y03Xr2REfFZDaNkA.png" /></figure><h3>Centralizado vs distribuído — a escolha de arquitetura</h3><p>Antes do NoSQL existia só um caminho: o mainframe. Uma máquina gigante, tudo centralizado, esquema vertical. Quando precisava crescer, você trocava a máquina por uma maior. Rígido, caro, difícil de escalar. Chegou uma hora que não tinha mais máquina maior pra comprar.</p><p>Sistemas distribuídos inverteram isso. Vários computadores conectados que, pra quem usa, parecem um só sistema. Quer crescer? Adiciona mais um nó no cluster. Sem trocar nada, sem parar nada, sem perder o que já tinha. Isso é escalabilidade horizontal — e é exatamente onde o NoSQL vive. Você vai adicionando máquinas baratas e comuns, e o sistema cresce junto.</p><h3>O teorema CAP — a escolha que ninguém te conta</h3><p>Em qualquer sistema distribuído você só consegue garantir dois dos três ao mesmo tempo: consistência, disponibilidade e tolerância a partições. Sempre vai abrir mão de um. O teorema CAP é basicamente isso — não existe sistema distribuído perfeito, existe o sistema certo pra cada cenário.</p><p>CP — consistência e tolerância a partição. Dado sempre correto, pode atrasar. Se a rede cair, o sistema para em vez de retornar dado desatualizado. É o caso do sistema bancário. Você fez um saque, o saldo tem que estar atualizado em todo lugar antes de qualquer resposta chegar. Um dado errado de saldo pode causar problema sério — então vale atrasar a resposta pra garantir que o dado está certo.</p><p>AP — disponibilidade e tolerância a partição. Sistema sempre no ar, pode ter dado levemente desatualizado. Quando a rede voltar, os nós sincronizam sozinhos. É o caso da rede social e do feed de notícias. Pouco importa se você vê 100 curtidas num servidor enquanto outro já mostra 1000. Ninguém vai tomar uma decisão crítica baseada nisso. O que importa é o sistema estar no ar.</p><p>A escolha entre CP e AP não é técnica — é de negócio. Você precisa entender o que dói mais: dado errado ou sistema fora do ar.</p><h3>Modelo relacional — ainda indispensável</h3><p>O SQL não morreu, ganhou vizinhos. O modelo relacional organiza dados em tabelas com esquema rígido — todas as linhas têm os mesmos campos, JOIN conecta tabelas diferentes. O processo de normalização elimina redundância mas aumenta o número de tabelas, e mais tabelas significa mais JOINs. JOIN é uma das operações mais caras que existe num banco.</p><p>Quando os dados são heterogêneos — cada registro com campos diferentes — o relacional começa a gerar uma maré de NULL. Espaço reservado pra informação que nunca vai existir. Mas quando o dado é previsível, estruturado e precisa de consistência total, o relacional ainda é o melhor. Pagamento, fatura, transação financeira, controle de estoque — qualquer coisa onde errar custa caro. Consistência forte, integridade referencial, controle de transações. Nenhum NoSQL substitui isso.</p><h3>Chave-Valor — o mais simples e o mais rápido</h3><p>Chave-Valor opera em tabela de hash na memória RAM. Uma chave, um valor. Sem estrutura interna, sem consulta complexa, sem JOIN. Você passa a chave, recebe o valor na hora. É o modelo mais simples que existe — e é exatamente por isso que é o mais rápido.</p><p>O exemplo mais claro: chave é o ID do Rômulo, valor são os R$500 no carrinho de compras. O sistema guarda isso no cache em memória. Quando a página carrega, não precisa fazer uma busca grande no banco, não precisa montar nenhuma query — vai direto no cache e retorna na hora. Isso é o que mantém o carrinho de compras do e-commerce responsivo mesmo com milhões de usuários ao mesmo tempo. Sessão de usuário, cache, dados temporários que precisam de resposta em milissegundos.</p><h3>Documento — flexibilidade de esquema</h3><p>Banco orientado a documentos elimina a rigidez do esquema fixo do SQL. Cada documento é um JSON autocontido — tem tanto o nome dos atributos quanto os valores, então você não precisa de um dicionário de dados externo pra entender o que está lendo. E cada documento pode ter uma estrutura completamente diferente dos outros na mesma coleção.</p><p>O exemplo que ficou na cabeça: exame de sangue e exame cardiológico do mesmo paciente têm campos completamente diferentes. No relacional você precisaria de tabelas separadas e um JOIN pra montar o prontuário completo. No MongoDB, cada exame é um documento com seus próprios campos — sem problema, sem NULL, sem JOIN. Notebook tem memória e processador. Camiseta tem tamanho e cor. Os dois ficam na mesma coleção sem nenhum campo vazio sobrando. Prontuário eletrônico, catálogo de produtos heterogêneos, qualquer dado onde cada registro tem uma cara diferente.</p><h3>Família de colunas — Bigtable e HBase</h3><p>Esse foi o modelo que mais deu nó na cabeça no começo, mas a analogia da padaria deixou claro. O Bigtable do Google é um mapa multidimensional, ordenado, esparso e distribuído. Os dados são endereçados por quatro dimensões: row key que identifica a linha como uma chave primária, column family que é um agrupador lógico de atributos, a coluna em si que pode ser criada dinamicamente conforme a necessidade, e o timestamp que mantém versões históricas da mesma célula.</p><p>O esparso é o que muda tudo: se um campo não existe pra um registro, ele simplesmente não ocupa espaço. Nenhum NULL, nenhum byte desperdiçado. E como as row keys ficam ordenadas, buscas por intervalo são rápidas — você sabe exatamente onde procurar sem varrer tudo.</p><p>O HBase é o filho open source do Bigtable, vivendo dentro do ecossistema Hadoop. Hadoop é a padaria inteira, HBase é só o balcão de atendimento. O HDFS guarda os dados fisicamente em blocos distribuídos entre servidores, com cópias em dois ou três lugares ao mesmo tempo. Se uma prateleira cai, tem outra com o mesmo produto. HBase fica em cima do HDFS — não guarda nada sozinho, só organiza o acesso. Você chega no balcão, pede a ficha do Rômulo, o HBase sabe em qual prateleira do depósito procurar.</p><h3>A analogia da padaria que ficou</h3><p>Imagina a padaria da dona Zélia. No banco relacional ela tem um caderno com uma coluna pra cada produto: pão, bolo, coxinha, café, suco. Os clientes ficam nas linhas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*z2zpBj7NGJ902udwGV1beQ.png" /></figure><p>Metade do caderno é null. Espaço desperdiçado. E se ela começar a vender pastel amanhã? Precisa refazer o caderno inteiro pra adicionar a coluna nova.</p><p>No Bigtable ela usa uma fichinha pra cada cliente. O nome em negrito no topo é a row key. A fichinha tem abas nas laterais — uma pra pães, outra pra bolos, outra pra bebidas — isso são as famílias de colunas. Em cada aba ela anota só o que o cliente de fato comprou. João nunca pediu bolo? A aba de bolo na fichinha dele simplesmente não existe. Isso é esparso — campo que não existe não ocupa espaço.</p><p>Cada anotação tem data e hora. Em janeiro o João comprava um pão, em março passou a comprar dois. Isso é o timestamp — o Bigtable mantém o histórico de versões da mesma célula, você consegue saber como estava o dado em qualquer momento no passado.</p><p>A padaria cresceu e abriu três filiais. As fichinhas foram distribuídas por intervalo de nome: filial 1 guarda A-H, filial 2 I-P, filial 3 Q-Z. Quando alguém pergunta pelo Rômulo, ela vai direto na filial 3 sem procurar nas outras. São os nós do cluster, cada um guardando um intervalo de chaves. Isso é o que permite encontrar dados em petabytes sem varrer tudo.</p><h3>Série temporal — quando o tempo é o dado</h3><p>Banco de série temporal é diferente de tudo que a gente aprende antes. O timestamp não é um atributo qualquer que você guarda pra saber quando o dado foi criado — ele é o dado de referência que dá sentido a tudo. Cada leitura de sensor gera um ponto no tempo, e você não sobrescreve o anterior, você acumula. Cada minuto é um dado novo, independente.</p><p>O InfluxDB organiza isso em measurement — o que está sendo medido, como batimentos cardíacos ou temperatura — fields que são os valores numéricos reais coletados, tags que são pares de chave e valor pra filtrar rápido, como qual hospital ou qual paciente, e o timestamp com precisão de milissegundos ou nanosegundos. Com isso você consegue compactar os minutos em horas, as horas em dias, e ainda responder: qual era a frequência cardíaca do paciente na UTI às 14h32 de terça-feira? E disparar alerta automaticamente quando passa de 90bpm. Em ambiente de UTI, essa diferença de segundos pode ser a diferença entre agir a tempo ou não.</p><h3>Grafo — quando a relação importa mais que a entidade</h3><p>Banco de grafo resolve um problema específico que o relacional não resolve bem: quando o que você quer consultar não é o dado em si, mas as conexões entre os dados. No modelo relacional isso viraria uma cadeia enorme de JOINs, lenta e difícil de manter. No grafo, os relacionamentos são armazenados explicitamente como arestas — não são calculados em tempo de execução, já estão lá.</p><p>O caso mais claro é rastreamento de contatos durante a pandemia. Quem esteve no mesmo local que a pessoa infectada, ao mesmo tempo, nos últimos 14 dias? No Neo4j isso é uma query simples percorrendo as arestas de visita entre pessoas e locais. Você consegue encontrar contatos indiretos em dois ou três níveis de profundidade em segundos. No relacional isso seria um pesadelo de JOINs encadeados. Sistema de recomendação também entra aqui — quem comprou X também comprou Y, quem assistiu A também assistiu B. O valor está na rede de conexões, não nos dados isolados.</p><h3>Persistência poliglota — a conclusão prática</h3><p>Depois de entender todos esses modelos, a conclusão é simples: nenhum banco resolve tudo. Um sistema maduro usa vários ao mesmo tempo, cada um onde é melhor. Chave-valor pra sessão de usuário e carrinho — velocidade máxima. Documento pra prontuário e catálogo — flexibilidade de esquema. Série temporal pra sensor de UTI e wearable — timestamp como eixo central. Grafo pra rastreamento e recomendação — relações explícitas. Família de colunas pra imagens em volume — esparso e distribuído. Relacional pra pagamento e transação financeira — consistência forte.</p><p>Isso não é fraqueza de arquitetura. É maturidade de engenharia. Você não usa chave de fenda pra apertar parafuso de estrela. A ferramenta certa pra cada trabalho.</p><p>Antes de escolher a tecnologia, entenda o problema. Qual é a natureza do dado? Com que velocidade chega? Quanto varia entre registros? Como vai ser consultado? A tecnologia é consequência. O entendimento do problema é a causa.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=033e8ccc449d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Testing in Practice — from concept to tooling]]></title>
            <link>https://medium.com/@fa.engeroff1996/software-testing-in-practice-from-concept-to-tooling-adea39ad8383?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/adea39ad8383</guid>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 10:14:36 GMT</pubDate>
            <atom:updated>2026-09-14T10:44:50.829Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s past 11pm, the system is down, the client opening tickets and the whole team in the group chat trying to figure out what went to production without being properly tested. Anyone who works in tech knows this scene happens more than it should.</p><p>Here I bring together the fundamentals of QA work and the tools I use day to day. A complete view for anyone who wants to understand the testing ecosystem end to end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_GylK2Qcf1GuFvi1illhQ.jpeg" /></figure><p><strong>Verification and validation — the distinction that matters</strong></p><p>Two concepts that come up together but mean different things.</p><p>Verification asks “are we building the product correctly?” — does the code implement what the spec says, were the requirements met, is the logic right? It’s the technical lens on what was built, before it reaches the user.</p><p>Validation asks “are we building the right product?” — does the system actually solve the problem of whoever uses it. In practice it’s where we check if the flow makes sense, if the improvement fits into the rest of the system without breaking what already existed, if nothing is out of place on the screen, if colors and elements are correct, if what was changed actually delivers what it should. It’s the user’s perspective, not the builder’s.</p><p><strong>Test types</strong></p><p><strong>Unit</strong><br> Tests functions and methods in isolation, it’s the smallest scope possible. TDD starts here — before writing the function, you describe the scenario and the expected result. What does this function need to receive? What should it return? What happens if the value comes in null or in the wrong format? Only after that the code gets written. The idea is that the test drives the implementation, not the other way around.</p><p><strong>Integration</strong><br> Each module works in isolation, but what about when they connect? This is where we validate flows that cross boundaries — a registration made on one screen needs to be saved, reflected and accepted by another part of the system. A CRUD that works perfectly on its own can break when another feature depends on it. Integration problems rarely show up in unit tests, they show up when the pieces come together and need to understand each other.</p><p><strong>System</strong><br> End-to-end test, the full flow as the user experiences it. Registration, enrollment, report generation, content access, certificate signing — all chained together, from start to finish. The goal is to make sure the system works as a whole, not just that each part works separately. If any step along the way breaks, the system test identifies exactly where.</p><p><strong>Acceptance</strong><br> Who validates here can be the client, the end user, support or even whoever is going to push to production — depends on each company’s process. It’s the perspective of whoever is going to use or deliver it, not whoever built it. The central question is simple: does the system do what was agreed? Is it ready to move forward?</p><p><strong>Regression</strong><br> Runs every time the code changes — a bug fix, a new feature, a dependency update. The goal is to make sure what already worked keeps working after the change. It’s the test type that benefits most from automation, because in practice it needs to run on every deploy, every pipeline, every time something gets merged. Doing this manually doesn’t scale.</p><p><strong>Exploratory</strong><br> It’s the test that comes after the basics described in the spec are already covered. From there it’s about thinking outside the normal flow — what could a user do that nobody predicted? What happens if they fill a field in an unusual way, navigate in the wrong order, try two actions at the same time, leave something blank where they shouldn’t? This is where creativity comes in, because there’s no script, just reasoning. The goal is to force behaviors the system wasn’t expecting and see how it reacts. If it freezes, returns wrong data, stays in an inconsistent state — exploratory is what catches that.</p><p><strong>Load and stress</strong><br> Load testing validates whether the system handles heavy expected usage — multiple users registering at the same time, sending large reports, uploading heavy images, switching between pages quickly. Stress testing pushes beyond that to see where it breaks and, more importantly, how it breaks. Does it freeze? Return a friendly error? Corrupt data? The difference between “it got slow” and “it went down” lives exactly in this validation.</p><p><strong>Black-box vs white-box</strong></p><p>Black-box tests by behavior — you interact with the system without knowing what happens inside, data goes in, the expected result has to come out. It’s the user’s view, not the builder’s. White-box goes into the code, validates the internal logic, the path the implementation takes to reach the result — usually done by a dev or technical QA who has access to the source.</p><p>Neither replaces the other. Black-box answers “does it do what it should?” and white-box answers “does it do it the right way?” The ideal is to combine both, because a system can deliver the correct result through a completely wrong path — and that becomes a problem down the line.</p><p><strong>Tools</strong></p><p><strong>Selenium</strong><br> The established standard for web test automation. Controls the real browser — Chrome, Firefox, Safari — simulating clicks, forms and navigation. More controlled, tests run sequentially and setup requires WebDriver configuration for each browser. Mature, with a huge community and a lot of content available. The downside is that control comes at a cost: it’s more verbose, slower and every wait needs to be explicit in the code — if the element takes longer to load than expected, the test breaks.</p><p><strong>Playwright</strong><br> Built by Microsoft, born solving Selenium’s pain points. Simple setup, native auto-wait — it waits for the element to be available before interacting, without needing to declare that in the code. The big shift is parallel execution: unlike Selenium, Playwright can run multiple tests at the same time, across different browsers, asynchronously. That significantly reduces feedback time. It also has a trace viewer that records a visual timeline of the test — when it breaks, you open it and see exactly what happened, frame by frame. The codegen generates the test code as you navigate the site, which speeds up the initial writing a lot.</p><p><strong>Grafana k6</strong><br> Load testing as code. JavaScript scripts, native CI/CD integration and real-time visualization via Grafana. Unlike JMeter, which has a heavy interface and manual configuration, k6 lives in the repository alongside the source code — anyone on the team can run, version and evolve it. Ideal for validating REST APIs, microservices and SLA scenarios.</p><p><strong>JUnit</strong><br> Standard framework for unit testing in Java. Simple, direct CI/CD pipeline integration, support for parameterized tests and custom assertions. It’s what runs in the pipeline on every push and makes sure the unit logic didn’t break.</p><p><strong>Postman</strong><br> API testing straight to the point. You set up the request, define what you expect back and validate. You can organize into collections and run via Newman in the pipeline. Useful for validating API contracts before pushing anything.</p><p><strong>SonarQube</strong><br> Not a testing tool — it’s static code analysis. Identifies vulnerabilities, code smells and technical debt. Plugs into the pipeline and blocks merges that don’t meet the quality gates defined by the team. It’s the layer that makes sure what goes to production has a minimum quality level before any test even runs.</p><p><strong>Selenium vs Playwright — the difference that matters in practice</strong></p><p>Selenium works in a more controlled and sequential way — one test at a time, each following its flow through the defined path. It works well, it’s reliable, but it’s slow when the test suite grows. Playwright flips that: asynchronous by nature, it can run multiple tests in parallel, across different browsers, at the same time. What would take minutes in Selenium can take seconds in Playwright. It’s not that one is absolutely better than the other — in legacy projects with Java teams, Selenium still makes sense. In new projects where feedback speed matters, Playwright has the edge.</p><p><strong>Test lifecycle</strong></p><p>Testing doesn’t start when you open the tool. It starts much earlier.</p><ol><li><strong>Planning</strong> — what will be tested, who will test, what’s the deadline and what resources are available.</li><li><strong>Design</strong> — where test cases are created: what’s the precondition, what goes in, what’s expected to come out.</li><li><strong>Execution</strong> — run the tests, collect what happened, log any deviation from expected.</li><li><strong>Report</strong> — defect description, severity, priority and the steps to reproduce.</li><li><strong>Closure</strong> — evaluate whether what was tested actually covered what needed to be covered and log what was learned for the next cycle.</li></ol><p>One thing that makes a real difference: a bug without reproduction steps is a bug nobody will be able to fix. Always describe:</p><ul><li>What was done</li><li>What was expected</li><li>What happened</li><li>With screenshot, with evidence, with context</li></ul><p><strong>Metrics</strong></p><p>You can’t improve what you don’t track:</p><ul><li><strong>Code coverage</strong> — how much of the system is being exercised by the tests. Reasonable target: 80–85%.</li><li><strong>Defect rate per module</strong> — where the system is most fragile and where to focus effort.</li><li><strong>Test efficiency</strong> — are the tests finding problems or sliding past them?</li><li><strong>Mean time to fix</strong> — from bug found to bug resolved. A direct indicator of team agility.</li></ul><p><strong>Closing</strong></p><p>Testing isn’t wasted time. Would you buy a car that wasn’t tested? Would you eat food whose packaging didn’t go through quality control? Software is no different.</p><p>Testing is part of the software engineering pipeline. It’s where improvement suggestions reach the analyst, bugs become tickets for the dev, and the flow gets refined until it’s clean enough for the end user to feel comfortable with the system. In the end, that’s what matters: making sure what was built actually solves the problem of whoever is going to use it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adea39ad8383" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testes de Software na Prática — do conceito à ferramenta]]></title>
            <link>https://medium.com/@fa.engeroff1996/testes-de-software-na-pr%C3%A1tica-do-conceito-%C3%A0-ferramenta-e48e57f458e2?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e48e57f458e2</guid>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 10:12:43 GMT</pubDate>
            <atom:updated>2026-09-14T10:46:53.912Z</atom:updated>
            <content:encoded><![CDATA[<p>Já passou das 23h, o sistema está fora do ar, o cliente abrindo chamado e o time todo no grupo tentando entender o que foi pra produção sem ser testado direito. Quem trabalha com tecnologia sabe que essa cena acontece mais do que deveria.</p><p>Aqui eu reúno os fundamentos do trabalho de QA e as ferramentas de uso no dia a dia. Uma visão completa pra quem quer entender testes de ponta a ponta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_GylK2Qcf1GuFvi1illhQ.jpeg" /></figure><h3>Verificação e validação — a distinção que importa</h3><p>Antes de falar de tipos de teste e ferramentas, vale alinhar dois conceitos que aparecem juntos mas têm escopos diferentes:</p><p><strong>Verificação</strong> é a pergunta “estamos construindo o produto corretamente?” — o código implementa o que a especificação pede, os requisitos foram atendidos, a lógica está certa. É o olhar técnico sobre o que foi construído, antes de chegar no usuário.</p><p><strong>Validação</strong> é a pergunta “estamos construindo o produto certo?” — o sistema resolve o problema real de quem usa. Na prática é onde a gente verifica se o fluxo faz sentido, se a melhoria se encaixa no resto do sistema sem quebrar o que já existia, se nada ficou fora do lugar na tela, se as cores e os elementos estão corretos, se o que foi alterado realmente entrega o que deveria. É o olhar de quem usa, não de quem construiu.</p><h3>Tipos de teste</h3><h3>Unitário</h3><p>Testa funções e métodos de forma isolada, é o menor escopo possível. A prática de TDD nasce aqui — antes de escrever a função, você descreve o cenário e o resultado esperado. O que essa função precisa receber? O que ela deve retornar? O que acontece se o valor vier nulo ou fora do formato esperado? Só depois disso que o código é escrito. A ideia é que o teste guie a implementação, não o contrário.</p><h3>Integração</h3><p>Cada módulo funciona isolado, mas e quando se conectam? É aqui que a gente valida os fluxos que cruzam fronteiras — um cadastro feito em uma tela precisa ser salvo, refletido e aceito por outra parte do sistema. Um CRUD que funciona perfeitamente sozinho pode quebrar quando outra funcionalidade depende dele. Problemas de integração raramente aparecem no unitário, eles aparecem quando as peças se juntam e precisam se entender.</p><h3>Sistema</h3><p>Teste end-to-end, o fluxo completo como o usuário vivencia. Cadastro, inscrição, geração de laudo, acesso ao conteúdo, emissão de certificado de assinatura — tudo encadeado, do começo ao fim. A ideia é garantir que o sistema funciona como um todo, não só que cada parte funciona separada. Se qualquer etapa desse caminho quebrar, o teste de sistema identifica exatamente onde.</p><h3>Aceitação</h3><p>Quem valida aqui pode ser o cliente, o usuário final, o suporte ou até quem vai subir em produção — depende do processo de cada empresa. É o olhar de quem vai usar ou entregar, não de quem construiu. A pergunta central é simples: o sistema faz o que foi combinado? Está pronto pra ir pra frente?</p><h3>Regressão</h3><p>Roda sempre que o código muda — uma correção de bug, uma nova funcionalidade, uma atualização de dependência. O objetivo é garantir que o que já funcionava continua funcionando depois da alteração. É o tipo de teste que mais se beneficia de automação, porque na prática ele precisa rodar em todo deploy, toda pipeline, toda vez que algo é mergeado. Fazer isso na mão não escala.</p><h3>Exploratório</h3><p>É o teste que vem depois dos básicos descritos na EF já estarem cobertos. A partir daí é pensar fora do fluxo normal — o que um usuário poderia fazer que ninguém previu? O que acontece se ele preencher um campo de um jeito inusitado, navegar na ordem errada, tentar fazer duas ações ao mesmo tempo, deixar algo em branco onde não deveria? É onde entra criatividade mesmo, porque não tem roteiro, tem raciocínio. O objetivo é forçar comportamentos que o sistema não estava esperando e ver como ele reage. Se travar, se retornar dado errado, se permanecer num estado inconsistente — o exploratório é quem pega isso.</p><h3>Carga e estresse</h3><p>Teste de carga valida se o sistema aguenta o uso intenso dentro do esperado — vários usuários cadastrando ao mesmo tempo, enviando laudos grandes, fazendo upload de imagens pesadas, alternando entre páginas rapidamente. Teste de estresse empurra além disso pra ver onde quebra e, mais importante, como quebra. Trava? Retorna erro amigável? Corrompe dado? A diferença entre “ficou lento” e “caiu” mora exatamente nessa validação.</p><h3>Caixa-preta vs caixa-branca</h3><p>Caixa-preta testa pelo comportamento — você interage com o sistema sem saber o que acontece por dentro, entra um dado, tem que sair o resultado esperado. É o olhar de quem usa, não de quem construiu. Caixa-branca já entra no código, valida a lógica interna, o caminho que a implementação percorre pra chegar no resultado — geralmente feito por dev ou QA técnico que tem acesso ao fonte.</p><p>Nenhuma substitui a outra. Caixa-preta responde “faz o que deveria?” e caixa-branca responde “faz do jeito certo?” O ideal é combinar as duas, porque um sistema pode entregar o resultado correto por um caminho completamente errado — e isso vira problema mais na frente.</p><h3>Ferramentas</h3><p>A parte que conecta conceito com o mercado real.</p><p><strong>Selenium</strong><br> O padrão estabelecido pra automação de testes web. Controla o navegador real — Chrome, Firefox, Safari — simulando cliques, formulários e navegação. É mais controlado, os testes rodam de forma sequencial e o setup exige configuração de WebDriver pra cada browser. Maduro, com comunidade enorme e muito conteúdo disponível. A desvantagem é que esse controle tem um custo: é mais verboso, mais lento e qualquer wait precisa ser explícito no código — se o elemento demorar pra carregar e você não previu, o teste quebra.</p><p><strong>Playwright</strong><br> Desenvolvido pela Microsoft, nasceu resolvendo as dores do Selenium. Setup simples, auto-wait nativo — ele espera o elemento estar disponível antes de interagir, sem precisar declarar isso no código. A grande virada é a execução paralela: diferente do Selenium, o Playwright consegue rodar vários testes ao mesmo tempo, em browsers diferentes, de forma assíncrona. Isso reduz bastante o tempo de feedback. Tem também o trace viewer, que grava uma timeline visual do teste — quando quebra, você abre e vê exatamente o que aconteceu, frame a frame. O codegen ainda gera o código enquanto você navega pelo site, o que acelera muito a escrita inicial.</p><p><strong>Grafana k6</strong><br> Teste de carga como código. Scripts em JavaScript, integração nativa com CI/CD e visualização em tempo real via Grafana. Diferente do JMeter, que tem uma interface pesada e configuração manual, o k6 vive no repositório junto com o código — qualquer pessoa do time consegue rodar, versionar e evoluir. Ideal pra validar APIs REST, microsserviços e cenários de SLA.</p><p><strong>JUnit</strong><br> Framework padrão pra testes unitários em Java. Simples, integração direta com pipelines de CI/CD, suporte a testes parametrizados e assertivas customizadas. É o que roda no pipeline a cada push e garante que a lógica unitária não quebrou.</p><p><strong>Postman</strong><br> Teste de API direto ao ponto. Você monta a requisição, define o que espera de retorno e valida. Dá pra organizar em coleções e rodar via Newman no pipeline. Útil pra validar contratos de API antes de subir qualquer coisa.</p><p><strong>SonarQube</strong><br> ão é uma ferramenta de teste — é análise estática de código. Identifica vulnerabilidades, code smells e dívida técnica. Entra no pipeline e bloqueia merge de código que não atinge os quality gates definidos pelo time. É a camada que garante que o que vai pra produção tem um nível mínimo de qualidade antes mesmo de rodar qualquer teste.</p><p><strong>Selenium vs Playwright — a diferença que importa na prática</strong></p><p>O Selenium trabalha de forma mais controlada e sequencial — um teste por vez, cada um seguindo seu fluxo pelo link definido. Funciona bem, é confiável, mas é lento quando a suite cresce. O Playwright inverte isso: assíncrono por natureza, consegue rodar múltiplos testes em paralelo, em browsers diferentes, ao mesmo tempo. O que levaria minutos no Selenium pode levar segundos no Playwright. Não é que um é melhor que o outro em absoluto — em projetos legados com times Java, o Selenium ainda faz sentido. Em projetos novos onde velocidade de feedback importa, o Playwright leva vantagem.</p><h3><strong>Ciclo de vida do teste</strong></h3><p>Teste não começa quando você abre a ferramenta. Começa muito antes.</p><ol><li><strong>Planejamento</strong> — o que vai ser testado, quem vai testar, qual o prazo e quais os recursos disponíveis.</li><li><strong>Design</strong> — onde os casos de teste são criados: qual a pré-condição, o que entra, o que se espera que saia.</li><li><strong>Execução</strong> — rodar os testes, coletar o que aconteceu, registrar qualquer desvio do esperado.</li><li><strong>Relatório</strong> — descrição do defeito, severidade, prioridade e os passos pra reproduzir.</li><li><strong>Encerramento</strong> — avaliar se o que foi testado realmente cobriu o que precisava e registrar o que aprendeu pro próximo ciclo.</li></ol><p>Um ponto que faz diferença na prática: bug sem passos de reprodução é bug que ninguém vai conseguir corrigir. Sempre descreva:</p><ul><li>O que foi feito</li><li>O que era esperado</li><li>O que aconteceu</li><li>Com print, com evidência, com contexto</li></ul><h3><strong>Métricas</strong></h3><p>Não dá pra melhorar o que não se acompanha:</p><ul><li><strong>Cobertura de código</strong> — quanto do sistema está sendo exercitado pelos testes. Meta razoável: 80–85%.</li><li><strong>Taxa de defeitos por módulo</strong> — onde o sistema está mais frágil e onde concentrar esforço.</li><li><strong>Eficiência dos testes</strong> — os testes estão encontrando problemas ou passando por cima deles?</li><li><strong>Tempo médio de correção</strong> — do bug encontrado ao bug resolvido. Indicador direto de agilidade da equipe.</li></ul><h3>Fechando</h3><p>Teste não é tempo perdido. Você compraria um carro que não foi testado? Consumiria um alimento cuja embalagem não passou por controle de qualidade? Software não é diferente.</p><p>O teste é parte da esteira da engenharia de software. É onde sugestões de melhoria chegam ao analista, bugs viram chamados pro dev, e o fluxo vai sendo lapidado até estar limpo o suficiente pro usuário final se sentir confortável com o sistema. No fim, é isso que importa: garantir que o que foi construído resolve o problema de quem vai usar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e48e57f458e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ What is HCI, Usability, and UX — and why it matters more than you think]]></title>
            <link>https://medium.com/@fa.engeroff1996/what-is-hci-usability-and-ux-and-why-it-matters-more-than-you-think-8199aa970b1b?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8199aa970b1b</guid>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <category><![CDATA[usability]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 17:47:58 GMT</pubDate>
            <atom:updated>2026-04-25T17:47:58.407Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is HCI, Usability, and UX — and why it matters more than you think</h3><p>Have you ever opened an app, tried to do something simple (like canceling a subscription), and felt like throwing your phone across the room? Yeah. That’s bad HCI in action.</p><p>And that’s exactly what this post is about. Let’s break it down.</p><h3>First: what is HCI?</h3><p><strong>HCI = Human-Computer Interaction.</strong></p><p>It’s not just “making the system work.” It’s making the system work <strong>for the person who’s using it</strong>. There’s a difference, and that difference is worth millions.</p><p>Think about it like this: the computer is one thing, you are another. Between the two, there needs to be a bridge — that bridge is the <strong>interface</strong>. And the way you cross that bridge is the <strong>interaction</strong>.</p><blockquote><em>Interface = the contact point (screen, button, voice, gesture). Interaction = what happens between you and the system (clicking, dragging, talking, tapping).</em></blockquote><p>A famous Steve Jobs quote sums it up: <em>“Design is not just what it looks like. Design is how it works.”</em> It can be as beautiful as a piece of art — if it’s hard to use, it loses its purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsgFnjKubP2SB3O1YkCcjA.png" /></figure><h3>Ergonomics: why your neck hurts after 3 hours on the laptop</h3><p>Ergonomics comes from Greek: <em>ergon</em> (work) + <em>nomos</em> (rules). In other words, the rules to adapt the work to the human — not the other way around.</p><p>There are three types you need to know:</p><p><strong>Physical ergonomics</strong> — posture, screen position, chair height. It’s what stops you from becoming hunched over by age 30.</p><p><strong>Cognitive ergonomics</strong> — how your brain processes information. Here’s the catch: your memory has a limit. If a system forces you to memorize 15 steps, it’s overloading you.</p><p><strong>Organizational ergonomics</strong> — how work is structured in teams, processes, and communication.</p><p>There’s also <strong>visual ergonomics</strong>: using readable fonts (Arial, Verdana, Tahoma), avoiding text over messy images, keeping decent contrast. Basic stuff that a lot of people ignore.</p><h3>The types of memory that matter for design</h3><p>Your brain has three “drawers”:</p><ul><li><strong>Sensory</strong> — lasts milliseconds. The flash you see and it’s gone.</li><li><strong>Short-term</strong> — lasts seconds. Like that verification code you read and type quickly.</li><li><strong>Long-term</strong> — lasts years. Like the floppy disk icon, which still means “save” even though no one uses floppy disks anymore.</li></ul><p><strong>Why does this matter?</strong> Because a good designer doesn’t push the user’s memory. Instead of forcing the person to memorize where everything is, the designer <strong>shows it</strong>. Recognition always wins over memorization.</p><h3>Know your user (or fail badly)</h3><p>You can’t design for “everyone.” Everyone is no one.</p><p>Kids want color, sound, images. Working adults want speed and clarity. Older users want bigger fonts and not having to hunt for buttons hidden in three-level menus.</p><p>The process usually goes like this:</p><ol><li>List your audience’s traits (age, experience, goal).</li><li>Talk to people who understand the business.</li><li>Prioritize what has the biggest impact.</li><li>Define the groups you’ll focus on.</li></ol><p>And here’s an important trick: <strong>ethnography</strong>. That’s just a fancy word for “watching the person use the system in their real environment.” Why? Because what people <em>say</em> they do and what they <em>actually</em> do are two very different things.</p><h3>Usability: the heart of it all</h3><p>ISO defines usability with three words:</p><ul><li><strong>Effectiveness</strong> — can the person do what they came to do?</li><li><strong>Efficiency</strong> — can they do it quickly and without too much effort?</li><li><strong>Satisfaction</strong> — did they leave happy or frustrated?</li></ul><p>If one of the three is missing, the product loses value.</p><p>Fun fact: in 1995, a study in Japan tested ATMs that were identical on the inside but had different looks on the outside. Guess which one people thought was “easier to use”? <strong>The prettier one.</strong> Beauty influences how easy something seems. Pretty <em>looks</em> like it works better, even when it works the same.</p><p>But careful: pretty that doesn’t work is still a problem. The goal is to be pretty <strong>AND</strong> functional.</p><h3>Nielsen’s 10 heuristics (the part that shows up on the test)</h3><p>Jakob Nielsen is one of the biggest names in usability. He created 10 heuristics — which is just a fancy word for “practical rules.” Write these down:</p><ol><li><strong>Visibility of system status</strong> — the system always tells you where you are and what’s happening. Like that loading bar. Without it, you think it crashed.</li><li><strong>Real-world language</strong> — use words the user understands. No invented technical terms. “Save” is better than “persist data.”</li><li><strong>Freedom and control</strong> — always give a back, cancel, or undo button. Mistakes are human, they shouldn’t be fatal.</li><li><strong>Consistency</strong> — if a button is blue on one screen, it’s blue everywhere. If “X” closes, it always closes. Patterns are good, surprises are bad.</li><li><strong>Error prevention</strong> — better than showing errors is not letting them happen. Like: “Are you sure you want to delete?” before deleting everything.</li><li><strong>Recognition, not memorization</strong> — show options, don’t force people to memorize. A visible menu beats a command you have to remember.</li><li><strong>Flexibility and efficiency</strong> — shortcuts for advanced users, easy paths for beginners. Both worlds covered.</li><li><strong>Minimalist aesthetic</strong> — less is more. Every extra element on the screen is one more thing for the brain to process.</li><li><strong>Help users recognize and fix errors</strong> — error messages need to say <strong>what</strong> went wrong and <strong>how</strong> to fix it. Not “Error 404,” but “this page doesn’t exist, want to go back?”</li><li><strong>Help and documentation</strong> — when a manual is needed, make it easy to find and easy to read.</li></ol><p>Memorize these 10. They show up on tests, in job interviews, and in real life.</p><h3>Accessibility: design for everyone, for real</h3><p>Accessibility is designing for people with disabilities — visual, motor, hearing, cognitive. But here’s the cool part: <strong>when you make something accessible, it gets better for everyone.</strong></p><p>Video captions? They help deaf people, but also someone on a bus without headphones. High contrast? Helps people with low vision, but also someone with the sun hitting their screen.</p><p>In Brazil, we have <strong>eMAG</strong> (the government’s accessibility model), which follows international standards (WCAG). And there’s the concept of <strong>Universal Design</strong> — design once, serve everyone.</p><p>There are two types of access:</p><ul><li><strong>Direct</strong> — no help needed.</li><li><strong>Indirect</strong> — with assistive technology (like a screen reader).</li></ul><h3>UX: the complete experience</h3><p>UX (User Experience) is how you <strong>feel</strong> while using the product. Before, during, and after.</p><p>Don Norman, who coined the term, said something brilliant:</p><blockquote>“A well-designed thing is harder to notice than a poorly-designed one.”</blockquote><p>When it’s good, you don’t even notice it. When it’s bad, you complain. Good design is invisible.</p><p>And here’s a classic mix-up: <strong>UX is not UI</strong>.</p><ul><li><strong>UI (User Interface)</strong> = the visual part, the buttons, the colors.</li><li><strong>UX (User Experience)</strong> = the complete feeling, the journey.</li></ul><p>UI is part of UX, but UX is much more than UI. UI is the menu, UX is the whole dinner — including whether the chair is comfortable and the waiter is friendly.</p><h3>The 3 emotional levels of design (Norman)</h3><p>Norman also figured out that we react to products on three levels:</p><p><strong>Visceral</strong> — the gut reaction, the “wow, that’s pretty.” It’s the first impact, before the brain even thinks.</p><p><strong>Behavioral</strong> — when you use it and it works well (or badly). The satisfaction of doing something without a headache.</p><p><strong>Reflective</strong> — what it means to you. Like using a product that matches your identity (“I’m an Apple person”).</p><p>All three happen at the same time. A good product hits all three.</p><h3>User-Centered Design (UCD)</h3><p>The idea here is simple and powerful: <strong>put the user at the center of everything from the start.</strong></p><p>It’s not about building the product and then testing with users. It’s about involving them in the whole process. Research, prototyping, testing, adjusting, testing again.</p><p>Why? Because your view of the problem is <strong>never</strong> the same as the user’s view. You think the button is obvious, they don’t. You think the flow makes sense, they get lost on step two.</p><p>As Travis Lowdermilk says: <em>“You can’t create products that go to the user if you’re not willing to go to the user.”</em></p><h3>Prototypes: test before spending a fortune</h3><p>Before building the real product, you make a prototype. It can be:</p><p><strong>Low fidelity</strong> — a sketch on paper, a wireframe, something simple. Fast, cheap, easy to change. Perfect for the start.</p><p><strong>High fidelity</strong> — almost like the final product. More expensive and slower, but you can test almost everything.</p><p>There’s also:</p><ul><li><strong>Horizontal</strong> — covers many functions, but shallow.</li><li><strong>Vertical</strong> — goes deep into one function only.</li></ul><p>And there’s the <strong>Wizard of Oz</strong> technique, my favorite as a concept: you pretend the system works on its own, but actually there’s a human behind the scenes responding. It’s like ChatGPT before ChatGPT existed.</p><h3>Real case: the 300 million dollar button</h3><p>A big American retailer had a problem: at checkout, the site forced users to register or log in. The result? People gave up on the purchase.</p><p>The fix? <strong>They replaced the “Register” button with “Continue.”</strong> Basically, they let people buy without signing up.</p><p>The result: <strong>+45% in sales. 300 million dollars more per year.</strong></p><p>Because of <strong>one button</strong>.</p><p>That’s usability in the real world. It’s not just designer fluff — it’s money on the table.</p><h3>Mobile First: because the phone won</h3><p>Data from 2018: <strong>80% of homes with internet in Brazil use phones to browse.</strong> More than computers. By 2026, that number is probably even higher.</p><p>That’s why <strong>Mobile First</strong> exists — design for the phone first, then adapt for desktop. Why? Because on a small screen, you’re <strong>forced</strong> to focus on what matters. No room for fluff.</p><p>Some rules:</p><ul><li>Font size 12px on phone, 16px on desktop.</li><li>Lines with 45–75 characters (more than that becomes a wall of text).</li><li>Left-aligned text (centered or justified can hurt readability).</li><li>Line spacing: 120% of the font size.</li></ul><h3>Design Thinking: think different, solve different</h3><p>Design Thinking is a way of solving problems that <strong>starts with the human</strong>, not the technology.</p><p>It has three pillars:</p><ul><li><strong>Empathy</strong> — understanding the user’s real pain.</li><li><strong>Collaboration</strong> — many minds thinking together.</li><li><strong>Experimentation</strong> — test, fail, adjust, test again.</li></ul><p>And the steps:</p><ol><li><strong>Immersion</strong> — dive into the problem.</li><li><strong>Analysis/Synthesis</strong> — organize what you found.</li><li><strong>Ideation</strong> — generate ideas (lots of them, no filter).</li><li><strong>Prototyping</strong> — turn the best ones into something real.</li><li><strong>Testing</strong> — put it out there and see what happens.</li></ol><p>It’s less of a formula and more of a mindset: thinking like a designer, even if you’re not one.</p><h3>And how do you check if you did it right?</h3><p>There are two main paths:</p><p><strong>Inspection-based evaluation</strong> (without users):</p><ul><li><em>Heuristic evaluation</em> — using Nielsen’s 10 to find problems.</li><li><em>Cognitive walkthrough</em> — simulating a beginner user step by step.</li><li><em>Semiotic inspection</em> — checking if the designer’s “message” comes across clearly.</li></ul><p><strong>Observation-based evaluation</strong> (with users):</p><ul><li><em>Usability testing</em> — having someone use it while you watch.</li><li><em>Paper prototyping</em> — testing before coding.</li></ul><p>Golden rule: <strong>many small, fast tests beat one big, expensive test</strong>. Always.</p><h3>The big picture (to stick on your mirror)</h3><ul><li>The interface is the bridge. The interaction is what happens on the bridge. Both matter.</li><li>Know your user. Without that, you’re designing in the dark.</li><li>Usability = effectiveness + efficiency + satisfaction.</li><li>Memorize Nielsen’s 10 heuristics.</li><li>UX is the whole experience. UI is just one part of it.</li><li>Good design is invisible. Bad design screams.</li><li>Test early, test often, test with real people.</li><li>Accessibility isn’t a favor — it’s a right, and it makes life better for everyone.</li><li>Mobile first. The phone won.</li></ul><h3>To wrap it up</h3><p>HCI isn’t a “technical” field in the cold sense of the word. It’s an area that brings together computer science, psychology, design, anthropology, and even philosophy. Because in the end, every piece of software is made for someone to use — and that someone is a person, with a brain, with pain, in a hurry, with mood swings.</p><p>The more you understand that, the better products you build. It’s that simple.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8199aa970b1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ O que é IHC, Usabilidade e UX — e por que isso importa mais do que você imagina]]></title>
            <link>https://medium.com/@fa.engeroff1996/o-que-%C3%A9-ihc-usabilidade-e-ux-e-por-que-isso-importa-mais-do-que-voc%C3%AA-imagina-bd7b4b1f0d52?source=rss-3bca9844656e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd7b4b1f0d52</guid>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[usabilidade]]></category>
            <category><![CDATA[tecnologia]]></category>
            <dc:creator><![CDATA[Fabricio Engeroff]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 17:47:29 GMT</pubDate>
            <atom:updated>2026-04-25T17:47:29.544Z</atom:updated>
            <content:encoded><![CDATA[<h3>O que é IHC, Usabilidade e UX — e por que isso importa mais do que você imagina</h3><p>Você já abriu um app, tentou fazer algo simples (tipo cancelar uma assinatura) e ficou com vontade de jogar o celular longe? Pois é. Isso aí é IHC mal feita.</p><p>E é exatamente sobre isso que esse texto vai falar. Bora descomplicar.</p><h3>Primeiro: o que é IHC?</h3><p><strong>IHC = Interação Humano-Computador.</strong></p><p>Não é só “fazer o sistema funcionar”. É fazer o sistema funcionar <strong>pra pessoa que está usando</strong>. Tem diferença, e essa diferença vale milhões.</p><p>Pensa assim: o computador é uma coisa, você é outra. No meio dos dois precisa existir uma ponte — essa ponte é a <strong>interface</strong>. E a forma como você atravessa essa ponte é a <strong>interação</strong>.</p><blockquote><em>Interface = o ponto de contato (tela, botão, voz, gesto). Interação = o que rola entre você e o sistema (clicar, arrastar, falar, tocar).</em></blockquote><p>Uma frase do Steve Jobs resume bem: <em>“Design não é só aparência, é como a coisa funciona.”</em> Pode ser bonito que nem uma obra de arte, se for difícil de usar, perde o propósito.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udqg-_KrQfmi2fqmDC1vOw.png" /></figure><h3>Ergonomia: por que seu pescoço dói depois de 3h no notebook</h3><p>Ergonomia vem do grego: <em>ergon</em> (trabalho) + <em>nomos</em> (regras). Ou seja, as regras pra adaptar o trabalho ao ser humano — e não o contrário.</p><p>Tem três tipos que você precisa conhecer:</p><p><strong>Ergonomia física</strong> — postura, posição da tela, altura da cadeira. É o que evita você virar um corcunda aos 30.</p><p><strong>Ergonomia cognitiva</strong> — como seu cérebro processa informação. Aqui mora o problema: sua memória tem limite. Se um sistema te obriga a decorar 15 passos, ele está te sobrecarregando.</p><p><strong>Ergonomia organizacional</strong> — como o trabalho é estruturado em equipe, processos e comunicação.</p><p>Tem ainda a <strong>ergonomia visual</strong>: usar fonte legível (Arial, Verdana, Tahoma), evitar texto sobre imagem confusa, manter contraste decente. Coisa básica que muita gente ignora.</p><h3>Os tipos de memória que importam pro design</h3><p>Seu cérebro tem três “gavetas”:</p><ul><li><strong>Sensorial</strong> — dura milissegundos. É o flash que você vê e some.</li><li><strong>Curta duração</strong> — dura segundos. Aquele código de verificação que você lê e digita rapidinho.</li><li><strong>Longa duração</strong> — fica anos. Tipo o ícone do disquete, que ainda significa “salvar” mesmo ninguém mais usando disquete.</li></ul><p><strong>Por que isso importa?</strong> Porque um bom designer não força a memória do usuário. Em vez de obrigar a pessoa a decorar onde fica cada coisa, ele <strong>mostra</strong>. Reconhecimento sempre vence memorização.</p><h3>Conheça seu usuário (ou perde feio)</h3><p>Não dá pra projetar pra “todo mundo”. Todo mundo é ninguém.</p><p>Criança quer cor, som, imagem. Adulto profissional quer rapidez e clareza. Idoso quer fonte grande e não ter que ficar caçando botão escondido em menu de três níveis.</p><p>O processo costuma ser mais ou menos esse:</p><ol><li>Liste os atributos do seu público (idade, experiência, objetivo).</li><li>Converse com quem entende do negócio.</li><li>Priorize o que tem mais impacto.</li><li>Defina os grupos que vai focar.</li></ol><p>E aqui entra um truque importante: <strong>etnografia</strong>. Que é só uma palavra chique pra “observar a pessoa usando o sistema no ambiente real dela”. Por que isso? Porque o que as pessoas <em>dizem</em> que fazem e o que elas <em>realmente</em> fazem são duas coisas bem diferentes.</p><h3>Usabilidade: o coração da parada</h3><p>A ISO define usabilidade com três palavras:</p><ul><li><strong>Eficácia</strong> — a pessoa consegue fazer o que veio fazer?</li><li><strong>Eficiência</strong> — ela faz isso rápido e sem esforço excessivo?</li><li><strong>Satisfação</strong> — ela saiu satisfeita ou frustrada?</li></ul><p>Se faltar uma das três, o produto perde valor.</p><p>Curiosidade interessante: em 1995, fizeram um teste no Japão com caixas eletrônicos idênticos por dentro, mas com aparências diferentes. Adivinha qual o pessoal achou “mais fácil de usar”? <strong>O mais bonito.</strong> Estética influencia a percepção de facilidade. O bonito <em>parece</em> funcionar melhor, mesmo quando funciona igual.</p><p>Mas atenção: bonito que não funciona continua sendo um problema. O ideal é ser bonito <strong>E</strong> funcional.</p><h3>As 10 heurísticas de Nielsen (a parte que cai na prova)</h3><p>Jakob Nielsen é uma das maiores referências em usabilidade. Ele criou 10 heurísticas — que é só uma palavra chique pra “regras práticas”. Anota aí:</p><ol><li><strong>Visibilidade do status</strong> — o sistema sempre informa onde você está e o que está acontecendo. Tipo aquela barrinha de carregamento. Sem ela, você fica achando que travou.</li><li><strong>Linguagem do mundo real</strong> — usar palavras que o usuário entende. Sem inventar termo técnico. “Salvar” é melhor que “persistir dados”.</li><li><strong>Liberdade e controle</strong> — sempre dar um botão de voltar, cancelar, desfazer. Errar é humano, não pode ser fatal.</li><li><strong>Consistência</strong> — se um botão é azul numa tela, é azul em todas. Se “X” fecha, sempre fecha. Padrão é bom, surpresa é ruim.</li><li><strong>Prevenção de erros</strong> — melhor que mostrar erro é não deixar ele acontecer. Tipo: “tem certeza que quer apagar?” antes de apagar tudo.</li><li><strong>Reconhecimento, não memorização</strong> — mostrar as opções, não obrigar a decorar. Menu visível vence comando que você precisa lembrar.</li><li><strong>Flexibilidade e eficiência</strong> — atalhos pro usuário avançado, caminho fácil pro iniciante. Os dois mundos atendidos.</li><li><strong>Estética minimalista</strong> — menos é mais. Cada elemento extra na tela é um a mais pro cérebro processar.</li><li><strong>Ajuda a reconhecer e resolver erros</strong> — mensagem de erro precisa dizer <strong>o que</strong> deu errado e <strong>como</strong> resolver. Não é “Erro 404”, é “essa página não existe, quer voltar?”</li><li><strong>Ajuda e documentação</strong> — quando precisar de manual, que ele seja fácil de achar e de ler.</li></ol><p>Decora essas 10. Vão cair em prova, em entrevista de emprego, e na vida real.</p><h3>Acessibilidade: design pra todo mundo, de verdade</h3><p>Acessibilidade é projetar pensando em quem tem alguma deficiência — visual, motora, auditiva, cognitiva. Mas tem uma coisa interessante: <strong>quando você faz algo acessível, melhora pra todo mundo.</strong></p><p>Legenda em vídeo? Ajuda quem é surdo, mas também quem está no ônibus sem fone. Contraste alto? Ajuda quem tem baixa visão, mas também quem está no sol batendo na tela.</p><p>No Brasil temos o <strong>eMAG</strong> (Modelo de Acessibilidade em Governo Eletrônico), que segue padrões internacionais (WCAG). E existe o conceito de <strong>Design Universal</strong> — projetar uma vez, servir pra todos.</p><p>Tem dois tipos de acesso:</p><ul><li><strong>Direto</strong> — sem ajuda nenhuma.</li><li><strong>Indireto</strong> — com tecnologia assistiva (leitor de tela, por exemplo).</li></ul><h3>UX: a experiência completa</h3><p>UX (User Experience) é como você <strong>se sente</strong> usando o produto. Antes, durante e depois.</p><p>Don Norman, que cunhou o termo, disse algo genial:</p><blockquote>“Um design bem feito é mais difícil de perceber do que um design mal feito.”</blockquote><p>Quando é bom, você nem nota. Quando é ruim, você reclama. Design bom é invisível.</p><p>E aqui rola uma confusão clássica: <strong>UX não é UI</strong>.</p><ul><li><strong>UI (User Interface)</strong> = a parte visual, os botões, as cores.</li><li><strong>UX (User Experience)</strong> = a sensação completa, o sentimento, a jornada.</li></ul><p>UI é parte da UX, mas UX é muito mais que UI. UI é o cardápio, UX é o jantar inteiro — incluindo se a cadeira é confortável e se o garçom é atencioso.</p><h3>Os 3 níveis emocionais do design (Norman)</h3><p>Norman também identificou que reagimos aos produtos em três níveis:</p><p><strong>Visceral</strong> — a reação instintiva, o “que bonito”. É o impacto inicial, antes do cérebro pensar.</p><p><strong>Comportamental</strong> — quando você usa e funciona bem (ou mal). É a satisfação de fazer algo sem dor de cabeça.</p><p><strong>Reflexivo</strong> — o significado que aquilo tem pra você. Tipo usar um produto que combina com sua identidade (“eu sou pessoa de Apple”).</p><p>Os três acontecem ao mesmo tempo. Um produto bom acerta nos três.</p><h3>Design Centrado no Usuário (DCU)</h3><p>A ideia aqui é simples e poderosa: <strong>coloque o usuário no centro de tudo desde o começo.</strong></p><p>Não é fazer o produto e depois testar com usuário. É envolver ele em todo o processo. Pesquisa, prototipagem, teste, ajusta, testa de novo.</p><p>Por quê? Porque sua percepção do problema <strong>nunca</strong> é igual à percepção do usuário. Você acha que o botão está óbvio, ele não acha. Você acha que o fluxo faz sentido, ele se perde no segundo passo.</p><p>Como diz Travis Lowdermilk: <em>“Não dá pra criar produtos que vão até o usuário, se a gente não vai até o usuário.”</em></p><h3>Protótipos: testa antes de gastar uma fortuna</h3><p>Antes de fazer o produto de verdade, você faz um protótipo. Que pode ser:</p><p><strong>Baixa fidelidade</strong> — desenho em papel, esboço, wireframe simples. Rápido, barato, fácil de mudar. Ideal pro começo.</p><p><strong>Alta fidelidade</strong> — quase a cara do produto final. Mais caro e demorado, mas dá pra testar quase tudo.</p><p>Tem também:</p><ul><li><strong>Horizontal</strong> — cobre muitas funções, mas raso.</li><li><strong>Vertical</strong> — vai fundo numa função só.</li></ul><p>E tem o <strong>Mágico de Oz</strong>, que é meu favorito como conceito: você finge que o sistema funciona sozinho, mas na verdade tem um humano por trás respondendo. É tipo o ChatGPT antes do ChatGPT existir.</p><h3>Caso real: o botão de 300 milhões de dólares</h3><p>Um varejista americano grande tinha um problema: na hora de finalizar a compra, o site obrigava o usuário a fazer cadastro/login. Resultado? A galera desistia da compra.</p><p>Solução? <strong>Trocaram o botão “Registrar” por “Continuar”.</strong> Ou seja, deixaram comprar sem cadastro.</p><p>Resultado: <strong>+45% nas vendas. 300 milhões de dólares a mais por ano.</strong></p><p>Por causa de <strong>um botão</strong>.</p><p>Isso é usabilidade no mundo real. Não é firula de designer, é dinheiro na mesa.</p><h3>Mobile First: porque o celular venceu</h3><p>Dado de 2018: <strong>80% das casas com internet no Brasil usam celular pra navegar.</strong> Mais que computador. Em 2026, esse número provavelmente está ainda maior.</p><p>Por isso existe o conceito de <strong>Mobile First</strong> — projetar primeiro pro celular, depois adaptar pro desktop. Por quê? Porque na tela pequena você <strong>é forçado</strong> a focar no essencial. Sem espaço pra encheção de linguiça.</p><p>Algumas regras:</p><ul><li>Fonte 12px no celular, 16px no desktop.</li><li>Linha com 45–75 caracteres (mais que isso vira parede de texto).</li><li>Texto alinhado à esquerda (centralizado e justificado pode atrapalhar a leitura).</li><li>Espaçamento entre linhas: 120% do tamanho da fonte.</li></ul><h3>Design Thinking: pensa diferente, soluciona diferente</h3><p>Design Thinking é uma forma de resolver problema que <strong>começa pelo humano</strong>, não pela tecnologia.</p><p>Tem três pilares:</p><ul><li><strong>Empatia</strong> — entender a dor real do usuário.</li><li><strong>Colaboração</strong> — várias cabeças pensando juntas.</li><li><strong>Experimentação</strong> — testar, errar, ajustar, testar de novo.</li></ul><p>E as etapas:</p><ol><li><strong>Imersão</strong> — mergulhar no problema.</li><li><strong>Análise/Síntese</strong> — organizar o que descobriu.</li><li><strong>Ideação</strong> — gerar ideias (muitas, sem filtro).</li><li><strong>Prototipação</strong> — materializar as melhores.</li><li><strong>Teste</strong> — colocar pra rodar e ver o que acontece.</li></ol><p>É menos uma fórmula e mais uma postura: pensar como designer, mesmo que você não seja designer.</p><h3>E como avaliar se você fez direito?</h3><p>Tem dois caminhos principais:</p><p><strong>Avaliação por inspeção</strong> (sem usuário):</p><ul><li><em>Avaliação heurística</em> — usar as 10 do Nielsen pra encontrar problemas.</li><li><em>Percurso cognitivo</em> — simular um usuário iniciante passo a passo.</li><li><em>Inspeção semiótica</em> — analisar se a “mensagem” do designer chega clara.</li></ul><p><strong>Avaliação por observação</strong> (com usuário):</p><ul><li><em>Teste de usabilidade</em> — colocar a pessoa pra usar e observar.</li><li><em>Prototipação em papel</em> — testar antes de programar.</li></ul><p>Regra de ouro: <strong>vários testes pequenos e rápidos vencem um teste gigante e caro</strong>. Sempre.</p><h3>Resumo da ópera</h3><ul><li>Interface é a ponte. Interação é o que rola na ponte. Os dois importam.</li><li>Conheça seu usuário. Sem isso, você está projetando no escuro.</li><li>Usabilidade = eficácia + eficiência + satisfação.</li><li>Decora as 10 heurísticas do Nielsen.</li><li>UX é a experiência inteira. UI é só uma parte dela.</li><li>Bom design é invisível. Mau design grita.</li><li>Testa cedo, testa sempre, testa com gente real.</li><li>Acessibilidade não é favor — é direito, e melhora a vida de todo mundo.</li><li>Mobile primeiro. O celular venceu.</li></ul><h3>Pra fechar</h3><p>IHC não é um campo “técnico” no sentido frio da palavra. É uma área que junta computação, psicologia, design, antropologia e até filosofia. Porque, no fim, todo software é feito pra alguém usar — e esse alguém é uma pessoa, com cérebro, com dor, com pressa, com humor variado.</p><p>Quanto mais você entende isso, melhores produtos você faz. Simples assim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd7b4b1f0d52" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>