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. I think this is one of the most important information for me.
    And i’m glad reading your article. But wanna remark on few general things, The site style is wonderful, the
    articles is really nice : D. Good job, cheers

  2. Nice post. I learn something totally new and challenging on blogs I stumbleupon every day.
    It’s always interesting to read through articles from other authors and use
    a little something from other sites.

  3. This is the perfect web site for everyone who hopes to understand this topic.
    You know a whole lot its almost tough to argue with
    you (not that I personally would want to…HaHa).
    You definitely put a new spin on a topic that’s been written about
    for years. Wonderful stuff, just excellent!

  4. Everything is ѵery open with a really clear description of the issues.
    It was definitely informаtive. Your site is extremely helpful.Thank
    you for sharing!

    Lookk into my blog … australian

  5. Hey there would you mind sharing which blog platform you’re using?
    I’m looking to start my own blog soon but I’m having a tough time deciding
    between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your layout seems different then most
    blogs and I’m looking for something unique. P.S
    Apologies for getting off-topic but I had to ask!

  6. Thanks for any other informative blog. The place else could I am
    getting that type of info written in such an ideal method?
    I have a challenge that I’m just now running on, and I
    have been on the look out for such info.

  7. My programmer is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type
    on numerous websites for about a year and am anxious about switching to another platform.

    I have heard great things about blogengine.net.
    Is there a way I can import all my wordpress posts into it?

    Any kind of help would be greatly appreciated!

    Look at my site – Derma Advanced Skin Cream

  8. Someone essentially assist to make significantly articles I’d
    state. That is the very first time I frequented your web page and
    to this point? I amazed with the analysis you made to create this particular post
    extraordinary. Excellent task!

  9. We are a group of volunteers and starting
    a new scheme in our community. Your site offered us with valuable info to
    work on. You have done a formidable job and our whole community will be grateful to you.

  10. Hello everyone, it’s my first visit at this web page,
    and piece of writing is genuinely fruitful in support of me, keep up posting these articles or
    reviews.

  11. Hi there this is somewhat 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 knowledge so
    I wanted to get advice from someone with experience. Any help would be greatly
    appreciated!

  12. Hello There.Ӏ found yоur blоg uѕing msn. This is an extremely well written article.
    I’lⅼ be sure to bookmark іt and com bacк to read more of your
    useful іnformation. Thanks foг the post. I will definitеly return.

    Here is myy page … slot onlijne (penzu.com)

  13. Hi there it’s me, I am also visiting this site daily, this website is truly fastidious and the users are truly sharing nice thoughts.

  14. Even after four years of stringent controls on immigration imposed underneath former President Donald J.

    Trump, the general share of Individuals born in different countries
    isn’t solely rising, however coming near ranges final seen within the
    late 19th century. 1960s and approaching the record 14.Eight p.c seen in 1890,
    shortly before giant numbers of Europeans started disembarking from vessels
    at Ellis Island. In 2021, the speed of inhabitants progress fell
    to an unprecedented 0.1 %. Immigration, even at diminished levels, is for the first time making up a majority of population progress.
    Thanks a lot for helping us with N-400, N336 application process
    and patiently answering all our questions time
    and once more. In 2021, that determine was 148,000, or one-tenth the achieve that was regular a decade ago, and smaller than worldwide migration for the first time
    ever. The most recent report, from the Census Bureau’s population estimates program, confirmed a internet gain of 244,000 new residents from immigration in 2021 – a far
    cry from the middle of the earlier decade, when the bureau
    recurrently attributed annual good points of a million or extra to immigration.

  15. Hello I am so delighted I found your website, I really found you
    by error, while I was researching on Askjeeve for something else,
    Anyways I am here now and would just like to say thanks a lot for a fantastic post
    and a all round entertaining blog (I also love the theme/design), I don’t have time to read
    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 much more, Please
    do keep up the awesome work.

    Review my web blog – bang4d

  16. Wonderful goods from you, man. I have understand your stuff previous to
    and you’re just too great. I really like what you’ve acquired here, certainly like what you’re saying and the way in which
    you say it. You make it entertaining and you still take care of
    to keep it sensible. I cant wait to read far more from you.
    This is really a tremendous web site.

    my site; jon4d

  17. Hey there! I’m at work surfing around your blog from my new apple iphone!
    Just wanted to say I love reading your blog and look forward to all your posts!
    Carry on the fantastic work!

  18. Fantastic website you have here but I was wanting to know if you knew of any community forums that cover
    the same topics talked about in this article?
    I’d really like to be a part of group where I can get feed-back from other
    knowledgeable individuals that share the same interest. If you have any suggestions, please
    let me know. Thanks a lot!

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.