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.
My relatives always say that I am killing my time here at net, except I know I am getting experience everyday by reading such pleasant posts.
Have you ever considered about adding a little bit
more than just your articles? I mean, what you say is important
and all. Nevertheless think of if you added some great
images or video clips to give your posts more, “pop”! Your content is excellent but with pics and clips, this blog could undeniably be one of the very best in its niche.
Good blog!
Fastidious answers in return of this matter with genuine arguments and explaining all about
that.
Wow, this article is pleasant, my sister is analyzing these things, therefore I am going
to tell her.
An intriguing discussion is worth comment. I think that
you need to publish more on this issue, it may not be a taboo subject but
typically folks don’t discuss these topics. To the next!
Cheers!!
Such a lively place.. wonderful walk tour around the university belt..
thanks for sharing
plavix brand plavix medication plavix brand name coupon
Hi there to all, how is the whole thing, I think every one is getting more from this website, and your views are
pleasant in support of new visitors.
На сайте https://avanchange.com/ вы сможете обменять валюту. Здесь же получится купить Эфириум, Биткоин, Monero и другое. Кроме того, есть возможность совершить обмен электронных денег. Регулярно добавляются новые направления обменника, чтобы вы смогли выполнить все необходимые действия прямо в эту минуту. Кроме того, на сайте описывается и способ покупки биткоина. Это очень просто сделать. Система позволяет скорректировать курс в том случае, если имеются скачки. Только здесь самый выгодный обмен, а сайт работает круглосуточно.
http://svoimi-rukamy.net/
Hallo, Ich finde den Aufbau der Seite klasse.
Macht bitte weiter so.
http://olgarober.ru/component/k2/item/32
Сайт https://lingolink.ru/ представляет собой сервис, предназначенный для сокращения ссылок. Все, что вам необходимо сделать, – это вставить ссылку, после чего нажать кнопку, чтобы ее сократить. При необходимости воспользуйтесь расширенными настройками, которые предоставят вам больше возможностей. Короткие ссылки потребуются и для умного таргетинга, проведения глубокой аналитики, а также распределения трафика. Этот сервис максимально простой, понятный и функциональный, а потому воспользоваться им сможет каждый.
tretinoin 0.1
вывод из запоя на дому https://vivod-zapoy-msk.ru/
Thanks for your marvelous posting! I certainly enjoyed reading
it, you’re a great author.I will make certain to bookmark your blog
and will eventually come back later on. I want to encourage one to continue your great job, have a nice day!
You really make it appear really easy with your presentation however I to find this matter to be really one thing which I feel I might by no means understand.
It seems too complicated and very extensive for me. I’m looking
forward for your next put up, I will attempt to get the hang of it!
Thanks, +
_________________
[URL=https://kzkkslots6.fun/]Ойын автоматтарынан[/URL]
That is according to a new report from staffing firm Randstad US,
whihh surveyed more than 1,200 employed U.S. adults.
Also visit my webpage: click here
Linnk exchange iss nothing else except iit is simplly placing the oter person’s webpage link on youhr
page aat proper place and oter person will also do same in support oof
you.
My spouse and I stumbled over here coming from a different page and
thought I should check things out. I like what I see so now
i am following you. Look forward to finding out about your web page yet
again.
5000 mg amoxicillin amoxicillin tab 875mg how can i get amoxicillin
celebrex india
At this time I am going to do my breakfast, when having my breakfast coming yet again to read other news.
Koe nikotiinipussi-maailman eri tuotteiden kirjo laajassa valikoimassamme!
I know this if off topic but I’m looking into starting my own weblog and was curious what all is
needed to get set up? I’m assuming having a blog like yours would cost a pretty penny?
I’m not very web smart so I’m not 100% positive. Any suggestions
or advice would be greatly appreciated. Kudos
Fantastic website you have here but I was wondering if you knew of any forums that cover
the same topics talked about in this article?
I’d really like to be a part of online community where I can get
responses from other knowledgeable people that share the same interest.
If you have any recommendations, please let me know.
Thanks!
I believe this is among the most significant information for me.
And i’m happy studying your article. However should observation on few basic
issues, The web site style is great, the articles is in point
of fact great : D. Just right activity, cheers
Very energetic post, I loved that a lot. Will there be a part 2?
Here is my blog: Buy my House fast for cash
Where can I find a trusted website to buy ciprofloraxin online?
A motivating discussion is worth comment. There’s no doubt that that you should write more about this issue, it might not be a taboo subject
but generally people do not speak about these subjects. To the next!
Best wishes!!
Howdy I am so excited I found your webpage, I really found you by mistake, while
I was browsing on Askjeeve for something else, Anyways I am here now and would
just like to say thanks a lot for a tremendous post and a all
round enjoyable blog (I also love the theme/design), I don’t have time to read it all at
the moment but I have book-marked 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 superb jo.
my web blog jdb
azithromycin 500mg online india
I’m curious to find out what blog system you happen to be
utilizing? I’m having some small security problems with my latest
website and I would like to find something more risk-free.
Do you have any solutions?
prednisone buying prednisone rx coupon prednisone without a rx
prednisone price ontario canada
buy viagra online
not working
_________________
ойын автоматтары ойнайды
Thanks for the auspicious writeup. It in truth used to be a entertainment account
it. Glance complex to far added agreeable from you! By the
way, how could we keep in touch?
This paragraph is genuinely a good one it assists new net visitors, who are wishing in favor of blogging.
It’s awesome for me to have a site, which is beneficial in favor of my know-how.
thanks admin
Useful information. Lucky me I discovered your site unintentionally, and I am stunned why this
accident didn’t happened earlier! I bookmarked
it.
actos alternatives
Today, while I was at work, my cousin stole my iPad and tested to see if it can survive
a 30 foot drop, just so she can be a youtube
sensation. My iPad is now destroyed and she has 83
views. I know this is entirely off topic but I had to share it with someone!
печать этикеток в Москве https://pechat-etiketka.ru/
If you would like to obtain a great deal from this post then you have
to apply such strategies to your won website.
My blog sell house fast
Wonderful post! We are linking to this particularly great
content on our website. Keep up the great writing.
Tutustu nikotiinipussit-maailman monipuolisiin tuotteisiin laajassa valikoimassamme!
what is ashwagandha good for
cefixime distribution
I could not refrain from commenting. Perfectly written!