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://clinika-sochi.ru/
Thank you, I have just been looking for information about this topic for a while and yours is the best I’ve found
out till now. But, what in regards to the conclusion? Are you positive in regards to the supply?
buy viagra online
Howdy are using WordPress for your blog platform? I’m new to the blog
world but I’m trying to get started and create my own. Do you require any coding knowledge to make your own blog?
Any help would be greatly appreciated!
What you typed made a great deal of sense. But, what about this?
what if you added a little content? I mean,
I don’t wish to tell you how to run your website, however suppose you added something to possibly
get a person’s attention? I mean Eclipse – Formatter e Save Action – Handerson Frota is a little plain. You might look
at Yahoo’s front page and see how they create news headlines to get people to click.
You might add a related video or a pic or two to grab people interested about
what you’ve got to say. In my opinion, it would bring your website a little livelier.
hi!,I love your writing so a lot! share we be in contact more about your post on AOL?
I need a specialist on this area to resolve my problem.
May be that is you! Having a look forward to see you.
I pay a quick visit each day some sites and sites to read articles or reviews, but this weblog provides quality based
writing.
https://overthecounter.pro/# over the counter birth control
flomax cost buy flomax in india flomax price comparison
amoxicillin 750 us amoxicillin 150 mg amoxicillin price comparison
Thank you for the good writeup. It in reality was once a amusement account it.
Glance complex to more introduced agreeable from you! By the way, how can we keep in touch?
This is a good tip particularly to those fresh to the blogosphere.
Simple but very accurate information… Appreciate your sharing this
one. A must read post!
I am really impressed witһ your writing skills as well аs with
the layout ᧐n yօur weblog. Ӏs this a paid theme οr
did yoս modify it yourѕelf? Ꭺnyway keep up tһe nice quality writing, it is rare tо sее а great blog like
this one nowadays.
my web blog; casino (Juanita)
If you desire to improve your know-how simply keep visiting this website and be updated with the most up-to-date
news posted here.
celebrex 200 mg online
На сайте https://etor-kazaki.ru/ находятся казаки туфли, полусапоги, сапоги летние, зимние, а также чопперы, мотообувь. Вся продукция реализуется по привлекательным ценам, с оперативной доставкой, а потому совершить выгодную покупку сможете и вы прямо сейчас. На портале также имеется и кожаная одежда, модные и стильные аксессуары, футболки и многое другое. Обязательно ознакомьтесь с новостями, которые точно будут интересны и вам. Есть раздел с горячими новинками, а также по лучшей цене.
Pretty nice post. Ι just stumbled upon your weblog ɑnd wished tߋ sɑy tһat
I have reallʏ enjoyed browsing ʏoսr blog posts.
Аfter aⅼl Ι’ll be subscribing to уⲟur rss feed
аnd I hope you write again very soon!
My site: casino
Tһanks f᧐r the marvelous posting! І quite enjoyed reading іt, yoᥙ migһt be a great
author. I wіll makе certain to bookmark уour blog and will eventually сome back from now on. I want to encourage one to continue үour great work, һave а
nice morning!
Feel free tо surf to my paցe :: lotto
So to Gruman, the one recommendation I’ve is to maybe spend a bit of bit of time
on the planet of iOS jailbreaking. Claiming that even venturing into the world of jailbreaking goes to end
in tears is concern-mongering, and nothing more.
There’s so much fallacious with this article from starting to finish that it could take
me 2,000 phrases to correct everything, so I’ll just level
out the most troubling bits. Sure, there are lots
of websites on the market attempting to trick you into downloading one thing shady, but no,
jailbreaking your iOS machine isn’t inherently harmful.
It takes roughly 5 minutes from the time you plug your iPhone, iPad, or iPod contact into
your pc for the hack to free your gadget and install Cydia, the jailbreaker’s
app retailer. I know all of this because I’ve an iPod touch that I have jailbroken utilizing Pangu, and it
performed flawlessly. Called Pangu, the tool has been updated persistently and
now supports even the most recent iOS 7.1.2 patch.
Also visit my site xnxx fucking video
%%
Hi there, I wanted to drop a comment and let you know that if you’re looking to buy some modern furnishings, it’s
worth it to browse through the latest collection of home decor ready on the internet.
You’ll be able to peruse the up-to-date virtual furniture choices today.
Don’t miss the opportunity to explore the latest
furnishing options ready digitally. Get a glimpse of the latest home decor styles on the web today.
Check out the newest virtual furnishing additions today.
I trust you discover something that catches your eye!
It’s going to be ending of mine day, however before
ending I am reading this wonderful piece of writing to improve my know-how.
Hello! This is my first visit to your blog!
We are a group of volunteers and starting a new initiative in a community in the same niche.
Your blog provided us useful information to work on. You have done a marvellous
job!
Here is my website: i want to sell my home fast
drug neurontin 200 mg neurontin 300 mg cost neurontin pfizer
baclofen purchase baclofen cost india baclofen pills
Fine way of explaining, and nice paragraph to obtain information about
my presentation subject matter, which i am going to deliver in university.
interesting news
_________________
ойын автоматтары демонстрациялық ойындарды тіркеусіз онлайн режимінде тегін ойнайды
cheap advair diskus
Hello, this weekend is good for me, because this point in time i am reading this wonderful educational paragraph here at my home.
Also visit my web-site: sell my house Fast for cash
motilium over the counter uk motilium otc australia buy motilium australia
I do believe all the ideas you have introduced to your post.
They are really convincing and will certainly work. Still,
the posts are very brief for beginners. Could you please extend them a bit from subsequent time?
Thanks for the post.
Thank you for every other magnificent article. Where else may anybody get that kind of information in such
a perfect manner of writing? I’ve a presentation subsequent week, and I’m on the look for such info.
blood pressure over the counter medication: over the counter erectile dysfunction pills – strongest over the counter diuretic
finasteride 5mg over the counter buy finasteride no prescription finasteride tablets 1mg price in india
I do not even know how I ended up here, but I thought
this post was great. I don’t know who you are but certainly you’re going to a famous blogger if you aren’t already ;
) Cheers!
https://offline-news.ir/بامین-تهویه-عملکرد-انواع-رادیاتور-راد/
diflucan over the counter: over the counter drugs – over the counter sleep aids that work
over the counter uti meds: over the counter medication – over the counter essentials
I’ve been browsing online more than 2 hours today, yet I never found any interesting article like yours.
It’s pretty worth enough for me. Personally, if all site owners and bloggers made good content as you did,
the net will be much more useful than ever
before.
RTP Live > Info RTP Live Slot Gacor Resmi Terakurat Di Jamin Maxwin Sensasional
2023
Game slot gacor sekarang semakin mudah untuk memainkan permain slot gacor gacor RTP live
slot saat ini begitu akurat sewaktu digunakan untuk memperoleh banyak kemenangan dan keuntungan. Tentunya kalian harus bermain dengan bocoran yang telah disediakan mempunyai tingkat
keakuratan tersendiri sehingga kalian tidak harus khawatir
dengan kekalahan ketika bermain pemerian slot online ini.
Sebelum bermain gunakan RTP slot ini untuk kalian dapat mempunyai tingkat
persentase kemenangan sehingga aman ketika bermain dengan kerugian seminimal mungkin.
RTP live slot merupakan informasi bocoran rtp slot gacor hari ini agar mudah dan gampang maxwin paling akurat di tahun 2023.
Sehingga kalian dapat melihat tingkat nilai persentase kemenangan dari slot online dengan beberapa
jenis pameran yang layak sekali kalian mainkan. Meskipun telah hadirnya bocoran RTP slot ini juga tidak akan menjamin keamanan setiap kalian putar,
setidaknya dapat mengurangi resiko dalam kesalahan yang fatal.
I seriously love your website.. Excellent colors & theme.
Did you build this website yourself? Please reply back as I’m trying to create my own site and want to find out where you
got this from or what the theme is named. Thank you!
I have read so many articles or reviews on the topic
of the blogger lovers but this post is in fact a good paragraph,
keep it up.
thank you very much
_________________
казинолық онлайн ойнаңыз yandex
avodart canada price
My brother suggested I might like this web site.
He was entirely right. This post truly made my day. You can not imagine simply how much time I
had spent for this information! Thanks!
I just like the helpful info you supply on your articles.
I’ll bookmark your blog and check again right here
frequently. I am slightly certain I will be told
many new stuff proper here! Good luck for the next!
I’m gone to tell my little brother, that he should also pay a
visit this weblog on regular basis to obtain updated from newest
information.
I know this if off topic but I’m looking into starting my own blog
and was wondering what all is required to get setup? I’m assuming having
a blog like yours would cost a pretty penny?
I’m not very web smart so I’m not 100% positive. Any tips
or advice would be greatly appreciated. Appreciate it
mupirocin ointment over the counter: over the counter erection pills – antibiotics over the counter
https://mobreport.ru/kakie-ekskursii-populyarny-na-sahaline-zimoj/
Lean In has coined the phrasee “the broken rung” to refer to the problem of young, certified ladies getting
passed more than for early management roles.
my webpage :: website