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, I enjoy reading all of your article. I wanted
to write a little comment to support you.
Everyone loves it when people get together and share ideas.
Great blog, continue the good work!
It’s perfect time to make some plans for the future and it
is time to be happy. I have read this post and if
I could I want to suggest you some interesting things or suggestions.
Maybe you can write next articles referring to this article.
I wish to read more things about it!
Ηi tto all, hoᴡ is everything, І think every one is getting
more from this weƄ sіte, and your views are fastidiouѕ iin support of new users.
My webpage; slot online
deep web search how to get on dark web
Good day! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success.
If you know of any please share. Kudos!
Hello it’s me, I am also visiting this web page daily, this web page
is in fact good and the users are genuinely sharing nice thoughts.
I’m not that much of a online reader to
be honest but your blogs really nice, keep it up!
I’ll go ahead and bookmark your website to come back later.
Cheers
I am regular visitor, how are you everybody? This post posted at this website
is truly fastidious.
Thanks , I have recently been looking for information about
this subject for a while and yours is the greatest I’ve came upon so far.
But, what about the conclusion? Are you sure concerning the source?
I’m really impressed with your writing skills and also with the
layout on your blog. Is this a paid theme or did you customize it yourself?
Either way keep up the nice quality writing,
it is rare to see a nice blog like this one these
days.
Hello There. I found your weblog the use of msn.
That is a very well written article. I’ll
make sure to bookmark it and return to learn more of your helpful information. Thank
you for the post. I’ll definitely return.
My blog post – dvt toto
I blog frequently and I genuinely appreciate your content.
This great article has really peaked my interest. I am going
to bookmark your site and keep checking
for new information about once per week. I subscribed to
your RSS feed too.
free sms https://smsreceiver24.io/
deep web drug markets darknet site
Pretty! This has been an extremely wonderful article. Many
thanks for supplying this info.
Feel free to surf to my web blog; สาระน่ารู้ทั่วไป
I like the valuable info you supply for your articles. I
will bookmark your weblog and take a look at once more
right here regularly. I’m moderately certain I’ll learn lots of new stuff right right here!
Best of luck for the following!
This is a topic that is close to my heart… Cheers! Where are your contact details though?
Feel free to surf to my site – Virology
Hi there, just became aware of your blog through Google, and found that it is really informative.
I am gonna watch out for brussels. I will be grateful if you continue this in future.
Numerous people will be benefited from your writing. Cheers!
Here is my blog post; wordpress hosting
darknet drug links darknet links
Great blog here! Also your site quite a bit up fast! What host are you
the use of? Can I get your affiliate hyperlink in your host?
I wish my web site loaded up as fast as yours lol
my blog – Influenza B
Drug prescribing information. Long-Term Effects.
eldepryl otc
Best what you want to know about meds. Get now.
http://shiba-inu.ru/forum/messages/forum1/topic17/message21/?result=new
What’s up to every one, as I am genuinely eager of reading this webpage’s post
to be updated daily. It consists of fastidious information.
Article writing is also a excitement, if you be acquainted with after that you can write or else it is complex to write.
Feel free to surf to my web blog – Art 27 Miami
http://lorail252bow.bestbb.ru/viewtopic.php?id=44
darkmarket list darknet drug store
I like what you guys are usually up too. This sort of
clever work and exposure! Keep up the superb works guys I’ve incorporated you guys to our blogroll.
Here is my blog; shared hosting
Great article! That is the kind of info that are supposed to be shared across the web.
Shame on the seek engines for now not positioning this post
higher! Come on over and visit my web site . Thanks =)
Here is my web site :: hanamsil.kr
I wanted to thank you for this exceⅼlent
read!! I definitely loved every little bit off it.
I’vе got you bookmarked to chec out new things you post…
Check out myу website: slot gacor 2023
Hi there, I want to subscribe for this weblog to obtain latest
updates, so where can i do it please help.
Hey, I think your blog might be having browser compatibility issues.
When I look at your blog in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping.
I just wanted to give you a quick heads up!
Other then that, terrific blog!
A fascinating discussion is definitely worth comment.
I believe that you need to publish more about this topic,
it may not be a taboo matter but typically people do not
speak about these topics. To the next! Many thanks!!
I am sure this article has touched all the internet viewers, its really really
nice paragraph on building up new web site.
http://chromerp.listbb.ru/viewtopic.php?f=13&t=134
I don’t even know how I ended up here, but I thought this post was good.
I do not know who you are but definitely you are going to a famous blogger if you are not already 😉 Cheers!
These are truly enormous ideas in on the topic of blogging.
You have touched some good factors here. Any way keep up wrinting.
I think this is among the most important info for me.
And i’m glad reading your article. But wanna remark
on few general things, The website style is ideal, the articles is really excellent
: D. Good job, cheers
Hi friends, how is everything, and what you want to say about this article,
in my view its truly amazing for me.
Heya i am for the first time here. I came across this board and I find
It truly useful & it helped me out a lot. I hope to give
something back and help others like you helped me.
Greetings! Very helpful advice within this article! It’s
the little changes which will make the greatest changes. Many thanks for sharing!
Howdy! I know this is somewhat off topic but I was wondering if you knew where I
could get a captcha plugin for my comment form? I’m using the same blog platform as yours and
I’m having trouble finding one? Thanks a lot!
Feel free to visit my web page – Art 27 Miami
http://impressiverp.listbb.ru/viewtopic.php?f=16&t=215
I am curious to find out what blog platform you happen to be
utilizing? I’m experiencing some minor security issues with my latest site and I’d like
to find something more safe. Do you have any suggestions?
Hello this is kinda of off topic but I was wondering if blogs use
WYSIWYG editors or if you have to manually code with HTML.
I’m starting a blog soon but have no coding experience so I wanted to get advice from someone with experience.
Any help would be enormously appreciated!
Also visit my website … 블로그마케팅프로그램
Hey would you mind letting me know which hosting company you’re
using? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot quicker then most.
Can you suggest a good internet hosting provider at a
reasonable price? Thanks, I appreciate it!
This is my first time pay a quick visit at here and i am in fact happy to read everthing at alone place.
I always emailed this weblog post page to all my associates, for
the reason that if like to read it next my friends will too.
It’s an amazing piece of writing for all the online people; they
will obtain benefit from it I am sure.
http://crewties.moibb.ru/viewtopic.php?f=2&t=40