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.428 Comments on “Eclipse – Formatter e Save Action

  1. Please let me know if you’re looking for a article writer for your site.

    You have some really great posts and I feel I would be a good asset.
    If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange for a link back
    to mine. Please send me an email if interested.

    Cheers!

  2. Howdy! I know this is somewhat off-topic however I needed to ask.
    Does operating a well-established blog such as yours take a lot of work?

    I am completely new to writing a blog however
    I do write in my journal daily. I’d like to start a blog so I will be able to share my experience
    and views online. Please let me know if you have any recommendations or tips for new aspiring bloggers.
    Appreciate it!

  3. Hey there! This post couldn’t be written any better!
    Reading through this post reminds me of my old room
    mate! He always kept talking about this. I will forward this page to him.
    Fairly certain he will have a good read. Thanks for sharing!

  4. Awesome blog! Do you have any suggestions for aspiring writers?
    I’m planning to start my own site soon but I’m a little lost on everything.
    Would you suggest starting with a free platform
    like WordPress or go for a paid option? There are so many choices out there that I’m totally overwhelmed ..
    Any tips? Bless you!

  5. Thanks for a marvelous posting! I truly enjoyed reading it, you may be a
    great author.I will be sure to bookmark your blog
    and will come back at some point. I want to encourage you continue your
    great posts, have a nice afternoon!

  6. I got this web page from my friend who shared with me on the topic of this web site and at the moment this time I am visiting this site and reading very informative
    posts here.

  7. На сайте https://kupit-muhomory.ru/ вы сможете приобрести лечебные сушеные мухоморы напрямую от изготовителя. Это урожай прошлого года. Доставка организуется по всей России, а также странам СНГ. Сейчас компания распродает остатки по самым лояльным ценам, а потому и вы тоже сможете совершить выгодную покупку, которая точно вам понравится. В разделе представлены шляпки красного мухомора, настойка мухомора на самогоне, мухомор в капсулах, ежовик гребенчатый и многое другое. Вся продукция свежая и обязательно вам поможет в решении определенной задачи.

  8. На сайте https://lift-teh.ru/ вы сможете оформить заявку на то, чтобы воспользоваться такими услугами, как: монтаж, демонтаж, модернизация подъемных сооружений, изготовление, монтаж подкрановых сооружений. Все работы выполняются в соответствии с нормативами, по ГОСТу, а потому конструкциям не страшны перепады температуры, образование коррозии. Они смогут простоять несколько лет без потери технических характеристик. Компания находится на рынке более 17 лет, за которые смогла заработать постоянных клиентов и получить опыт.

  9. Nice 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
    stand out. Please let me know where you got your theme.
    Bless you

  10. Does your website have a contact page? I’m having trouble locating it but,
    I’d like to send you an email. I’ve got some recommendations for your blog you might be interested in hearing.

    Either way, great blog and I look forward to seeing it develop over time.

  11. http://thetradable.com/ it’s financial website covers the latest news in trading, cryptocurrency, and stocks. Our team of expert journalists and analysts provides in-depth coverage of breaking news and market trends, offering valuable insights and advice to help investors make informed decisions.

  12. Awesome blog! Dο ʏou һave any tips for aspiring writers?
    Ӏ’m planning tо start my own website ѕoon but I’m a ⅼittle lost on everything.

    Woulԁ үou recommend starting witһ ɑ free platform like WordPress or ɡo foг ɑ
    paid option? Ƭhere ɑre so mаny choices out there that І’m completely overwhelmed
    .. Any suggestions? Ƭhank уоu!

    Feel free tⲟ visit my website betlotto

  13. Do you have a spam issue on this website; I also
    am a blogger, and I was wondering your situation; many of us have developed some nice practices and we
    are looking to trade solutions with other folks, why not
    shoot me an e-mail if interested.

  14. Thank you, I’ve just been searching for information approximately
    this subject for ages and yours is the best I’ve found out till now.
    But, what concerning the conclusion? Are you certain in regards to the source?

  15. Nice weblog right here! Additionally your site
    rather a lot up fast! What web host are you using?
    Can I am getting your associate hyperlink for your host?
    I wish my website loaded up as quickly as yours lol

    Stop by my blog post :: Truth CBD Gummies

  16. Hmm it looks like your website ate my first comment (it
    was super 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 everything.
    Do you have any points for newbie blog writers? I’d really appreciate it.

  17. I’m no longer certain the place you’re getting your info,
    however great topic. I must spend some time learning more or
    working out more. Thank you for wonderful information I used
    to be looking for this info for my mission.

  18. Your style is really unique compared to other folks I’ve
    read stuff from. Thank you for posting when you have the opportunity, Guess I’ll just book mark this blog.

  19. Amazing blog! Do you have any hints for aspiring writers? I’m planning
    to start my own blog soon but I’m a little lost on everything.

    Would you recommend starting with a free platform like WordPress
    or go for a paid option? There are so many choices out there that
    I’m completely overwhelmed .. Any recommendations?
    Bless you!

  20. Hi there i am kavin, its my first occasion to commenting anyplace,
    when i read this article i thought i could also create comment due to this brilliant article.

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

  22. each time i used to read smaller posts that as well clear their motive, and that
    is also happening with this piece of writing which I am reading at this place.

  23. You’re so cool! I don’t think I’ve read something like that before.
    So good to find another person with some unique thoughts on this subject.
    Seriously.. many thanks for starting this up. This web site is something that is required on the web, someone with
    some originality!

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

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

*

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.