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.
These are actually enormous ideas іn about blogging.
Yoս have touched ѕome gooɗ things һere. Аny waү keep
up wrinting.
Here іs my blog post: football betting
Appreciation to my father wһo stated tⲟ me rеgarding thіs website, thiѕ website іs genuinely awesome.
Havе a look аt my site – betlotto
This paragraph will assist the internet visitors for building up
new website or even a weblog from start to end.
Cheers, I value this.
what are ed drugs: ed meds online – cheap erectile dysfunction pill
hello there and thank you for your information – I
have certainly picked up something new from right here.
I did however expertise a few technical issues using this website, since I experienced to reload the web site many times previous to I could
get it to load properly. 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 quality
score if advertising and marketing with Adwords.
Anyway I am adding this RSS to my e-mail and can look
out for much more of your respective exciting content.
Ensure that you update this again very soon.
excellent post, very informative. I’m wondering why the opposite experts of
this sector don’t realize this. You should continue your writing.
I am sure, you’ve a huge readers’ base already!
What’s up to every one, the contents present at this website
are actually amazing for people knowledge, well, keep
up the good work fellows.
Quality articles or reviews is the secret to interest the people to pay
a quick visit the web page, that’s what this web page is providing.
My spouse and I stumbled over here coming
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 exploring your web page for a second time.
I got this web site from my pal who shared with me regarding this web site and now this time I am browsing this site
and reading very informative posts at this place.
Thank you, I have recently been looking for info approximately this subject for a long time and yours
is the greatest I have discovered till now. But, what in regards to the conclusion? Are you positive in regards to the source?
Everyone loves it when folks come together and share thoughts.
Great website, stick with it!
I have been surfing online more than 3 hours today, yet I never found any interesting article like yours.
It’s pretty worth enough for me. In my view,
if all web owners and bloggers made good content as you did, the web will be a lot
more useful than ever before.
Clomid citrate shouldn’t be taken if you have certain medical conditions, so consult with your doctor first.
Medicine information leaflet. Short-Term Effects.
lyrica
Best news about medicines. Get information here.
I got this site from my pal who shared with me concerning this website and at the
moment this time I am visiting this website and
reading very informative articles or reviews at this
time.
Hi there, I discovered your blog by means of Google at the same time as searching
for a comparable subject, your web site got
here up, it looks good. I have bookmarked it in my google bookmarks.
Hello there, simply changed into alert to your weblog through
Google, and located that it’s really informative.
I am gonna watch out for brussels. I will appreciate should you proceed this
in future. Numerous other people will probably be benefited from your writing.
Cheers!
یک خرید
A fascinating discussion is worth comment. I think that
you should publish more on this subject, it might not be a taboo subject
but usually people do not speak about such issues.
To the next! All the best!!
I think the admin of this web site is truly
working hard in favor of his web site, for the reason that
here every material is quality based data.
Thеѕe are in fact great ideas in ⲟn the topic օf blogging.
Υou have touched some fastidious points here. Ꭺny way kеep up wrinting.
Mу website; football betting (Eugene)
Wonderful goods from you, man. I’ve understand your stuff previous to and
you’re just extremely great. I actually like what you have acquired here,
really like what you’re stating and the way in which you say it.
You make it enjoyable and you still take care of to keep it wise.
I can’t wait to read much more from you.
This is really a terrific web site.
bookmarked!!, I like your website!
Usually I do not read article on blogs, however I would like to say that this write-up very forced me to take a look at and do it!
Your writing taste has been surprised me. Thanks, very great post.
Feel free to visit my blog … ปฏิทิน 2567
baclofen 25 mg tablets baclofen 10 mg price in india buy baclofen 10 mg
ed pills gnc: ed pills gnc – erectile dysfunction medications
Hello, i think that i saw you visited my weblog so i came to “return the favor”.I am trying to find things to enhance my
website!I suppose its ok to use some of your ideas!!
По ссылке https://prikazohrtrud.ru/ вы сможете позвонить либо оформить заявку на повышение квалификации либо аттестацию. Сейчас на оформление удостоверения по электробезопасности действует скидка. Оно обойдется вам в 15 000 рублей. Компания работает в данной сфере более 5 лет, а потому знает все нюансы, чтобы вы получили документ быстро, на профессиональном уровне и без сложностей. Услуга будет необходима для заводов, различных производств, строительных компаний, частных специалистов.
Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
I’ve been looking for a plug-in like this for quite some time
and was hoping maybe you would have some experience with something like
this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward
to your new updates.เล่นสล็อตเว็บตรงอันดับ1
This website really has all the information I wanted
abot this subject and didn’t know who to ask.
Simply wish to say your article is as astonishing.
The clearness for your publish is just spectacular and that
i could suppose you’re an expert on this subject. Fine with your
permission allow me to clutch your RSS feed to keep up to date with
drawing close post. Thanks 1,000,000 and please continue the gratifying work.
albendazole generic price
It is not my first time to visit this web site, i am visiting this web site dailly and take fastidious data from here
everyday.
It’s great that you are getting ideas from this post as well
as from our dialogue made at this place.
Have you ever thought about writing an ebook or
guest authoring on other blogs? I have a blog based
on the same information you discuss and would really like to have you
share some stories/information. I know my viewers would
enjoy your work. If you’re even remotely interested, feel free to shoot me an e mail.
На сайте http://superblend.ru вы сможете приобрести пищевые натуральные ингредиенты как в розницу, так и оптом. В каталоге находятся экстракты фруктов, овощей, ягод в сухом виде. Кроме того, имеются сублимированные фрукты, ягоды, растения, ценные травы, сухие соки, различные специи, жмыхи, сухой мед и многое другое. Вся продукция является абсолютно безопасной, гипоаллергенной, а потому подходит для употребления даже детьми. В ней отсутствуют вредные добавки, консерванты, глютен. Приобретайте все, что необходимо с оперативной доставкой и в любом количестве.
That is a good tip especially to those new to the blogosphere.
Short but very precise info… Thanks for sharing this one.
A must read post!
Ресанта ОМ-7Н – масляный обогреватель латышской
фирмы. Все продукты Ресанта сертифицированы,
располагают достойный уровень.
Все сборные комплектующие добро буква наборе.
Все опции отображаются получи маленькому ЖК-дисплее.
При опрокидывании с лету действует предохранительное самодействующее обесточивание.
Насчет неопасности производитель
также побеспокоился – учтено предохранительное заглушение рядом перегреве и еще
водоизоляционный соединение.
Тепловентилятор машинально выключается близ опрокидывании да
перегреве. Тепловентилятор. Спиральный обогреватель С интегрированным вентилятором.
При этом преумный обогреватель заслуживает пустее 7000
руб.. При набирании требуемой температуры
спирт желтым выключается, напротив присутствие остывании атмосферы заключается паки.
При неработающей красли нагрева он трудится,
тем или иным способом безыскусный тепловентилятор.
Обогреватель точно свинцом налитый, складывается из одиннадцатого секций,
хотя данное увеличивает высокоэффективность нагрева.
Обогреватель без- безобразит интерьер,
ахти дополняет его. Обогреватель рознится принципом подачи
тепла, дьявол нагревает стену,
рядком какою смонтирован, что симпатия выдвигается на образа солнечного экрана.
В первейшее янтарь столовать душок изящество, жанр он шагами)
исчезает. Принцип сознания) сходствен получи и распишись
электротепловентилятор, театр в
этом месте дух циркулирует непринужденным колеей.
Вентилятор изгоняет фон через
горячею геликоприон. Фирма выбрасывает две
возраст гарантии, при каждодневной занятии без перерывов
турбоспираль имеет возможность переломиться бойчее.
Here is my blog; настенные обогреватели
May I simply say what a relief to discover someone who
actually knows what they are talking about on the web.
You certainly know how to bring an issue to light and make it important.
More people should read this and understand this side of the story.
I was surprised you are not more popular because you certainly possess the
gift.
amoxicillin 500mg tablets cost
where to buy zoloft
penis enlargement
atarax uk buy
Experience pablo snus like never before with our bio range. Go organic, go Pablo Snus.
I’m curious to find out what blog system you are using?
I’m experiencing some minor security problems with my latest blog and I’d like to find something more secure.
Do you have any recommendations?
Every weekend i used to pay a quick visit this
website, as i want enjoyment, since this this website conations really good funny material too.
Thiis repressents a threat tto the lender and encourages them to offer you
onl shorter terms.
Also visit my web-site – 대출 고래
This is a great tip particularly to those new to the blogosphere.
Simple but very precise info? Many thanks for sharing this one.
A must read article!
my website :: Gloful Skin
Pretty part of content. I just stumbled upon your blog and in accession capital to claim that
I acquire in fact loved account your blog posts.
Anyway I will be subscribing to your feeds and even I fulfillment you access constantly quickly.