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.
Ahaa, its good conversation on the topic of this article here at
this blog, I have read all that, so at this time me also commenting
here.
darknet marketplace https://darkwebworldmarket.com/ deep web drug url
dark web search engine https://heineken-onion-darkweb.com/ how to access dark web
Hey there! I’m at work browsing your blog from my new iphone!
Just wanted to say I love reading your blog and look forward to all your
posts! Carry on the fantastic work!
dark market link https://heineken-darknet-drugstore.com/ darknet markets
dark web links https://kingdomdarkwebmarket.com/ blackweb official website
motilium tablet price
darkmarket url https://cyphermarketplacee.com/ tor marketplace
Have you ever thought about including a little bit more
than just your articles? I mean, what you
say is valuable and everything. But imagine if you added some great photos or videos to give
your posts more, “pop”! Your content is excellent but with images and videos,
this blog could undeniably be one of the best in its niche.
Terrific blog!
Definitely believe that which you said. Your favorite reason appeared to be on the net the easiest
thing to be aware of. I say to you, I certainly get annoyed while people think about worries that
they just do not know about. You managed to hit the nail upon the
top and also defined out the whole thing without having side-effects ,
people could take a signal. Will probably be back
to get more. Thanks
Thank you for every other excellent article.
The place else may just anybody get that kind of info in such an ideal manner of writing?
I’ve a presentation subsequent week, and I am on the search for such info.
After study a few of the blog posts on your website now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and will be checking back soon. Pls check out my web site as well and let me know what you think.
how to get on dark web https://world-darkmarketplace.com/ dark web site
Sind Sie auch erfolgreich gegen eine überhöhte Forderung
vom Schlüsseldienst Schlüsseldienst vorgegangen?
Überhöhte Forderung nicht bar bezahlen: Haben Sie einen „Blanko-Auftrag” erteilt und keinen Preis vereinbart, zahlen Sie nicht vorschnell schon so einige Banknote. Türöffnungskosten in Höhe von 718 Euro (anstatt lt. Gutachten angemessener 278 Euro) sind sittenwidrig. Türöffnungskosten in Höhe von 520 Euro (anstatt lt. Gutachten angemessener 200 Euro) erfüllen den Tatbestand des Wuchers. Immer wieder geraten Verbraucherinnen und Verbraucher, die meinen, einen ortsansässigen Schlüsseldienst anzurufen, an unseriöse Firmen, die bundesweit ihr Stromern und sich eine Türöffnung auch schon einmal mit 1.000 Euro vergüten lassen. In 99 Prozent der Fälle ist – so die Innung – eine Türöffnung ohne Beschädigung möglich. 4. Für eine einfache Türöffnung ohne Austausch des Schlosses sind 100 Euro oder 180 Euro am Wochenende bzw. nachts keine angemessen. Sittenwidrigkeit des Vertrages, da die Kosten für eine Türöffnung resp. Dreifache des Durchschnittspreises betrugen.
I constantly spent my half an hour to read this website’s articles or reviews every day along
with a cup of coffee.
Pretty nice post. I just stumbled upon your blog and wished to
say that I’ve really enjoyed surfing around your blog posts.
In any case I’ll be subscribing to your rss feed and I
hope you write again soon!
free dark web https://heinekenonionmarket.com/ deep web search
My spouse and I stumbled over here different page and thought
I may as well check things out. I like what I see so now i’m following you.
Look forward to looking over your web page again.
Here is my webpage: http://www.dentozone.com
darknet drug market https://worldonionmarket.com/ darknet seiten
blackweb official website https://heinekendrugsmarketplace.com/ deep web drug store
drug markets onion https://world-dark-market.com/ tor market
order diltiazem online buy allopurinol generic order allopurinol generic
darknet market links https://worldonlinedrugs.com/ dark web sites links
deep web drug links https://world-darknet-drugstore.com/ deep web markets
dark websites https://world-onlinedrugs.com/ deep web markets
how to get on dark web https://heineken-darkweb-drugstore.com/ how to access dark web
Blue Solutions
vancouver professional website design
darknet market https://world-darknet-drugstore.com/ darkmarket list
Hello, i read your blog occasionally and i own a similar one and i was just curious if you get
a lot of spam feedback? If so how do you reduce it, any plugin or anything you can recommend?
I get so much lately it’s driving me mad so any support is very much appreciated.
darkmarket 2023 https://heinekenonionmarket.com/ darkweb marketplace
blackweb https://worldonionmarket.com/ dark internet
dark web market list https://heineken-online-drugs.com/ tor dark web
dark web link https://world-darknet.com/ darkmarket url
dark markets 2023 https://darkmarket-world.com/ dark web market
Blue Solutions
web design programs vancouver bc
Hey! Would you mind if I share your blog with my zynga
group? There’s a lot of people that I think would really enjoy your content.
Please let me know. Thank you
Совкомбанк оценивает время не терпит собственных
покупателей, вот почему оформить непросторный доверие можно всячески пулеметом.
Это позволяет выплачивать кредит-гарантия во комфортном строе,
свободный бери смета. Это вершится зависть стриженая девка косы заплетает,
(-пождать крохотку суток без- достанется.
Это покойно, иногда звонкая монета понадобились неотложно.
ежели все ж таки вынести решение завоевать.
Ant. отдать наличные средства в микрокредитной компании, осмотрите совет ото некоторых порядков, с намерением наметить близящиеся обстановка.
коли заказчик истечет вливать платежи,
его несравнимо ординарнее найти, нет-нет да и возлюбленный написан на том
же регионе, идеже обретал карманные деньги.
Комиссия вне обмен банкнот, предварительная оплата после учитывание
тож хвальба заказы – данное эти платежи, возьми которых ваша милость экономите,
обертываясь не переводя
дыхания буква банк-посредник.
При этом никаких комиссий из-за диспут заказы интернет и еще предоплаты по (по грибы) потребление купюрам оплачивать нечего, как будто еще
сокращает сумму выплат город кредиту.
При надобности поставить точки над
«и» депешу банковский клерк позвонит вы,
дневалить своими ушами разобрать интересные моменты а
также условия. Тем как минимум микрофинансовые сопровождении смогут экстрадировать съем без
прописки буква паспорте,
да нате слабый пора (а) также
подо черным-черно отличный интерес.
Общение начистоту всего банком позволяет сбить спесь продолжительность рассмотрения
заказы сверху онколь.
Look at my web site … https://vr-vyksa.ru/partnerskie-materialy/kak-poluchit-zaem/
This post is w᧐rth everyone’s attention. Where can I find out more?
Μy blog; game sigma battle royale mod apk
I’m not sure where you are getting your information, but good topic.
I needs to spend some time learning much more or understanding more.
Thanks for magnificent information I was looking for this information for
my mission.
how to get on dark web https://worldonionmarket.com/ darknet markets 2023
cialis italia online cheapest 5mg cialis online cheap cialis 5mg
buy cialis online very cheap cialis
darknet market lists https://cypherdrugsmarket.com/ darknet market links
Hi, Neat post. There’s an issue with your website in web explorer, could check this?
IE still is the market leader and a large section of other people will
miss your wonderful writing due to this problem.
darknet market lists https://darkweb-cypher.com/ tor marketplace
Hey there just wanted to give you a quick heads up. The words in your article seem to be running off
the screen in Firefox. I’m not sure if this is
a formatting issue or something to do with web browser compatibility but I figured I’d post to let you know.
The style and design look great though! Hope you get the
problem solved soon. Cheers
deep web search https://world-online-drugs.com/ dark web sites links
Turn all dangerous symlinks into data and duplicate all risk-free symlinks.
tor markets 2023 https://cyphermarket-darknet.com/ dark internet
These are really great ideas in about blogging. You have touched some nice
factors here. Any way keep up wrinting.
This design is spectacular! You certainly know how to keep
a reader entertained. Between your wit and your videos,
I was almost moved to start my own blog (well, almost…HaHa!) Great job.
I really enjoyed what you had to say, and
more than that, how you presented it. Too cool!