Eclipse – Formatter e Save Action

Depois de ter falado sobre Code Templates para comentários no código, vou neste post falar sobre a formatação e como otimizar isso para lhe ajudar e não atrapalhar.

Muitos desenvolvedores tem problemas com o famoso Ctrl+Shift+F, que promete formatar seu código e muitas vezes acaba é deixando ele mais confuso.

Bem, o nosso padrão de código(se é que posso chamar assim) é muito diferente(ou um pouco depende) dos códigos dos gringos, ou seja, o Eclipse formata no padrão deles pode dizer assim ;).

Para resolver esse “problema” o desenvolvedor tem que fazer uma configuração simples, mas um pouco chata(considerada por alguns) mas no pior caso será feita apenas uma única vez ;).
Vá em Windows –> Preferences –> Java –> Code Style –> Formatter.

Vamos agora criar um novo profiler, clique em New e digite um nome para o seu novo profile.



Pronto, agora vamos personalizar, clique em editar.



Vou tentar falar um pouco sobre cada aba de opção.

Indentation
Nesta aba você vai selecionar a indentação em si e o tamanho dela, normalmente o tamanho da tab é 4.

Braces
Nesta aba você vai personalizar a posição das chaves(“{” , “}”).

White Space
Está é interessante, pois você poderá personalizar até os espaços em branco entre cada variável, método e assinaturas de todo tipo de objeto, desde strings até arrays e várias outras.

Blank Lines
Nesta aba você irá definir as quebras de linhas(linhas em branco) entres métodos, variáveis, pacotes e etc. Aqui você irá definir por exemplo que o espaço de linha entre a declaração de um package para um import seja de 2 linhas por exemplo.

New Lines
Nesta aba você define como um método vazio deverá ficar, se você deseja inserir uma nova linha neste método, definir também como um array declarado deverá ser exibido e identado, assim como uma annotation.

Control Statements
Esse é bem interessante mesmo, pois aqui você irá definir como seus else, IF, catch, while etc devem ser identados.

Line Wrapping
Neste você define o tamanho Maximo da coluna que uma linha pode comportar, como deve ser a identação de uma assinatura de um método, métodos declarados, enum, variáveis declaradas e etc.

Comments
Isso é referente a identação do Java Doc, blocos de comentários normais(//, /**/), qual o formato das tags HTML, espaço entre os textos do comentário e se desejar remover qualquer linha em branco que esteja no comentário.

Todas essa opções podem já serem visualizadas no código de exemplo ao lado de cada uma, facilitando assim a personalização.
Então supondo que você já criou e personalizou seu profile vamos agora tentar otimizar isso.

Para se utilizar do profile basta você executar o atalho dentro do código, que é o Ctrl + Shitf + F, pronto ele aplica a sua configuração personalizada.
Mas supondo que você criou um profile e quer sempre executar ele, fica meio chato você ficar sempre digitando o Ctrl+Shit+F correto ? Que tal otimizar isso ?

Save Actions
Vá em Windows –> Preferences –> Java –> Editor –> Save Actions.


Para ativar(caso não esteja) basta selecionar a opção “Perform the selected actions on save”.

Agora podemos adicionar uma formatação automática, selecione o Format source code e clique em Formatter.



Verifique se o seu profile está selecionado como profile ativo(Active Profile), clique em Ok e pronto, na próxima vez que você salvar(Ctrl + S) qualquer arquivo .java(classe) ele irá aplicar a(s) sua(s) configuração(ões) automaticamente.

Para definir como padrão para todos os integrantes da equipe, basta seguir os passos abaixo.

Vá em Windows –> Preferences –> Java –> Code Style –> Formatter –> Edit –> Export –> Salve seu profile.

Agora cada desenvolvedor irá poder importar toda a configuração de formatação de código, ou você mesmo poderá levar para onde quiser a sua formatação.

Simples não ?

Ações adicionais do Save Action

Se você quiser personalizar ainda mais a sua formatação é possível ainda inserir algumas formatações adicionais. Na tela de Save Actions temos o Configure onde você poderá definir mais configurações que serão executadas ao salvar qualquer classe Java.


Vou tentar explicar um pouco cada uma delas:

Code Style
Responsável em adicionar ou criar blocos fechados({, }) no bloco de IF/while/for/do.Definir se você quer parênteses em condições por exemplo:
(((i > 0) && (i < 10)) || (i == 50)) ou sem (i > 0 && i < 10 || i == 50).
Se quer adicionar o modificador final em todas os parâmetros onde seja necessário, e quais tipos de parâmetros(private, parameter, local variables).

Member Accesses
Usar o “this” em todos as variáveis e métodos locais ou somente onde for necessário. Como devem ser declarados os métodos e variáveis etc.

Unnecessary Code
Como o nome mesmo já diz, remove trechos de códigos desnecessários, como imports de classes que não existem dentre outras configurações.

Missing Code
Adiciona automaticamente as tags “@Override” e “@Deprecated” nos métodos.

Code Organizing
Organiza a ordem do métodos.

Bem essa são as formas simples de como otimizar o código, seja pela formatação dele ou até por simples comentários, mas essa é a intenção, não perder tempo com coisas simples e repetitivas ;).

Abraços e espero ter contribuído com este artigo para agilizar o processo de desenvolvimento.

