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

  1. When I initially left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and from
    now on whenever a comment is added I receive 4 emails with the same comment.
    Is there a way you are able to remove me from that service?
    Appreciate it!

  2. Quality articles or reviews is the main to invite the users to pay a visit the web page,
    that’s what this web page is providing.

  3. Pretty section of content. I just stumbled upon your blog
    and in accession capital to assert that I acquire actually
    enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access
    consistently fast.

  4. Hello there, I discovered your site by way of Google whilst searching for a comparable topic, your web site came up, it appears to
    be like good. I’ve bookmarked it in my google
    bookmarks.
    Hello there, simply became alert to your blog thru Google, and
    located that it is truly informative. I am gonna watch out for
    brussels. I’ll be grateful in the event you proceed this in future.
    Numerous people will be benefited out of your writing. Cheers!

  5. This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want?HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great!

  6. Awesome website you have here but I was wanting to know if you knew of any community forums that cover the same topics talked about in this article?
    I’d really love to be a part of online community
    where I can get feedback from other knowledgeable people that share the same interest.
    If you have any recommendations, please let me know.
    Appreciate it!

  7. Having read this I believed it was extremely enlightening.
    I appreciate you spending some time and effort to put this short article together.
    I once again find myself spending way too much time both reading and commenting.
    But so what, it was still worthwhile!

  8. Greetings! This is my 1st comment here so I just wanted to give a quick shout
    out and tell you I really enjoy reading your posts.
    Can you recommend any other blogs/websites/forums that go over the same topics?
    Thanks for your time!

  9. Hey I amm so grateful I founnd yoir webpage, I rerally
    found youu by mistake,while I was looking oon Bing ffor sometjing else, Nonetheless I aam hede noow and would
    jst lioke too say mamy tthanks ffor a marvelous
    post and a all round enjoyable blog (I alsso ove the theme/design), I don’t havee
    time to look ovfer itt all at the moment butt I have book-marked it and
    alsso added in your RSS feeds, so when Ihave time I will be back tto read much more, Pleasde
    doo ksep up the excellent jo.

  10. Hi! I just wanted to ask if you ever have any issues with hackers?
    My last blog (wordpress) was hacked and I ended up losing a
    few months of hard work due to no backup. Do you have any methods to stop hackers?

  11. Hello! I realize this is somewhat off-topic but I needed to ask.
    Does operating a well-established website such as yours require a large amount of work?
    I am brand new to blogging however I do write in my diary on a daily basis.
    I’d like to start a blog so I can easily share my experience and thoughts online.
    Please let me know if you have any suggestions or tips for
    new aspiring blog owners. Thankyou!

    Feel free to surf to my web-site … Haparchive

  12. First off I would like to say terrific blog! I had a quick question that I’d like to
    ask if you don’t mind. I was curious to find out how you center yourself and clear your thoughts before writing.
    I’ve had a tough time clearing my thoughts in getting my thoughts out.

    I do enjoy writing however it just seems like the first 10 to 15 minutes
    are usually lost simply just trying to figure out how to begin. Any recommendations or hints?
    Thanks!

  13. This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want?HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great!

  14. OMG! This is amazing. Ireally appreciate it~
    May I give true love to a secret only I KNOW and if you want
    to have a checkout You really have to believe mme and have faith and I will show how to
    change your life Once again I want to show my appreciation and may all the blessing goes to you now!.

  15. I have been surfing online more than 3 hours today, yet I never found
    any interesting article like yours. It is pretty worth enough for me.
    In my opinion, if all webmasters and bloggers made good content as you did,
    the net will be much more useful than ever before.

  16. Hi this is kind of of off topic but I was wondering if blogs use WYSIWYG editors
    or if you have to manually code with HTML. I’m starting a blog soon but
    have no coding skills so I wanted to get advice from someone with
    experience. Any help would be enormously appreciated!

  17. Hi there! I could have sworn I’ve been to this website before
    but after browsing through some of the posts I realized it’s new to me.
    Nonetheless, I’m certainly happy I came across it and I’ll be book-marking it and
    checking back frequently!

  18. Very good blog you have here but I was curious if you knew of any community forums that cover the same topics discussed here?
    I’d really love to be a part of group where I can get comments from
    other experienced individuals that share the same interest.
    If you have any suggestions, please let me know. Many thanks!

  19. Hey! I know this is kind of off topic but I was wondering if you knew where I could find a captcha plugin for my
    comment form? I’m using the same blog platform as yours and
    I’m having problems finding one? Thanks a lot!

  20. Hey there would you mind letting me know which web
    host you’re using? I’ve loaded your blog in 3 completely different internet browsers and I must say this blog loads a lot
    faster then most. Can you recommend a good hosting provider at a
    reasonable price? Cheers, I appreciate it!

    Feel free to surf to my web site :: shop-kt.net

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.