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. Great goods from you, man. I’ve understand your stuff previous
    to and you are just extremely magnificent. I actually
    like what you’ve acquired here, really like what you’re saying and thee way in which yoou say
    it. You make it entertaining and you still take care of
    to keep it smart. I cant wait to read far more from you.

    This is really a terrific site.

    my web page – asvab test (http://everything.explained.today/Capel_Manor_College/)

  2. 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.

  3. Slot Pulsa Deposit Termurah Hanya 10Rb Saja Terpercaya
    Apakah penyebab situs judi slot deposit pulsa tanpa potongan makin merebak disegala penjuru pencarian di internet?
    selama ini, metode dalam bermain Slot Online deposit pulsa
    merupakan pilihan yang banyak digunakan oleh para slotter mania di Indonesia karena menghadirkan deposit pulsa dengan minimal
    deposit 10 ribu tanpa potongan.

    Dikarenakan situs judi slot terbaik nyatanya akan memberikan bonus pulsa bagi yang bermain lewat
    slot via deposit pulsa loh. Bermain slot dengan pulsa semakin populer di masa kini,
    namun dengan hadirnya slot deposit pulsa tanpa potongan, kini semakin memudahkan para pemain untuk bermain. Slot lewat deposit pulsa
    menjadi ciri khas dari situs judi slot pulsa terpercaya dan terbaru
    di tahun 2023. Oleh karena itu, kami hadir di sini untuk memastikan kalian bisa menikmati slot deposit pulsa tanpa potongan dengan minimal deposit hanya 10 ribu.

    Sebagai penyedia taruhan judi slot pulsa, kami di situs slot deposit pulsa tanpa potongan memiliki provider slot terpercaya dengan sistem terbaru
    di tahun 2023. Namun, itu tidaklah cukup. Kami juga menawarkan beragam keuntungan menarik yang bisa Anda dapatkan setelah bergabung di sini.
    Dengan fasilitas yang lengkap, kami menjamin kenyamanan bermain yang tak tertandingi hanya untuk Anda.

  4. Thank you for another great post. The place else
    may just anybody get that type of information in such an ideal approach of
    writing? I’ve a presentation subsequent week, and I’m at the look for such
    information.

  5. Awesome blog! Is your theme custom made or did you download it from somewhere?
    A theme like yours with a few simple adjustements would really make my blog
    shine. Please let me know where you got your theme.
    Kudos

  6. Ꮋello I аm so grateful Ӏ fⲟund yoᥙr web site, I reɑlly
    foսnd yоu by mistake, ԝhile Ι ԝas searching оn Yahoo fоr ѕomething else, Ꭱegardless Ι am here now and wouⅼd just like to say tһank you for
    a fantastic post аnd а all round exciting blog (I also love thе theme/design),
    І don’t have time to browse it aⅼl at the moment but I have saved it аnd alѕ᧐ aԁded your RSS feeds, so when I hɑve time I wіll be back t᧐ read mοгe, Pleаse do keep սp tһe great
    work.

    Heгe is my blog :: lotto

  7. На сайте https://prosmmtop.ru вы сможете воспользоваться такими важными услугами, как раскрутка телеграм канала, группы в сети, а также продвижение в инстаграме. Применение такой панели является оптимальным решением раскрутить свой бизнес, сделать его популярным, а заодно и прорекламировать товар так, чтобы о нем узнали многие. Есть возможность пополнить баланс именно так, как вам удобно. Это лучшие услуги, которые имеются на рынке. Для вас действует оперативная доставка услуг. При этом вам не придется платить лишних денег.

  8. Its like you read my thoughts! You seem to grasp a lot about this,
    like you wrote the book in it or something. I feel that you simply could do with a few p.c.
    to pressure the message house a bit, but instead of that,
    this is magnificent blog. An excellent read. I will definitely be back.

  9. 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.

  10. It’s truly very difficult in this full of activity life to listen news on TV,
    so I simply use internet for that reason, and take the newest
    information.

  11. What i do not understood is in truth how you are not actually a lot more neatly-liked than you may be now.
    You’re so intelligent. You realize therefore significantly relating to this matter, made me in my opinion believe it
    from so many various angles. Its like men and women don’t
    seem to be fascinated unless it is one thing to accomplish
    with Lady gaga! Your personal stuffs great. Always deal with it
    up!

  12. I’m amazed, I have to admit. Rarely do I encounter a blog that’s both equally educative and engaging,
    and let me tell you, you’ve hit the nail on the head. The problem is something too few folks are
    speaking intelligently about. Now i’m very happy that I
    found this in my search for something concerning this.

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

  14. What’s Taking place i am new to this, I stumbled upon this I have discovered It positively useful and it has helped me out loads.
    I hope to give a contribution & aid other users like its helped me.

    Great job.

  15. There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game. Both boys and girls feel the impact of just a moment?s pleasure, for the rest of their lives.

  16. Its like you read my mind! You seem to know so much about this, like you wrote the book
    in it or something. I think that you could do with a few pics to drive the message home a little bit,
    but other than that, this is fantastic blog. A fantastic read.
    I will certainly be back.

  17. With havin so much content do you ever run into any problems of plagorism or copyright infringement?
    My blog has a lot of completely unique content I’ve
    either created myself or outsourced but it looks like
    a lot of it is popping it up all over the web without my agreement.
    Do you know any techniques to help stop content from being stolen? I’d
    really appreciate it.

  18. Thank you a lot for sharing this with all of us you actually
    know what you’re speaking approximately! Bookmarked. Please additionally
    discuss with my website =). We may have a link exchange agreement between us

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.