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.
Thanks for helping out, good information.
Medicament information sheet. What side effects?
zofran medication
Some news about medicine. Get now.
buy viagra online
I like it whenever people come together and share thoughts.
Great website, keep it up!
Feel free to surf to my web site car insurance car insurance
I just like the valuable info you supply on your articles.
I will bookmark your blog and check once more here regularly.
I’m slightly certain I will be told many new stuff proper right
here! Best of luck for the following!
Pretty! This has been an incredibly wonderful
article. Many thanks for supplying this info.
For newest news you have to pay a quick visit the web and on world-wide-web I found this web page as
a most excellent web site for newest updates.
buy disulfiram canada
I visited several web sites except the audio quality for audio songs existing at this web page is really fabulous.
Here is my web page – shymca.org
Drugs prescribing information. Cautions.
viagra buy
All about medication. Get now.
menara368
Step up your vaping game with elf bar! Join us to discover more!
tops pharmacy
lisinopril 40 mg for sale
Experience elf bar‘s incredible range of vaping options like never before!
Hey there, You’ve done a fantastic job.
I’ll certainly digg it and personally recommend to my friends.
I am confident they will be benefited from this web site.
Thanks , I have recently been searching for info about this topic for a long time and yours is the best I’ve came upon so
far. But, what about the conclusion? Are you certain concerning
the supply?
what can a doctor prescribe with lisinopril
Thanks for your marvelous posting! I quite enjoyed reading it, you will be a great author.I will be sure to bookmark your blog and may come back from now on. I want to encourage yourself to continue
your great posts, have a nice weekend!
It’s very straightforward to find out any matter on web as compared to textbooks, as I found this
paragraph at this site.
my homepage :: slot online
Why viewers still use to read news papers when in this technological world the whole thing is accessible on net?
I know this if off topic but I’m looking into starting my own blog and was wondering what all is
needed to get setup? I’m assuming having a blog like yours would cost a pretty penny?
I’m not very internet savvy so I’m not 100% sure. Any tips or advice would be greatly appreciated.
Many thanks
Amazing! Its in fact remarkable article, I have got much clear idea concerning
from this paragraph.
Meds information leaflet. Short-Term Effects.
pregabalin
Actual trends of medication. Get here.
This is a topic which is close to my heart… Many thanks!
Where are your contact details though?
Check out my homepage slot terpercaya
advair 250 cost
Ремонт стиральных машин срочно.
I am not sure where you’re getting your info, but good topic.
I needs to spend some time learning much more or understanding more.
Thanks for magnificent info I was looking for this information for my mission.
Hi! I could have sworn I’ve been to this blog before but after reading through some of the post I realized it’s new to me.
Anyways, I’m definitely happy I found it and I’ll be book-marking and
checking back frequently!
Review my homepage – D1 Keto Gummies Review
Хотите покорить вершины Тетриса https://1tetris.ru? Откройте секреты виртуозного мастерства и достигайте невероятных рекордов! Улучшайте свою концентрацию, реакцию и стратегическое мышление. Разберемся, какие тактики помогут вам выжать максимум из каждого блока. Поделитесь своими советами и узнайте, какие техники используют другие игроки. Готовы ли вы стать настоящим чемпионом Тетриса?
Heya superb blog! Does running a blog like this require a massive amount work?
I have virtually no understanding of coding but I was hoping to start my own blog in the
near future. Anyway, if you have any ideas
or tips for new blog owners please share. I understand this is off topic nevertheless I just
wanted to ask. Many thanks!
That is very interesting, You’re an excessively skilled blogger.
I’ve joined your rss feed and look forward to in quest of extra of your wonderful post.
Additionally, I’ve shared your web site in my social networks
Hi, this weekend is pleasant for me, because this moment i am
reading this impressive educational post here at my house.
Truly when someone doesn’t know then its up to other people that
they will assist, so here it takes place.
I believe people who wrote this needs true loving because
it’s a blessing. So let me give back and show my appreciatation change your life and if you want to really findout?
I will share info about how to make a fortune Don’t forget..
I am always here for yall. Bless yall!
Hi I am so thrilled I found your site, I really found
you by mistake, while I was researching on Askjeeve for something else, Regardless I am here
now and would just like to say many thanks for a tremendous post and a all round entertaining 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 added your RSS feeds, so when I have time I will be
back to read more, Please do keep up the excellent work.
What’s up, I desire to subscribe for this web site to obtain newest
updates, so where can i do it please help out.
watch porn video
atarax price canada
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!
Medication information for patients. What side effects can this medication cause?
quetiapine
Best trends of medicines. Get information here.
Medicament information. Short-Term Effects.
viagra tablets
Some about drug. Get information now.
legit canadian pharmacy
Very good blog post. I definitely appreciate this site.
Continue the good work!
кухни на заказ
Hi, of course this post is really fastidious and I have learned lot of things from it concerning blogging.
thanks.
Medicine information for patients. Short-Term Effects.
synthroid pill
All trends of pills. Get now.
Today, I went to the beach with my kids.
I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the
shell to her ear and screamed. There was a hermit crab inside
and it pinched her ear. She never wants to go back!
LoL I know this is entirely off topic but I had to tell someone!
usa pharmacy
generic elimite cream