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.
Greetings! I know this is kinda off topic however , I’d figured I’d ask.
Would you be interested in exchanging links or maybe guest
authoring a blog post or vice-versa? My website goes over a lot of the same
topics as yours and I think we could greatly benefit
from each other. If you are interested feel free to send me
an e-mail. I look forward to hearing from you! Superb blog
by the way!
OMG! This is amazing. Ireally appreciate it~ May I shout out on a secret only I KNOW
and if you want to seriously get to hear You really have to
believe mme and have faith and I will show how to get connected to girls easily and quick Once again I want
to show my appreciation and may all the blessing goes to you now!.
Oh my goodness! Awesome article dude! Thank you
so much, However I am going through difficulties with your RSS.
I don’t understand why I can’t join it. Is there anyone else getting the same RSS issues?
Anybody who knows the answer will you kindly respond? Thanx!!
It’s going to be finish of mine day, but before finish I
am reading this impressive piece of writing to increase my knowledge.
Wow, awesome blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your site is excellent, as well as
the content!
An impressive share! I have just forwarded this onto a coworker who had been conducting
a little homework on this. And he actually ordered
me lunch due to the fact that I stumbled upon it for him…
lol. So let me reword this…. Thank YOU for the
meal!! But yeah, thanx for spending time to discuss this matter here on your site.
Good day I am so delighted I found your webpage, I really found you by
error, while I was researching on Google for something else, Anyways I
am here now and would just like to say many thanks for a tremendous post
and a all round interesting blog (I also love the theme/design), I don’t have time
to read 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 much more, Please do keep up the fantastic work.
What’s up it’s me, I am also visiting this web site daily, this site
is in fact pleasant and the people are really sharing pleasant
thoughts.
Flossing protects against gum tissue illness, dental cavity, and bad breath.
canada flomax
Простая навигация: Благодаря нашему удобному интерфейсу найти нужную информацию не составит труда. Ищете ли вы статьи по обслуживанию автомобиля, обзоры новых автомобилей или форумы сообщества – наш портал genzer.ru создан для того, чтобы облегчить поиск нужной информации. Так почему бы не посетить нас сегодня и не убедиться в том, что наш автомобильный портал является самым популярным местом для автолюбителей!
Hola! I’ve been following your blog for a long time now and finally got the bravery to go ahead and give you a shout out from
Porter Tx! Just wanted to say keep up the fantastic work!
This is a good tip especially to those fresh to the
blogosphere. Short but very accurate info… Many
thanks for sharing this one. A must read post!
I like what you guys tend to be up too. Such clever work and coverage!
Keep up the awesome works guys I’ve added you guys to our blogroll.
Exceptional post but I was wondering if you could write a litte more on this subject?
I’d be very grateful if you could elaborate a little bit more.
Thanks!
my webpage: UltraMax Keto Gummies
ashwagandha plant
На сайте https://okirove.ru/ вы сможете почитать увлекательные, интересные и актуальные новости не только Кирова, но и области. Так имеются данные, которые касаются первых лиц города. Они делятся своим экспертным мнением, помогают лучше понять обстановку. Они дают комментарии, которые касаются наболевших вопросов, разъясняют обстановку и помогают лучше сориентироваться в ней. Все новости свежие, произошли только сегодня или несколько часов назад. Вот почему вы узнаете о них первыми.
It is in point of fact a great and useful piece of info.
I’m satisfied that you simply shared this helpful info with us.
Please stay us informed like this. Thanks for sharing.
Spot on with this write-up, I honestly believe this web
site needs far more attention. I’ll probably be back
again to read through more, thanks for the info!
This is very interesting, You are a very skilled blogger.
I’ve joined your rss feed and look forward to seeking more of your magnificent post.
Also, I have shared your site in my social networks!
of course like your web site however you need to check the
spelling on several of your posts. Several of them are rife with spelling issues and I find it very
troublesome to inform the truth however I will
certainly come again again.
Clomid IUI requires a lot of monitoring, but I’m willing to do it if it means getting pregnant.
This article will help the internet users for setting up new
web site or even a weblog from start to end.
cefixime in breastfeeding
Good day! I simply wish to offer you a big thumbs up for
your excellent info you have right here on this post.
I am coming back to your website for more soon.
These ceiling lights are suspended by a chain or downrod as well as can be found in numerous various designs.
Drugs information for patients. Cautions.
cost cytotec
Everything news about medicine. Get now.
Дзен Ремонт Санкт-Петербург.
where can i buy lexapro online otc lexapro where can i buy lexapro
https://500px.com/p/haahrlgzdavis
Great post. I’m going through some of these issues as well..
I really like what you guys are usually up too.
This sort of clever work and reporting! Keep up the amazing
works guys I’ve you guys to our blogroll.
fantastic submit, very informative. I ponder why the opposite experts of this
sector don’t notice this. You must proceed your writing.
I’m confident, you have a great readers’ base already!
ยินดีต้อนรับเข้าสู่ครอบครัว โคตร KS ทางเรายินดีให้บริการตลอด
24 ชั่วโมง
Kardinal Stick เทคโนโลยีใหม่ล่าสุดในปี 2020 ด้วยดีไซน์ที่หรูหราใช้งานง่าย เหมาะแก่การใช้เป็นตัวเลือกในการเลิกบุหรี่ที่ดีที่สุดในตอนนี้ ?
My child’s Lasix 10 mg tablet can interact with other medications, so I have to be careful.
Modafinil online India offers a convenient and affordable option for those seeking cognitive enhancement.
Дзен Ремонт СПб.
https://edpills.pro/# cheap ed pills
cleocin uses
Thanks on your marvelous posting! I really enjoyed reading it, you’re a great author.
I will make certain to bookmark your blog and will eventually
come back someday. I want to encourage you
to continue your great job, have a nice holiday weekend!
Respect to op, some excellent information.
Feel free to surf to my blog: Pura Vida Keto ACV Gummies Reviews
Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your
blog posts. After all I’ll be subscribing to your rss feed and I hope you write again very soon!
Look at my webpage :: Cabinet Design for kitchen
dapoxetine price in india cost of dapoxetine where can i buy dapoxetine in canada
Link Slot Server Bangkok
Daftar Sekarang
https://situs-slot-bangkok.powerappsportals.com/
Today, I went to the beach front with my kids.
I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed.
There was a hermit crab inside and it pinched her ear. She never wants to go back!
LoL I know this is entirely off topic but I had to tell someone!
На сайте https://mangamammy.ru почитайте интересные манги на самую разную тему, включая про любовь, дружбу, приключения. Многие из них состоят не из одной главы и нескольких томов. Есть комедии, которые никого не оставят равнодушным. Для того чтобы получить больше привилегий, пройдите регистрацию. Также есть раздел, посвященный истории чтения. Так вы узнаете о том, какие книги вы уже прочитали. Все манги невероятно интересные и увлекательные, а потому не заставят заскучать. С первых строк они погружают в приятные эмоции, а потому ими можно зачитаться.
Oh my goodness! Amazing article dude! Many thanks, However
I am experiencing troubles with your RSS. I don’t know the reason why I cannot subscribe to it.
Is there anybody getting identical RSS problems?
Anyone who knows the answer will you kindly respond?
Thanx!!
It’s actually a great and useful piece of information. I am glad that you
simply shared this useful information with us.
Please stay us up to date like this. Thanks for sharing.
Дзен-Ремонт питер.
Hi there, all the time i used to check blog posts here in the early hours in the dawn, because i like to
learn more and more.