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.
What’s Going down i’m new to this, I stumbled upon this I’ve
found It absolutely useful and it has aided me out loads.
I am hoping to contribute & aid different customers
like its aided me. Great job.
Terrific work! This is the type of information that are supposed
to be shared across the internet. Shame on the seek engines for not positioning this put up upper!
Come on over and talk over with my web site . Thanks =)
Hi there, just wanted to say, I enjoyed this article.
It was inspiring. Keep on posting!
Best site from all Apes and original NFT Monkey.
I read this piece of writing fully concerning the resemblance of
newest and previous technologies, it’s amazing article.
Wonderful blog! Do you have any recommendations for aspiring writers?
I’m hoping to start my own site soon but I’m a little lost
on everything. Would you advise starting with a free platform like WordPress or go
for a paid option? There are so many choices out there that I’m totally confused
.. Any recommendations? Many thanks!
I loved as much as you’ll receive carried out right here.
The sketch is attractive, your authored material stylish.
nonetheless, you command get got an impatience
over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you
shield this increase.
I like the valuable information you provide in your articles.
I will bookmark your blog and check again here
regularly. I am quite certain I will learn lots of new
stuff right here! Good luck for the next!
hello!,I really like your writing very much! percentage we be
in contact more approximately your post on AOL?
I require an expert in this house to solve my
problem. Maybe that’s you! Taking a look forward to see you.
Забор из металлопрофиля или профлиста — это практичное и долговечное решение для ограждения территории.
Такой забор обеспечивает надежную защиту, препятствуя несанкционированному проникновению и
обеспечивая конфиденциальность.
Профнастил, из которого часто изготавливают заборы,
обладает высокой устойчивостью к атмосферным воздействиям и механическим
нагрузкам. Кроме того, забор из профнастила легко монтируется и имеет доступную цену.
Если вы хотите получить качественный забор из профнастила под ключ, важно обратиться к опытным специалистам, которые смогут выполнить работы профессионально и эффективно.
При выборе забора из профлиста или металлопрофиля следует учесть не
только цену,
но и качество материалов, дизайн и общую надежность конструкции, чтобы быть
уверенным в долговечности и безопасности вашего забора.
If some one wishes to be updated with hottest technologies then he must be pay a quick visit this website and be up to date every day.
After exploring a handful of the blog articles on your
site, I truly like your way of blogging. I added it to my bookmark
website list and will be checking back in the near future. Take a
look at my web site too and tell me your opinion.
Yesterday, while I was at work, my sister stole my apple ipad and tested
to see if it can survive a 40 foot drop, just so she can be a youtube
sensation. My iPad is now destroyed and she has 83 views.
I know this is completely off topic but I had to share
it with someone!
I love reading through a post that will make people think.
Also, thanks for allowing me to comment!
largest darknet market pill with crown on it [url=https://world-dark-market.com/ ]darknet live stream [/url]
tor2door market link underground hackers black market [url=https://world-onion-darkmarket.com/ ]alphabay darknet market [/url]
Awesome blog! Do you have any helpful hints for aspiring writers?
I’m hoping to start my own blog soon but I’m a little lost on everything.
Would you propose starting with a free platform like WordPress or go for a
paid option? There are so many options out
there that I’m totally overwhelmed .. Any ideas? Many thanks!
where can i purchase valtrex
atarax 10mg otc
Asking questions are actually fastidious thing if you are not understanding anything completely, except this
post provides nice understanding yet.
Gߋod way οf telling, and pleasant post tо take information гegarding my presentation subject matter,
ᴡhich i am ɡoing to deliver in academy.
Feel free tо visit my site – casino – Krystle,
Synthroid levothyroxine may cause side effects such as hair loss, weight changes, and mood swings.
Howdy great blog! Does running a blog similar to this require a great deal of work?
I’ve very little understanding of coding but I had been hoping to start my own blog in the near future.
Anyhow, should you have any suggestions or tips for new blog owners please share.
I understand this is off subject but I just wanted to ask.
Thanks a lot!
When someone writes an article he/she maintains the plan of a user in his/her brain that how
a user can be aware of it. So that’s why this paragraph is amazing.
Thanks!
Here is my site; junk yards miami fl
I do not even know how I ended up here, but I thought this
post was great. I do not know who you are but definitely you are going to a
famous blogger if you aren’t already 😉 Cheers!
I’ve heard that taking too much Synthroid 50mcg can be dangerous.
Wow, incredible blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your website is magnificent,
let alone the content!
Also visit my webpage … companies that buy houses for cash
Hi my loved one! I want to say that this post is amazing, great written and come
with approximately all significant infos. I would like to see more
posts like this .
Hello, I enjoy reading all of your post. I wanted to write a little comment to support you.
Hmm is anyone else having problems with the pictures 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.
I’ve been exploring for a little bit for any high-quality articles
or weblog posts on this sort of area . Exploring in Yahoo I eventually stumbled upon this website.
Studying this info So i am satisfied to express
that I’ve an incredibly good uncanny feeling I found out exactly
what I needed. I so much unquestionably will make sure to do not forget this web
site and give it a look regularly.
Terrific article! This is the type of information that are supposed
to be shared around the web. Disgrace on Google for
not positioning this submit upper! Come on over and
seek advice from my website . Thank you =)
It’s awesome to visit this web page and reading the views of all
friends concerning this post, while I am also eager of getting knowledge.
ทางเรา mothervaper ยังมี ผลิตภัณฑ์ บุหรี่ไฟฟ้า Pod System อื่นๆ ที่กำลังจะนำเข้ามา ให้ผู้ใช้ได้เลือกใช้อีกด้วย ไม่ว่าจะเป็น Infy Pod ,
Vmc Pod , Relx Bubble Mon , Coga และอื่นๆ อีกมากมาย โดย น้ำยาบุหรี่ไฟฟ้า หรือ บุหรี่ไฟฟ้า พอตใช้แล้วทิ้ง ทุกรุ่น
ล้วนแล้วแต่มี ราคาถูก แต่ให้คุณภาพที่ดีเยี่ยมทั้งนั้น อีกทั้งยังเป็นรุ่นยอดนิยมอีกด้วย
Patients with a history of depression should let me know before starting Lyrica capsules.
clonidine purchase
Hey I am so excited I found your website, I really found you by accident, while I was researching on Askjeeve for
something else, Regardless I am here now and would just like to
say thanks a lot for a remarkable post and a all round thrilling blog (I also love the theme/design), I don’t have time to browse
it all at the moment but I have saved it and also added in your RSS feeds, so when I
have time I will be back to read more, Please do keep up the great job.
вх для ксго – купить читы кс го приватные, midnight im чит
I used to be able to find good advice from your
blog articles.
It’s fantastic that you are getting thoughts from
this paragraph as well as from our dialogue made at this time.
New York’s on the web sportss betting market place was
expected to attain $1 billion in annual revenue, according to Macquarie.
Look at my webb ite more info
Do you have any video of that? I’d love to find out some additional information.
Don’t let the cost of medication prevent you from getting the treatment you need – use a brand Synthroid coupon.
robaxin 750 mg price robaxin v robaxin for sale online
valtrex online prescription
Hello this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML.
I’m starting a blog soon but have no coding skills so I
wanted to get guidance from someone with experience.
Any help would be greatly appreciated!
Very rapidly this web site will be famous among all blogging viewers, due to it’s
pleasant articles or reviews
Hello there! I simply would like to offer you a big thumbs up for
the excellent information you’ve got here on this post.
I’ll be coming back to your website for more soon.
Your method of explaining everything in this paragraph
is genuinely pleasant, every one can without difficulty understand it, Thanks a lot.
Amazing things here. I am very satisfied to look
your article. Thanks a lot and I am looking forward
to contact you. Will you kindly drop me a e-mail?