Policies/Kdelibs Coding Style/pt-br: Difference between revisions

    From KDE TechBase
    (Created page with "Políticas/Estilo de código da Kdelibs")
     
    (Updating to match new version of source page)
    (42 intermediate revisions by 2 users not shown)
    Line 1: Line 1:
    <languages />
    <languages />
    This document describes the recommended coding style for kdelibs. Nobody is forced to use this style, but to have consistent formatting of the source code files it is recommended to make use of it.
    Esse documento descreve o estilo de código recomendado para kdelibs. Ninguém é forçado a usá-lo, mas para ter uma formatação consistente dos seus arquivos de código-fonte é recomendado fazer uso dele.


    '''In short: Kdelibs coding style follows the [http://wiki.qt-project.org/Coding_Style Qt 4 coding style].'''
    <span class="mw-translate-fuzzy">
    '''Em síntese: O estilo de código da Kdelibs segue o [http://wiki.qt-project.org/Coding_Style estilo de código do Qt 4].'''
    </span>


    == Indentation ==
    == Indentação ==
    * No tabs
    * Sem abas
    * 4 Spaces instead of one tab
    * 4 espaços ao invés de uma aba


    == Variable declaration ==
    == Declaração de variável ==
    * Each variable declaration on a new line
    * Cada declaração de variável em uma nova linha
    * Each new word in a variable name starts with a capital letter (so-called camelCase)
    * Cada nova palavra no nome de uma variável começa com uma letra maiúscula (o chamado camelCase)
    * Avoid abbreviations
    * Evitar abreviações
    * Take useful names. No short names, except:
    * Usar nomes significativos. Não use nomes curtos, exceto:
    ** Single character variable names can denote counters and temporary variables whose purpose is obvious
    ** Nomes de variáveis com um único caractere podem indicar contadores e variáveis temporárias cujo propósito é óbvio
    ** Variables and functions start with a lowercase letter
    ** Variáveis e funções começam com uma letra minúscula


    Example:
    Exemplo:
    <syntaxhighlight lang="cpp-qt">
    <syntaxhighlight lang="cpp-qt">
    // wrong
    // errado
    KProgressBar *prbar;
    KProgressBar *prbar;
    QString prtxt, errstr;
    QString prtxt, errstr;


    // correct
    // certo
    KProgressBar *downloadProgressBar;
    KProgressBar *downloadProgressBar;
    QString progressText;
    QString progressText;
    Line 28: Line 30:
    </syntaxhighlight>
    </syntaxhighlight>


    == Whitespace ==
    * Use blank lines to group statements
    * Use only one empty line
    * Use one space after each keyword
    * For pointers or references, use a single space before '*' or '&', but not after
    * No space after a cast


    Example:
    == Espaço em branco ==
    * Use linhas em branco para agrupar comandos
    * Use somente uma linha em branco
    * Use um espaço depois de cada palavra-chave
    * Para ponteiros ou referências, use um único space antes de '*' ou '&', nenhum depois
    * Não use espaço após um cast
     
    Exemplo:
    <syntaxhighlight lang="cpp-qt">
    <syntaxhighlight lang="cpp-qt">
    // wrong
    // errado
    QString* myString;
    QString* myString;
    if(true){
    if(true){
    }
    }


    // correct
    // certo
    QString *myString;
    QString *myString;
    if (true) {
    if (true) {
    Line 48: Line 51:
    </syntaxhighlight>
    </syntaxhighlight>


    == Braces ==
    == Chaves ==
    As a base rule, the left curly brace goes on the same line as the start of the statement.
    Como uma regra básica, a abertura da chave fica na mesma linha do comando que inicia o bloco.


    Example:
    Exemplo:
    <syntaxhighlight lang="cpp-qt">
    <syntaxhighlight lang="cpp-qt">
    // wrong
    // errado
    if (true)
    if (true)
    {
    {
    }
    }


    // correct
    // certo
    if (true) {
    if (true) {
    }
    }
    </syntaxhighlight>
    </syntaxhighlight>


    Exception: Function implementations, class, struct and namespace declarations always have the opening brace on the start of a line.
    Exceção: A chave de abertura das implementações de função, declarações de classes, struct's e namespace's deve ser sempre colocada no início da linha seguinte.


    Example:
    Exemplo:
    <syntaxhighlight lang="cpp-qt">
    <syntaxhighlight lang="cpp-qt">
    void debug(int i)
    void debug(int i)
    Line 77: Line 80:
    </syntaxhighlight>
    </syntaxhighlight>


    Use curly braces even when the body of a conditional statement contains only one line.
    Use as chaves mesmo quando o corpo de um bloco condicional contiver apenas uma linha.


    Example:
    Exemplo:
    <syntaxhighlight lang="cpp-qt">
    <syntaxhighlight lang="cpp-qt">
    // wrong
    // errado
    if (true)
    if (true)
         return true;
         return true;
    Line 88: Line 91:
         qDebug("%i", i);
         qDebug("%i", i);


    // correct
    // certo
    if (true) {
    if (true) {
         return true;
         return true;
    Line 98: Line 101:
    </syntaxhighlight>
    </syntaxhighlight>


    == Switch statements ==
    == Comando switch ==
    Case labels are on the same column as the switch
    Case labels ficam na mesma coluna do switch


    Example:
    Exemplo:
    <syntaxhighlight lang="cpp-qt">
    <syntaxhighlight lang="cpp-qt">
    switch (myEnum) {
    switch (myEnum) {
    Line 116: Line 119:
    </syntaxhighlight>
    </syntaxhighlight>


    == Line breaks ==
    == Quebra de linha ==
    Try to keep lines shorter than 100 characters, inserting line breaks as necessary.
    Tente manter linhas menores que 100 caracteres, inserindo quebras de linha conforme for necessário.


    == Qt Includes ==
    == Qt Includes ==
    * If you add #includes for Qt classes, use both the module and class name.  This allows library code to be used by applications without excessive compiler include paths.
    * Se você adicionar #includes para as classes do Qt, use o nome do módulo e da classe. Isso permite que a biblioteca seja utilizada sem uso excessivo de parâmetros para o compilador


    Example:
    Exemplo:
    <syntaxhighlight lang="cpp-qt">
    <syntaxhighlight lang="cpp-qt">
    // wrong
    // errado
    #include <QString>
    #include <QString>


    // correct
    // certo
    #include <QtCore/QString>
    #include <QtCore/QString>
    </syntaxhighlight>
    </syntaxhighlight>


    == Artistic Style (astyle) automatic code formatting ==
    == Formatação automática com Artistic Style (astyle) ==
    You can use [http://astyle.sourceforge.net/ astyle] (>=1.23) to format code or to test if you have followed this document. Run the following command:
    Você pode usar [http://astyle.sourceforge.net/ astyle] (>=1.23) para formatar o código ou testá-lo se você tiver seguido esse documento. Execute o seguinte comando:
    <syntaxhighlight lang="text">
    <syntaxhighlight lang="text">
    astyle --indent=spaces=4 --brackets=linux \
    astyle --indent=spaces=4 --brackets=linux \
    Line 141: Line 144:
    </syntaxhighlight>
    </syntaxhighlight>


    With astyle (>=2.01) you need to run the following command:
    Com astyle (>=2.01) você precisa executar o seguinte comando:
    <syntaxhighlight lang="text">
    <syntaxhighlight lang="text">
    astyle --indent=spaces=4 --brackets=linux \
    astyle --indent=spaces=4 --brackets=linux \
    Line 150: Line 153:
    </syntaxhighlight>
    </syntaxhighlight>


    A related shell script could be found for unix in [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/astyle-kdelibs kdesdk/scripts/astyle-kdelibs] and for windows in [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/astyle-kdelibs.bat kdesdk/scripts/astyle-kdelibs.bat].
    <span class="mw-translate-fuzzy">
    Um shell script relacionado pode ser encontrado para unix em [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/astyle-kdelibs kdesdk/scripts/astyle-kdelibs] e para windows em [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/astyle-kdelibs.bat kdesdk/scripts/astyle-kdelibs.bat].
    </span>
     
    * [https://projects.kde.org/projects/kde/kdesdk/kde-dev-scripts/repository/revisions/master/raw/astyle-kdelibs kde-dev-scripts/astyle-kdelibs] (POSIX)
    * [https://projects.kde.org/projects/kde/kdesdk/kde-dev-scripts/repository/revisions/master/raw/astyle-kdelibs.bat kde-dev-scripts/astyle-kdelibs.bat] (Windows)


    == Emacs and Vim scripts ==
    <span class="mw-translate-fuzzy">
    The "scripts" directory in the kdesdk module contains, among other useful things, some useful additions to the Emacs and Vim text editors that make it easier to edit KDE code with them.
    == Scripts para Emacs e Vim ==
    O diretório "scripts" no módulo kdesdk contém, entre outras coisas, algumas adições úteis para os editores de texto Emacs e Vim que tornam mais fácil editar código do KDE code.
       
       
    === Emacs ===
    === Emacs ===
    The [http://websvn.kde.org/trunk/KDE/kdesdk/scripts/kde-emacs kde-emacs] directory contains a set of key bindings, macros and general useful code. It is compatible with both GNU Emacs and XEmacs.
    O diretório [http://websvn.kde.org/trunk/KDE/kdesdk/scripts/kde-emacs kde-emacs] contém um conjunto de mapeamento de teclas, macros e código útil em geral. Isso é compatível com GNU Emacs e XEmacs.
    </span>


    To start using kde-emacs, add the following to your .emacs:
    Para iniciar o uso de kde-emacs, adicione o seguinte para seu .emacs:


    <syntaxhighlight lang="text">
    <syntaxhighlight lang="text">
    Line 165: Line 175:
    </syntaxhighlight>
    </syntaxhighlight>


    Many settings can be changed by editing the "kde-emacs" group via <tt>M-x customize-group</tt>.
    Muitas configurações podem ser alteradas pela edição do grupo "kde-emacs" via <tt>M-x customize-group</tt>.


    For more information, including what the key bindings are and what additional settings you could add to your .emacs, please check <tt>kde-emacs.el</tt> itself.
    Para mais informações, incluindo quais teclas estão mapeadas e quais configurações extras você pode adicionar ao seu .emacs, por favor, verifique <tt>kde-emacs.el</tt>


    <span class="mw-translate-fuzzy">
    === Vim ===
    === Vim ===
    You can find a vim script in [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/kde-devel-vim.vim kdesdk/scripts/kde-devel-vim.vim] that helps you to keep the coding style correct. In addition to defaulting to the kdelibs coding style it will automatically use the correct style for Solid and kdepim code. If you want to add rules for other projects feel free to add them in the SetCodingStyle function.
    Você pode encontrar um script para o vim em [http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/kde-devel-vim.vim kdesdk/scripts/kde-devel-vim.vim] que o ajuda a manter o correto estilo de código. Além de utilizar o estilo da kdelibs por padrão, ele automaticamente utilizará o estilo do Solid e kdepim quando necessário.
    </span>


    To use the script, include it in your {{path|~/.vimrc}} like this:
    Para usar o script, inclua-o em seu {{path|~/.vimrc}} assim:
    <syntaxhighlight lang="text">
    <syntaxhighlight lang="text">
    source /path/to/kde/sources/kdesdk/scripts/kde-devel-vim.vim
    source /path/to/kde/sources/kdesdk/scripts/kde-devel-vim.vim
    Line 178: Line 190:




    Document started by Urs Wolfer. Some parts of this document have been adopted from the Qt Coding Style document posted by Zack Rusin on kde-core-devel.
    Documento criado por Urs Wolfer. Algumas partes desse documento foram adotadas do documento Qt Coding Style postado por Zack Rusin no kde-core-devel.


    [[Category:Policies]] [[Category:C++]]
    [[Category:Políticas]] [[Category:C++]]

    Revision as of 10:31, 30 May 2013

    Esse documento descreve o estilo de código recomendado para kdelibs. Ninguém é forçado a usá-lo, mas para ter uma formatação consistente dos seus arquivos de código-fonte é recomendado fazer uso dele.

    Em síntese: O estilo de código da Kdelibs segue o estilo de código do Qt 4.

    Indentação

    • Sem abas
    • 4 espaços ao invés de uma aba

    Declaração de variável

    • Cada declaração de variável em uma nova linha
    • Cada nova palavra no nome de uma variável começa com uma letra maiúscula (o chamado camelCase)
    • Evitar abreviações
    • Usar nomes significativos. Não use nomes curtos, exceto:
      • Nomes de variáveis com um único caractere podem indicar contadores e variáveis temporárias cujo propósito é óbvio
      • Variáveis e funções começam com uma letra minúscula

    Exemplo:

    // errado
    KProgressBar *prbar;
    QString prtxt, errstr;
    
    // certo
    KProgressBar *downloadProgressBar;
    QString progressText;
    QString errorString;
    


    Espaço em branco

    • Use linhas em branco para agrupar comandos
    • Use somente uma linha em branco
    • Use um espaço depois de cada palavra-chave
    • Para ponteiros ou referências, use um único space antes de '*' ou '&', nenhum depois
    • Não use espaço após um cast

    Exemplo:

    // errado
    QString* myString;
    if(true){
    }
    
    // certo
    QString *myString;
    if (true) {
    }
    

    Chaves

    Como uma regra básica, a abertura da chave fica na mesma linha do comando que inicia o bloco.

    Exemplo:

    // errado
    if (true)
    {
    }
    
    // certo
    if (true) {
    }
    

    Exceção: A chave de abertura das implementações de função, declarações de classes, struct's e namespace's deve ser sempre colocada no início da linha seguinte.

    Exemplo:

    void debug(int i)
    {
        qDebug("foo: %i", i);
    }
    
    class Debug
    {
    };
    

    Use as chaves mesmo quando o corpo de um bloco condicional contiver apenas uma linha.

    Exemplo:

    // errado
    if (true)
        return true;
    
    for (int i = 0; i < 10; ++i)
        qDebug("%i", i);
    
    // certo
    if (true) {
        return true;
    }
    
    for (int i = 0; i < 10; ++i) {
        qDebug("%i", i);
    }
    

    Comando switch

    Case labels ficam na mesma coluna do switch

    Exemplo:

    switch (myEnum) {
    case Value1:
        doSomething();
        break;
    case Value2:
        doSomethingElse();
        // fall through
    default:
        defaultHandling();
        break;
    }
    

    Quebra de linha

    Tente manter linhas menores que 100 caracteres, inserindo quebras de linha conforme for necessário.

    Qt Includes

    • Se você adicionar #includes para as classes do Qt, use o nome do módulo e da classe. Isso permite que a biblioteca seja utilizada sem uso excessivo de parâmetros para o compilador

    Exemplo:

    // errado
    #include <QString>
    
    // certo
    #include <QtCore/QString>
    

    Formatação automática com Artistic Style (astyle)

    Você pode usar astyle (>=1.23) para formatar o código ou testá-lo se você tiver seguido esse documento. Execute o seguinte comando:

    astyle --indent=spaces=4 --brackets=linux \
           --indent-labels --pad=oper --unpad=paren \
           --one-line=keep-statements --convert-tabs \
           --indent-preprocessor \
           `find -type f -name '*.cpp'-or -name '*.cc' -or -name '*.h'`
    

    Com astyle (>=2.01) você precisa executar o seguinte comando:

    astyle --indent=spaces=4 --brackets=linux \
           --indent-labels --pad-oper --unpad-paren --pad-header \
           --keep-one-line-statements --convert-tabs \
           --indent-preprocessor \
           `find -type f -name '*.cpp' -or -name '*.cc' -or -name '*.h'`
    

    Um shell script relacionado pode ser encontrado para unix em kdesdk/scripts/astyle-kdelibs e para windows em kdesdk/scripts/astyle-kdelibs.bat.

    Scripts para Emacs e Vim

    O diretório "scripts" no módulo kdesdk contém, entre outras coisas, algumas adições úteis para os editores de texto Emacs e Vim que tornam mais fácil editar código do KDE code.

    Emacs

    O diretório kde-emacs contém um conjunto de mapeamento de teclas, macros e código útil em geral. Isso é compatível com GNU Emacs e XEmacs.

    Para iniciar o uso de kde-emacs, adicione o seguinte para seu .emacs:

    (add-to-list 'load-path "/path/to/kde-emacs")
    (require 'kde-emacs)
    

    Muitas configurações podem ser alteradas pela edição do grupo "kde-emacs" via M-x customize-group.

    Para mais informações, incluindo quais teclas estão mapeadas e quais configurações extras você pode adicionar ao seu .emacs, por favor, verifique kde-emacs.el

    Vim

    Você pode encontrar um script para o vim em kdesdk/scripts/kde-devel-vim.vim que o ajuda a manter o correto estilo de código. Além de utilizar o estilo da kdelibs por padrão, ele automaticamente utilizará o estilo do Solid e kdepim quando necessário.

    Para usar o script, inclua-o em seu ~/.vimrc assim:

    source /path/to/kde/sources/kdesdk/scripts/kde-devel-vim.vim
    


    Documento criado por Urs Wolfer. Algumas partes desse documento foram adotadas do documento Qt Coding Style postado por Zack Rusin no kde-core-devel.