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.
Hello there, just became aware of your blog through Google, and found that it is truly informative.
I am gonna watch out for brussels. I will appreciate if you continue this
in future. Lots of people will be benefited from your writing.
Cheers!
Greetings! Very helpful advice within this post! It’s the little changes which
will make the largest changes. Thanks for sharing!
No matter if some one searches for his required thing, so he/she wants to be
available that in detail, therefore that thing is maintained over here.
Drugs information for patients. Generic Name.
promethazine otc
Some trends of drugs. Read here.
Hello to all, how is the whole thing, I think every one is getting more from this website, and
your views are pleasant in favor of new viewers.
Hmm is anyone else experiencing problems with the images
on this blog loading? I’m trying to find out if its a problem on my end or if it’s
the blog. Any feedback would be greatly appreciated.
Thanks for your personal marvelous posting! I truly enjoyed reading it, you happen to be a great author.
I will be sure to bookmark your blog and definitely will
come back down the road. I want to encourage you to definitely continue your
great writing, have a nice morning!
This is a topic which is close to my heart… Cheers!
Exactly where are your contact details though?
citalopram without a prescription
seroquel tablets buy
May I simply say what a comfort to discover a person that
truly knows what they are talking about on the net. You
definitely know how to bring an issue to light and make it important.
A lot more people must look at this and understand this side of the story.
It’s surprising you aren’t more popular given that you certainly possess
the gift.
My web-site zlatana01
It’s very straightforward to find out any topic on wweb as comared tto books, aas
I found this article at this website.
What i do not understood is if truth be told how you are not really a lot more neatly-favored than you might be right now.
You’re very intelligent. You realize thus considerably in the case of
this subject, made me personally imagine
it from numerous various angles. Its like men and women aren’t
interested unless it’s one thing to do with Woman gaga! Your individual stuffs outstanding.
Always deal with it up!
Hello There. I found your blog using msn.
This is an extremely well written article. I’ll make sure to
bookmark it and come back to read more of your useful info.
Thanks for the post. I’ll definitely return.
propecia 0.5 mg
menara368
Wow, this paragraph is nice, my younger sister is analyzing these things, so I am going to inform her.
Drug information leaflet. Effects of Drug Abuse.
paxil
All trends of pills. Get now.
This piece of writing will assist the internet
people for setting up new web site or even a blog from start to
end.
Нас цепляет следующая мысль: http://kmdcds.com/hello-world/
immune system support
tizanidine cap 4mg
Drug information leaflet. What side effects?
trazodone
All about medication. Get here.
I will right away clutch your rss feed as I can not in finding your e-mail subscription link or e-newsletter service.
Do you’ve any? Kindly permit me recognize in order that I could subscribe.
Thanks.
https://multfilmion.ru/
An interesting discussion is definitely worth comment.
I think that you ought to write more on this topic,
it may not be a taboo subject but generally folks don’t talk about
these subjects. To the next! Kind regards!!
Pills information leaflet. Drug Class.
clomid
All trends of drugs. Read information here.
비아그라 후기 비아그라는 남성 성기능 장애 치료제로 유명합니다. 이 글에서는 비아그라를 사용해본 분들의 후기를 모아 효과와 부작용, 사용 방법 등을 자세히 알려드립니다. 비아그라를 처음 사용해보는 분들은 이 글을 참고하여 적절한 사용 방법과 주의사항을 숙지하시기 바랍니다.
carpet cleaning professional – https://kameronesuim.bloguetechno.com/,
I read this piece of writing fully on the topic of the comparison of most up-to-date and earlier technologies, it’s remarkable article.
Hi Dear, are you truly visiting this web page on a regular basis, if so
afterward you will absolutely take pleasant know-how.
Can you tell us more about this? I’d want to find
out some additional information.
Everyone loves what you guys tend to be up too. This type of clever work and reporting!
Keep up the terrific works guys I’ve included you guys to my blogroll.
Valuable information. Fortunate me I discovered your site accidentally, and I’m shocked why this accident didn’t came about earlier!
I bookmarked it.
Having read this I believed it was rather informative.
I appreciate you finding the time and effort to put this information together.
I once again find myself spending a lot of time both reading and commenting.
But so what, it was still worthwhile!
На сайте http://kuzinfo.ru вы сможете изучить интересные, актуальные новости, которые касаются политики, экономики, финансов. Имеются интервью, мнения первых лиц государств, их комментарии по поводу обстановки в России и мире. Здесь вы найдете и поздравление губернатора Кузбасса с профессиональными праздниками. Все новости сопровождаются красочными картинками, фотографиями, которые помогут наглядно рассмотреть ситуацию. Имеются новости, которые касаются США. Все они свежие и написаны простым языком.
Register and take part in the drawing, win-a-prize.us
lioresal canada
I visited several blogs except the audio quality for audio songs existing at this
web page is in fact fabulous.
Pov порно видео
Thank you for sharing your thoughts. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.
I was curious if you ever considered changing the layout of your blog?
Its very well written; I love what youve got to say.
But maybe you could a little more in the way of content so people could connect with it better.
Youve got an awful lot of text for only having one or 2 images.
Maybe you could space it out better?
mafia slot adalah kumpulan komunitas paling mantap
mafia slot
ингаляторы little doctor купить
Medicament information for patients. Brand names.
lyrica medication
Some what you want to know about medicines. Get information now.
I know this if off topic but I’m looking into starting my own blog and was wondering what all
is required to get setup? I’m assuming having a blog like yours would cost a pretty penny?
I’m not very web smart so I’m not 100% sure. Any suggestions or
advice would be greatly appreciated. Kudos
Also visit my web page: buy my house fast for Cash
Write more, thats all I have to say. Literally, it seems as though you
relied on the video to make your point. You definitely
know what youre talking about, why throw away your intelligence on just posting videos to your weblog when you could be giving us something informative to
read?
cefixime therapy
Wow, fantastic blog layout! How long have you been blogging for?
you made blogging look easy. The overall look of
your site is excellent, as well as the content!
Remarkable! Its genuinely amazing article, I have got much clear idea concerning
from this paragraph.
So if an channce to do additional operafe on thee sde appears, don’t turn it down on the basis of obtaining too pay secondary tax.
Visit my homepage – 노래방알바