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.
На сайте https://www.informteh.ru вы сможете заказать проектирование, а также установку, сервисное обслуживание систем вентиляции, кондиционирования, обогрева помещений. Предприятие считается официальным дистрибьютором техники, которая реализуется напрямую от производителя по доступным ценам и с оперативной доставкой. Действуют особые условия покупки. При необходимости всегда можно проконсультироваться у квалифицированных менеджеров. Дополнительно на сайте можно изучить полезные и информативные тематические статьи.
Whats up very cool website!! Man .. Excellent
.. Superb .. I’ll bookmark your website and take the feeds
additionally? I am glad to seek out numerous useful information right here within the
submit, we need work out extra techniques on this regard,
thanks for sharing. . . . . .
you are really a just right webmaster. The site loading velocity is amazing.
It seems that you are doing any distinctive trick. In addition, The
contents are masterpiece. you have performed a wonderful task on this topic!
It’s perfect time to make some plans for the future and it’s time to be happy.
I have read this post and if I could I wish to suggest you some interesting things or advice.
Perhaps you can write next articles referring to this article.
I want to read even more things about it!
Hi Dear, are you genuinely visiting this web page daily, if so then you will absolutely take nice
knowledge.
dipyridamole drug
I think this is one of the most vital info
for me. And i am glad reading your article. But should remark on some general things, The website style
is ideal, the articles is really nice : D. Good job,
cheers
Awesome! Its actually remarkable post, I have got much clear idea about from this
piece of writing.
ampicillin buy online
https://overthecounter.pro/# clobetasol cream over the counter
A person essentially lend a hand to make seriously articles I might state.
That is the very first time I frequented your
website page and to this point? I amazed with the research you made to make this particular submit amazing.
Magnificent task!
my site … Ace Keto ACV Gummies
These values now total 130%, which means that the book
has an overround of 30 (130−100).
Feel free to visit my blog post :: 파워볼
I visited multiple web pages however the audio feature for audio
songs existing at this site is really marvelous.
Hiya! Quick question that’s totally off topic. Do
you know how to make your site mobile friendly?
My site looks weird when browsing from my iphone4.
I’m trying to find a template or plugin that might be able to correct this problem.
If you have any suggestions, please share. Cheers!
The 1st rechorded lottery dates from the Han Dynasty,which ruled among 205 and 187 BC.
Lookk into my weeb blog – 스포츠토토
Hey would you mind letting me know which web host you’re
utilizing? I’ve loaded your blog in 3 completely
different browsers and I must say this blog loads a lot faster then most.
Can you recommend a good hosting provider at a reasonable price?
Many thanks, I appreciate it!
Thiss blog ѡas… hoѡ do you say it? Relevant!!
Finalⅼy I have found somethіng that helped mе. Tһanks!
Also visit my webpage – Cheap Vapes Larnaca
buy silagra 100 mg silagra 100mg silagra 100 mg tablet
cara daftar situs slot gacoe 2023
http://m.gun-go.com/member/login.html?noMemberOrder=&returnUrl=http%3A%2F%2Fwww.skigateway.com%2F__media__%2Fjs%2Fnetsoltrademark.php%3Fd%3Dutechpus.com
cara daftar situs slot gacoe 2023
http://tazzel.com/__media__/js/netsoltrademark.php?d=utechpus.com
What an good article!
Is it okay I copy your post and share it with my site subscribers?
Come check our channel! It is about Korean 검증커뮤니티
If ever your interested, feel free to come to my channel and have a look.
Thank you and Keep up the nice work!
Thanks for your personal marvelous posting! I quite enjoyed reading it, you are a great author.
I will always bookmark your blog and will eventually come back from now on. I want to encourage you continue your great writing,
have a nice weekend!
Great blog you have got here.. It’s hard to find high quality writing like yours these days.
I truly appreciate individuals like you!
Take care!!
I don’t even know how I stopped up right here,
however I thought this post was once good. I
don’t realize who you’re however definitely you are going to a famous blogger for those who aren’t
already. Cheers!
We 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 exploring your web page for a second time.
You ought to be a part of a contest for one of the
most useful websites on the internet. I’m going to highly recommend this website!
Hallo, Ich finde den Aufbau der Webseite sehr gut.
Macht bitte weiter so.
https://kylerjbqc19764.tdlwiki.com/90760/daftar_nine_situs_slot_deposit_pulsa_tanpa_potongan_terpercaya
This design is steller! You certainly know how to keep a reader entertained.
Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Great job.
I really enjoyed what you had to say, and more than that,
how you presented it. Too cool!
What’s Taking place i’m new to this, I stumbled upon this I’ve found It positively helpful and it has aided me
out loads. I’m hoping to contribute & help different customers like its aided me.
Good job.
vermox sale vermox online vermox uk buy
Hi there everyone, it’s my first pay a visit at this website, and paragraph is actually fruitful in favor of me, keep up posting these posts.
Balkly Bett and WynnBET aree the two sportsbooks most recent
to acquiore licenses to operate in the state.
Also visit my web site 검증놀이터
I like it when individuals get together and share thoughts.
Great site, continue the good work!
Heya are using WordPress for your blog platform?
I’m new to the blog world but I’m trying to get started and create my own. Do you
need any coding expertise to make your own blog? Any help would be greatly appreciated!
Forr hottest informaton yyou hhave too ppay a visait web and on world-wide-web I found tthis site as a best web
page for mosst recent updates.
I am regular visitor, how are you everybody? This article posted at this website is genuinely good.
Here is my web page; Pure Life Keto Max Review
where can i buy ampicillin
cheap buy generic avodart buy generic avodart avodart 0 5mg
I wanted to thank you for this excellent read!! I absolutely enjoyed every little bit of it.
I’ve got you bookmarked to look at new stuff you post…
Hurrah, that’s what I was searching for, what a material!
present here at this web site, thanks admin of this site.
регистрация в Москве https://registracia-msk.ru/
Get The Little Known System For Ending The Constant Struggle Most Home Business Owners Will Never Escape
And Finally ‘Crack The Code’ To Building Your Home
Business Like All Other Top Money Earners In Our Modern Age.
Inadequate Employee Engagement:This usually happens when your employees are not
motivated enough. As simple as typing “time management skills” on the internet search toolbar,
you’ll find tonnes of self-help websites that provide
good time management skills.
It’s a pity you don’t have a donate button! I’d definitely donate to this outstanding
blog! I suppose for now i’ll settle for bookmarking
and adding your RSS feed to my Google account. I look forward to new
updates and will talk about this website with my Facebook
group. Chat soon!
Whoa! This blog looks just like my old one! It’s
on a totally different subject but it has pretty much
the same page layout and design. Superb choice of colors!
The allopurinol 100mg tablets price here is absolutely unbeatable.
Merely a smiling visitor here to share the love (:,
btw great style and design.
It’s actually very difficult in this busy life to listen news on TV,
thus I simply use world wide web for that purpose, and get the most recent news.
Мы максимально подробно консультируем своих клиентов — по телефону или в наших магазинах в Минске – widzy-nptc.by и честно подходим к ценообразованию.
вскрытие дверных замков https://yazamok24-msk.ru/
I do not even know how I stopped up here, however I assumed this post was great.
I don’t understand who you might be but definitely you’re going to a famous blogger in case you aren’t already.
Cheers!