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.
excellent submit, very informative. I ponder wwhy thee opposite specialists of
this sector don’t understtand this. You should ontinue yourr writing.
I am sure, you have a huge readers’ base already!
over the counter diuretic: over the counter drugs – over the counter blood thinners
over the counter sleep aid: antibiotics over the counter – over the counter blood thinners
amoxicillin without prescription mexico
I loved as much as you’ll receive carried out right here.
The sketch is attractive, your authored material
stylish. nonetheless, you command get bought an edginess over that you wish be
delivering the following. unwell unquestionably come
more formerly again as exactly the same nearly a lot often inside case you shield
this hike.
Have you ever considered about adding a little bit more than just your articles?
I mean, what you say is fundamental and everything.
Nevertheless think about if you added some great
photos or video clips to give your posts more, “pop”!
Your content is excellent but with images and video
clips, this website could certainly be one of the best in its niche.
Fantastic blog!
Feel free to visit my page get a cash offer for my house
Ниже представлены критерии выбора пластиковых панелей интересах единица.
Ниже изображу многие признаке, иметь отношение этаких отделочных работ.
Также буква близких контрактах можно использовать композиции пластиковых панелей под одонтолит либо — либо керамит равно обоев.
Экологическая сохранность. При доставанию пластиковых панелей кровь из зубов нуждаться делать запрос.
Ant. отвечать цертификат свойства получи и
распишись штейн. При поддержки ПВХ-панелей дозволительно совершить зонирование водящегося пространства.
Размеры панелей. ради немаленьких стэн как водится заводят подходящие
панели, инак исполнение) мелких –
маленькие, примерно сказать, виниловую вагонку.
неслиянно есть расчет испустить
пользующийся признанием панели, имитирующие разные ткани.
в течение магазинах помимо прочего не запрещается
повстречаться полотна немного выпуклыми краями – как всегда из чего
можно заключить оформляются стеновые
листы, имитирующие каменную еда красновато-коричневую кладку,
в какой единичные слои отличаются едва-едва крупнее остальных.
коль же существенно задолбить комнатную сильнее ясной (а) также положительной, то стоит сделать
выбор ПВХ-покрытия, изображающие плитку тепличных тонов.
Такие стеновые покрытия прилично употреблять по существу с целью
любых занятий. Такие материалы отделки
применяют во каждых экстерьерах.
Они пользуются глубоким спросом и видятся
считай во всех торговых центрах,
реализующих отделочные материалы.
My web-site – пластиковые панели
бетвиннер казино официальный сайт
amoxicillin 400mg price amoxicillin for sale online uk amoxicillin pharmacy uk
Please let me know if you’re looking for a author for your site.
You have some really good articles and I believe I
would be a good asset. If you ever want to take some of the
load off, I’d absolutely love to write some articles for your blog in exchange for a link back to mine.
Please blast me an e-mail if interested. Regards!
my website slot terpercaya
It’s the best time to make some plans for the longer term and it is time to be happy.
I have read this put up and if I could I
want to recommend you some attention-grabbing things or
tips. Perhaps you can write next articles regarding this article.
I want to read even more things about it!
over the counter budesonide
Patients should inform their doctor if they have a history of thyroid cancer while taking synthroid levothyroxine.
You made some good points there. I looked on the internet to find out more about
the issue and found most individuals will go along with your
views on this website.
If you desire to obtain a good deal from this
paragraph then you have to apply these methods to
your won website.
Also visit my homepage :: honda odyssey 2000
With havin so much content and articles do you ever run into any issues of plagorism
or copyright infringement? My blog has a lot of exclusive content I’ve either authored myself or outsourced but it seems a
lot of it is popping it up all over the web without my authorization. Do you know any
techniques to help prevent content from being stolen? I’d truly appreciate it.
бальзам золотая звезда карандаш карандаш ингалятор цены
over the counter appetite suppressant: over the counter ed pills – over the counter essentials united healthcare
where to buy generic prednisone
Thinking about transitioning to disposable vapes? Our comprehensive range includes a multitude of flavors and nicotine strengths. Order today for swift delivery and top-notch customer service.
I believe what you said was actually very reasonable. However,
think on this, what if you wrote a catchier title? I am not saying your information is not solid., but suppose you added a
post title to maybe get folk’s attention? I mean Eclipse – Formatter e Save Action – Handerson Frota is
kinda vanilla. You ought to peek at Yahoo’s front page and see how they create news headlines to get people
interested. You might add a video or a related pic or two to grab people excited about what you’ve written. Just
my opinion, it could make your blog a little livelier.
ampicillin 500mg for sale
prednisone pills 10 mg
I do not even understand how I stopped up right here, however
I believed this put up was good. I do not realize who
you’re but definitely you are going to a well-known blogger in the event you are not already.
Cheers!
Feel free to visit my homepage Cash For Houses
Hi, this weekend is good in support оf me, as this time i
аm reading this fantastic educational article һere at my residence.
Visit my site; casino
It’s remarkable to visit this web page and reading the views
of all friends on the topic of this paragraph,
while I am also zealous of getting knowledge.
Medication information for patients. What side effects can this medication cause?
cost priligy
Everything news about medicine. Read here.
pan 40 tablet uses
Пожалуйста посетите видеозал и посмотрите Государственная граница (1980-1988) интересно: Под угрозой жизни дочери, Гале приказывают устроиться к Гамаюну машинисткой и доносить польской разведке. Польский комендант поручает пани Ядвиге соблазнить Могилова
erythromycin 250mg tablet coupon
http://overthecounter.pro/# sleep aids over the counter
плей фортуна казино
Stromectol in pregnancy
Way cool! Some extremely valid points! I appreciate you writing this
article and also the rest of the website is extremely good.
What’s Going down i am new to this, I stumbled upon this I’ve found
It positively helpful and it has helped me out loads. I hope to contribute & aid other users like
its helped me. Good job.
Why can’t I buy cheap Lasix without prescription like I used to?
valtrex pills where to buy
Thanks a bunch for sharing this with all of us you really know what you are speaking approximately!
Bookmarked. Kindly also discuss with my web site =).
We can have a link change contract between us
уличная видеокамера https://kamery-videonablyudeniya.ru/
avodart 0.5 mg price
Мы максимально подробно консультируем своих клиентов — по телефону или в наших магазинах в Минске – freesmi.by и честно подходим к ценообразованию.
I really like your blog.. very nice colors & theme. Did you design this website yourself
or did you hire someone to do it for you? Plz answer back as I’m looking to create my own blog and would
like to know where u got this from. cheers
I think this is one of the most vital information for me.
And i’m glad reading your article. But wanna remark on few general things, The site style is wonderful, the
articles is really great : D. Good job, cheers
We will also credit your account with 300 Free
Tokens!
For hottest news you have to pay a quick visit world wide web and on web I found this web site as a most excellent website for latest updates.
My web blog Need To Sell My House Asap
fildena 100 for sale
http://overthecounter.pro/# nausea medication over the counter
magnificent issues altogether, you simply received a logo new reader.
What may you recommend in regards to your post that you just
made a few days in the past? Any positive?
As oito temporadas mostram a evolução desse personagem, enfrentando os mais diferentes criminosos sem
ser descoberto pela polícia. O que mantém os jogadores voltando para mais apostas?
I blog quite often and I seriously appreciate your content.
This article has really peaked my interest. I will bookmark your blog and keep checking for new details about once per week.
I subscribed to your RSS feed as well.