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.
Medicine information leaflet. Long-Term Effects.
retrovir
Some information about medication. Read now.
Nice post. I learn something new and challenging on blogs I stumbleupon every day.
It’s always helpful to read through content from other writers and practice a little
something from other sites.
prograf order now
Immerse yourself in the top-notch elf bar range with our premium ink selection!
Hey! Do you know if they make any plugins to safeguard against hackers?
I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?
Synthroid generally costs significantly more than levothyroxine.
На сайте https://sprotyv.org/ вы сможете почитать увлекательные, интересные и содержательные новости Украины, которые касаются самых разных сфер, включая экономику, политику, последние данные о спецоперации. Есть любопытные материалы о бизнесе, криминале, культуре, здоровье. Этот ресурс также будет интерес и женщинам, которые следят за собой, ведь на портале имеются ценные советы и рекомендации, касающиеся ухода за лицом. Материалы сопровождаются красочными картинками, цитатами. Регулярно появляются новые статьи.
На сайте https://fankino.ru/ вы сможете ознакомиться с новостями, посвященными кино, сериалам, различным развлечениям. Только здесь самый актуальный, свежий и интересный контент, который позволит отследить выхода новых серий любимого сериала. Имеются трейлеры, которые помогут определиться с тем, стоит ли смотреть продолжение фильма. Есть обзоры различных фильмов, их содержание, то, чем закончатся, количество серий, актерский состав и многое другое. Еще имеется контент, касающийся примет, праздников, образования.
Appreciate the recommendation. Let me try it out.
На сайте https://shopfishing.com.ua вы сможете приобрести все, что нужно для ловли рыбы. Здесь богатый ассортимент продукции, которая понравится не только дилетантам, но и заядлым рыбакам, желающим обновить свой арсенал. Вас обрадует оперативная доставка, а также безупречный клиентский сервис, зачисление бонусов за покупки. Весь товар является оригинальным и качественным. На него установлены привлекательные цены. Оплата любым, наиболее удобным способом. Регулярное расширение ассортимента.
Hey there I am so thrilled I found your site, I really found you by error, 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 fantastic post and
a all round thrilling blog (I also love the theme/design), I don’t have time to read it
all at the minute but I have saved it and also included your RSS feeds,
so when I have time I will be back to read much more, Please do keep up the great b.
На сайте https://fairspin-qn.ru почитайте информацию о популярном онлайн – заведении Fairspin. Оно открылось не так давно, но уже заполучило постоянных клиентов, которые облюбовали его и регулярно на него заходят. Онлайн-казино отличается наличием лицензии. Дизайн выполнен в приятной цветовой гамме, который не отвлекает от игры. Регистрация на этом портале займет всего пару минут и не вызовет сложностей. В настоящий момент насчитывается около 2 сотен симуляторов от лучших производителей.
clonidine 3 mg
Greetings! Very helpful advice in this particular post!
It is the little changes that make the most significant
changes. Many thanks for sharing!
Hey there! I know this is kind of off topic but I was wondering which blog platform are you using for this site?
I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at
options for another platform. I would be fantastic if you could point me in the direction of a
good platform.
Feel free to visit my web site – Sell My house Online For free
OneMain Economic strictly delivers personal loans to buyers and specializes in assisting these with pokor
credit.
Here is my page: more info
Every weekend i used to pay a visit this site, because i wish for enjoyment,
since this this website conations truly pleasant funny material too.
buy celebrex online no prescription
Oh mmy goodness! Impressive article dude! Thank you soo much, However I am having difficulties with your RSS.
I don’t know the reason why Ican’t join it.
Is there anyone else getting identicl RSS problems?
Anyone that knows the solution will you kindly respond?
Thanx!!
This permits them to supply the highest value bed linens possible.
Medicament prescribing information. Effects of Drug Abuse.
abilify
Best information about meds. Read information here.
cypher market link https://dark-market-heineken.com/
https://fixikionline.ru/
I think the admin of this web site is truly working hard in favor of his site, because here every data
is quality based information.
penis enlargement
Protonix reviews
This is a topic that’s close to my heart… Many thanks!
Where are your contact details though?
I used to be suggested this blog by means of my cousin. I am not sure whether or not this post is written via him as no one else understand such
detailed approximately my trouble. You’re amazing!
Thank you!
Heya i’m for the first time here. I found this
board and I find It really useful & it helped me out much.
I hope to give something back and aid others like you aided me.
Attractive section of content. I simply stumbled upon your website and
in accession capital to assert that I get
actually enjoyed account your weblog posts. Any way I will be
subscribing in your feeds and even I achievement you get right of entry to persistently fast.
My web-site … 2000 expedition ford
Medicines prescribing information. Brand names.
minocycline
All what you want to know about drug. Get here.
There’s definately a lot to learn about this issue.
I love all of the points you made.
Hello there! I know this is kind of ooff topic butt I was wondering which blog platform are you using for this website?
I’m getting tired of WordPress because I’ve had issues with
hackers and I’m looking at options for another platform.
I would be awesome if you could poit mee in the direction of a good platform.
Also vjsit my web blog – 2006 chevy silverado abs brake line diagram (infi.me)
Hello there! I know this is somewhat off topic but I was wondering which blog platform are you using for
this site? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at
options for another platform. I would be awesome if you could point me in the direction of a
good platform.
This text is invaluable. How can I find out more?
We’re a vertically integrated firm, which means that we rarely outsource work.
my webpage; web page
I think this is among the such a lot significant
info for me. And i am glad reading your article. But want to statement on some basic issues, The web
site taste is wonderful, the articles is actually excellent : D.
Excellent activity, cheers
Hey there! I know this is kind of off topic but I was wondering if you
knew where I could get a captcha plugin for my comment form?
I’m using the same blog platform as yours and I’m having problems finding one?
Thanks a lot!
I enjoy reading a post that can make men and women think.
Also, thanks for allowing for me to comment!
Very interesting information!Perfect just what I was looking for!
This site was… how do you say it? Relevant!! Finally I’ve found something that helped me.
Cheers!
elimite coupon
Hi Dear, are you really visiting this web site regularly, if
so afterward you will without doubt take nice knowledge.
atarax 10
продажа квартир в сочи
Excellent goods from you, man. I have understand your stuff previous to and you’re just too magnificent.
I actually like what you have acquired here, really like what you are saying and the
way in which you say it. You make it entertaining and you still take care of to
keep it sensible. I cant wait to read much more from you. This is really a great
site.
tadacip 20 mg price in india
Hello very cool web site!! Man .. Excellent .. Wonderful ..
I’ll bookmark your site and take the feeds also? I am glad
to find a lot of helpful info right here in the submit,
we’d like develop more techniques in this regard, thank
you for sharing. . . . . .
Hi there! This is kind of off topic but I need some advice from an established blog.
Is it difficult to set up your own blog? I’m not very techincal but I can figure things out pretty quick.
I’m thinking about creating my own but I’m not sure where to begin. Do you
have any points or suggestions? Cheers
What’s up friends, nice paragraph and nice urging commented at this place,
I am actually enjoying by these.