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. What’s Going down i’m new to this, I stumbled upon this I’ve
    found It absolutely useful and it has aided me out loads.
    I am hoping to contribute & aid different customers
    like its aided me. Great job.

  2. Terrific work! This is the type of information that are supposed
    to be shared across the internet. Shame on the seek engines for not positioning this put up upper!
    Come on over and talk over with my web site . Thanks =)

  3. Wonderful blog! Do you have any recommendations for aspiring writers?
    I’m hoping to start my own site soon but I’m a little lost
    on everything. Would you advise starting with a free platform like WordPress or go
    for a paid option? There are so many choices out there that I’m totally confused
    .. Any recommendations? Many thanks!

  4. I loved as much as you’ll receive carried out right here.
    The sketch is attractive, your authored material stylish.
    nonetheless, you command get got an impatience
    over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you
    shield this increase.

  5. I like the valuable information you provide in your articles.
    I will bookmark your blog and check again here
    regularly. I am quite certain I will learn lots of new
    stuff right here! Good luck for the next!

  6. hello!,I really like your writing very much! percentage we be
    in contact more approximately your post on AOL?
    I require an expert in this house to solve my
    problem. Maybe that’s you! Taking a look forward to see you.

  7. Забор из металлопрофиля или профлиста — это практичное и долговечное решение для ограждения территории.
    Такой забор обеспечивает надежную защиту, препятствуя несанкционированному проникновению и
    обеспечивая конфиденциальность.
    Профнастил, из которого часто изготавливают заборы,
    обладает высокой устойчивостью к атмосферным воздействиям и механическим
    нагрузкам. Кроме того, забор из профнастила легко монтируется и имеет доступную цену.
    Если вы хотите получить качественный забор из профнастила под ключ, важно обратиться к опытным специалистам, которые смогут выполнить работы профессионально и эффективно.

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

  8. After exploring a handful of the blog articles on your
    site, I truly like your way of blogging. I added it to my bookmark
    website list and will be checking back in the near future. Take a
    look at my web site too and tell me your opinion.

  9. Yesterday, while I was at work, my sister stole my apple ipad and tested
    to see if it can survive a 40 foot drop, just so she can be a youtube
    sensation. My iPad is now destroyed and she has 83 views.
    I know this is completely off topic but I had to share
    it with someone!

  10. Awesome blog! Do you have any helpful hints for aspiring writers?
    I’m hoping to start my own blog soon but I’m a little lost on everything.
    Would you propose starting with a free platform like WordPress or go for a
    paid option? There are so many options out
    there that I’m totally overwhelmed .. Any ideas? Many thanks!

  11. Gߋod way οf telling, and pleasant post tо take information гegarding my presentation subject matter,
    ᴡhich i am ɡoing to deliver in academy.

    Feel free tо visit my site – casino – Krystle,

  12. Howdy great blog! Does running a blog similar to this require a great deal of work?
    I’ve very little understanding of coding but I had been hoping to start my own blog in the near future.
    Anyhow, should you have any suggestions or tips for new blog owners please share.
    I understand this is off subject but I just wanted to ask.

    Thanks a lot!

  13. Hmm is anyone else having problems with the pictures on this
    blog loading? I’m trying to determine if its a problem on my end or if it’s the blog.
    Any suggestions would be greatly appreciated.

  14. I’ve been exploring for a little bit for any high-quality articles
    or weblog posts on this sort of area . Exploring in Yahoo I eventually stumbled upon this website.
    Studying this info So i am satisfied to express
    that I’ve an incredibly good uncanny feeling I found out exactly
    what I needed. I so much unquestionably will make sure to do not forget this web
    site and give it a look regularly.

  15. Terrific article! This is the type of information that are supposed
    to be shared around the web. Disgrace on Google for
    not positioning this submit upper! Come on over and
    seek advice from my website . Thank you =)

  16. It’s awesome to visit this web page and reading the views of all
    friends concerning this post, while I am also eager of getting knowledge.

  17. ทางเรา mothervaper ยังมี ผลิตภัณฑ์ บุหรี่ไฟฟ้า Pod System อื่นๆ ที่กำลังจะนำเข้ามา ให้ผู้ใช้ได้เลือกใช้อีกด้วย ไม่ว่าจะเป็น Infy Pod ,
    Vmc Pod , Relx Bubble Mon , Coga และอื่นๆ อีกมากมาย โดย น้ำยาบุหรี่ไฟฟ้า หรือ บุหรี่ไฟฟ้า พอตใช้แล้วทิ้ง ทุกรุ่น
    ล้วนแล้วแต่มี ราคาถูก แต่ให้คุณภาพที่ดีเยี่ยมทั้งนั้น อีกทั้งยังเป็นรุ่นยอดนิยมอีกด้วย

  18. Hey I am so excited I found your website, I really found you by accident, while I was researching on Askjeeve for
    something else, Regardless I am here now and would just like to
    say thanks a lot for a remarkable post and a all round thrilling blog (I also love the theme/design), I don’t have time to browse
    it all at the moment but I have saved it and also added in your RSS feeds, so when I
    have time I will be back to read more, Please do keep up the great job.

  19. Hello this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding skills so I
    wanted to get guidance from someone with experience.
    Any help would be greatly appreciated!

  20. Hello there! I simply would like to offer you a big thumbs up for
    the excellent information you’ve got here on this post.
    I’ll be coming back to your website for more soon.

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.