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.
baclofen 20 mg online buy baclofen australia baclofen 10 mg tablet brand name
Seriously need to make an Accutane purchase, these zits are too much.
Can you tell us more about this? I’d want to find out some additional information.
My blog :: https://avtonomera-77.ru/
OMG! This is amazing. Ireally appreciate it~ May I give my hidden information on a secret only I KNOW and if you want to really findout?
You really have to believe mme and have faith and I will show how to make a fortune Once again I want to show my
appreciation and may all the blessing goes to you now!.
Hello! I know this is somewhat off-topic howeѵer I needed to asҝ.
Does building a well-establіshed website like yours takе a maѕsiνe amount worҝ?
I’m completely new to writing a blog however I do write in my diary everyday.
I’d like to start a blog so І can easily share my experience and feelings
online. Please let me knoᴡ if you have any recommendatiоns or tips for brand new aѕpiring bloggers.
Thankyоu!
Feel free to visit my blog; Психология [pedagog-razvitie.ru]
ผลิตภัณฑ์ Relx Infinity นั้น ถือเป็น ผลิตภัณฑ์ ที่ถูก พัฒนาขึ้นมา จากการนำเอา ปัญหา จากรุ่นก่อนอย่าง Relx Zeero
และ Relx Alpha ควบคู่กับ
เทคโนโลยีสมัยใหม่จนได้ออกมาเป็น ผลิตภัณฑ์ ที่มีดีไซน์ ที่เรียบหรู กว่าเดิม ทนทาน กว่าเดิม และที่สำคัญ ให้ฟีลสูบ หรือ รสชาติ ที่ แน่น
ชัดเจน แต่นุ่มนวล ไม่แทงคอ ไม่ว่าจะเป็นมือใหม่หรือมือเก่า ก็สามารถใช้งานไ
Fastidious answer back in return of this issue with firm arguments and explaining all on the topic of that.
3D заборы представляют собой
новую эстетическую тенденцию в строительстве ограждений.
Они сочетают функциональность обычных
заборов с уникальным трехмерным дизайном.
3D заборы могут быть выполнены из различных материалов,
таких как металлическая сетка или пластик,
обеспечивая прочность и долговечность.
Эти ограждения становятся все более популярными в современном ландшафтном дизайне благодаря своей элегантной внешности и разнообразности
дизайнерских вариантов.
Engage with zyn and dive into the world of nicotine pouches online. Explore the vibrant Zyn1 community and share your experiences.
I truly love your site.. Very nice colors & theme.
Did you create this site yourself? Please reply back as I’m hoping to create my very own blog and would love to learn where you got
this from or just what the theme is named. Cheers!
Hey would you mind letting me know which hosting company you’re
using? I’ve loaded your blog in 3 completely different internet browsers and I must
say this blog loads a lot faster then most. Can you suggest a
good web hosting provider at a honest price?
Kudos, I appreciate it!
When someone writes an post he/she maintains the thought of
a user in his/her mind that how a user can understand it.
So that’s why this post is outstdanding. Thanks!
Join the zyn revolution and discover the finest selection of nicotine pouches at Zyn1 Shop. Share your Zyn experiences and reviews with our community.
Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out much.
I hope to give something back and aid others like you helped me.
Hey very nice blog!
Thanks for the good writeup. It in reality used
to be a enjoyment account it. Glance advanced to more added agreeable from you!
However, how could we be in contact?
3D заборы обладают рядом преимуществ.
Во-первых, они создают эффект
объемности и глубины благодаря своей трехмерной структуре,
что придает уникальный внешний вид всему забору.
Во-вторых, такие заборы обеспечивают дополнительную приватность
и безопасность, так как плотная
структура 3D забора предотвращает проникновение посторонних и обеспечивает ограниченный обзор снаружи.
I’m curious to find out what blog system you are using?
I’m having some small security problems with my latest
website and I’d like to find something more secure. Do you
have any solutions?
I do trust all the ideas you have presented
on your post. They are really convincing and
can definitely work. Nonetheless, the posts are too quick
for starters. Could you please extend them a
little from next time? Thank you for the post.
Just want to say your article is as astonishing. The clearness in your post is just nice and i can assume you’re an expert
on this subject. Well with your permission let
me to grab your feed to keep up to date with forthcoming post.
Thanks a million and please carry on the rewarding work.
Medicines information for patients. What side effects can this medication cause?
zofran cost
Some what you want to know about medicines. Get information here.
It’s amazing to go to see this web page and reading the views of all friends concerning this post, while I am also zealous of
getting familiarity.
Do you have a spam problem on this blog; I also am a blogger, and I was curious about your situation; many of
us have created some nice procedures and we are looking to swap solutions with others, why not shoot me an email if interested.
Wow, this piece of writing is pleasant, my younger sister is analyzing
these kinds of things, therefore I am going to let know her.
buy generic proscar online buy proscar online canada proscar order online
This article is actually a good one it assists new the web visitors, who are wishing in favor of blogging.
Wonderful goods from you, man. I have understand your stuff previous to and you are
just extremely magnificent. I really like what you’ve
acquired here, really like what you are saying and the
way in which you say it. You make it enjoyable and you still care
for to keep it sensible. I can’t wait to read far more from you.
This is really a wonderful web site.
If some one wiishes to be updated with latest technologies after that hee must
be pay a visit this site and be up to date all the time.
fake marriages for citizenship price
It’ѕ neɑrly impossible tߋ fіnd educated people аbout thiѕ subject, bᥙt уoս sound
ⅼike you know wһat you’re talking аbout! Thanks
my blog casino
Wow, fantastic blog layout! How long have you been blogging for?
you make blogging look easy. The overall look
of your web site is magnificent, as well as the content!
I do consiⅾer all the concepts уoᥙ hаve introduced іn your post.
Τhey aгe vеry convincing and cаn certainly ᴡork.
Ѕtill, the posts are too short fօr novices. May you ρlease prolong tһem a little from next time?
Ƭhank yօu fօr tһe post.
Check out my web site lotto
When I initially commented I clicked the “Notify me when new comments are added” checkbox
and now each time a comment is added I get several emails with the same comment.
Is there any way you can remove people from that
service? Cheers!
Aw, this was an exceptionally nice post. Taking the time and actual
effort to produce a very good article… but what can I say… I hesitate a
whole lot and don’t manage to get nearly anything done.
proscar canada price proscar price how to get proscar prescription
Thanks in favor of sharing such a good thought, piece of writing is fastidious, thats
why i have read it entirely
What’s up mates, how is all, and what you would like to say regarding this post, in my view its truly remarkable
for me.
WOW just what I was looking for. Came here by searching for porn
I read this article completely on the topic of the comparison of hottest and
earlier technologies, it’s remarkable article.
Link exchange is nothing else except it is only placing the
other person’s website link on your page at proper place and other person will
also do similar for you.
I can’t wait to get out of here and continue my treatment with Cipro IV at home.
dipyridamole 25 mg tablet
Best site from all Apes. Primates and original NFT Monkey.
https://satbayev.university
hello!,I like your writing so much! share we communicate extra
approximately your post on AOL? I need an expert on this house to
solve my problem. Maybe that is you! Having a look forward
to see you.
Thankfulness to my father who stated to me regarding this blog,
this website is actually remarkable.
Have a look at my blog post – nolimit123
Excuse me, can I buy Metformin over the counter here?
I am genuinely thankful to the holder of this website who has
shared this wonderful post at here.
lexapro 1 mg lexapro 2.5 mg can i buy lexapro online without prescription
It’s thee only timme of my career that I seriously thought of a significantly lss demanding job.
Review my webpage 여자알바