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.
erythromycin 40mg
Hello! I could have sworn I?ve been to this site before but
after browsing through many of the posts I realized it?s
new to me. Nonetheless, I?m certainly happy I discovered it and I?ll be book-marking it and checking back
regularly!
Also visit my web site :: Bio Pure Keto Gummies
Good site you have got here.. It’s difficult to find high-quality writing like yours these
days. I really appreciate people like you! Take care!!
Thanks for every other wonderful article.
Where else may anyone get that kind of info in such an ideal manner of writing?
I’ve a presentation subsequent week, and I am on the look for such info.
It’s nearly impossible to find knowledgeable people about this subject, however, you sound like you know what you’re talking about!
Thanks
of course like your web-site but you need to take a look at the spelling on quite a few of your
posts. Many of them are rife with spelling issues and I to find it very troublesome to tell the truth however
I’ll surely come again again.
If some one needs expert view about blogging afterward i
recommend him/her to go to see this webpage, Keep up the pleasant work.
Feel free to surf to my web page: jdb
Inspiring quest there. What occurred after? Thanks!
Inject some fun into your nicotine experience with nordic spirit. Our nicotine pouches are not just about the nicotine, they’re about enjoying the moment and having a great time.
flomax over the counter flomax medicine flomax otc uk
over the counter muscle relaxer: over the counter ed meds – over the counter tapeworm treatment for dogs
Very good post. I’m facing many of these issues as well..
can i buy colchicine price
Hello I am so grateful I found your weblog, I really found you
by error, while I was researching on Digg for something else, Anyhow I am here now
and would just like to say many thanks for a incredible post and
a all round thrilling blog (I also love the theme/design), I don’t have time to
go through it all at the moment but I have saved it and also added your RSS feeds,
so when I have time I will be back to read a lot
more, Please do keep up the superb jo.
atenolol 10mg drug atenolol 25 mg atenolol 20 mg price
You actually make it seem really easy together with
your presentation but I find this topic to be actually one thing that I believe I’d by no means understand.
It kind of feels too complex and extremely wide for me.
I am taking a look forward in your next put up, I’ll try to get the
grasp of it!
My family members always say that I am wasting my time here at net, except I
know I am getting familiarity everyday by reading such good articles.
jock itch treatment over-the-counter: over the counter drugs – diuretics over the counter
avodart cost generic avodart generic cost avodart mexico
over the counter asthma inhalers: over the counter pill – over the counter inhaler
Hmm is anyone else encountering problems with the images
on this blog loading? I’m trying to determine if its a problem on my
end or if it’s the blog. Any suggestions would be greatly appreciated.
my site; puyallup hyundai
I’m not that much of a online reader to be honest but your blogs really nice,
keep it up! I’ll go ahead and bookmark your website to come back in the
future. All the best
It’s in fact very complex in this busy life to listen news on TV, so I only use internet for that reason, and take the newest news.
Hi there, the whole thing is going nicely here and ofcourse every one is sharing
data, that’s in fact fine, keep up writing.
Look at my blog … Slot Telkomsel
What’s up i am kavin, its my first occasion to
commenting anyplace, when i read this paragraph i thought i
could also create comment due to this brilliant post.
Feel free to surf to my blog :: slot idn
Experience the convenience of nordic spirit online. Enjoy the finest nicotine pouches delivered straight to your doorstep.
If some one wishes to be updated with most recent technologies
after that he must be go to see this web site and be up to
date all the time.
Ӏ’m extremely impressed tߋgether ԝith yߋur writing talents ɑnd also with the layout to your blog.
Іs this a paid topic or did you modify it youг sеⅼf?
Either way stay up thе excellent һigh quality writing,
іt’ѕ uncommon tօ peer a ցreat blog lіke this one todaʏ..
Aⅼso visit mү blog: casino
I never received a response from Clomid UK after filing a complaint.
That is very attention-grabbing, You are a very professional blogger.
I have joined your feed and sit up for in quest of extra of
your wonderful post. Additionally, I’ve shared your site in my social networks
Discover a wide array of nordic spirit nicotine pouches in our shop. Find your ideal flavor and strength today.
https://overthecounter.pro/# over the counter erection pills
Fantastic goods from you, man. I have remember your stuff previous to and you’re just too
excellent. I actually like what you’ve bought here, really like what you are stating and the
way in which wherein you are saying it. You are making it enjoyable and you still take care of to stay it sensible.
I can’t wait to read much more from you. That is actually a great web site.
Greetings I am so excited I found your blog,
I really found you by accident, while I was searching on Digg for something else, Regardless I am here now and would just
like to say thanks a lot for a marvelous post and a all
round entertaining blog (I also love the theme/design), I don’t have time to look over it
all at the minute but I have saved it and also added in your RSS feeds, so
when I have time I will be back to read a great deal more,
Please do keep up the excellent job.
over the counter sleep aids that work: over the counter erectile dysfunction pills – over the counter ed meds
Hello there, There’s no doubt that your website could possibly be
having web browser compatibility problems.
When I take a look at your web site in Safari, it looks fine however,
when opening in I.E., it has some overlapping issues.
I simply wanted to provide you with a quick heads up!
Besides that, excellent blog!
Whhen someone writes ann articpe he/she maintaions
the plan of a user in his/her brain that how a useer cann undertand
it. Therrefore that’s why this piece of writing iis perfect.
Thanks!
Heya i’m for the primary time here. I found this board
and I in finding It really useful & it helped me out a
lot. I am hoping to offer one thing back and help others like you aided
me.
This is really interesting, You are a very skilled blogger.
I’ve joined your feed and look forward to seeking more of your
great post. Also, I’ve shared your site in my social networks!
Visit my site – kalender deutschland
Обзоры на Tour Ultra By все для туризма и отдыха – https://1st-digital.ru/sekrety-vybora-mobilnogo-telefona/ горячие новости со всего мира.
Saving every penny for a Clomid sale is my only hope.
I heard it’s dangerous to order Modafinil online, is this true?
Hi are using WordPress for your blog platform?
I’m new to the blog world but I’m trying to get started and set
up my own. Do you require any html coding knowledge to make your own blog?
Any help would be greatly appreciated!
Does anyone know of a reliable Clomid Mexico pharmacy?
medication finasteride 5mg finasteride prescription uk finasteride 5mg pill
https://vk.com/monolitnye_raboty_minsk?w=wall-213701595_12
Really nice design and excellent content, nothing else we require :D.
my site … Tri Leaf CBD Gummies Reviews
https://overthecounter.pro/# strongest over the counter pain reliever
ทางเรา relxchill.com ต้องขอบอกได้เลยว่า เป็นตัวแทนหลักอย่างเป็นทางการในไทย ที่ใหญ่ที่สุด และเป็นเจ้าเดียวกับ RELX
THAILAND สินค้าทุกแบรนด์
ทุกรุ่น เราได้ทำการคัดสรร บุหรี่ไฟฟ้า ที่เป็นหนึ่งในนวัตกรรม ช่วยเลิกบุหรี่ ที่มีประสิทธิดีเยี่ยม และช่วยได้จริง มาให้ลูกค้าได้เลือกใช้ Relx Infinity plus
, Ks quik , Ks Kurve , Ks Kurve lite , Kardinal Stkck ,
ks pod โดยสินค้าทุกชิ้นของเรา สั่งตรงจากโรงงาน
I pay a visit day-to-day a few websites and information sites to read articles, but this blog offers feature
based content.