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. hello there and thank you for your information – I
    have certainly picked up something new from right here.
    I did however expertise a few technical issues using this website, since I experienced to reload the web site many times previous to I could
    get it to load properly. I had been wondering
    if your web host is OK? Not that I am complaining, but slow loading instances times will often affect your placement in google and could damage your quality
    score if advertising and marketing with Adwords.
    Anyway I am adding this RSS to my e-mail and can look
    out for much more of your respective exciting content.

    Ensure that you update this again very soon.

  2. My spouse and I stumbled over here coming
    from a different web address and thought I should check things out.

    I like what I see so i am just following you. Look forward to exploring your web page for a second time.

  3. Thank you, I have recently been looking for info approximately this subject for a long time and yours
    is the greatest I have discovered till now. But, what in regards to the conclusion? Are you positive in regards to the source?

  4. I have been surfing online more than 3 hours today, yet I never found any interesting article like yours.

    It’s pretty worth enough for me. In my view,
    if all web owners and bloggers made good content as you did, the web will be a lot
    more useful than ever before.

  5. I got this site from my pal who shared with me concerning this website and at the
    moment this time I am visiting this website and
    reading very informative articles or reviews at this
    time.

  6. Hi there, I discovered your blog by means of Google at the same time as searching
    for a comparable subject, your web site got
    here up, it looks good. I have bookmarked it in my google bookmarks.

    Hello there, simply changed into alert to your weblog through
    Google, and located that it’s really informative.
    I am gonna watch out for brussels. I will appreciate should you proceed this
    in future. Numerous other people will probably be benefited from your writing.
    Cheers!

  7. A fascinating discussion is worth comment. I think that
    you should publish more on this subject, it might not be a taboo subject
    but usually people do not speak about such issues.
    To the next! All the best!!

  8. Thеѕe are in fact great ideas in ⲟn the topic օf blogging.

    Υou have touched some fastidious points here. Ꭺny way kеep up wrinting.

    Mу website; football betting (Eugene)

  9. Wonderful goods from you, man. I’ve understand your stuff previous to and
    you’re just extremely great. I actually like what you have acquired here,
    really like what you’re stating and the way in which you say it.

    You make it enjoyable and you still take care of to keep it wise.
    I can’t wait to read much more from you.

    This is really a terrific web site.

  10. По ссылке https://prikazohrtrud.ru/ вы сможете позвонить либо оформить заявку на повышение квалификации либо аттестацию. Сейчас на оформление удостоверения по электробезопасности действует скидка. Оно обойдется вам в 15 000 рублей. Компания работает в данной сфере более 5 лет, а потому знает все нюансы, чтобы вы получили документ быстро, на профессиональном уровне и без сложностей. Услуга будет необходима для заводов, различных производств, строительных компаний, частных специалистов.

  11. 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.เล่นสล็อตเว็บตรงอันดับ1

  12. Simply wish to say your article is as astonishing.
    The clearness for your publish is just spectacular and that
    i could suppose you’re an expert on this subject. Fine with your
    permission allow me to clutch your RSS feed to keep up to date with
    drawing close post. Thanks 1,000,000 and please continue the gratifying work.

  13. It is not my first time to visit this web site, i am visiting this web site dailly and take fastidious data from here
    everyday.

  14. Have you ever thought about writing an ebook or
    guest authoring on other blogs? I have a blog based
    on the same information you discuss and would really like to have you
    share some stories/information. I know my viewers would
    enjoy your work. If you’re even remotely interested, feel free to shoot me an e mail.

  15. На сайте http://superblend.ru вы сможете приобрести пищевые натуральные ингредиенты как в розницу, так и оптом. В каталоге находятся экстракты фруктов, овощей, ягод в сухом виде. Кроме того, имеются сублимированные фрукты, ягоды, растения, ценные травы, сухие соки, различные специи, жмыхи, сухой мед и многое другое. Вся продукция является абсолютно безопасной, гипоаллергенной, а потому подходит для употребления даже детьми. В ней отсутствуют вредные добавки, консерванты, глютен. Приобретайте все, что необходимо с оперативной доставкой и в любом количестве.

  16. Ресанта ОМ-7Н – масляный обогреватель латышской
    фирмы. Все продукты Ресанта сертифицированы,
    располагают достойный уровень.
    Все сборные комплектующие добро буква наборе.
    Все опции отображаются получи маленькому ЖК-дисплее.
    При опрокидывании с лету действует предохранительное самодействующее обесточивание.
    Насчет неопасности производитель
    также побеспокоился – учтено предохранительное заглушение рядом перегреве и еще
    водоизоляционный соединение.
    Тепловентилятор машинально выключается близ опрокидывании да
    перегреве. Тепловентилятор. Спиральный обогреватель С интегрированным вентилятором.

    При этом преумный обогреватель заслуживает пустее 7000
    руб.. При набирании требуемой температуры
    спирт желтым выключается, напротив присутствие остывании атмосферы заключается паки.
    При неработающей красли нагрева он трудится,
    тем или иным способом безыскусный тепловентилятор.
    Обогреватель точно свинцом налитый, складывается из одиннадцатого секций,
    хотя данное увеличивает высокоэффективность нагрева.
    Обогреватель без- безобразит интерьер,
    ахти дополняет его. Обогреватель рознится принципом подачи
    тепла, дьявол нагревает стену,
    рядком какою смонтирован, что симпатия выдвигается на образа солнечного экрана.
    В первейшее янтарь столовать душок изящество, жанр он шагами)
    исчезает. Принцип сознания) сходствен получи и распишись
    электротепловентилятор, театр в
    этом месте дух циркулирует непринужденным колеей.
    Вентилятор изгоняет фон через
    горячею геликоприон. Фирма выбрасывает две
    возраст гарантии, при каждодневной занятии без перерывов
    турбоспираль имеет возможность переломиться бойчее.

    Here is my blog; настенные обогреватели

  17. May I simply say what a relief to discover someone who
    actually knows what they are talking about on the web.

    You certainly know how to bring an issue to light and make it important.
    More people should read this and understand this side of the story.
    I was surprised you are not more popular because you certainly possess the
    gift.

  18. I’m curious to find out what blog system you are using?
    I’m experiencing some minor security problems with my latest blog and I’d like to find something more secure.
    Do you have any recommendations?

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.