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.
I have to thank you for the efforts you have put in penning
this site. I really hope to see the same high-grade content from you later on as well.
In truth, your creative writing abilities has encouraged me
to get my own, personal website now 😉
Also visit my web page: We Buy Any house Reviews
Pills information for patients. Short-Term Effects.
lisinopril
Some what you want to know about pills. Get information now.
кухни на заказ
Greetings I am so delighted I found your blog page, I really
found you by error, while I was researching on Google for something else,
Nonetheless I am here now and would just like to say thanks
for a remarkable post and a all round entertaining blog (I
also love the theme/design), I don’t have time to look over it all at the moment
but I have saved it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up
the great work.
Hi just wanted to give you a quick heads up and let you know a few of the images
aren’t loading correctly. I’m not sure why but I think its
a linking issue. I’ve tried it in two different browsers and both show the same results.
Meds prescribing information. Generic Name.
finasteride
Best information about medicine. Get now.
Hey there! This post couldn’t be written any better!
Reading through this post reminds me of my good old room mate!
He always kept chatting about this. I will forward this
article to him. Fairly certain he will have a good read.
Many thanks for sharing!
This post is really a pleasant one it helps
new the web viewers, who are wishing in favor of blogging.
buy hydroxychloroquine 200 mg
Drugs prescribing information. Brand names.
mobic generic
Everything information about medication. Read here.
I really like it when people come together and share thoughts.
Great website, stick with it!
Saved as a favorite, I like your web site!
With havin so much written content do you ever run into any problems
of plagorism or copyright violation? My website has a lot of completely unique content I’ve either written myself or outsourced
but it appears a lot of it is popping it up all over the web without
my agreement. Do you know any techniques to help prevent content from being stolen? I’d
certainly appreciate it.
naturally like your web-site however you need to check the
spelling on several of your posts. Many of them are rife with spelling issues
and I find it very troublesome to inform the truth nevertheless I’ll certainly come
back again.
I have to thank you for the efforts you’ve put in writing this site.
I really hope to check out the same high-grade content from you in the future as well.
In fact, your creative writing abilities has motivated me to get my own website now 😉
Medicines information for patients. Brand names.
zoloft generics
Some information about drug. Get information now.
Great post. I was checking continuously this blog and I’m impressed!
Extremely helpful information particularly the last part 🙂 I care for such information a lot.
I was seeking this particular info for a very long time.
Thank you and good luck.
I’d like to thank you for the efforts you have put in penning this blog.
I really hope to check out the same high-grade content from you later on as well.
In fact, your creative writing abilities has encouraged me to get
my own site now 😉
It’s not my first time to go to see this site, i am visiting this website
dailly and take fastidious data from here daily.
I used to ƅe able to find gooɗ info frοm your blog articles.
Feel free t᧐ surf to my homeρage – casino
Thanks for your personal marvelous posting! I genuinely
enjoyed reading it, you can be a great author.
I will make certain to bookmark your blog and definitely will come back at some point.
I want to encourage you to definitely continue your great writing, have a
nice afternoon!
Appreciating the time and energy you put into your website and in depth information you provide.
It’s nice to come across a blog every once in a while that isn’t the same unwanted rehashed information. Wonderful read!
I’ve saved your site and I’m including your RSS feeds to
my Google account.
Also visit my homepage … https://usascripthelpers.com/
Drugs prescribing information. Short-Term Effects.
isordil online
Actual what you want to know about medicine. Read information here.
Everything is very open with a very clear description of the challenges.
It was truly informative. Your website is useful. Many thanks for sharing!
Medicines information for patients. What side effects?
rx flagyl
All news about medication. Get now.
Hmm it seems like your site ate my first comment (it was super long) so I guess
I’ll just sum it up what I submitted and say, I’m thoroughly
enjoying your blog. I as well am an aspiring blog writer but I’m
still new to the whole thing. Do you have any
tips and hints for first-time blog writers? I’d genuinely appreciate it.
naturally like your web-site but you need to terst the
spelling on quite a few oof your posts. Many oof themm
aare rie wigh spelling issues and I find it very
troublesome too inform the reality however I’ll
surely come baxk again.
Hi, I do believe this is a great site. I stumbledupon it
😉 I will revisit once again since I saved as a favorite it.
Money and freedom is the best way to change, may you be rich and continue to guide others.
Drugs information leaflet. Drug Class.
pregabalin without dr prescription
All information about medicines. Read here.
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 months of hard work due
to no backup. Do you have any methods to protect against hackers?
OMG! This is amazing. Ireally appreciate it~ May I give
my hidden information on a secret only I KNOW and if you want to seriously get to hear You really have
to believe mme and have faith and I will show how to become a millionaire Once
again I want to show my appreciation and may all
the blessing goes to you now!.
Aw, this was an extremely nice post. Taking the time and actual effort to create a
good article… but what can I say… I procrastinate a lot
and never manage to get nearly anything done.
planet adalah situs paling di percaya semua masyarakat di 2023
planet88
Thank you, I have recently been searching for information approximately this subject for ages and yours is the
greatest I’ve found out till now. However, what
concerning the bottom line? Are you positive in regards to the source?
Join us at elf bar wiki for the best vaping insights and community discussions!
Step into a world of elite vaping experience at elf bar – enhancing your life one puff at a time!
effient blood thinner
You’ve made some decent points there. I looked on the net for more information about the issue and found most individuals will go along with your
views on this website.
This design is wicked! You definitely know how to keep a reader amused.
Between your wit and your videos, I was almost
moved to start my own blog (well, almost…HaHa!)
Great job. I really loved what you had to say, and
more than that, how you presented it. Too cool!
Thanks, I’ve been looking for this for a long time
_________________
матчқа арналған букмекерлік кеңсе
Hey There. I found your blog using msn. This is an extremely well written article.
I will be sure to bookmark it and return to read more of
your useful info. Thanks for the post. I will definitely return.
wonderful points altogether, you just gained a new reader.
What would you suggest in regards to your put up that you just made a few days ago?
Any sure?
hey there and thank you for your info – I’ve definitely picked up something new from right here.
I did however expertise several technical points using this web site, since I
experienced to reload the website lots of times previous to I could get it to load properly.
I had been wondering if your hosting is OK?
Not that I am complaining, but sluggish loading instances times will very frequently
affect your placement in google and could damage your quality score if
advertising and marketing with Adwords.
Anyway I’m adding this RSS to my e-mail and can look out for much more of your respective fascinating content.
Ensure that you update this again very soon.
Meds information leaflet. Brand names.
paxil
Actual trends of drugs. Read information now.
Medication information for patients. Short-Term Effects.
generic viagra
Everything what you want to know about medication. Read now.
This design is incredible! You definitely know how to keep a reader entertained.
Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful
job. I really loved what you had to say, and more than that, how you presented it.
Too cool!
Нас волнует вопрос – http://calidesign.net/hello-world#comment-12480
you are truly a excellent webmaster. The web site loading pace is incredible.
It kind of feels that you’re doing any unique trick.
Also, The contents are masterpiece. you’ve done a fantastic task in this topic!
I got this site from my pal who shared with me on the topic of this web site and now this time
I am browsing this site and reading very informative
posts at this time.
Heya! I know this is kind of off-topic however I needed to ask.
Does operating a well-established website like yours require a lot of
work? I’m brand new to operating a blog but I do write in my diary on a daily basis.
I’d like to start a blog so I can share my own experience and feelings online.
Please let me know if you have any kind of suggestions or tips for brand
new aspiring bloggers. Thankyou!