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

  1. Do you have a spam problem on this website; I also
    am a blogger, and I was wanting to know your situation;
    many of us have developed some nice practices and we are looking
    to exchange methods with others, please shoot me an e-mail if interested.

  2. Hey there, You’ve done an incredible job. I’ll definitely ddigg it aand personally suuggest to myy friends.
    I’m confident they’ll be benefited from
    thijs website.

  3. When I initially commented I seem to have clicked the -Notify me when new comments are
    added- checkbox and from now on every time a comment is added I get four
    emails with the exact same comment. There has to be a means you are able to
    remove me from that service? Thanks!

  4. Сайт https://dom-plenki.ru/ представляет собой подробный справочник, на котором находятся компании, которые продают упаковочный материал, а также тару в огромном ассортименте. Предприятия отсортированы по городам, районам. Для того чтобы подобрать подходящий вариант, необходимо изучить телефон, адрес, а также карту проезда. Все это поможет принять правильное решение. При необходимости вы можете оставить комментарий, написать отзывы, чтобы другой человек оперативно сориентировался.

  5. Heya i am for the primary time here. I came across this board and
    I find It really useful & it helped me out much. I hope
    to present one thing back and aid others such as you aided me.

  6. I believe people who wrote this needs true loving because it’s a blessing.
    So let me give back and tell you exactly how to do change your life and if you want to
    seriously get to hear I will share info about how to find hot girls for free Don’t forget..
    I am always here for yall. Bless yall!

  7. Hello,
    This is a nice site!
    May I scrape your post and share this with my channel subscribers?

    Check out my site! It’s about Korean 먹튀검증
    If ever you are interested, feel free to come to my site and
    check it out.
    Thanks a lot and Continue with the good work!

  8. You really make it appear so easy along with your presentation but I find this
    matter to be actually something which I think I would by
    no means understand. It seems too complicated and very large for me.

    I’m taking a look ahead for your subsequent
    publish, I will try to get the cling of it!

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

  10. When I originally commented I seem to have clicked the -Notify me when new
    comments are added- checkbox and now whenever a comment is added I recieve 4 emails with the same comment.
    Perhaps there is an easy method you are able to remove me
    from that service? Kudos!

    My site: 2001 bmw 330ci

  11. Поэтому в толпа из ТОП-десять изображу клубы маленький неповторимыми играми – лотереи,
    госмонополия, сик ну, ругай. Поэтому бережливо разбирайте дела получения (а) также в соответствии с отыгрышу.

    Условия не отыгрышу сообразуются
    наиболее высокопоставленными. Более такого,
    амба воротить вейджер и уродится повыводить
    навар. Более того, игровые автоматы быть
    разными сюжетными установками, анимацией,
    лишними ватерпасами и еще
    внутриигровыми бонусами.

    Вас ожидают легендарные игровые автоматы с оригинальными опциями, внутриигровыми скидками.

    Лицензионные игровые платформы сотрудничают вместе
    с всяческими платёжными сервисами.
    Внимательно ознакомьтесь вместе с законами, недорогими платёжными инструментами а также лимитами нате депозиты также
    выплаты. Возможность скалькировать
    прирост быть наименьших комиссиях.
    Всё потому, что потребуется учесть многообразные аспекты, влияющие получи и распишись подлинный случай показать шлем.
    Всё потому, что отбренчать вейджер х20 предостаточно не составляющий ни малейшего труда, а вот х80
    навряд ли прокрутят ажно стреляные гэмблеры.
    подходящий, на нашем ТОП-десять casino изображу едва лишь
    клубы мало энергичными лицензиями также
    сертификатами контролей через свободных лабораторий.
    Вот фигли спесиво делать выбор кодло из
    испытанного ТОП-10.

    Feel free to visit my web site – лучшие казино 2022

  12. It’s actually very difficult in this full of activity life to listen news on Television, thus
    I only use internet for that purpose, and take the hottest news.

  13. Hi there! This is my first comment here so I just wanted to give a quick shout out and say
    I truly enjoy reading your blog posts. Can you suggest any
    other blogs/websites/forums that go over the
    same subjects? Appreciate it!

  14. Recent flowers are not just a good way of expressing ones self
    but they depart very optimistic impacts on ones health. The prices of the freshly cut flowers aren’t very high and
    there are very few people who know methods to handle
    different things in order that they’ll wish their cherished one sin a pleasant means on New Yr.
    Husbands send their wives such things when they’re away on enterprise journeys.
    Recent roses are lovely and if they are packed in a styled
    approach and presented in a nice means it adds to their
    magnificence. Flowers are a love in each season,
    folks love flowers and they’re used to precise all kind of feelings in every means.
    There are many people who’ve been ready for
    the winter season because then it is lovely to purchase or reward flowers as they remain fresh for an extended time frame.

    Also visit my blog: https://flowershopn5.com/collections/new-baby

  15. Undeniably believe that which you said. Your favorite reason seemed to be on the web the simplest thing to be aware of.
    I say to you, I certainly get annoyed while people think about worries that they just do
    not know about. You managed to hit the nail upon the top
    and defined out the whole thing without having side effect , people can take a signal.
    Will probably be back to get more. Thanks

  16. I do agree with all of the concepts you have introduced in your post.
    They’re very convincing and will certainly work. Still, the
    posts are very quick for beginners. May you please prolong them a little from subsequent time?
    Thanks for the post.

  17. Hi there, just became aware of your blog through Google, and found
    that it’s truly informative. I’m going to watch out for brussels.
    I will appreciate if you continue this in future.
    Many people will be benefited from your writing.
    Cheers!

  18. I like what you guys are usually up too. This kind of clever work and coverage!
    Keep up the very good works guys I’ve incorporated you guys to blogroll.

  19. Переходя на сайт https://bezdep-master.ru/ вы сможете получить бездепозитные бонусы за регистрацию. Casino бездепозитный бонус работает всегда, с возможностью вывода. Бездепозитные бонусы для топовых казино, таких как вавада, play fortuna, rox, джойказино, win. Плюсом вы можете получить бесплатные фриспины по промокоду на сайте.

  20. We’re a grup of volunteers and opening a new scheme inn our community.
    Your site offered us with valuable info to work on. Youu havbe done
    a formidable job and our whle community will be grateful to
    you.

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.