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. An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!

  2. Great goods from you, man. I have understand your stuff previous to
    and you’re just too excellent. I actually like what you have acquired here, certainly
    like what you are saying and the way in which you say it. You make
    it enjoyable and you still care for to keep it wise.
    I can’t wait to read much more from you. This is really a terrific site.

  3. На сайте https://www.globussalon.ru вы сможете приобрести все, что необходимо для очистки пруда, аэраторы, а также пленку для пруда, нассы для фильтров, ручьи, изливы, подводную подсветку и многое другое. Кроме того, имеются интерьерные и садовые фонтаны. Только на этом сайте самый большой ассортимент того, что вам необходимо для организации пространства. Вся продукция высокого качества, надежная, а потому прослужит очень долго. Выбирайте и заказывайте все, что вам необходимо. Все товары продаются по доступным ценам.

  4. На сайте https://www.krasser.ru/met_izdel.html закажите производство металлоизделий, а также конструкций, выполненных из металла, баки, емкости и многое другое. Для того чтобы сориентироваться в выборе, воспользуйтесь прайс-листом, где указаны все расценки. Работы выполняются в соответствии с ГОСТом и строго по техническому заданию, эскизам, чертежам. Стоимость проекта будет зависеть от его сложности и масштаба. Воспользуйтесь и вы услугами популярной компании, которая предлагает весь комплекс работ, соблюдает сроки.

  5. I’ll immediately take hold of your rss as I can not to find your e-mail subscription hyperlink or newsletter
    service. Do you’ve any? Please let me recognize so that I may just subscribe.
    Thanks.

  6. I have been exploring for a little bit for any
    high quality articles or weblog posts in this
    sort of area . Exploring in Yahoo I eventually
    stumbled upon this site. Reading this info So i’m satisfied to exhibit that I’ve a
    very just right uncanny feeling I discovered just
    what I needed. I so much undoubtedly will make certain to don?t omit this web site and provides it a look on a
    relentless basis.

  7. This excellent website definitely has all of the information I needed about this subject
    and didn’t know who to ask.

  8. Great post howevеr I was wanting to know if уou could write a litte mоre on this
    subјect? I’d be ery grateful if you could elɑboratе a little bit further.
    Many thanks!

    Feel fгee to visit mmy blog; slot online

  9. На сайте https://kamaz97.ru/ вы сможете получить всю необходимую информацию, которая касается КАМАЗов. Так вы узнаете о самых успешных проектах, о том, почему именно эти громоздкие машины входят в список самых надежных, практичных и добротных. Есть данные и про сцепление на грузовиках, имеется информация про панель евро: о преимуществах и характеристиках. Опубликован материал о передних подшипниках и причинах их поломки, о том, как произвести замену, а также обслуживание. Так вы узнаете о том, как заменить некоторые детали.

  10. After study a few of the blog posts on your website now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and will be checking back soon. Pls check out my web site as well and let me know what you think.

  11. This is the right blog for anyone who hopes to find out about this topic.

    You realize so much its almost tough to argue with you (not that I really will need to…HaHa).
    You definitely put a new spin on a subject that has been written about
    for decades. Great stuff, just great!

  12. certainly like your website but you have to take a look
    at the spelling on several of your posts. Several of them are rife with spelling issues and I in finding it very troublesome to inform the reality then again I will
    definitely come back again.

  13. Can I simply just say what a comfort to discover a person that
    genuinely knows what they are talking about on the internet.
    You certainly know how to bring an issue to light and make it important.

    A lot more people really need to check this out and understand this side of your story.
    It’s surprising you aren’t more popular because you
    definitely have the gift.

  14. whoah this weblog is magnificent i love studying your articles.
    Keep up the great work! You already know, lots of individuals are hunting around for this information, you could
    aid them greatly.

  15. ⭐ GET UP TO 1000$ BONUS ON STAKE.COM ⭐
    ✅ Open account and deposit at least 50$
    ✅ Go to Settings > Offer > Input “NEWBONUS”
    code
    ✅ Enjoy HUGE bonuses from STAKE.COM

    URL: https://bit.ly/43oZGPU
    ⭐ GET UP TO 1000$ BONUS ON STAKE.COM ⭐

  16. Thank you a lot for sharing this with all of us you realky know what you are talking approximately!
    Bookmarked. Kindly also discuss with my web site =).
    We may have a link change arrangement among us!

    my webpage – military entrance exam, Jeannette,

  17. You’re so cool! I don’t suppose I’ve truly read through something like that before.
    So great to find another person with some unique thoughts on this subject matter.
    Really.. thanks for starting this up. This web site
    is one thing that is needed on the web,
    someone with a bit of originality!

  18. Great blog! Is your theme custom made or did you download it from somewhere?

    A design like yours with a few simple adjustements would really make my
    blog jump out. Please let me know where you got
    your theme. Many thanks

  19. Greetings from Colorado! I’m bored to death at work so I decided to check out your blog on my iphone during lunch break.
    I enjoy the knowledge you present here and can’t wait to take a look
    when I get home. I’m amazed at how quick your blog loaded on my cell phone ..

    I’m not even using WIFI, just 3G .. Anyhow, wonderful blog!

  20. ⭐ FREE APP LIMITED TIME⭐
    The Dropshipping Business Made Easy for Retailers with E-Commerce Stores!

    Meet TopDawg: Top Products to Sell Online for Your Dropshipping
    Business
    ✅ Setup e-commerce site in seconds
    ✅ Connect TopDawg with your Store
    ✅ Select from over 500,000 products to add to your store.

    ✅ Products sell and our dropship suppliers
    fulfill the orders.

    TopDawg FOR FREE For a Limited Time!
    LINK: https://bit.ly/43JfL2x
    FREE CODE: DEBF23
    ⭐ FREE APP LIMITED TIME⭐

  21. Woah! I’m really enjoying the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s very difficult to get that
    “perfect balance” between user friendliness and appearance.

    I must say that you’ve done a awesome job with this.
    Additionally, the blog loads very fast for
    me on Firefox. Exceptional Blog!

  22. Nice post. I learn something totally new and challenging on websites I stumbleupon every day.

    It will always be interesting to read content from other authors
    and use a little something from their web sites.

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.