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.428 Comments on “Eclipse – Formatter e Save Action

  1. Wow that was odd. I just wrote an really long comment but
    after I clicked submit my comment didn’t show up. Grrrr…

    well I’m not writing all that over again. Anyhow, just wanted to say
    fantastic blog!

  2. Just want to say your article is as astonishing. The clearness in your put up is just spectacular
    and i could think you’re a professional in this subject.
    Fine along with your permission let me to snatch
    your RSS feed to stay updated with approaching post.
    Thanks one million and please carry on the rewarding work.

  3. Вы ищете доступное и надежное решение для кондиционирования воздуха? Обратите внимание на компанию «Техолод». Они предлагают широкий ассортимент колонных кондиционеров по непревзойденным ценам.
    Колонные кондиционеры — это отличный способ обеспечить прохладу в доме или офисе без лишних затрат. Их элегантный дизайн делает их идеальными для любого помещения, а их энергоэффективность гарантирует, что вам не придется беспокоиться о высоких счетах за электричество. Кроме того, благодаря простоте установки и низким требованиям к обслуживанию, они являются идеальным выбором для тех, кто хочет обновить свою систему охлаждения, не тратя при этом слишком много денег: канальная сплит система. В компании Теххолод понимают, что бывает трудно найти подходящий вариант кондиционера по оптимальной цене. Именно поэтому они предлагают такие конкурентоспособные цены на свои колонные кондиционеры — чтобы каждый мог наслаждаться преимуществами качественного охлаждения, не беспокоясь о стоимости.

  4. Decrease to world, Chandigarh, woman escorts might be helping you and also attempting to keep
    you active in a spectacular way. We may keep our bookings
    on time, we are accepting less bookings attributable to safety.
    You’re safe when you take our escorts providers in Chandigarh.
    If you’d like thrilling expertise then contact us for Call Girls in Chandigarh .
    Therefore, If you are in seek for younger and intelligent with
    sizzling Hot Independent Call Girls in Chandigarh then we are
    all pleased to introduce to you meet your all pleasurable and special
    fun session o you that you simply are looking to have fun on demand.
    You may discover the photographs are blurred, however when you show
    your interest for hiring an escort, the escort service
    provider in Chandigarh will furnish you the photographs of the escorts.
    If you feel that the lady is suitable, you’ll be able to proceed or ask the
    service supplier to connect you with another damsel.
    Hello I am ANANDJOT I’m from Chandigarh Escorts Services nonetheless I
    am getting married however I’m very hot and sexy married lady who are very younger
    my age is twenty six and determine could be very lusty and
    seductive.

  5. Zenith Immigration is the pioneer Canada immigration regulation agency that strives to help qualified professionals
    to attain their dream to migrate to Canada and receive Canadian Permanent Residency.
    At present Zenith Immigration stands out and stands tall in the field of immigration legal services
    in Sri Lanka through the results brought about to the
    shoppers which have significantly contributed towards creating a global Sri Lankan id.
    Legislation Center online as we speak. Immigration Legislation Affiliation: A student
    run group for these excited about training immigration and studying more about immigration law and policy.

    Yes. Whether you might be looking for a everlasting visa, momentary visa, or student visa, we’re here to assist make the method simpler for you.

    We are a good immigration company based mostly in Ludhiana, Punjab,
    which primarily work in scholar visa, work visa, PR, and so on. Immigration Marketing consultant Ludhiana experts have continually been offering the
    standard and reliable counseling to people in search of steerage and
    help for visa matters or immigration companies.

  6. ทางเรา mothervaper ยังมี ผลิตภัณฑ์ บุหรี่ไฟฟ้า Pod System อื่นๆ ที่กำลังจะนำเข้ามา ให้ผู้ใช้ได้เลือกใช้อีกด้วย ไม่ว่าจะเป็น Infy Pod , Vmc Pod ,
    Relx Bubble Mon , Coga และอื่นๆ อีกมากมาย โดย น้ำยาบุหรี่ไฟฟ้า
    หรือ บุหรี่ไฟฟ้า พอตใช้แล้วทิ้ง ทุกรุ่น ล้วนแล้วแต่มี ราคาถูก แต่ให้คุณภาพที่ดีเยี่ยมทั้งนั้น อีกทั้งยังเป็นรุ่นยอดนิยมอีกด้วย

  7. Magnificent goods from you, man. I have understand your stuff previous to and you are simply too wonderful.
    I really like what you have acquired here, certainly like what you are stating and the way in which you assert it.
    You make it entertaining and you still take care of to
    stay it wise. I cant wait to learn much more from you.
    This is really a tremendous site.

  8. I don’t even understand how I ended up here, however I assumed
    this submit was once good. I do not recognize who you’re
    however definitely you are going to a well-known blogger for
    those who aren’t already. Cheers!

  9. I’m really loving the theme/design of your web site. Do you ever run into any browser compatibility problems?
    A handful of my blog audience have complained about my blog not operating correctly in Explorer but looks great
    in Opera. Do you have any suggestions to help fix this problem?

    Visit my page … stars77 slot login

  10. First of all I would like to say superb blog! I had a quick question which I’d like to ask if
    you do not mind. I was interested to know how you center yourself and clear your mind before writing.
    I’ve had difficulty clearing my thoughts in getting
    my thoughts out. I truly do take pleasure in writing however it just seems like
    the first 10 to 15 minutes are wasted just trying to figure out how
    to begin. Any recommendations or tips? Many thanks!

Deixe um comentário

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

*

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.