32.352 Comments on “Eclipse – Formatter e Save Action

  1. With havin so much written content do you ever run into any issues of
    plagorism or copyright infringement? My site has a lot of
    unique content I’ve either authored myself or outsourced
    but it looks like a lot of it is popping it up
    all over the web without my permission. Do you know any solutions to help reduce
    content from being stolen? I’d genuinely appreciate it.

  2. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my
    newest twitter updates. I’ve been looking for a
    plug-in like this for quite some time and was hoping maybe
    you would have some experience with something like this.
    Please let me know if you run into anything.

    I truly enjoy reading your blog and I look forward to your new updates.

  3. This is a great tip particularly to those new to the blogosphere.
    Brief but very accurate info… Many thanks for sharing this one.
    A must read post!

    my web page; Ilsungac

  4. Your dentist will need to clean your cavity to do away with the hazardous microorganisms and also fill it. In situation the tooth cavity is left unattended, it will only aggravate the scenario. A tiny dental caries can create chaos and also damage your tooth down to the nerve or pulp.

    Those rich in roughage or fiber can help to scrub germs and also little bits of plaque off the teeth. Others form barriers to plaque or have chemicals that aid to neutralize the acids that deteriorate enamel. A dentist or dental hygienist will utilize instruments to scrape, blast, or rub tartar and also plaque far from teeth. A dental professional may likewise execute small procedures to bleach the teeth and also protect them from additional decay.

    L. Williams, served as the structure for the current description of the etiology of decays. Several of the certain pressures of lactobacilli were determined in 1921 by Fernando E. Rodríguez Vargas. Historical evidence reveals that dental caries is an ancient disease dating much right into prehistory.
    Dental Cavity In Kids
    When the plaque adheres to the teeth this acid gnaws the outermost layer of the tooth– the enamel. If a cavity causes an abscessed tooth, or the damages is also significant, you might require a tooth removal. A dental professional can discuss your therapy options carefully. When tooth decay goes neglected for as well long, you can lose a large portion of your tooth as well as need a removal. Advanced tooth decay can bring about a serious infection inside your tooth and under your gums. If origin canal therapy isn’t feasible, your healthcare provider might recommend tooth removal.

    Whether you require oral crowns, dental fillings, or a mix of treatments, No Voids Dental can help restore your smile and also self-confidence. A dental caries can take anywhere from six months to five years to develop prior to it needs treatment. The vast array right here is influenced by the problems in an individual’s mouth, including their hygiene, diet regimen, and genetic variables. The area where the tooth cavity is creating can additionally affect the rate at which it establishes. Fortunately, the beginning stages of a dental caries can be turned around by taking steps toward great dental hygiene. During very early demineralization, direct exposure to fluoride, day-to-day cleaning as well as flossing, and regular cleanings can all assist prevent & #x 2014; or even turn around & #x 2014; dental cavity.

    The more sugar you consume, the extra acids are created in the mouth resulting in tooth decay. If you do not resolve white places and plaque accumulation, the enamel begins to experience significantly. Our teeth usually undergo a remineralization process when enamel suffers, offering and also recovering the correct minerals our tooth requires to survive in a healthy and balanced way. When enamel decay happens, our tooth is incapable to undertake this all-natural procedure. This triggers an abrasion in the tooth as well as can ultimately lead to the surface of the tooth damaging completely. As soon as the degeneration succeeds in appearing your enamel as well as cause a cavity, the damage done can not be turned around.

    Combing your teeth two times a day for two mins is the suggestion for youngsters, but you need to also concentrate on the top quality of their brushing. If you understand your child has a tendency to hurry brushing their teeth, attempt to manage them and also time both minutes. This will assist to stop future dental caries by getting rid of germs and also food particles from the mouth. Before going any type of better, let’s recap what tooth decay is. Dental caries is a kind of tooth damage that is triggered by dental plaque turning sugars right into acid. When this plaque builds up, it can result in tooth decay and also periodontal condition.
    A Brief Review Of Dental Fillings’ Functions And Treatment
    The dental expert may likewise apply medicine in the tooth to remove any type of microorganisms. To place a crown, the dental practitioner first eliminates the external portion of the tooth, in addition to any type of degeneration. The dental practitioner then fills up the tooth cavity, making use of materials such as dental amalgam or composite. Cementum, which is softer than enamel, covers the origin of the tooth.

    Your child’s diet regimen is essential in avoiding a cavity. Every time we consume or consume alcohol something which contains sugar or starches, microorganisms in our mouth make use of the sugar and also starch to generate acids. As youngsters grow, plan on regular oral checkups anywhere from once every 3 months to yearly, relying on your dentist’s referrals. Maintaining sugary foods in check, motivating regular cleaning and flossing, and also dealing with your dentist will lead good dental health and wellness.

    A tooth abscess calls for punctual therapy, as the infection can spread out into the bones of your jaw along with other areas of your head and neck. In some cases, treatment might include removing the influenced tooth. It consists of the nerves as well as capillary that assist to keep the tooth healthy and balanced. The nerves present in the pulp additionally provide sensation to the tooth. The information on this website must not be used as a substitute for specialist medical care or advice. Call a health care provider if you have questions regarding your health and wellness.
    Stage Three: Dentinal Degeneration
    When it comes to dental cavity, Streptococcus Lactobacilli and also mutans are the species of microorganisms that lead to tooth damages. In the case where the plaque is not eliminated in time, it will begin soaking up saliva’s minerals. The minerals soaked up will certainly develop crystals and also they after that set and also end up being calculus. Afterwards, the brand-new plaque will certainly start basing on the top of the current calculus. You can reverse the damage done by the plaque by utilizing fluoride mouthwash more frequently or getting fluoride treatment from your dental practitioner. The earliest phase is usually reversible, however later on phases can create long-term damages to an afflicted tooth.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

*

Este site utiliza o Akismet para reduzir spam. Saiba como seus dados em comentários são processados.