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.
Hi, і feel that i saw yoս visited my blog sߋ i cаme to return thе want?.I am
trying to іn finding issues tօ enhance my website!І guess itѕ ok to make use ߋf
a few of үour concepts!!
Feel free tօ visit my web-site; casino
Wow! Thank you! I constantly needed to write on my blog something like
that. Can I implement a part of your post to my blog?
Good site you have here.. It’s difficult to
find high-quality writing like yours nowadays.
I truly appreciate individuals like you! Take care!!
proscar 5mg online proscar prescription online proscar generic buy
Normally I do not read article on blogs, however I would like
to say that this write-up very forced me to take a look at
and do it! Your writing taste has been surprised me. Thanks, quite nice post.
dipyridamole aspirin
It’s a shame you don’t have a donate button! I’d without a doubt donate to this brilliant blog!
I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account.
I look forward to new updates and will share this site with my
Facebook group. Chat soon!
Its such as yoս гead my mind! You appear tо understand а
ⅼot about thіs, ѕuch as y᧐u wrote the guide іn it oг sometһing.
I believe thɑt yoս simply can do with some percent tо drive thе message house а bit, howeᴠer insteaԁ of
that, tһiѕ is magnificent blog. A greɑt read.
I’ll definitеly bе baϲk.
Ꮋere is my webpage :: football betting
На сайте https://tent3302.com/ вы сможете приобрести шины, двигатель, запчасти, трансмиссию на Газель. Компания «ПАРКМОТОРС» продает со склада шины в Москве. На портале вы сможете ознакомиться с полным ассортиментом товаров, который получится приобрести прямо сейчас. И главное, что вся продукция, которая находится на портале, оригинальная, качественная и сертифицированная. На нее даются гарантии. Она увеличивает эксплуатационные сроки транспортного средства. За установкой деталей лучше обращаться в проверенную и надежную компанию.
Can I show my graceful appreciation and give my
hidden information on really good stuff and if you want to really findout?
Let me tell you a brief about how to get connected
to girls for free I am always here for yall you know that right?
cara daftar situs slot gacoe 2023
http://www.chembuilder.com/__media__/js/netsoltrademark.php?d=citizenjobsource.com%2F__media__%2Fjs%2Fnetsoltrademark.php%3Fd%3Dutechpus.com
Good site you have got here.. It’s hard to find
high-quality writing like yours these days. I really appreciate individuals like you!
Take care!!
Drugs information sheet. Long-Term Effects.
priligy
Actual information about medication. Get information here.
Hello gгeat blog! D᧐eѕ running a blog such as thiѕ
require a lot ⲟf woгk? I haνе virtually no understanding ᧐f comрuter programming but Ӏ ᴡas hoping t᧐ start my own blog іn the near future.
Ꭺnyhow, sһould you hаve any ideas ⲟr tips for new blog owners ρlease share.
Ӏ understand this is off topic hoԝever I just wanted to aѕk.
Mɑny thanks!
Feel free tߋ visit my site :: baccarat (Declan)
https://ide.geeksforgeeks.org/tryit.php/eac16f65-8426-4924-92ca-4cbdf88378f2
Hey There. I found your blog using msn. This is a really well written article.
I’ll be sure to bookmark it and come back to read more of your useful
info. Thanks for the post. I’ll definitely comeback.
Hi, Neat post. There’s a problem together
with your site in internet explorer, may test this?
IE nonetheless is the marketplace chief and a big part of folks will miss your fantastic writing due
to this problem.
You really make it seem so easy with your presentation but
I find this topic to be actually something that I think I would never understand.
It seems too complicated and very broad for me.
I am looking forward for your next post, I will try to get the hang of it!
Conveniently manage your loan activity with On-line Banking and
the Elements Mobile App.
Also visiot my page: 대출뱅크
It’s nearly impossible to find well-informed people on this subject, but you seem like you know what you’re talking about!
Thanks
I know this if off topic but I’m looking into starting my own weblog
and was curious 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 smart so I’m not 100% certain. Any recommendations or advice
would be greatly appreciated. Kudos
Also visit my web blog; sell house fast Houston
виват запчасти https://vivatsklad.ru/
This is an nice post!
Can I scrape your post and share it with my site subscribers?
Check out my site! It’s about Korean 한국야동
If you are interested, feel free to come to my community and have a look.
Thanks and Keep up the cool work!
It’s the best time to make a few plans for thhe long run and it’s tim to be happy.
I’ve read this put up and if I may I desiree to suggest you some
fascinating issues or tips. Perhaps you could write next articles relating
to this article.I desire to read moree thkngs approxmately it!
discount actos
Will Synthroid 175 affect my mood or emotions?
Thanks , I have just been looking for information approximately this
topic for ages and yours is the best I have discovered so far.
But, what concerning the bottom line? Are you sure in regards to the supply?
Сайт https://habitsbad.com/ представляет собой дистанционного помощника, который смотивирует вас на то, чтобы отказаться от вредных привычек. На сайте опубликованы курсы, которые помогут вам справиться с токсичной зависимостью, курением навсегда. Лекции по самоорганизации будут вам полезны в этом вопросе. Отказ от пагубных привычек поможет вам улучшить здоровье, укрепить иммунитет и даже выглядеть намного лучше. Здесь не будут однотипные рассказы либо заезженные шаблоны. Только реальные и действенные советы, которые обязательно вам помогут.
Heya terrific website! Does running a blog like this require a massive amount work?
I’ve absolutely no understanding of coding but I had been hoping to start my own blog in the near
future. Anyways, if you have any recommendations
or tips for new blog owners please share. I understand this is off subject however
I simply had to ask. Many thanks!
Hello there, just became aware of your blog through
Google, and found that it’s truly informative. I’m gonna
watch out for brussels. I will be grateful if you continue
this in future. Many people will be benefited from your writing.
Cheers!
Very interesting information!Perfect just what I was looking for!
Also visit my page: Nature’s Boost Blood Formula
Great goods from you, man. I have understand your stuff previous to and you’re just
too wonderful. I actually like what you have acquired here, certainly like
what you’re stating and the way in which you
say it. You make it entertaining and you still care for
to keep it smart. I can not wait to read far more from you.
This is actually a terrific website.
Hello Dear, are you actually visiting this site daily, if so after that you will without doubt obtain pleasant know-how.
Medicines information sheet. Cautions.
cytotec
Best news about medication. Read information here.
Hmm is anyone else experiencing problems with the pictures on this blog loading?
I’m trying to figure out if its a problem on my end or if it’s the blog.
Any responses would be greatly appreciated.
Article writing is also a excitement, if you be acquainted with then you can write if not
it is complex to write.
Hi it’s me, I am also visiting this site daily, this site is actually fastidious and the visitors are really sharing good thoughts.
I was recommended this website by my cousin. I’m not sure whether this post is
written by him as nobody else know such detailed about my problem.
You are incredible! Thanks!
Spot on with this write-up, I absolutely feel this site needs far more attention. I’ll probably be returning to read
more, thanks for the info!
ashwagandha pills
generic for plavix plavix generics plavix 75 price
Hello, after reading this amazing paragraph i am as well delighted to share
my experience here with mates.
AI technology has revolutionized my online business strategy!
This innovative platform provides a comprehensive set
of tools and resources that have helped me maximize my online revenue,
enhance my marketing efforts, and boost overall engagement.
If you’re looking to make a significant impact in the competitive online landscape, this AI-driven solution is a
game-changer.
This site was… how do I say it? Relevant!!
Finally I’ve found something that helped me. Kudos!
I’m extremely impressed with your writing skills as well as with the layout on your blog.
Is this a paid theme or did you modify it yourself?
Either way keep up the nice quality writing, it’s rare to
see a nice blog like this one these days.
fildena 25
Great beat ! I would like to apprentice while you amend your site, how could i subscribe for a blog
web site? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast
provided bright clear idea
Excellent article. Keep writing such kind of information on your blog.
Im really impressed by your blog.
Hi there, You have performed an incredible job. I’ll definitely digg it and personally suggest to my friends.
I’m sure they will be benefited from this website.
There’s definately a lot to learn about this issue.
I like all of the points you’ve made.
budesonide 1 mg tablet