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. It’s in reality a great and useful piece of information. I
    am satisfied that you just shared this helpful info
    with us. Please stay us informed like this. Thanks for sharing.

  2. На сайте https://lovely-professional.ru вы сможете приобрести составы для ламинирования ресниц, а также краску для бровей, ресниц и различную другую продукцию, которая поможет сделать взгляд более выразительным и роскошным. На портале также имеются и различные расходные материалы, а также сопутствующая атрибутика, которая потребуется для создания привлекательного образа. И самое главное, что вся продукция качественная, сертифицированная, не вызывает аллергии. Регулярно на портале появляются новинки, которые понравятся и вам.

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

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

  5. Today, I went to the beach front with my children. I found a sea shell and gave it to my
    4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed
    the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is entirely off
    topic but I had to tell someone!

  6. На сайте https://buckshee.net/ вы сможете почитать всю интересную и любопытную информацию, новости со всего мира, которые касаются политики, экономики. Есть раздел «Фитнес качалка», а также мужской, женский форумы, туристический форум, на котором вы сможете найти единомышленников, пообщаться и обсудить важные темы. Также имеются и видеоматериалы хорошего качества. Ознакомьтесь с ними сейчас. Вверху страницы опубликован курс валют. А прямо перед вами лента тех новостей, которые произошли буквально сегодня, несколько дней назад.

  7. Thank you for the auspicious writeup. It in fact used to
    be a leisure account it. Glance complex to more added agreeable from you!
    However, how could we be in contact?

  8. На сайте https://studio-mint.com.kg/ закажите обратный звонок для того, чтобы воспользоваться разработкой дизайн-проекта при помощи компетентных, квалифицированных специалистов, которые отличаются огромным опытом, а потому они учтут ваши пожелания, предпочтения и различные нюансы. Все работы выполняются под ключ. В компании выполнят дизайн коттеджей, квартир, фасадов, коммерческих интерьеров. Для того чтобы лучше ознакомиться с услугами, изучите портфолио, где представлены работы за различный период. Также есть статьи в блоге. Почитайте их сейчас.

  9. My spouse and I stumbled over here by a different web address and thought I might check things out.
    I like what I see so now i am following you.
    Look forward to looking over your web page repeatedly.

  10. It’s truly very complex in this active life to listen news on Television, thus I just use web for that reason, and
    obtain the latest news.

  11. I believe this is one of the so much vital info
    for me. And i’m happy reading your article.
    However wanna observation on some basic things, The website style is ideal, the
    articles is in reality excellent : D. Good activity, cheers

  12. You’ve made some really good points there. I looked on the internet to
    find out more about the issue and found most individuals
    will go along with your views on this website.

  13. Hello! I’m at work browsing your blog from my new apple iphone!

    Just wanted to say I love reading your blog and look forward
    to all your posts! Keep up the excellent work!

  14. Hmm it looks like your site ate my first comment (it was
    extremely long) so I guess I’ll just sum it up what I had written 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 recommendations for novice
    blog writers? I’d genuinely appreciate it.

  15. you are truly a just right webmaster. The website loading velocity is amazing.

    It kind of feels that you are doing any unique trick. Furthermore, The
    contents are masterpiece. you’ve done a magnificent job on this subject!

  16. I’m not that much of a internet reader to be honest but your blogs
    really nice, keep it up! I’ll go ahead and bookmark your site to come
    back in the future. All the best

  17. Admiring the hard work you put into your website and detailed information you provide.
    It’s nice to come across a blog every once in a while that isn’t the same unwanted
    rehashed material. Great read! I’ve saved your site and I’m adding
    your RSS feeds to my Google account.

  18. Howdy would you mind letting me know which webhost you’re working with?
    I’ve loaded your blog in 3 completely different web browsers
    and I must say this blog loads a lot faster then most.
    Can you recommend a good internet hosting provider at a honest
    price? Kudos, I appreciate it!

  19. Hi there, just became aware of your blog through Google, and found that it is truly informative.
    I’m gonna watch out for brussels. I will be grateful if you
    continue this in future. Lots of people will be benefited from your writing.

    Cheers!

  20. First of all I would like tto say wonderful blog! I had a quick
    quuestion that I’d like tto ask if yyou do not mind.

    I was interested to find outt how you center yourself and clear your mind prior to
    writing. I’ve had difficulty clearing mmy thoughts in getting myy ideas out there.
    I do enjoy writing but it just seems like the firet 10 to 15 minutes
    tend to be lost just trying to figure out how to begin. Anny recommendations or tips?
    Appreciate it!

    My web-site total gym 1500 parts diagram (Rex)

  21. Hello my friend! I wish to say that this article is amazing,
    great written and come with almost all important infos.

    I would like to see more posts like this .

  22. First of all I would like to say superb blog! I had a quick question in which I’d
    like to ask if you do not mind. I was interested to find out how you center yourself and clear your mind before writing.
    I have had a hard time clearing my thoughts in getting my ideas
    out there. I do enjoy writing but it just seems like
    the first 10 to 15 minutes tend to be lost simply just trying to figure out how
    to begin. Any recommendations or hints? Cheers!

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.