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

  1. Hmm it аppears like your website ate my first comment
    (it wаs extremely long) so I guess I’ll just sum it up ᴡhat I ԝrote
    and say, I’m thoroughly enj᧐уing your blοg. I as well am an aspiring blog blogger
    but I’m stіll new to the wһole thing. Do you һave any
    points for inexperienced blog writers? I’d genuinely appreciate it.

    Aⅼѕo visit my site https://yogicentral.science

  2. We absolutely love your blog and find the majority of your post’s to be just what I’m looking for.

    can you offer guest writers to write content in your case?
    I wouldn’t mind publishing a post or elaborating on many of the subjects you write with regards to here.
    Again, awesome web site!

  3. На сайте https://fx-roboforex.com/ изучите всю нужную и актуальную информацию, которая касается заработка на Форекс вместе с RoboForex. Для того чтобы успешно продавать, необходимо подобрать честного брокера. Важной целью такого сайта является поделиться с пользователями всей ценной информацией, которая касается трейдинга. Этот портал полностью посвящен именно этому брокеру, который заполучил уважение многих, кто принимает участие в торгах. На сайте регулярно появляются свежие записи, которые будут интересны и вам.

  4. I really love your site.. Very nice colors & theme. Did you
    create this site yourself? Please reply back as I’m wanting
    to create my own blog and would like to know where you got this
    from or just what the theme is called. Many thanks!

  5. Hi there would you mind stating which blog platform you’re
    using? I’m planning to start my own blog soon but I’m having a hard time making a decision 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 completely unique.
    P.S Apologies for being off-topic but I had to ask!

    Visit my web blog – sell ugly house

  6. What’s up i am kavin, its my first time to commenting anywhere, when i read
    this paragraph i thought i could also make comment due
    to this brilliant piece of writing.

  7. I do believe all the ideas you have presented in your post.
    They are very convincing and will certainly work.
    Still, the posts are very brief for newbies. Could you please lengthen them a little from subsequent time?
    Thank you for the post.

  8. After I initially left a comment I appear to have clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with
    the exact same comment. There has to be a means you can remove me
    from that service? Thanks!

  9. Do you mind if I quote a few of your posts as long as I
    provide credit and sources back to your site? My website is in the exact same area of interest
    as yours and my visitors would definitely benefit from a lot of the information you present here.
    Please let me know if this ok with you. Cheers!

  10. With havin so much written content do you ever run into any problems of plagorism or copyright infringement?
    My site has a lot of exclusive content I’ve either created
    myself or outsourced but it appears a lot of it is popping it up all over the
    internet without my authorization. Do you know any solutions to help prevent content from being ripped off?

    I’d genuinely appreciate it.

  11. Simply want to say your article is as astonishing.
    The clearness in your publish is just spectacular
    and i can suppose you’re a professional in this subject.
    Well together with your permission allow me to clutch your
    feed to keep up to date with approaching post. Thanks one million and please carry on the gratifying work.

  12. I believe people who wrote this needs true loving because it’s a blessing.
    So let me give back and shout out on change your
    life and if you want to really findout? I will share info about
    how to find good hackers for good price Don’t forget..

    I am always here for yall. Bless yall!

  13. It’s hard to find educated people in this particular topic, but you sound
    like you know what you’re talking about! Thanks

  14. Hey there this is somewhat of off topic but I
    was wanting to know if blogs use WYSIWYG editors or if you have to manually code
    with HTML. I’m starting a blog soon but have no coding expertise so I wanted to get guidance from someone
    with experience. Any help would be enormously appreciated!

  15. Hello, i think that i saw you visited my web site so i came to “return the favor”.I’m trying to find things to enhance my website!I
    suppose its ok to use some of your ideas!!

  16. We absolսtely love уoᥙr blog and find nearly all оf your post’s to be precisely ѡһat I’m looking for.
    can yօu offer guest writers tⲟ ᴡrite content for you personally?
    I ѡouldn’t mind producing a post or elaborating ⲟn a number of the subjects yߋu write
    aƅout herе. Agɑin, awesome website!

    Feel free to visit my webpage; football betting (Eulah)

  17. Oh my goodness! Awesome article dude! Thanks, However I
    am going through issues with your RSS. I don?t know why I can’t subscribe to it.
    Is there anybody else getting identical RSS problems?
    Anyone that knows the solution can you kindly respond?
    Thanx!!

    my webpage: NTX Max

  18. Its not my fіrst time to visit this web site, i ɑm visiting tһіs site dailly аnd oƅtain nice data from here еverу day.

    My blog post sport betting, Lola,

  19. My spouse and I stumbled over here from a different page and thought I should check things out.
    I like what I see so i am just following you.
    Look forward to going over your web page repeatedly.

  20. I am no longer positive the place you’re getting your info, however great topic.
    I must spend a while studying much more or figuring out more.

    Thank you for excellent info I used to be on the lookout for this info for my mission.

  21. What’s Going down i’m new to this, I stumbled upon this I’ve discovered It absolutely helpful and it has aided me out
    loads. I am hoping to give a contribution & help other users like its aided me.
    Good job.

  22. When some one searches for his vital thing, therefore he/she desires to be available
    that in detail, therefore that thing is maintained
    over here.

  23. Hello there, I discovered your website via Google at the same time as looking for a similar matter,
    your website got here up, it seems to be good. I have
    bookmarked it in my google bookmarks.
    Hi there, just changed into aware of your weblog via Google,
    and found that it is really informative.
    I’m gonna be careful for brussels. I will appreciate if you continue this in future.

    A lot of folks will likely be benefited out of
    your writing. Cheers!

  24. ยินดีต้อนรับเข้าสู่ครอบครัว โคตร KS ทางเรายินดีให้บริการตลอด
    24 ชั่วโมง
    Kardinal Stick เทคโนโลยีใหม่ล่าสุดในปี
    2020 ด้วยดีไซน์ที่หรูหรา ใช้งานง่าย เหมาะแก่การใช้เป็นตัวเลือกในการเลิกบุหรี่ที่ดีที่สุดในตอนนี้ ?

  25. My brother suggested I might like this website. He used
    to be entirely right. This post truly made my day.
    You cann’t imagine just how much time I had spent for this information! Thanks!

  26. I was suggested this website through my cousin. I am
    no longer certain whether or not this post is written by him
    as nobody else realize such special approximately my problem.
    You’re amazing! Thank you!

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.