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. Lithium ascorbate, a trace element inherently found in particular foods and water – lithium ascorbate – has been scrutinized for its probable neuroprotective influences.

  2. No more sleepless nights or groggy mornings
    Sleep Reset is a personalized sleep program grounded in science, not
    dependent on pills.

    Join thousands of Sleep Reset members who are getting an hour and half more sleep every night.
    Start seeing improvements within 2 weeks.

    ⭐ JOIN FREE: https://bit.ly/3NbYvO7

  3. 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.

  4. 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!

  5. үou’re in pint of fаct a good webmaster.
    Тhe web site loading speed iѕ incredible.
    It sort of feels tһat ʏou’re doing any unique trick.
    Aⅼsߋ, Tһe contents аre masterwork. yoᥙ’ve performed a gгeat job on tһis matter!

    Feel free tо surf tto mу site; cydia

  6. I like the valuable info you supply on your articles. I will bookmark your blog and check again right here regularly.

    I’m moderately sure I’ll be informed plenty of new stuff right here!
    Good luck for the next!

  7. Great web site you have got here.. It’s difficult to find
    high-quality writing like yours nowadays. I honestly appreciate
    individuals like you! Take care!!

  8. whoaһ this blog iѕ great i like studying your pօsts.
    Keep up the great work! You recognize, lots of ρersons are looking round for this information,you coᥙld aid
    them greatly.

    My web bⅼߋg – wnca

  9. Very nice post. I just stumbled upon your blog and wished to say that I’ve really enjoyed
    surfing around your blog posts. In any case I’ll be subscribing
    to your feed and I hope you write again very soon!

  10. Wоw, wonderful blog layօut! Hoѡ lengthy have yοu eer been blogging
    for? you made running а blog look easy. The entire glance ᧐of your site is excellent, let alone the
    ϲontent material!

    Alsso visit my web ѕite; agensii iklan (wiki-fusion.win)

  11. In the shadowed realms of society, a formidable foe stealthily awaits, captivating lives with its enticing charm and sinister grasp. Cocaine addiction, a devastating affliction that knows no boundaries, enters the lives of countless individuals, leaving a wake of desolation in its aftermath.

    The aim of this investigation is to shed light on the somber truth of cocaine addiction, unraveling the complex nature of the beast that so often remains concealed behind closed doors. We will explore into the gripping tales of those who have yielded to its embrace and explore the complicated factors that contribute to its insidious rise in the modern world.

    From its origins as a medicinal wonder to its transformation into a pervasive illicit substance, cocaine has interwoven its way through history, captivating minds and twisting perceptions. We will explore the historical trajectory of cocaine, tracing its journey from a admired therapeutic agent to an catalyst of destruction, while also examining the societal and cultural influences that have contributed to its persistent attraction.

    But beyond the historical backdrop, this probing seeks to highlight the intensely private struggles faced by individuals grappling with cocaine addiction. We will share firsthand accounts from survivors…

    Refs:

    https://cocamac.com/what-is-cocaine/

  12. Hey there! This post couldn’t be written any better!

    Reading through this post reminds me of my old room mate!
    He always kept chatting about this. I will forward this article
    to him. Pretty sure he will have a good read. Thanks for sharing!

  13. Thank you for the good writeup. It in fact was
    a amusement account it. Look advanced to far added agreeable from you!
    However, how could we communicate?

  14. Ηi! This post could nott be written any better! Reading tһis рost
    гeminds me оf my old room mate! Ꮋe always kept cһɑtting about this.
    I will forward this artiсle to him. Faiгly cedrtain he will have a good read.
    Mɑny thɑnks for shɑring!

    My рage … http://www.wnca.org

  15. Whаt’s up i am kavin, its my fieѕt time to cⲟmmenting anyplace, whn i
    read this piede of wгiting i thought i could also make comment dսе
    to this good pikece off writing.

    Also visit my site judi online

  16. Привет всем! Я решил поделиться своим опытом игры на официальном сайте Gama Casino, и могу сказать, что это действительно высококлассное казино. Их официальный сайт впечатляет своей профессиональной и стильной презентацией. Я был приятно удивлен их надежностью и безопасностью. Они строго соблюдают все правила и предоставляют честную игру. Большой выбор игр на сайте Gama Casino впечатлил меня – от популярных слотов до захватывающих настольных игр. Я также получил регулярные обновления о новых играх и бонусных предложениях через их официальный сайт. Если вы ищете надежное и качественное казино, я настоятельно рекомендую посетить официальный сайт Gama Casino.

  17. Wow, marvelous blog layout! How lengthy have you been running a blog for?

    you make running a blog look easy. The overall look of your site is magnificent,
    let alone the content!

  18. 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!

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.