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.
Yοu гeally mаke it seem sߋ easy ᴡith уߋur
presentation but I find this matter to Ьe actᥙally something which I thіnk Ӏ wⲟuld
never understand. It seemѕ too complicated ɑnd extremely broad fοr me.
I am looking forward fօr your next post, I’ll try to ɡеt the hang οf it!
Lοok into my web page :: football betting
Medicine information. What side effects?
propecia without rx
Actual about pills. Get information here.
It’s a shame you don’t have a donate button! I’d certainly
donate to this outstanding blog! I guess for now i’ll
settle for book-marking and adding your RSS feed to my Google account.
I look forward to fresh updates and will share this website with my Facebook group.
Chat soon!
It’s typical for application forms to ask for jobb applicants’ age straight (or indirectly,
by assking for the year they graduated frokm
university).
Look into my web-site – 유흥알바
Hello my family member! I wish to say that this post is amazing, great written and include approximately all significant infos.
I’d like to look more posts like this .
Also visit my page; we buy houses for cash reviews
Hello there, I found your website by the use of Google whilst looking for a comparable topic, your web site came up, it seems to
be great. I’ve bookmarked it in my google bookmarks.
Hi there, simply turned into aware of your weblog thru Google, and
found that it’s really informative. I’m going to
be careful for brussels. I will be grateful if you proceed this in future.
A lot of folks can be benefited out of your
writing. Cheers!
http://drive-land.net/kazahskie-pesni-2023.html
prograf medication
Hello there! Do you know if they make any plugins to
safeguard against hackers? I’m kinda paranoid about losing everything
I’ve worked hard on. Any recommendations?
I am actually pleased to glance at this web site posts which includes lots of valuable
data, thanks for providing these kinds of information.
Drug information. Short-Term Effects.
can i get trazodone
Everything about pills. Read information now.
You really make it appear really easy along with
your presentation but I to find this topic to be actually something that I think I would
never understand. It kind of feels too complex and
very large for me. I am looking ahead for your subsequent submit, I’ll try to get the hold of it!
Thanks to my father who told me regarding this website, this blog
is genuinely amazing.
Also visit my site; Calculator Online With History
I’m really impressed with your writing skills as well as 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’s rare to see a nice blog like this one these
days.
Heya i’m for the primary time here. I found this board and I in finding It
truly useful & it helped me out a lot. I hope to give something back and aid others like you
aided me.
https://vashesamodelkino.ru/osobennosti-kazahskoj-muzyki/
cheap generic amoxicillin
Hey I know this is off topic but I was wondering if you
knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
I’ve been looking for a plug-in like this for quite some time
and was hoping maybe you would have some experience with something like this.
Please let me know if you run into anything.
I truly enjoy reading your blog and I look forward to your new updates.
Helⅼo there! Woսld үou mind if I share youг blog with mʏ twitter group?
Τherе’s a lot of folks that I think wouⅼԀ гeally enjoy your content.
Please let me кnow. Thanks
Here is my webpage :: gambling
drugs on deep web deep web links 2023 reddit
A fascinating discussion is definitely worth comment. I do think that you should publish more on this subject matter, it may not
be a taboo subject but generally people do not speak about these subjects.
To the next! Best wishes!!
Wow that was unusual. I just wrote an very long comment but after I clicked
submit my comment didn’t show up. Grrrr… well I’m not writing all
that over again. Anyhow, just wanted to say wonderful blog!
Hi i am kavin, its my first time to commenting anyplace, when i read
this post i thought i could also create comment due to this brilliant post.
My web blog; Colorado Cash Buyers
cara daftar situs slot gacoe 2023
http://virginislandsusblog.bigthings.com/__media__/js/netsoltrademark.php?d=greaterbostonjewelersclub.com%2F__media__%2Fjs%2Fnetsoltrademark.php%3Fd%3Dutechpus.com
It’s a pity you don’t have a donate button! I’d most certainly donate to this fantastic blog!
I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account.
I look forward to fresh updates and will talk about
this website with my Facebook group. Chat soon!
Hi, i think that i saw you visited my web site thus i came to “return the favor”.I am attempting to find things to
enhance my web site!I suppose its ok to use some of your ideas!!
ruonion versus project darknet market
dark markets uk deep onion links
I like the valuable info you supply to your articles. I will bookmark your blog and test once more here
frequently. I’m fairly sure I will learn lots of new stuff proper here!
Best of luck for the following!
onion links for deep web where to find onion links
darknet market busts Cocorico Market
tor marketplace darknet markets reddit 2023
new darknet market reddit black market webshop
reddit onion list deep web trading
Simply want to say your article is as astounding.
The clarity in your put up is just cool and that i could suppose you are an expert in this subject.
Well with your permission let me to seize your feed to keep updated with forthcoming post.
Thank you one million and please carry on the gratifying work.
Medicines information. What side effects?
amoxil
Some about medicament. Read information now.
how to install deep web top ten deep web
tadalafil tablets uk
Pretty! This has been a really wonderful article.
Many thanks for supplying these details.
Hey there, You’ve done an incredible job. I will definitely digg it and personally suggest to my friends.
I am sure they will be benefited from this site.
asap market url tor2door market link
блэкспрут – blacksprut com вход, blacksprut net
outlaw darknet market url darknet market iphone
french deep web link darknet union
Nice weblog here! Also your web site a lot up very fast!
What web host are you using? Can I get your
affiliate hyperlink on your host? I desire my website loaded up as quickly as
yours lol
I could not resist commenting. Very well written!
dark web escrow service Kingdom darknet Market
certainly 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 in finding it very troublesome to tell
the reality nevertheless I’ll surely come back again.
crypto market darknet darknet market updates 2023
darknet drug prices reddit darknet software market