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.
indianpharmacy com canadian pharmacy cialis pharmacy online 365
На сайте https://tent3302.ru/ вы сможете приобрести запчасти, оригинальные детали на отечественные автомобили. Компания реализует шины и диски, двигатели, а также запчасти на Валдай, Камминз, УАЗ, КАМАЗ ЗиЛ. Всегда в наличии почти вся продукция, а потому вы сможете приобрести ее в наиболее комфортное время. Однако перед тем как совершить покупку, необходимо ознакомиться со всеми техническими характеристиками, а также позвонить по обозначенному телефону, чтобы уточнить по наличию. Но в компании вы сможете приобрести не только запчасти, но и шины, а еще двигатели, диски.
There’s certainly a lot to know about this subject. I love all of the
points you’ve made.
https://etextpad.com/
Awesome! Its really remarkable piece of writing, I have got much clear idea about from this paragraph.
buy generic proscar proscar 1mg online cheap proscar
I always spent my half an hour to read this blog’s
content everyday along with a cup of coffee.
ieee
We’re a group of volunteers and opening a new scheme in our community.
Your website provided us with valuable info to work on. You have done a formidable job and our entire community will be thankful to you.
You’re so cool! I don’t suppose I’ve truly read through
a single thing like this before. So wonderful to discover someone with some original thoughts on this subject matter.
Really.. many thanks for starting this up. This website is something that is needed
on the web, someone with some originality!
Huge savings on clomid for sale online cheap.
Hello, the whole thing is going nicely here and ofcourse every one is
sharing data, that’s in fact excellent, keep up writing.
Don’t let high medication costs weigh you down – buy Lyrica cheap online.
I needed to thank you for this great read!! I certainly
loved every bit of it. I’ve got you bookmarked to look at new things you post…
I think this is one of the most vital information for me.
And i am happy studying your article. However want
to remark on some general issues, The website taste is ideal,
the articles is truly great : D. Good job, cheers
I typically start patients on a low dose of Lyrica capsules and gradually increase it as needed.
From the start to finish, they were great to work with! Kind, professional, timely, and great job.
Very happy with their work. Thank you. Will definitely recommend them.
We just had our fence installed by the team, they were great!
They paid great attention to detail with the install and
kept our property looking clean throughout the entire install.
We would definitely recommend Michels Screen and Fence!
Our experience with this company was great. Since we
recently completed the build on our new home,
we know how important communication and simply showing up is.
The representative was on-time, polite and presentable when he arrived in our home.
He walked us through the process, provided us the information we needed to make a decision and
gave us a timetable for ordering and installation. When our
fence was ready (within that timetable), the
company let us know they’d be out the day before to
establish the perimeter. The installation professionals showed up on time, finished the job, cleaned the yard
and left us with a beautiful fence! We like that the fence is made in the US, has UV
protectant built in and has a decent warranty.
We would use and recommend this company again.
payday loan
xenical cost canada orlistat prescription canada buy orlistat pills
When someone writes an article he/she retains the thought of a user in his/her brain that how a user can be aware
of it. So that’s why this post is outstdanding. Thanks! https://bukovets.com/spring/
http://edpills.pro/# mens erection pills
triamterene-hctz 37.5
It’s in reality a great and useful piece of info.
I am satisfied that you shared this useful info with us.
Please stay us informed like this. Thank you for sharing.
Thanks very nice blog!
Pretty component to content. I simply stumbled upon your website and
in accession capital to claim that I get in fact enjoyed
account your weblog posts. Anyway I will be subscribing in your feeds or even I achievement
you get admission to constantly quickly.
Hi! This is kind of off topic but I need some advice from an established blog.
Is it very hard to set up your own blog? I’m not very
techincal but I can figure things out pretty fast.
I’m thinking about making my own but I’m not sure where to begin. Do you
have any ideas or suggestions? Many thanks
Hurrah! At last I got a webpage from where I know how to
genuinely obtain helpful facts regarding my study and knowledge.
I have been exploring for a bit for any high-quality articles or weblog posts on this kind of space .
Exploring in Yahoo I ultimately stumbled upon this site.
Reading this info So i am glad to express that I’ve an incredibly good uncanny feeling I came upon just what I needed.
I so much for sure will make sure to don?t overlook
this web site and give it a glance on a continuing basis.
Hello! Do you use Twitter? I’d like to follow you if that would be
ok. I’m definitely enjoying your blog and look forward to new updates.
На сайте https://arenda-kolyasok.ru вы сможете оформить заявку на то, чтобы арендовать инвалидную коляску. В компании только качественные, надежные конструкции, которые обрабатываются, дезинфицируются после каждого пользователя. Именно поэтому клиент получает коляску в ухоженном, чистом виде. Взять в аренду изделие вы сможете в любое время и даже на несколько дней. Именно от интервала зависит итоговая стоимость. Выбирайте ту модель, которая подходит вам больше всего. Организуется оперативная доставка по Москве.
It’s nearly impossible to find educated people on this subject,
but you seem like you know what you’re talking about!
Thanks
I am really grateful to the holder of this web page who has shared this great piece of writing at at this
place.
Hey There. I found your blog using msn. This is an extremely well written article.
I’ll be sure to bookmark it and return to read more of your useful info.
Thanks for the post. I’ll definitely comeback.
Great beat ! I would like to apprentice while you amend your site,
how can i subscribe for a blog web site? The account helped me
a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear idea
I believe people who wrote this needs true loving because it’s a blessing.
So let me give back and show true love on change your life and if you want to seriously get to hear I will share info about how to become a millionaire Don’t forget..
I am always here for yall. Bless yall!
Hi there mates, its great piece of writing regarding cultureand entirely explained, keep
it up all the time.
Why users still use to read news papers when in this technological globe the whole thing
is existing on web?
You should be a part of a contest for one of the most useful websites
online. I am going to recommend this blog!
https://pastebin.pl/view/f621eca8
На сайте https://krasiva-i-lubima.ru/ ознакомьтесь с информацией, которая касается женской аудитории. Здесь опубликованы материалы об уходе за собой, лицом и волосами. Вы узнаете о том, как содержать комнатные цветы в домашних условиях. Есть рекомендации о том, как правильно делать поделки из бисера, что можно создать из отслуживших капроновых чулок. Все материалы любопытные, исчерпывающие, содержательные, а потому они несут в себе реальную пользу. Они помогут взглянуть на привычные вещи с другого угла.
What’s up Dear, are you really visiting this web page daily,
if so afterward you will definitely take good knowledge.
Howdy! Someone in my Facebook group shared this site with us so
I came to take a look. I’m definitely enjoying the information. I’m book-marking and will be tweeting
this to my followers! Wonderful blog and brilliant design.
I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone
to do it for you? Plz respond as I’m looking to construct my own blog and would like to
know where u got this from. many thanks
What’s up it’s me, I am also visiting this website regularly,
this web site is genuinely nice and the users are truly sharing fastidious thoughts.
Howdy would you mind stating which blog platform you’re using?
I’m going to start my own blog in the near future but I’m having a tough
time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique.
P.S Sorry for getting off-topic but I had to ask!
When someone writes an paragraph he/she keeps the image of a user in his/her mind that how a user can understand it.
So that’s why this paragraph is perfect. Thanks!
canadian pharmacy store online pharmacy delivery canada pharmacy online
You actually make it seem so easy with your presentation but I find this matter to
be actually something that I think I would never understand.
It seems too complicated and extremely broad for me.
I’m looking forward for your next post, I will try to get the
hang of it!
Excellent post. I was checking constantly this blog and I’m inspired!
Extremely helpful information specially the final part :
) I handle such information much. I used to be seeking this particular info for
a very long time. Thanks and good luck.
Hi, always i used to check website posts here early
in the break of day, since i love to learn more and more.