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. King855 Online Casino Singapore Crowns Lucky Winner with Unimaginable
    Riches!

    Are you ready to hear about the biggest online casino win in Singapore?
    Grit your teeth, because King855 Online Casino has just crowned a lucky winner with
    unimaginable riches! This is not just any ordinary win, but a life-changing one which will leave you
    in awe. The winner, who wishes to remain anonymous, won an impressive SGD 10 million jackpot on the favorite slot game Mega
    Moolah.

    The news of this incredible win has sent shockwaves throughout the online casino community in Singapore.
    It isn’t each day that someone wins such a large amount of money, in fact it is
    even rarer for this to occur at an online casino.
    This win has proven that online casinos are just as capable of producing big winners as
    their land-based counterparts.

    The Mega Moolah slot game is known because of its massive jackpots, and
    contains been responsible for some of the biggest online casino wins in history.
    The game features four progressive jackpots, with the Mega Jackpot being the
    biggest. To win the Mega Jackpot, players must
    trigger the game’s bonus round, where they spin a wheel to find out
    which jackpot they’ll win. The lucky winner at King855 Online Casino were able
    to hit the Mega Jackpot, which had been steadily growing for months.

    The winner was understandably overjoyed if they heard bout their win. They said
    that they had been playing at King855 Online Casino for a couple months and had always enjoyed playing Mega Moolah.
    They never expected to win such a large amount
    of money and were still in shock when they received the news.

    The CEO of King855 Online Casino was also thrilled concerning the win. He said that it was always
    exciting to see players win big at their casino and that they were proud to have produced this type
    of massive jackpot winner. He also mentioned that King855 Online Casino
    takes responsible gambling seriously and encourages players to gamble responsibly.

    This win has put King855 Online Casino on the map among the top online casinos in Singapore.

    It shows that they offer fair games with big payouts and that players
    can trust them with their money. The casino
    supplies a wide variety of games, including slots,
    table games, and live dealer games, so there’s something for everyone.

    If you are feeling lucky and desire to try your hand at winning
    big just like the lucky winner at King855 Online Casino,
    then head to their website and start playing today! Who knows,
    you could be another big winner!

    Also visit my website live casino king855 games singapore

  2. My brother suggested I would possibly like this blog.
    He was entirely right. This put up actually made my day.
    You cann’t believe just how a lot time I had spent for this information! Thanks!

  3. Nice post. I learn something new and challenging on websites
    I stumbleupon everyday. It’s always useful to read through articles from other
    writers and practice something from their websites.

    my page – new dvd movies

  4. Thanks a lot for sharing this with all folks you actually recognize
    what you are talking approximately! Bookmarked. Kindly additionally seek advice from my web site =).
    We could have a hyperlink change contract
    among us

  5. This is the perfect webpage for anybody who really wants to
    understand this topic. You realize so much its almost hard to argue with you (not that I actually would want to…HaHa).
    You certainly put a fresh spin on a subject that has been discussed
    for many years. Great stuff, just great!

  6. На сайте https://adventuresinminecraft.com/home вы сможете погрузиться в удивительный мир Minecraft. Обязательно посетите магазин, в котором вы найдете все, что нужно для активной, яркой и необычной игры. Оформите покупку всего того, чтобы получить новые возможности прямо сейчас. И самое главное, что покупка обойдется вам недорого. Мгновенная оплата наиболее комфортным для вас способом. После того, как сумма поступит на счет, на почту придет оповещение. Есть раздел с последними покупками.

  7. I do consider all the ideas you have offered to your post.

    They are very convincing and will definitely work. Still,
    the posts are very quick for beginners. Could you please lengthen them a little from subsequent time?
    Thanks for the post.

  8. Does your website have a contact page? I’m having trouble locating it but, I’d like to shoot you an email.
    I’ve got some ideas for your blog you might be
    interested in hearing. Either way, great website and I
    look forward to seeing it expand over time.

    Here is my web blog: dvd distribution

  9. Hi there, i read your blog from time to time and i own a similar one and i was just wondering if you get
    a lot of spam feedback? If so how do you protect against it, any plugin or anything you can advise?
    I get so much lately it’s driving me insane so
    any assistance is very much appreciated.

    Stop by my web site; discount dvd warehouse

  10. Ɗoes your website һave a contact page? I’m havinjg trouble l᧐cating it but, I’d liuke to send you aan e-mail.
    I’ᴠe gօt some suggestions for your blog you might be іnteresteԀ in hearing.
    Either way, ցreat webѕite and I ⅼook forward to seeing it develop over time.

    mү homepage … chính hãng thương hiệu Malanaz. Túi xách nữ đeo chéo Malanaz phù hợp với mọi phong cách thời trang công sở

  11. I do not even know how I ended up right here, but I believed this post was great.
    I don’t realize who you might be however definitely you’re going to a famous blogger if you aren’t already.
    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.