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

  1. Greetings I am so delighted I found your blog page, I really
    found you by error, while I was researching on Google for something else,
    Nonetheless I am here now and would just like to say thanks
    for a remarkable post and a all round entertaining blog (I
    also love the theme/design), I don’t have time to look over it all at the moment
    but I have saved it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up
    the great work.

  2. Hi just wanted to give you a quick heads up and let you know a few of the images
    aren’t loading correctly. I’m not sure why but I think its
    a linking issue. I’ve tried it in two different browsers and both show the same results.

  3. Hey there! This post couldn’t be written any better!
    Reading through this post reminds me of my good old room mate!
    He always kept chatting about this. I will forward this
    article to him. Fairly certain he will have a good read.
    Many thanks for sharing!

  4. With havin so much written content do you ever run into any problems
    of plagorism or copyright violation? My website has a lot of completely unique content I’ve either written myself or outsourced
    but it appears a lot of it is popping it up all over the web without
    my agreement. Do you know any techniques to help prevent content from being stolen? I’d
    certainly appreciate it.

  5. naturally like your web-site however you need to check the
    spelling on several of your posts. Many of them are rife with spelling issues
    and I find it very troublesome to inform the truth nevertheless I’ll certainly come
    back again.

  6. I have to thank you for the efforts you’ve put in writing this site.
    I really hope to check out the same high-grade content from you in the future as well.
    In fact, your creative writing abilities has motivated me to get my own website now 😉

  7. I’d like to thank you for the efforts you have put in penning this blog.
    I really hope to check out the same high-grade content from you later on as well.
    In fact, your creative writing abilities has encouraged me to get
    my own site now 😉

  8. Thanks for your personal marvelous posting! I genuinely
    enjoyed reading it, you can be a great author.
    I will make certain to bookmark your blog and definitely will come back at some point.
    I want to encourage you to definitely continue your great writing, have a
    nice afternoon!

  9. Appreciating the time and energy you put into your website and in depth information you provide.
    It’s nice to come across a blog every once in a while that isn’t the same unwanted rehashed information. Wonderful read!
    I’ve saved your site and I’m including your RSS feeds to
    my Google account.

    Also visit my homepage … https://usascripthelpers.com/

  10. Everything is very open with a very clear description of the challenges.

    It was truly informative. Your website is useful. Many thanks for sharing!

  11. Hmm it seems like your site ate my first comment (it was super long) so I guess
    I’ll just sum it up what I submitted and say, I’m thoroughly
    enjoying your blog. I as well am an aspiring blog writer but I’m
    still new to the whole thing. Do you have any
    tips and hints for first-time blog writers? I’d genuinely appreciate it.

  12. naturally like your web-site but you need to terst the
    spelling on quite a few oof your posts. Many oof themm
    aare rie wigh spelling issues and I find it very
    troublesome too inform the reality however I’ll
    surely come baxk again.

  13. Hi, I do believe this is a great site. I stumbledupon it
    😉 I will revisit once again since I saved as a favorite it.
    Money and freedom is the best way to change, may you be rich and continue to guide others.

  14. Hello! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing months of hard work due
    to no backup. Do you have any methods to protect against hackers?

  15. OMG! This is amazing. Ireally appreciate it~ May I give
    my hidden information on a secret only I KNOW and if you want to seriously get to hear You really have
    to believe mme and have faith and I will show how to become a millionaire Once
    again I want to show my appreciation and may all
    the blessing goes to you now!.

  16. Aw, this was an extremely nice post. Taking the time and actual effort to create a
    good article… but what can I say… I procrastinate a lot
    and never manage to get nearly anything done.

  17. Thank you, I have recently been searching for information approximately this subject for ages and yours is the
    greatest I’ve found out till now. However, what
    concerning the bottom line? Are you positive in regards to the source?

  18. You’ve made some decent points there. I looked on the net for more information about the issue and found most individuals will go along with your
    views on this website.

  19. This design is wicked! You definitely know how to keep a reader amused.
    Between your wit and your videos, I was almost
    moved to start my own blog (well, almost…HaHa!)
    Great job. I really loved what you had to say, and
    more than that, how you presented it. Too cool!

  20. hey there and thank you for your info – I’ve definitely picked up something new from right here.

    I did however expertise several technical points using this web site, since I
    experienced to reload the website lots of times previous to I could get it to load properly.
    I had been wondering if your hosting is OK?
    Not that I am complaining, but sluggish loading instances times will very frequently
    affect your placement in google and could damage your quality score if
    advertising and marketing with Adwords.
    Anyway I’m adding this RSS to my e-mail and can look out for much more of your respective fascinating content.

    Ensure that you update this again very soon.

  21. This design is incredible! You definitely know how to keep a reader entertained.
    Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful
    job. I really loved what you had to say, and more than that, how you presented it.

    Too cool!

  22. I got this site from my pal who shared with me on the topic of this web site and now this time
    I am browsing this site and reading very informative
    posts at this time.

  23. Heya! I know this is kind of off-topic however I needed to ask.
    Does operating a well-established website like yours require a lot of
    work? I’m brand new to operating a blog but I do write in my diary on a daily basis.
    I’d like to start a blog so I can share my own experience and feelings online.

    Please let me know if you have any kind of suggestions or tips for brand
    new aspiring bloggers. Thankyou!

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.