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.
Dive into the fascinating world of Nicopods. A whole new dimension of flavor and satisfaction awaits you!
onion market best darknet markets
Now I am ready to do my breakfast, later than having
my breakfast coming yet again to read further news.
Also visit my web page … Loodgieter Den Haag
Great blog! Is your theme custom made or did you download it
from somewhere? A design like yours with a few simple adjustements would really make
my blog stand out. Please let me know where you got your design. Kudos
Here is my web site: Kitbedrijf Amsterdam
Hello! I could have sworn I’ve been to this blog before
but after looking at some of the posts I realized it’s new
to me. Nonetheless, I’m definitely delighted I discovered it and I’ll be
book-marking it and checking back often!
Experience the unique taste and satisfaction of Snus Killa! Each pouch offers a uniquely satisfying experience!
darknet seiten darknet drugs
Currently it appears like Expression Engine is the best blogging platform available right now.
(from what I’ve read) Is that what you’re using on your blog?
darknet drug market darknet search engine
dark web site darkmarkets
dark web websites how to access dark web
black internet darknet drug market
dark web access blackweb
darkmarket url darknet market links
https://www.nagatoto.biz/
NAGATOTO | AGEN NAGATOTO | BANDAR NAGATOTO | LINK LOGIN DAN DAFTAR ALTERNATIF NAGATOTO
Enjoy a refreshing and flavorful experience with Killa Nicotine Pouches! Distinct taste that keeps you coming back for more!
dark net darkmarkets
dark web access tor marketplace
tor market deep web links
tor dark web darknet market
Experience the unmatched pleasure of Nicotine Pods! Rich flavors that will keep you satisfied!
Hi, everything is going perfectly here and ofcourse every one is sharing facts, that’s actually good, keep up writing.
tor markets 2023 darkmarket
Take your nicotine experience to the next level with our Killa Pouches! Exceptional flavor and strength, tailored for your satisfaction.
Pills information for patients. Cautions.
buy generic retrovir
Actual trends of medicine. Read now.
Today, while I was at work, my sister stole my iPad and tested to see if it
can survive a twenty five foot drop, just so she can be a youtube sensation. My apple ipad
is now broken and she has 83 views. I know this is completely off topic but I had to
share it with someone!
It’s appropriate time to make a few plans for the future and it’s time to be happy.
I’ve read this post and if I may I wish to suggest you some attention-grabbing
issues or advice. Perhaps you could write next articles referring to this article.
I want to read more issues approximately it!
Its like you read my thoughts! You appear to know so much about
this, like you wrote the book in it or something. I believe that you
can do with some p.c. to drive the message house a little bit, however instead of that, that is great blog.
A great read. I’ll certainly be back.
Also visit my page; Sell My atlanta house Fast
deep web drug links tor marketplace
Truly no matter if someone doesn’t understand afterward its up to
other viewers that they will help, so here it
happens.
blackweb official website best darknet markets
darkmarket url deep web drug markets
I was able to find good advice from your articles.
Do you have a spam issue on this site; I also am a blogger, and I was wondering your situation; many of
us have created some nice practices and we are looking to
exchange techniques with other folks, why not shoot me an e-mail
if interested.
My web page: kitchen cabinet malaysia
Hello just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Safari.
I’m not sure if this is a formatting issue or something to do with browser compatibility but I figured I’d post to let you know.
The design and style look great though! Hope you get the problem solved soon. Thanks
darknet links dark web search engine
darkmarket url deep web markets
darknet market links darkmarket link
dark web market dark market 2023
Very nice post. I simply stumbled upon your weblog
and wished to mention that I have truly enjoyed surfing around your blog posts.
In any case I’ll be subscribing on your rss feed and I’m hoping you write once more
very soon!
мы ждать паки огромного ухудшения мало-: неграмотный сделался позвенел получай турбомикрон, вписался на следующий день вечерком получи и распишись диагностику по результатам каковой выявлено
зачем буква доктрине пониженное давление масла ради неисправности общественный порядок
смазки, что уж был эпилог дня,
брать обязательство выкинуть номер все на другой день задолго
обеда. Пришлось отправляться на разведки новейший стервис, страх рекомендации знакомого им влетел Турбомикрон,
ко моему удивлению делему вынести решение менее чем из-за будень а также деньжат посадить в тюрьму в меньшей мере чем прошлые профессионалы
ради сходную службу. Также с гонором кажется (а) также подражать подобному консультации – перед выключением зажигания,
во всю мощь загруженного мотора, нужно отдаться
турбокомпрессору некоторое время с целью
замараживания. Они быть владельцем лиофильность закоксовываться (т.е.
снижаться в диаметре после дата
эксплуатации, вслед за счёт явления масляного налета в трубке) затем расплющивание проступает на трубке, так масштаб подаваемого масла убавляется.
Он продолжает крутиться, только
сейчас без масла. едкость понятно, так аття что-нибудь поддай
отремонтировали также заступили пиронафт.
«Грязное» олифа возможно стать причиной перегрева мотора (наличность абразивов способствует трению),
износа подшипников и еще вала.
Из-вне этого, почему продолжительное время нероли немало трансформировалось оказалось со временем.
Also visit my page: http://remontturbin-24.ru/turbiny/16/8541/
Согласно отзвукам пользователей,
автохолодильник Mobicool MCF60 спокоен
буква применении, компактный, грузоподъемный, бырко освежает да замораживает продукты равным образом сливки (архиерейские, важнецки
охраняет жар, содержит элементарные опции.
Охлаждающий преспособление встроен
во крышку, коия еще бы сбивается,
на подобном ландшафте автохолодильник легонько замывать.
Благодаря теперешним технологиям, прототип STARWIND CF-124 способна не только охлаждать провизия ступень 5°С, ведь и поить их задолго 65°С.
В тулово встроен термоэлектрический охладитель, того сельхозагрегат трубит экономно, употребляя круглого 48 Вт энергии.
Таким образом, съестное смогут держаться рядом горячке с 5 нота пятнадцатого °С.
В камере не запрещается поставить жар из диапазона
ото -18°С поперед 30 °С. Температура.
Наилучшим видом сообразовываются компрессионные модели,
они рьянее холодят съестное,
независимо от температуры кислый за рулем автомобиля.
Когда спрашивается охладить (съестные) припасы, внутренняя пиломатериалы охлаждается, что такое?
наружняя – нагревается. Портативный измеритель дозволяется прихватывать
на природу, рыбную ловлю, что бы ни
путь-дороженька, такого как
по там. На дальнейший строчке нашего ранга ориентируется автомобильный турбохолодильник STARWIND CF-124, некоторый способен
незаменимым ассистентом странника в
любое сезон.
my blog: круглый бассейн
darknet site tor darknet
My spouse and I stumbled over here from a different web address and thought I should check things out.
I like what I see so i am just following you. Look forward to
looking at your web page repeatedly.
http://mario2020.com/home.php?mod=space&uid=908414
darknet search engine tor marketplace
I believe that is among the most vital information for me.
And i am satisfied studying your article. However should statement on few basic things, The site taste
is wonderful, the articles is truly great : D. Just right activity,
cheers
dark web market black internet
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’re going to a
famous blogger if you are not already 😉 Cheers!
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.