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. Right here is the perfect blog for everyone who would like to
    find out about this topic. You realize so much its almost hard to argue with you (not that I
    actually will need to…HaHa). You definitely put a brand new spin on a topic that
    has been discussed for years. Excellent stuff, just excellent!

  2. Asking questions are genuinely pleasant thing if
    you are not understanding anything entirely, but this post provides
    fastidious understanding yet.

  3. Hi, i read your blog occasionally and i own a
    similar one and i was just curious if you get a lot of spam responses?
    If so how do you protect against it, any plugin or anything
    you can suggest? I get so much lately it’s driving me crazy so any help is very
    much appreciated.

  4. If you are in search of somewhere that permits you to match a number of odds at once, then an online sportsbook is the option to go!
    Odds on certain futures will usually be updated all through the offseason as players change
    teams or endure accidents. German shepherds kind extraordinarily strong bonds with their
    homeowners and households and will protect a child
    with their lives. American Kennel Club. “German Shepherd”.
    American Kennel Club. “Collie”. For that reason, a savvy dwelling invader may very well be capable of subdue a collie
    with only a scratch underneath the chin and a few small discuss.
    Assuming you possibly can put up with a little bit of drool, the Saint Bernard
    may be the right pet for you. Anticancer remedies, amorphine, and opioid-based mostly ache medications
    are sometimes thought-about emetogenic, which means they could induce nausea and vomiting.
    When you don’t have a cable connection and you’re a giant
    fan of sports, then the live sports and TV app is just for you.

  5. If you wish for to increase your knowledge simply keep visiting this website and be updated
    with the most recent news posted here.

  6. Thank you for another magnificent post. The place else may anyone get that kind of information in such an ideal manner
    of writing? I’ve a presentation next week, and I am
    at the search for such information.

  7. ผลิตภัณฑ์ Relx Infinityนั้น ถือเป็น ผลิตภัณฑ์
    ที่ถูก พัฒนาขึ้นมา จากการนำเอา ปัญหา จากรุ่นก่อนอย่าง Relx
    Zerro และ Relx Alpha ควบคู่กับ เทคโนโลยีสมัยใหม่ จนได้ออกมาเป็น ผลิตภัณฑ์ ที่มีดีไซน์ ที่เรียบหรู กว่าเดิม ทนทาน กว่าเดิม และที่สำคัญ ให้ฟีลสูบ
    หรือ รสชาติ ที่ แน่น ชัดเจน แต่นุ่มนวลไม่แทงคอ ไม่ว่าจะเป็นมือใหม่หรือมือเก่า
    ก็สามารถใช้งานไ

  8. Just desire to say your article is as astounding. The clarity in your post is
    simply cool and i could assume you’re an expert on this subject.
    Fine with your permission let me to grab your RSS feed to keep up to date with forthcoming
    post. Thanks a million and please continue the rewarding work.

  9. Hey I am so glad I found your blog page, I really found you by error, while I was browsing on Bing for something else, Regardless I am here now
    and would just like to say cheers for a incredible post and
    a all round enjoyable blog (I also love the theme/design), I
    don’t have time to look over it all at the minute but I have book-marked it and also added in your RSS feeds, so when I have time I
    will be back to read a great deal more, Please do keep up the awesome work.

  10. Magnificent goods from you, man. I’ve understand
    your stuff previous to and you’re just extremely fantastic.
    I really like what you’ve acquired here, really like what you’re saying and the
    way in which you say it. You make it enjoyable and you still take care of to keep it
    wise. I cant wait to read far more from you. This is actually a tremendous web site.

  11. Hello, Neat post. There’s an issue with your web site in web explorer, might check
    this? IE still is the market leader and a large component to other folks will pass over
    your magnificent writing because of this problem.

  12. Hello there! This is my 1st comment here so I just wanted to give a quick
    shout out and tell you I really enjoy reading through your articles.
    Can you suggest any other blogs/websites/forums that cover the
    same subjects? Thanks!

  13. Hey! Do you know if they make any plugins to help with Search Engine Optimization?
    I’m trying to get my blog to rank for some targeted keywords but I’m
    not seeing very good gains. If you know of any please share.
    Thank you!

  14. Link exchange is nothing else however it is only placing the
    other person’s website link on your page at appropriate place and other person will also do same for you.

  15. На сайте http://abc.informbureau.com находится экономический словарь с исчерпывающей информацией. Так вы узнаете огромное количество новых терминов, интересных и нужных слов, которые вы сможете использовать в повседневном обиходе. Словарь поможет расширить кругозор и узнать много новых, интересных слов, о существовании которых вы даже не догадывались. Этот словарь понадобится не только студентам, но и учителям, экономистам, финансистам, которые стремятся быть в курсе последних изменений.

  16. Hey there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but
    I’m not seeing very good gains. If you know of any please share.

    Many thanks!

  17. I know this site presents quality depending posts and extra information, is there
    any other web site which gives these information in quality?

  18. На сайте https://ab-korea.ru/ вы сможете оформить заявку на подбор автомобиля из Южной Кореи с гарантиями. Если транспортное средство не будет найдено в соответствии с вашими параметрами в течение пары месяцев, то предоплата будет возвращена в полном объеме. Все платежи осуществляются через специальную систему, что подтверждает прозрачность, безопасность сделки. При необходимости будет оказана услуга подбора автомобиля с участием высококлассного менеджера. Доставка автомобиля происходит с использованием качественной техники.

  19. На сайте https://widgenta.com вы сможете воспользоваться лучшими и проверенными виджетами, которые идеально подходят для вашего сайта. Компания смогла разработать уникальный сервис с востребованными виджетами. В обязательном порядке применяются революционные и инновационные технологии, которые помогают получить необходимый результат. Укажите свою электронную почту для того, чтобы получить ранний бесплатный доступ, а также новости. Все максимально просто. Для каждого клиента действуют особые, уникальные предложения.

  20. You really make it appear so easy alokng wioth your presentation howesver I to find this topic too be actually something which Ibelieve I’d by no means understand.
    It seems too complex and extremely vast forr
    me. I am having a look forward to your next put up, I’ll try tto get the cling of it!

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.