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.
Why users still use to read news papers when in this technological
globe the whole thing is available on net?
I believe this is one of the so much vital info for me.
And i’m happy reading your article. But should remark on few general things, The web site taste
is great, the articles is in reality great : D.
Good activity, cheers
http://blackscarpions.bestbb.ru/viewtopic.php?id=52
Do you mind if I quote a couple of your articles as long
as I provide credit and sources back to your website?
My blog is in the exact same niche as yours and my visitors would genuinely benefit from some of
the information you present here. Please
let me know if this ok with you. Regards!
Na sajtu https://oosacheer.com/ moci cete kupiti tako efikasan lijek kao sto je Nautubone. Gel je dokazan i efikasan lijek koji se savrseno nosi sa bolovima u zglobovima. U isto vrijeme, moci cete brzo, efikasno i bez nezeljenih efekata zacijeliti. Sadrzi prirodne aktivne sastojke koji se brzo nose ne samo sa simptomima, vec i uzrok njegovog izgleda. Medu glavnim komponentama je kanadski jelen, koji se odupire unistenju, ostecenju tkiva.
I was able to find good information from your content.
Very rapidly this web site will be famous among all blog visitors, due to it’s fastidious articles or reviews
UK branding knowledgeable Rita Clifton, chairman of enterprise consultancy BrandCap,
says that Natura Siberica has been successful in the “astonishingly competitive” cosmetics
market due to its distinctive Siberian provenance. Mr Trubnikov
says he believes that it’s because they are hot nations, which
makes buying skincare products from someplace that may be as cold as Siberia
appear particularly interesting. As such, he says the company is now looking to tie-up
with a big web associate. If it wasn’t for the intoxicating scent of competing perfumes, you would
possibly assume that cosmetics firm Natura Siberica was making ice cream.
Thankfully for Mr Trubnikov he then tried the French market instead, and
Natura Siberica was soon a success there, earlier than increasing into different
European nations together with the UK the place outlets have been now
pleased to stock the products as they’d proven popular in different countries.
my website … most successful ecommerce businesses
http://karasteamfulldmroleplay.getbb.ru/viewtopic.php?f=62&t=100
Article writing is also a fun, if you be familiar with afterward
you can write otherwise it is difficult to write.
Thanks a bunch for sharing this with all folks you actually know what you are speaking about!
Bookmarked. Kindly additionally discuss with my web site =).
We will have a hyperlink change agreement among us
Другим направлением в уменьшении травматизма пешеходов являются защитные приспособления, удерживающие пешехода после удара и предохраняющие его от падения на дорогу. При срабатывании такого приспособления в первой стадии наезда (через 0, 2- 0, 3 с) пешеход забрасывается на капот автомобиля. После начала торможения автомобиля пешеход, продолжая двигаться с приобретенной скоростью, сползает вперед по капоту и падает вниз. Защитная сетка начинает автоматически выдвигаться примерно спустя 0, 2 с после удара. Через 1 с выдвижение ее полностью заканчивается, и сетка принимает падающего человека.
9) открывает краны и выпускает воду из рабочей полости насоса по завершении работы, после чего их закрывает.
Кроме указанных неполадок, лампа подушек безопасности может загореться из-за неправильной замены руля, поскольку нам необходимо помнить и о самой подушке безопасности, и о других расположенных в руле или непосредственной близости от него элементах защитной системы. Поэтому в первую очередь следует проверять руль и его компоненты.
а) движущиеся части не могли быть приведены в действие, пока они находятся в зоне досягаемости оператора;
Какими бывают системы безопасности в автомобилях, и какие машины самые защищенные.
https://myautolider.ru/salon-avto/kak-vysushit-poly-v-mashine-kak-vysushit-salon-mashiny-posle-livnya/
9) производить диагностирование пожарного автомобиля на ходу при неподключенном заборнике отработанных газов и выключенной приточно-вытяжной вентиляции.
3) определение единого сигнала оповещения личного состава пожарной охраны об опасности;
Регулятор ремня безопасности для детей Kumary (4 цвета)
3.29. Работающий с ручным электроинструментом, должен знать о том, что по степени защиты электроинструмент выпускается следующих классов:
6) слияния, разделения или перекрещивания транспортных потоков на пересечениях дорог, съездах, примыканиях, переходно-скоростных полосах;
Quality articles is the main to interest the visitors to pay
a quick visit the web page, that’s what this web site is providing.
Hi, after reading this remarkable article i am as well glad to share my familiarity here with colleagues.
Excellent blog here! Also your site loads up
fast! What host are you using? Can I get your affiliate link to
your host? I wish my website loaded up as quickly as yours lol
It’s very troսble-free to find out any matter on web as compared to textbooks, as I found thius
article at thbis website.
Also visit my web sitе mafiatoto (https://gitarin.ru/rezultaty-novogodnego-konkursa-marafona)
Slither.io, a browser-based on the net multiplayer game, consists
of taken the gaming international through storm for the reason that its launch in just 2016.
With its uncomplicated however addictive gameplay, it contains captured the awareness of hundreds of thousands of players throughout the world.
In just this post, we will delve into the mechanics, strategies, and the
charm of Slither.io. We will take a look at the game’s origins,
its have an affect on upon the gaming community, and talk about why it is
made up of come to be such a prominent sensation.
Thank you, I have just been searching for information approximately
this topic for a long time and yours is the best I’ve found out so far.
But, what about the bottom line? Are you sure in regards to the source?
My partner and I absolutely love your blog and find the majority
of your post’s to be exactly I’m looking for.
Does one offer guest writers to write content for yourself?
I wouldn’t mind publishing a post or elaborating on a lot
of the subjects you write about here. Again, awesome website!
This is a really good tip especially to those
fresh to the blogosphere. Simple but very accurate information… Thank you for sharing this one.
A must read article!
Saved as a favorite, I love your web site!
http://panther.80lvl.ru/viewtopic.php?f=15&t=86
Hey there just wanted to give you a quick heads up. The text in your article seem to be running
off the screen in Internet explorer. I’m not sure if this is a formatting
issue or something to do with internet browser compatibility but I thought I’d post to let you know.
The design and style look great though! Hope you get the issue fixed soon. Kudos
Mу coder іis trying ttо persuade me to move to .net from PHP.
I have always dislikеd the idea because of the costs.
But he’s tryіong none the less. I’ve been using Movable-tyрe on a numbeг
of ѡebѕites fоr about a year and am worried about sԝitching to anothewr
platform. I have heard great things abоut blogengine.net.
Is there a wayy I ϲan іmport all mү wordpress
posts into it? Any help would be greatly appreciated!
My ᴡeb site: kartutoto
Thanks a bunch for sharing this with all of us you really recognise what you are talking approximately!
Bookmarked. Kindly additionally talk over with my website =).
We will have a hyperlink alternate arrangement between us
mebendazole price
It masterfully merges the individual merits of its constituents, lithium and ascorbic acid – normotim effect – providing an array of advantageous health impacts.
Hɑvbing read this I belioeved itt was ratherr enlightening.
I appreciate you spending some tіme and energy to put
this information together. I once again fijnd myself ѕρejding a significant amоnt
of time both reading and commеnting. Bᥙt so what, it
was syill worth іt!
Stop by my web site; butchdike
I need to to thank you for this great read!!
I absolutely enjoyed every little bit of it. I have got you saved as a favorite to check out new things you post…
Howdy! I realize this is kind of off-topic however I needed
to ask. Does building a well-established blog like yours require a massive amount work?
I am completely new to operating a blog however I do write in my journal on a daily basis.
I’d like to start a blog so I can share my experience and feelings online.
Please let me know if you have any ideas or tips for brand new aspiring bloggers.
Appreciate it!
darknet market deep web sites
buy cialis cheap online
celebrex without a prescription purchase
Hello, i feel that i saw you visited my site so i got here to
go back the prefer?.I am trying to to find things to
improve my website!I guess its ok to use some of your ideas!!
Great blog right here! Additionally your web site quite a bit up very fast!
What host are you the usage of? Can I get your
affiliate hyperlink in your host? I want my site loaded up as quickly
as yours lol
I like the һhelpful info you provide on your articles.
I’ll bookmark your blog and check once more right here fгequently.
I’m reasonably sսre I’ll lеarn a lot of new
stuff poper right here! Best of luck for the next!
Here iis my web page :: link alternatif totojitu
Hello, I enjoy reading through your article post.
I like to write a little comment to support you.
I loved as much as you will receive carried out right here.
The sketch is tasteful, your authored subject matter stylish.
nonetheless, you command get got an edginess over that you wish be delivering the following.
unwell unquestionably come more formerly again since exactly the same
nearly very often inside case you shield this hike.
Thank you for another informative blog. The place else may just
I get that type of info written in such an ideal method?
I’ve a venture that I am just now working on, and I’ve been at the glance out for such info.
After looking over a number of the blog articles on your web site, I seriously
appreciate your technique of writing a blog.
I book marked it to my bookmark site list and will
be checking back soon. Please visit my web site too
and tell me what you think.
dark websites how to get on dark web
Hi there to all, how is the ᴡhole thing, I think every one is getting more from this site, and your views are fastidіous
in support of neew people.
My webpage; Backdoorman
darknet drug links darkmarket
I’m pretty pleased to discover this web site. I need to to thank you for
ones time due to this wonderful read!! I definitely
enjoyed every little bit of it and I have you saved to fav to look at new information on your site.
Howdy! I know this is somewhat off topic but I was
wondering which blog platform are you using for this website?
I’m getting tired of WordPress because I’ve had issues with hackers and I’m
looking at options for another platform.
I would be awesome if you could point me in the
direction of a good platform.
where can i buy cipralex
I’ll immediately clutch your rss as I can’t find your
e-mail subscription hyperlink or e-newsletter service.
Do you’ve any? Please allow me know so that I could subscribe.
Thanks.
Appreciate this post. Will try it out.
Useful info. Lucky me I discovered your web site unintentionally,
and I am stunned why this accident did not came about in advance!
I bookmarked it.
If you desire to take a good deal from this piece of writing then you have to apply these methods to your won weblog.