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. Thank you, I have just been looking for information about this topic for a while and yours is the best I’ve found
    out till now. But, what in regards to the conclusion? Are you positive in regards to the supply?

  2. Howdy are using WordPress for your blog platform? I’m new to the blog
    world but I’m trying to get started and create my own. Do you require any coding knowledge to make your own blog?
    Any help would be greatly appreciated!

  3. What you typed made a great deal of sense. But, what about this?
    what if you added a little content? I mean,
    I don’t wish to tell you how to run your website, however suppose you added something to possibly
    get a person’s attention? I mean Eclipse – Formatter e Save Action – Handerson Frota is a little plain. You might look
    at Yahoo’s front page and see how they create news headlines to get people to click.
    You might add a related video or a pic or two to grab people interested about
    what you’ve got to say. In my opinion, it would bring your website a little livelier.

  4. hi!,I love your writing so a lot! share we be in contact more about your post on AOL?
    I need a specialist on this area to resolve my problem.
    May be that is you! Having a look forward to see you.

  5. This is a good tip particularly to those fresh to the blogosphere.
    Simple but very accurate information… Appreciate your sharing this
    one. A must read post!

  6. I am really impressed witһ your writing skills as well аs with
    the layout ᧐n yօur weblog. Ӏs this a paid theme οr
    did yoս modify it yourѕelf? Ꭺnyway keep up tһe nice quality writing, it is rare tо sее а great blog like
    this one nowadays.

    my web blog; casino (Juanita)

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

  8. Pretty nice post. Ι just stumbled upon your weblog ɑnd wished tߋ sɑy tһat
    I have reallʏ enjoyed browsing ʏoսr blog posts.
    Аfter aⅼl Ι’ll be subscribing to уⲟur rss feed
    аnd I hope you write again very soon!

    My site: casino

  9. Tһanks f᧐r the marvelous posting! І quite enjoyed reading іt, yoᥙ migһt be a great
    author. I wіll makе certain to bookmark уour blog and will eventually сome back from now on. I want to encourage one to continue үour great work, һave а
    nice morning!

    Feel free tо surf to my paցe :: lotto

  10. So to Gruman, the one recommendation I’ve is to maybe spend a bit of bit of time
    on the planet of iOS jailbreaking. Claiming that even venturing into the world of jailbreaking goes to end
    in tears is concern-mongering, and nothing more.
    There’s so much fallacious with this article from starting to finish that it could take
    me 2,000 phrases to correct everything, so I’ll just level
    out the most troubling bits. Sure, there are lots
    of websites on the market attempting to trick you into downloading one thing shady, but no,
    jailbreaking your iOS machine isn’t inherently harmful.
    It takes roughly 5 minutes from the time you plug your iPhone, iPad, or iPod contact into
    your pc for the hack to free your gadget and install Cydia, the jailbreaker’s
    app retailer. I know all of this because I’ve an iPod touch that I have jailbroken utilizing Pangu, and it
    performed flawlessly. Called Pangu, the tool has been updated persistently and
    now supports even the most recent iOS 7.1.2 patch.

    Also visit my site xnxx fucking video

  11. Hi there, I wanted to drop a comment and let you know that if you’re looking to buy some modern furnishings, it’s
    worth it to browse through the latest collection of home decor ready on the internet.
    You’ll be able to peruse the up-to-date virtual furniture choices today.
    Don’t miss the opportunity to explore the latest
    furnishing options ready digitally. Get a glimpse of the latest home decor styles on the web today.
    Check out the newest virtual furnishing additions today.
    I trust you discover something that catches your eye!

  12. It’s going to be ending of mine day, however before
    ending I am reading this wonderful piece of writing to improve my know-how.

  13. Fine way of explaining, and nice paragraph to obtain information about
    my presentation subject matter, which i am going to deliver in university.

  14. I do believe all the ideas you have introduced to your post.

    They are really convincing and will certainly work. Still,
    the posts are very brief for beginners. Could you please extend them a bit from subsequent time?

    Thanks for the post.

  15. Thank you for every other magnificent article. Where else may anybody get that kind of information in such
    a perfect manner of writing? I’ve a presentation subsequent week, and I’m on the look for such info.

  16. I’ve been browsing online more than 2 hours today, yet I never found any interesting article like yours.
    It’s pretty worth enough for me. Personally, if all site owners and bloggers made good content as you did,
    the net will be much more useful than ever
    before.

  17. RTP Live > Info RTP Live Slot Gacor Resmi Terakurat Di Jamin Maxwin Sensasional
    2023
    Game slot gacor sekarang semakin mudah untuk memainkan permain slot gacor gacor RTP live
    slot saat ini begitu akurat sewaktu digunakan untuk memperoleh banyak kemenangan dan keuntungan. Tentunya kalian harus bermain dengan bocoran yang telah disediakan mempunyai tingkat
    keakuratan tersendiri sehingga kalian tidak harus khawatir
    dengan kekalahan ketika bermain pemerian slot online ini.
    Sebelum bermain gunakan RTP slot ini untuk kalian dapat mempunyai tingkat
    persentase kemenangan sehingga aman ketika bermain dengan kerugian seminimal mungkin.

    RTP live slot merupakan informasi bocoran rtp slot gacor hari ini agar mudah dan gampang maxwin paling akurat di tahun 2023.
    Sehingga kalian dapat melihat tingkat nilai persentase kemenangan dari slot online dengan beberapa
    jenis pameran yang layak sekali kalian mainkan. Meskipun telah hadirnya bocoran RTP slot ini juga tidak akan menjamin keamanan setiap kalian putar,
    setidaknya dapat mengurangi resiko dalam kesalahan yang fatal.

  18. I seriously love your website.. Excellent colors & theme.

    Did you build this website yourself? Please reply back as I’m trying to create my own site and want to find out where you
    got this from or what the theme is named. Thank you!

  19. I have read so many articles or reviews on the topic
    of the blogger lovers but this post is in fact a good paragraph,
    keep it up.

  20. My brother suggested I might like this web site.
    He was entirely right. This post truly made my day. You can not imagine simply how much time I
    had spent for this information! Thanks!

  21. I just like the helpful info you supply on your articles.
    I’ll bookmark your blog and check again right here
    frequently. I am slightly certain I will be told
    many new stuff proper here! Good luck for the next!

  22. I know this if off topic but I’m looking into starting my own blog
    and was wondering what all is required to get setup? I’m assuming having
    a blog like yours would cost a pretty penny?
    I’m not very web smart so I’m not 100% positive. Any tips
    or advice would be greatly appreciated. Appreciate it

  23. Lean In has coined the phrasee “the broken rung” to refer to the problem of young, certified ladies getting
    passed more than for early management roles.

    my webpage :: website

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.