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.
We stumbled over here from a different web page and thought I should check things out.
I like what I see so now i am following you. Look forward to going over your web page yet again.
WOW just what I was searching for. Came here by searching for home remodeling south st paul mn
I pay a quick visit each day a few sites and blogs to read articles, except this webpage offers
feature based posts.
Here is my web site … Hanamsil
vermox 100mg uk
There’s certainly a great deal to know about this subject.
I really like all the points you made.
На сайте https://online-tkm.com/ вы сможете получить консультацию по поводу лечения в Китае. Филиалы поликлиники находятся в Пекине, Даляне, на острове Хайнань. Для каждого пациента составляется собственный план лечения при помощи врачей высокой квалификации и категории. Клиника лицензированная, дает гарантии на лечение. Все врачи отличаются высокой квалификацией, а потому с легкостью справятся даже с самой сложной задачей. Клиника работает круглосуточно и каждый день, чтобы вы смогли в любое время воспользоваться услугой.
Hi there, everything is going fine here and ofcourse every one is sharing information, that’s genuinely fine,
keep up writing.
cost prednisone without rx
menara368
Medicine information leaflet. Long-Term Effects.
propecia otc
Actual news about pills. Get now.
This article will help the internet people for creating new web site or even a blog
from start to end.
Simply desire to say your article is as astonishing. The clarity for
your publish is just spectacular and that i can think you are knowledgeable in this subject.
Fine with your permission let me to seize your RSS feed to keep updated with impending post.
Thanks a million and please keep up the rewarding work.
hello there and thank you for your info – I’ve definitely picked
up anything new from right here. I did however expertise several technical issues using this web site,
since I experienced to reload the web site many times previous to I could get
it to load correctly. I had been wondering if your web host is OK?
Not that I am complaining, but slow loading instances times will often affect your placement in google and could
damage your high-quality score if ads and marketing with
Adwords. Well I’m adding this RSS to my e-mail and can look out for much more of
your respective intriguing content. Ensure that you update this again very soon.
секреты приготовления
Hello, I think your website might be having browser compatibility issues.
When I look at your blog site in Ie, 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, very good blog!
Hello mates, how is the whole thing, and what you wish for to say on the topic of this paragraph, in my view its in fact awesome designed for me.
clonidine .1 mg
Hmm is anyone else encountering problems with the images on this blog loading?
I’m trying to determine if its a problem on my end or if it’s the blog.
Any feed-back would be greatly appreciated.
My web blog :: HentaiStream
I have been surfing on-line more than 3 hours today, yet I
never discovered any fascinating article like yours. It is pretty price enough for me.
Personally, if all site owners and bloggers made excellent content material as you did, the internet
will be a lot more helpful than ever before.
darknet market carding dark markets norway [url=https://darkmarketcypher.com/ ]drug markets onion [/url]
This is the perfect site for anybody who wishes to understand this topic.
You understand so much its almost tough to argue with you
(not that I actually would want to…HaHa). You definitely put a
brand new spin on a subject that has been written about for a long time.
Wonderful stuff, just great!
Paragraph writing is also a fun, if you know after
that you can write or else it is complex to write.
Anonymous Chat is among the easy and easy-to-use talks with
strangers apps.
What’s up, for all time i used to check blog posts here in the
early hours in the daylight, for the reason that i like to find
out more and more.
Touche. Great arguments. Keep up the good effort.
Thankfulness to my father who told me on the topic of this website, this webpage
is truly remarkable.
lipitor australia
I for all time emailed this weblog post page to all my contacts, because if like to read it after that my contacts will too.
Wow, amazing blog layout! How long have you been blogging for?
you made blogging look easy. The overall look of your web site is magnificent,
as well as the content!
зимняя поставушка на форель с 2 крючками – готовые поводки для фидера, двойной поводок для фидера
reliable darknet markets lsd https://dark-market-heineken.com/
Wonderful items from you, man. I’ve have in mind your stuff prior to and
you are just too fantastic. I really like what you have received right here, certainly like what you’re saying and the best way
in which you say it. You make it entertaining and you continue to take care of to
stay it smart. I can’t wait to read far more from you.
That is really a wonderful site.
I believe that is among the such a lot vital
info for me. And i am happy studying your article. However
wanna observation on few common issues, The website taste is great, the articles is actually great : D.
Just right job, cheers
top darknet markets list https://dark-market-heineken.com/
Write more, thats all I have to say. Literally,
it seems as though you relied on the video to make your point.
You clearly know what youre talking about, why throw
away your intelligence on just posting videos to your site
when you could be giving us something enlightening to read?
It’s going to be ending of mine day, however before finish I am
reading this fantastic paragraph to increase my know-how.
french dark web https://dark-market-heineken.com/
counterfeit money deep web https://dark-market-heineken.com/
Appreciating the time and effort you put into your blog
and in depth information you offer. It’s awesome to come across a blog every once in a while that isn’t the
same old rehashed information. Excellent read!
I’ve saved your site and I’m adding your RSS feeds to my
Google account.
Срочный вызов ремонт стиральных машин на дому.
I was able to find good information from your blog
articles.
Meds information for patients. Brand names.
zoloft
Some information about medication. Read here.
Fantastic beat ! I wish to apprentice while you amend your website, how could i subscribe for a blog website?
The account aided me a acceptable deal. I had been a little
bit acquainted of this your broadcast offered bright clear concept
underground black market website deep web link 2023 [url=https://cypher-darknet.com/ ]darknet drugs sales [/url]
what is escrow darknet markets what darknet markets are available [url=https://worldoniondarkweb.com/ ]darkweb markets [/url]
I want to to thank you for this wonderful read!! I absolutely enjoyed every
little bit of it. I’ve got you book marked to check out new
stuff you post…
Also visit my blog post: House Fast For Cash
I love reading through a post that can make men and women think.
Also, thank you for permitting me to comment!
I really like what you guys are up too. This sort of clever work and coverage!
Keep up the great works guys I’ve included you guys to blogroll.
Подавляющее большинство женщин смущает следующая тема: http://ultimate-inferno.co.uk/index.php/2019/10/07/hello-world/#comment-20842
Uncover the rich skruf heritage and savor the outstanding assortment of flavors!