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.
If some one needs expert view about blogging and site-building then i suggest him/her to pay a quick visit this web site, Keep up the
nice work.
Thanks, I’ve been looking for this for a long time
_________________
cs go болжамдар болжамдары
webcam video
Hі! I could have sworn I’ve Ьeen to this blog bеfore but aftеr ցoing tһrough many of tһe posts
I realized it’ѕ new to me. Anyhow, I’m definitеly pleased І stumbled uρⲟn іt and I’ll Ƅe book-marking іt and checking back regularly!
Мy web ρage: casino, Glenna,
It’s a pity you don’t have a donate button! I’d definitely
donate to this superb blog! I guess for now i’ll settle for
book-marking and adding your RSS feed to my Google account.
I look forward to brand new updates and will talk about
this blog with my Facebook group. Talk soon!
It’s appropriate time to make some plans for the long run and it is time to be happy.
I have learn this post and if I may I want to recommend you some fascinating things
or advice. Perhaps you could write next articles relating to this
article. I wish to learn more things approximately it!
Sadisflix et le seul est l’unique Site de Streaming 100%
Français et Gratuit qui propose une grande variété de Films
et de Séries en qualité HD. Découvrez notre catalogue exclusif et profitez d’un divertissement illimité.
Nous vous offrons une sélection de contenus adaptée à vos préférences et
à vos envies, ainsi que des mises à jour régulières
pour vous offrir toujours plus de choix. Rejoignez notre communauté et profitez de la meilleure expérience de streaming VF et VOSTFR, sans aucune limite
Really no matter if someone doesn’t understand after that its up to other users that they will
help, so here it happens.
Amazing! Its actually amazing paragraph, I have got much
clear idea on the topic of from this paragraph.
Hi there! This is kind of off topic but I need some guidance 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 quick. I’m thinking about making my own but I’m not
sure where to begin. Do you have any points or suggestions?
Many thanks
https://satbayev.university
Hi there, just became aware of your blog through
Google, and found that it’s really informative. I am gonna watch out for brussels.
I’ll be grateful if you continue this in future. Many people will be
benefited from your writing. Cheers!
I love looking through a post that can make people think.
Also, thanks for allowing me to comment!
buy viagra online
canadian online pharmacy
Excellent site you have here but I was curious about if you knew of any discussion boards that cover the same topics talked about here?
I’d really like to be a part of online community where I can get opinions from other knowledgeable people that share the same interest.
If you have any suggestions, please let me know. Many thanks!
Greate article. Keep writing such kind of information on your blog.
Im really impressed by it.
Hi there, You have done a great job. I’ll certainly digg it and for my part suggest to my friends.
I am sure they’ll be benefited from this website.
Top Places to Visit in Kuwait – Best Restaurants in Kazakhstan, Best Restaurants in Maldives
Keep thіѕ ցoing please, great job!
Here is my website … gambling
Hi! I could have sworn I’ve been to this site before but after going
through many of the posts I realized it’s new to me.
Anyways, I’m certainly pleased I found it and I’ll be bookmarking it and checking back regularly!
Awesome post.
http://www.mathforum.ru/gitweb/pgs/gama_casino_registraciya__preimushestva_i_otzuvu.html
Hey just wanted to give you a quick heads up.
The text in your article seem to be running off the screen in Opera.
I’m not sure if this is a format issue or something to do with browser compatibility but I figured I’d post to let you know.
The style and design look great though! Hope you get the problem resolved soon. Kudos
Hi Dear, are you truly visiting this web site regularly, if so after that you will without
doubt obtain nice knowledge.
There’s certainly a lot to know about this topic. I like all of the points you have made.
These are truly wonderful ideas in about blogging.
You have touched some pleasant factors here. Any way keep
up wrinting.
Asking questions are truly fastidious thing if you are not understanding anything totally, except
this post offers nice understanding yet.
I blog frequently and I seriously appreciate
your content. This article has truly peaked my interest.
I will book mark your website and keep checking for
new details about once a week. I subscribed to your RSS feed too.
Spot on with this write-up, I absolutely believe that
this site needs much more attention. I’ll probably be returning
to read through more, thanks for the info!
This is really interesting, You’re a very skilled blogger.
I’ve joined your feed and look forward to seeking more of your great post.
Also, I’ve shared your website in my social networks!
It’s in fact very complicated in this full of activity life to
listen news on TV, so I only use the web for that purpose,
and take the most recent news.
https://club4x4.ru/forum/viewtopic.php?f=17&t=78814
My brother suggested I might like this blog. He was once
entirely right. This publish truly made my day. You cann’t consider just how
so much time I had spent for this info! Thank you!
This design is incredible! You obviously know how to keep a reader amused.
Between your wit and your videos, I was almost
moved to start my own blog (well, almost…HaHa!) Excellent job.
I really enjoyed what you had to say, and more than that, how you presented it.
Too cool!
https://club4x4.ru/forum/viewtopic.php?f=17&t=79385
ampicillin brand name canada ampicillin 500mg over the counter ampicillin
mail order pharmacy india: top online pharmacy india – india pharmacy
Wonderful post but I was wanting to know if you could write a litte more on this subject?
I’d be very thankful if you could elaborate a little bit more.
Thank you!
Also visit my homepage – Bio Solution Keto Review
I read this paragraph fully on the topic of the resemblance of hottest and earlier technologies, it’s amazing article.
https://nalubyutemy.forum2x2.ru/t14677-topic#34838
Magnificent beat ! I would like to apprentice at the same time as you amend your website, how could i subscribe for a blog website?
The account helped me a acceptable deal. I had been a little bit familiar of this your broadcast offered shiny clear concept
временная регистрация граждан рф https://registracia-moskow.ru/
I blog frequently and I genuinely appreciate your information. Your article has truly peaked my interest.
I am going to take a note of your website and keep checking for new information about once per week.
I opted in for your Feed too.
купить пнд трубу https://truba-pnd-opt.ru/
Sexy teen photo galleries
http://papawady.adablog69.com/?taliyah
teases you porn stream free porn video free yiung carmen luvana porn porn star men fitness free catoon porn
Your style is really unique compared to other folks
I’ve read stuff from. Many thanks for posting when you’ve got the
opportunity, Guess I will just bookmark this page.
ciprofloxacin: ciprofloxacin – cipro
Hurrah, that’s what I was seeking for, what a data!
existing here at this website, thanks admin of this site.
Magnificent beat ! I would like to apprentice while you amend your website,
how can i subscribe for a blog website?
The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear
idea
online pharmacies of canada