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 website you have here but I was wondering if you knew of any community forums that cover the
    same topics discussed here? I’d really like to be a part of group where I can get feedback from
    other experienced people that share the same interest. If you have any suggestions, please let me know.
    Kudos!

  2. fantastic put up, very informative. I’m wondering
    why the other specialists of this sector do not understand this.
    You should continue your writing. I am sure, you have a great readers’ base
    already!

  3. I’m not sure exactly why but this weblog is
    loading very slow for me. Is anyone else having this
    issue or is it a issue on my end? I’ll check back later and see if the problem still exists.

  4. A 43-year-old man was left with a ‘huge’ hole in his face
    after being diagnosed with eye cancer. Daniel Jackson, from Margate in Kent, revealed doctors originally treated
    him with antibiotics and eye drops when he first complained of a watery and
    irritated eye nine years ago.But the father-of-three’s symptoms didn’t go away.Subsequent
    scans revealed he had a tumour growing in his ethmoid sinus — hollow spaces in the bones around
    the nose — and his right eye had to be removed to
    treat it.Mr Jackson, who regularly wears a eye patch, said his face
    was ‘hollowed out to the extreme that I could look in a mirror and
    see my tongue moving’.After undergoing facial reconstruction, he is now happy with his appearance and campaigns for
    disfigurement charities.Nasal and sinus cancers strike
    around 460 Britons and 2,000 Americans every year. 
    Scans revealed he had a tumour growing in his ethmoid sinus — hollow spaces in the bones around
    the nose — and his eye had to be removed to treat it.

    Mr Jackson said his face was ‘hollowed out to the extreme that I could look
    in a mirror and see my tongue moving’ Mr Jackson, who was 34 when he first eye
    irritation symptoms, said he avoided making an appointment with his GP because he ‘was a young strong male who frankly didn’t have the patience to see my GP’
    Mr Jackson — who now often wears an eye patch — underwent facial reconstruction and now campaigns for disfigurement charities.

    He said: ‘I am now happy with the way I look. I have
    made peace with the fact I can never look the way I once did,
    but I won’t let it stop me living my second
    chance of life’ RELATED ARTICLES

    Share this article
    Share
    14 shares

    Mr Jackson, who was 34 when his eye irritation symptoms began, avoided making an appointment with his GP.He didn’t think it
    was a serious medical issue because he ‘was a
    young, strong male who frankly didn’t have the patience to see my GP about my irritated eye’.After being prescribed various treatments
    to alleviate his symptoms, scans revealed a tumour growing behind
    his eye, which was pushing against the eye ball and causing it to
    water. Mr Jackson said he was left in ‘utter disbelief’ when he was
    shown his scan, which revealed the ‘huge tumour’ growing inside his face. He said:
     ‘I came to find the answers as to why my innocent watery eye was not
    stopping, instead I left a dead man walking.<div class="art-ins mol-factbox floatRHS health" data-version="2" id="mol-125eed60-327b-11ec-bd53-c3627c9346f3" website left with a &apos;huge&apos; hole in face after eye cancer diagnosis

  5. I seriously love your website.. Pleasant colors & theme.
    Did you build this site yourself? Please reply back as I’m hoping to create my own personal blog and want to learn where you got this from or what the theme is named.
    Many thanks!

  6. I think this is among the such a lot vital information for me.

    And i’m satisfied reading your article. But should remark on few common things,
    The website taste is perfect, the articles is actually nice : D.
    Excellent process, cheers

  7. Wow, amazing blog layout! How long have you been blogging
    for? you made blogging look easy. The overall look of your site is fantastic, let alone the content!

  8. I always used to study article iin news papers but
    now as I am a user of web thus from now I am using
    net for articles, thanks to web.sepele berhasil setiap hari
    tengah mencari tempat slot online tentu saja enggak
    lah yan sulit. pada kebanyakan agen slot gaxor jempolan cuma mengadakan sanderaan bersama menggunakan uang asli tapi raja zeus slot pula memasok demo
    slot. lamun payah laun pertukaran era menciptakan

  9. Admiring the time and effort you put into your site and
    detailed information you present. It’s great to come across a blog every once in a while that isn’t the same
    unwanted rehashed material. Excellent read! I’ve bookmarked your site and I’m including your RSS feeds to my
    Google account.

  10. Heya! I know this is somewhat off-topic however I had to ask.
    Does running a well-established website such as yours take a massive amount work?
    I am completely new to blogging but I do write in my journal on a
    daily basis. I’d like to start a blog so I can share my own experience and thoughts online.
    Please let me know if you have any suggestions or tips for brand new aspiring bloggers.

    Thankyou!

  11. I’m not sure where you are getting your info, but good topic.
    I needs to spend some time learning more or understanding more.
    Thanks for magnificent info I was looking for this information for my mission.

  12. I don’t know whether it’s just me or if everyone else experiencing
    problems with your blog. It appears like some of the written text within your content are running off the screen. Can somebody else
    please comment and let me know if this is happening to them as well?

    This could be a issue with my internet browser because I’ve had this
    happen previously. Thank you

  13. Hi, this weekend is good for me, for the reason that this occasion i am reading this great informative article here at
    my home.

  14. I every time used to study article in news papers
    but now as I am a user of internet therefore from now I am using net for articles or reviews,
    thanks to web.

  15. I’m really enjoying the theme/design of your site. Do you ever run into any internet browser compatibility problems?
    A small number of my blog audience have complained about my website not operating correctly in Explorer but looks great in Chrome.
    Do you have any tips to help fix this issue?

  16. Good day! I could have sworn I’ve visited this website before
    but after going through some of the posts I realized
    it’s new to me. Regardless, I’m definitely pleased I discovered it and I’ll be bookmarking it and checking back regularly!

    My web site she shack

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.