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.
На сайте https://moyasimka.ru вы сможете приобрести сим-карты, а также выбрать наиболее подходящий тариф. Предлагается товар дня, который реализуется на самых выгодных условиях и с хорошей скидкой. Ознакомьтесь с лучшими тарифами за этот год. Есть и безлимитные Сим карты для интернета, звонков, для звонков на собственный номер. Кроме того, имеются и модемы. При необходимости воспользуйтесь специальным фильтром по стоимости, новизне, популярности, наличию, в обратном порядке.
most reliable online pharmacy canadian online pharmacy no prescription the canadian pharmacy
http://hanley94vest.jigsy.com/entries/general/You-can-be-everything-a-warrior-singer-plumber-or-hedgehog-when-playing-video-games-Whether-you-want-to-venture-back-in-time-or-out-into-space-there-are-a-few-things-you-need-to-know-This-article-can-help
erectile dysfunction medications cheap ed drugs ed drugs compared
This is really interesting, You’re a very skilled blogger.
I’ve joined your feed and look forward to seeking more of your wonderful
post. Also, I’ve shared your site in my social networks!
Do you have any video of that? I’d love to find out more details.
My page – Organic Labs CBD Reviews
canadian pharmacy no prescription needed: online canadian discount pharmacy – best canadian pharmacy for viagra
kinokong
Thanks for the marvelous posting! I really enjoyed reading
it, you might be a great author.I will always bookmark your
blog and may come back at some point. I want to encourage one to continue your great job, have
a nice evening!
These are actually great ideas in about blogging. You have touched some pleasant factors here.
Any way keep up wrinting.
fildena 100 mg price in india fildena 100 mg price fildena 100mg
мешки для строительного мусора https://meshki-musornie.ru/
I love what you guys tend to be up too. This type of clever work and
exposure! Keep up the amazing works guys I’ve incorporated you guys
to my blogroll.
I’vе been surfing online more than 3 һourѕ toԀay, yet I never found ɑny іnteresting article liқe yours.
It’s pretty worth enoսgh f᧐r me. Ιn mү view, if all site owners and
bloggers mаde good content aѕ you diԀ, thе web
will be a lοt morе usefuⅼ than ever before.
Review my site … football betting (Willard)
тонировка автомобиля – тонировка стекла, тонировка стекол автомобиля
It’s actually very complicated in this busy life to listen news on TV, so I
only use web for that reason, and take the most recent news.
Excellent goods from you, man. I’ve understand your stuff previous to and you are just too magnificent.
I really like what you’ve acquired here, really like what
you’re saying and the way in which you say it. You make it entertaining and you still take care of
to keep it smart. I cant wait to read much more from you.
This is really a wonderful website.
Hi there to every one, the contents present at this web site are genuinely awesome for people knowledge, well,
keep up the good work fellows.
Pretty section of content. I simply stumbled upon your
web site and in accession capital to assert that I acquire actually
enjoyed account your blog posts. Anyway I’ll be subscribing on your feeds
or even I fulfillment you get admission to persistently quickly.
you’re really a good webmaster. The site loading pace is incredible.
It kind of feels that you’re doing any unique trick.
Moreover, The contents are masterwork. you’ve performed
a excellent process on this topic!
Like the rest of the Alder Lake family, the $122 Core i3-12100 comes to market with disruptive
pricing, but it has seen price hikes that have brought it to
$140, which isn’t competitive. You can find the six-core 12-thread Ryzen 5 5600 at $140, a deep discount brought on by competitive pressure from Intel.
Intel ships the 12100F with deactivated integrated graphics, but it is identical to the 12100 in all other ways.
However, Intel supports memory overclocking on Z690, B660, and
H670 motherboards (Z690 doesn’t make sense for
this class of chip, though). The Intel chip is also 3% and
39% faster in single- and multi-threaded productivity apps, respectively.
The chip also has a 65W TDP rating, meaning it runs exceptionally
cool and quiet given its capabilities. Intel’s Alder Lake drops into
Socket 1700 motherboards from the 600- and 700-series, though
the B660, and H610 boards are the most logical fit for a chip at this price
point. Existing AMD owners with a 500-series
motherboard will breathe a sigh of relief as the 5600X drops right into existing 500-, 400-, and 300-series motherboards.
Just be aware that DDR5 is more expensive, and DDR5 motherboards add a bit more to the cost equation, too.
My blog post; https://Social.msdn.microsoft.com
I visited many web sites however the audio quality for audio
songs current at this web site is genuinely fabulous.
юрист по земельным вопросам в московской области
When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment.
Is there any way you can remove people from that service?
Thanks a lot!
my site; Colorado Home Buyers
Hi there just wanted to give you a quick heads up.
The text in your content seem to be running off the screen in Chrome.
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 design look great though!
Hope you get the issue resolved soon. Thanks
графика для квадроциклов – графика на квадроциклы, наклейки на квадроцикл стелс
https://www.boredpanda.com/author/yusufhaagensen703/
Исследуйте мир онлайн сервисов со всевозможными возможностями: переводчики, социальные сети, видео-платформы, Авито, Озон, Вайлдберриз, Валберис, финансовые сервисы, Mail.ru, Яндекс.Почта, Gmail, новостные порталы, развлекательные ресурсы, погода, курс доллара, курс доллара на сегодня, учи.ру, гдз, налоговая личный кабинет, телепрограммы и многое другое. Познакомьтесь с этих воздействии на повседневности, о нюансах применения а также об развитии данных сервисов на протяжении времени
электронный дневник
Спешите! До конца акции вам доступно эксклюзивная скидка: получите грандиозную скидку на подписке на наш еженедельный дайджест. Регистрируйтесь прямо сегодня и быть в курсе самых актуальных новостей из мира гаджетов. Успейте воспользоваться предложением, пока оно действует только до конца недели!
These are really impressive ideas in regarding blogging.
You have touched some fastidious factors here.
Any way keep up wrinting.
buying drugs canada: certified canadian international pharmacy – trusted canadian pharmacy
I’ll right away clutch your rss as I can’t find your
e-mail subscription link or e-newsletter service.
Do you have any? Kindly allow me understand so that I may subscribe.
Thanks.
online pharmacies canadian online canadian discount pharmacy online pharmacy no prescription
I could not refrain from commenting. Well written!
lordfilm сериалы
generic proscar prescription where to get proscar proscar pills for sale
Lisinopril no prescription is a miracle drug for people with high blood pressure.
Nice post. I was checking constantly this blog and I’m impressed!
Extremely helpful info specifically the last part :
) I care for such information a lot. I was seeking this certain information for a very long time.
Thank you and good luck.
For many of the tourists or new citizens of Dubai best fitness clubs in dubai the visit to another city is not a reason to abandon the care about their health.
It could be the likelihood of all of your final folur betting picks becoming right.
Look into my site: 스피드키노
Howdy very nice blog!! Guy .. Excellent .. Wonderful
.. I’ll bookmark your blog and take the feeds additionally?
I am glad to seek out a lot of helpful info here within the
submit, we want develop extra techniques in this regard, thanks
for sharing. . . . . .
It’s nearly impossible to find knowledgeable people in this
particular topic, but you seem like you know what you’re talking
about! Thanks
Howdy just wanted to give you a quick heads up.
The text in your post seem to be running off the screen in Ie.
I’m not sure if this is a format 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 issue fixed soon. Cheers
На сайте https://www.kartapobytupoznan.pl/ru вы сможете получить помощь в оформлении карты побыту. Закажите звонок прямо сейчас, чтобы воспользоваться профессиональной помощью квалифицированного менеджера, который ответит вам на все вопросы, даст ценные советы. Карта побыту считается первым шагом к получению польского гражданства. К тому же, она дает огромное количество привилегий. Кроме того, вы сможете пребывать в других странах без необходимости оформления Шенгенской визы. С такой картой вы сможете устроиться на работу официально.
plavix 75mg price in uk plavix 40 mg price plavix medicine price
You could definitely see your expertise within the article you
write. The arena hopes for more passionate writers like you who aren’t afraid
to say how they believe. All the time follow your heart.
That is really interesting, You are an excessively skilled blogger.
I’ve joined your feed and stay up for searching for extra of your
excellent post. Also, I have shared your website in my social networks
It’s going to be ending of mine day, but before end I am
reading this great piece of writing to improve my knowledge.
Hi Dear, are you genuinely visiting this web site on a regular basis,
if so then you will without doubt get good experience.
Hi there, this weekend is pleasant in support of me, as this point in time i
am reading this wonderful educational paragraph here at my house.
Hey There. I found your weblog the use of msn. This is a
very neatly written article. I will make sure to bookmark it and return to read extra of your
useful info. Thank you for the post. I will certainly comeback.