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

  1. Very good blog you have here but I was wondering if you knew of
    any community forums that cover the same topics talked about here?
    I’d really love to be a part of community where I can get suggestions from
    other experienced individuals that share the same interest.
    If you have any suggestions, please let me know.
    Many thanks!

  2. I have read some just right stuff here. Certainly worth bookmarking for revisiting.
    I wonder how a lot attempt you place to create any such
    great informative website.

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

  4. hi!,I love your writing so a lot! percentage we be in contact more about
    your post on AOL? I require a specialist on this space to solve
    my problem. May be that’s you! Taking a look forward to see
    you.

  5. Hello! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing many months of hard work
    due to no backup. Do you have any solutions to protect against hackers?

  6. Everything published was actually very reasonable.
    But, what about this? what if you were to write a awesome
    headline? I ain’t saying your content isn’t good, but suppose you
    added a title that makes people want more? I mean Eclipse – Formatter
    e Save Action – Handerson Frota is kinda
    plain. You should glance at Yahoo’s front page and watch how they write news titles
    to grab people to open the links. You might add a related video or a related picture or two to grab people excited about everything’ve got to say.
    Just my opinion, it could bring your blog a
    little livelier.

  7. Excellent post however , I was wanting to know if you could write a litte more on this subject?
    I’d be very thankful if you could elaborate a little bit further.
    Thanks!

  8. Good day I am so happy I found your web site, I really found you by accident, while I was
    looking 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 interesting blog (I also love the theme/design), I don’t have time to read through it all at the moment
    but I have saved it and also included your RSS feeds, so when I have
    time I will be back to read more, Please do keep up the awesome work.

  9. Wonderful blog! I found it while browsing on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo
    News? I’ve been trying for a while but I never seem
    to get there! Thanks

  10. Hello There. I discovered your weblog the use of msn. That is
    a really smartly written article. I’ll be sure to
    bookmark it and return to learn more of your useful information. Thank you for the post.
    I will definitely return.

    Check out my blog post – Colorado Cash Buyers

  11. It’s a pity you don’t have a donate button! I’d most certainly donate to this brilliant blog!

    I guess for now i’ll settle for book-marking and
    adding your RSS feed to my Google account. I look forward to new updates and will share this
    blog with my Facebook group. Talk soon!

  12. It’s actually a nice and useful piece of info.
    I’m satisfied that you shared this useful info with
    us. Please keep us up to date like this. Thanks for sharing.

  13. I have to voice my passion for your kind-heartedness supporting those
    people that should have guidance on this important concept.
    Your very own dedication to passing the solution all-around had been extremely interesting and has all the time helped men and women just like me to
    reach their endeavors. Your informative information indicates this
    much a person like me and a whole lot more to my office colleagues.
    Many thanks; from everyone of us.

    My web site; forex trading

  14. Hey 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 know-how so
    I wanted to get advice from someone with experience. Any help
    would be greatly appreciated!

  15. Hey There. I found your blog using msn. This is a very well written article.
    I will be sure to bookmark it and return to read more of your useful info.
    Thanks for the post. I’ll certainly comeback.visit to see my page

  16. Live dealer games are already a must at the best online casino sites. The live casinos stream videos in HD from casino tables at studios with professional dealers or at actual land-based casinos. The players can interact with the dealers through a chat, which provides a highly authentic casino experience. While we can’t give you an all-inclusive answer, Red Dog will be the best online casino for most players. We say this because it covers the bases pretty well and offers the most generous welcome bonus. The Garden State was the very first to enter the market in the U.S. and is the most developed. It has the most comprehensive selection of casino operators, with around 30 different brands for players. This is undoubtedly a positive for players as there are plenty of welcome offers and online casino bonus promotions to take advantage of. The maturity of the NJ market also means the highest levels of user experience, game options, and user safety.
    https://thezoneshop.co.kr/bbs/board.php?bo_table=free&wr_id=114197
    To ease players, 2022 online poker au and Chidwick busted. Offers a confidential help line, so they will do anything to keep your interest on a high level. The best way to win then change from the reels to the will give you a pair of golden 7s, which attracts many high rollers and VIP punters. Yes, players must be 18 or older to play online poker at Ignition Casino Australia. We require players to provide proof of age and identity before allowing access to the online poker. Can Australians Play Roulette Online For Real Money There’s nothing in the Australian law that makes it illegal for citizens of Australia to use or access online poker sites. Therefore, it’s legal for the residence of Australia to play poker online if they choose. There are several overseas online operators that gladly accept customers from Australia, so there’s a fantastic selection of online poker sites to choose from. There are also plenty of licensed sports betting websites available for Australians, too.

  17. Hi! I’m at work surfing around your blog from my new iphone 4!
    Just wanted to say I love reading through your blog and look forward to all
    your posts! Keep up the outstanding work!

  18. I’m not that much of a internet reader to be honest but
    your blogs really nice, keep it up! I’ll go ahead and bookmark your website
    to come back down the road. All the best

  19. This is very interesting, You are an excessively skilled blogger.
    I’ve joined your feed and sit up for in quest of extra of your magnificent post.
    Additionally, I have shared your website in my social networks

  20. pinup casino bГґnus vip ruby fortune cassino online wazamba cadoola Casino YoYo Casino giros grГЎtis bodog Г© confiГЎvel revisГЈo completa Bonus 2023 Entenda como resulta o LibraBet bГґnus de boas vindas Evobet Г© confiavel 1xBet Г© confiГЎvel ruby fortune bГґnus de boas-vindas como funciona o LeoVegas Cassino Online 1xBet RevisГЈo 2023 Melhores Cassinos 22Bet

    Copagolbet Casino bГґnus grГЎtis winner casino wazamba bГґnus 2023 como se registrar no site Cadoola Winner Casino Г© confiavel

    YoYo Cassino apostas ruby fortune brasil sportingbet vantagens e desvantagens betwinner Г© confiГЎvel pin-up vantagens e desvantagens sportingbet apostas online Casas de Apostas On-line KTO casino Vera e John 188Bet anГЎlise completa

    como se registrar no site CampoBet Casino wazamba site oficial como funciona o LibraBet registro pin-up YoYo Casino mГ©todos de pagamento

    por que 188Bet foi an escolha correcta Futwin Г© confiГЎvel Bet365 Brasil Г© confiГЎvel como se registrar no site Wazamba seus bГґnus casas de aposta

  21. Just desire to say your article is as amazing.
    The clearness in your post is just great and i can assume you are a professional on this subject.
    Fine together with your permission allow me to clutch your RSS feed to keep
    up to date with forthcoming post. Thank you 1,000,000 and please continue
    the rewarding work.

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.