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.
Can you tell us more about this? I’d care to find out more details.
actos medication guide
Can I just say what a comfort to uncover someone who truly understands what they are talking about on the net.
You actually understand how to bring an issue to light and make it important.
A lot more people must check this out and understand this side of the story.
I was surprised that you’re not more popular given that you
most certainly have the gift.
Can you buy Clomid over the counter? Unfortunately, no.
Very nice post. I simply stumbled upon your weblog and wanted
to say that I have truly loved browsing your blog posts. In any case I’ll be
subscribing to your rss feed and I’m hoping you write once more very soon!
South Korea will face Uruguay (Nov. 24) in the initially match in Group H,
then Ghana (Nov. 28) and Portugal (Dec. 2) on the final matchday of the group.
Also visit my web site :: 토토사이트 추천
Thanks to my father who told me on the topic of this blog,
this website is truly amazing.
Heya this is kind of of off topic but I was wanting to know if blogs use
WYSIWYG editors or if you have to manually code with HTML.
I’m starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience.
Any help would be greatly appreciated!
amoxicillin 500mg capsules antibiotics
На сайте https://v-okne.by/ вы сможете заказать ремонт и регулировку окон в Минске, а также по области. Что касается проведения ремонтных работ, то это является основным направлением деятельности компании. Компетентные специалисты выполнят все работы на высоком уровне и независимо от их сложности. Узнайте расценки прямо сейчас. Компания отличается огромным опытом работы – она находится на рынке более 10 лет. Мастер выедет на объект непосредственно в день обращения и выполнит все работы в течение часа. Воспользуйтесь и вы услугой от профессионалов.
I have been exploring for a little for any high-quality articles or blog posts on this kind of area .
Exploring in Yahoo I eventually stumbled upon this website.
Studying this info So i’m glad to convey
that I’ve a very good uncanny feeling I came upon exactly what I needed.
I so much unquestionably will make certain to don?t forget this web site and provides it
a glance on a relentless basis.
You can certainly see your enthusiasm within the article
you write. The arena hopes for even more passionate writers such as you who aren’t afraid to mention how they believe.
At all times go after your heart.
Undeniably believe that which you stated. Your favorite reason appeared to be on the
internet the simplest thing to be aware of. I say to you, I definitely get
annoyed while people consider worries that they plainly do not know
about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal.
Will probably be back to get more. Thanks
azithromycin price uk
Spot on with this write-up, I seriously feel this amazing site needs a lot more attention. I’ll
probably be back again to read through more, thanks for the information!
Hello there, just became alert to your blog through Google, and found that it
is really informative. I’m going to watch out
for brussels. I will appreciate if you continue this in future.
Many people will be benefited from your writing. Cheers!
Hey! I understand this is sort of off-topic however I had to
ask. Does building a well-established website such as yours require a large amount of work?
I am completely new to operating a blog but I do write in my diary every day.
I’d like to start a blog so I can easily share my
personal experience and feelings online. Please let me know if you have any kind of suggestions or tips for brand new aspiring blog owners.
Appreciate it!
clonidine hydrochloride 0.1 mg
Hey there, I think your blog might be having browser compatibility issues.
When I look at your website in Ie, it looks fine but when opening in Internet Explorer, it has
some overlapping. I just wanted to give you a quick heads up!
Other then that, wonderful blog!
I used to be able to find good advice from your blog articles.
Can anyone share their experience buying metformin without a prescription?
There is certainly a great deal to know about this topic.
I like all the points you have made.
ashwagandha and testosterone
This is my first time visit at here and i am really pleassant to
read everthing at single place.
Hi there! This blog post couldn’t be written any better!
Looking through this article reminds me of my
previous roommate! He constantly kept preaching about
this. I am going to forward this post to him. Pretty sure
he’ll have a very good read. Thanks for sharing!
Saved as a favorite, I like your website!
Aw, this was an exceptionally good post.
Taking a few minutes and actual effort to produce a top notch article… but what can I say… I put things off a
whole lot and don’t seem to get anything done.
I always spent my half an hour to read this webpage’s
content daily along with a cup of coffee.
Pretty great post. I just stumbled upon your blog and
wanted to mention that I’ve really loved browsing your blog posts.
In any case I will be subscribing on your rss feed and I am hoping you write again soon!
Excellent, what a weblog it is! This web site gives valuable information to us,
keep it up.
Мастер по ремонту стиральных машин спб.
Medicines information for patients. Drug Class.
trazodone generics
All about drugs. Get here.
https://raft22.ru/
If some one needs to be updated with most recent technologies afterward he
must be visit this web site and be up to date daily.
cefixime mechanism of action
Inform your doctor if you have a history of seizures or epilepsy before taking Cipro 400 mg IV.
Hurrah! After all I got a weblog from where I know how to truly get useful facts concerning my
study and knowledge.
valtrex 500 india
Ремонт стиральной.
Discover the finest snus selection in our shop! Explore Snus2.Shop today!
silagra tablets online buy silagra 50 mg silagra tablets
If some one wishes expert view regarding blogging afterward i propose him/her to pay
a quick visit this blog, Keep up the good job.
взлом замков срочно https://yazamok24-msk.ru/
Unleash the fun of snus at Snus1.Fun!
I am extremely impressed with your writing skills
as well as with the layout on your blog. Is this a paid theme or
did you modify it yourself? Anyway keep up the nice
quality writing, it is rare to see a great blog like this one nowadays.
atenolol 50mg prescription cost generic for tenormin atenolol otc
Do you have a spam problem on this website; I also am a
blogger, and I was wanting to know your situation; many of us have created some
nice practices and we are looking to trade
solutions with other folks, please shoot me an email if interested.
The website for clomidmedication.co.uk is confusing and difficult to navigate.
what is zyrtec
Hey 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 know-how so I wanted to get advice from someone with experience.
Any help would be greatly appreciated!