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.
This is my first time pay a visit at here and i am actually impressed to read
all at single place.
Don’t waste time and money on expensive doctor visits when you can get Clomid online.
Hey there would you mind letting me know which webhost
you’re using? I’ve loaded your blog in 3 completely different browsers
and I must say this blog loads a lot quicker then most.
Can you recommend a good internet hosting provider at a honest price?
Kudos, I appreciate it!
На сайте https://podshipnik.info/ находится самый полный каталог подшипников. Здесь вам окажут поддержку в выборе, продаже. Доставка происходит по всей стране. Перед вами ни одна сотня наименований. При этом в разделе находятся исключительно лучшие, проверенные бренды, которые реализуют надежную, качественную продукцию. Эту компанию выбирают из-за того, что она предлагает гарантии на все товары, огромный ассортимент. При желании воспользуйтесь комфортным поиском, а также оперативной обратной связью.
Надежные и высококачественные тяговые аккумуляторные батареи 24 вольта для складской техники теперь доступны на сайте https://toyota-akb24v.ru/ Выбирайте тяговые аккумуляторные батареи 24 вольта для вилочных погрузчиков, штабелеров и электротележек Toyota. Мы гарантируем быструю доставку и высокий уровень сервиса
I was recommended this blog by my cousin. I’m not sure whether
this post is written by him as nobody else know
such detailed about my problem. You’re wonderful!
Thanks!
It is appropriate time to make a few plans for the long
run and it is time to be happy. I have read this publish and if I could I
wish to counsel you few interesting things or suggestions.
Perhaps you could write next articles referring to this article.
I wish to read more issues approximately it!
Gօod write-uр. Ӏ ϲertainly apprеciate tһis site.
Keeρ it up!
Ηere іs mʏ paɡe – lotto
Ahaa, its nice conversation regarding this article at this place at this webpage, I have read all
that, so now me also commenting here.
Казино Gama Casino открыло свои двери в 2023 году, предлагая своим клиентам захватывающие и уникальные азартные игры онлайн – мобильная версия гамма казино
Wow, that’s what I was looking for, what a stuff!
existing here at this website, thanks admin of this web page.
Thanks for a marvelous posting! I genuinely enjoyed reading it, you
could be a great author. I will ensure that I bookmark
your blog and will often come back at some point.
I want to encourage yourself to continue your great posts, have a nice evening!
Hi just wanted to give you a brief heads up aand let you know a few
of the pictures aren’t loading properly. I’m
not sure why but I think its a linking issue.
I’ve tried it in twwo different browsers annd both show the
samke outcome.
Aw, this was an exceptionally good post. Taking a few minutes and actual effort to create a top notch
article… but what can I say… I put things off a whole lot and never manage to get anything done.
купить камеру видеонаблюдения скрытую https://kamery-videonablyudeniya.ru/
cheap zoloft online
Hi, There’s no doubt that your blog might be having web browser compatibility issues.
Whenever I take a look at your blog in Safari, it looks fine however, when opening in Internet Explorer,
it has some overlapping issues. I merely wanted to provide you with a quick heads up!
Aside from that, wonderful website!
What’s up, its fastidious post about media print, we all be aware of media is a enormous source of facts.
If you are going for most excellent contents like I do, simply visit this site all the time because it gives quality contents, thanks
Simply desire to say your article iis as amazing. The clearness on your submit is simply great and
i can suppose you’re a professional on this subject. Fiine together with you permission let mee to grab
your RSS feed to stay up to ate with imminent post.
Tanks 1,000,000 and please keep up the enjoyable work.
bactrim uk bactrim canada bactrim generic
Thanks for the good writeup. It in fact used to be a
leisure account it. Look complicated to far introduced agreeable from you!
However, how could we keep in touch?
proscar 5mg online proscar price where can i buy proscar online
You really make it appear really easy together with
your presentation but I to find this topic
to be really one thing which I think I might never understand.
It sort of feels too complex and very extensive for me. I’m looking forward to your subsequent put up, I’ll attempt
to get the hang of it!
Hi there, I log on to your new stuff daily.
Your story-telling style is awesome, keep doing what you’re doing!
Nancy is part of the forexsignals team at Easy
Pips Forex Signals. Set a limit order of 200 pips and a stop loss order of 50 pips.
Greetings, I believe your site could possibly be having
internet browser compatibility issues. When I look
at your web site in Safari, it looks fine but when opening in I.E., it’s got
some overlapping issues. I just wanted to give you a quick heads
up! Besides that, great site!
Quality articles is the secret to be a focus for the users to pay
a quick visit the web site, that’s what this web
site is providing.
I every time used to study article in news papers but now as I am a user of web so from now I am using net for content,
thanks to web.
I was suggested this website by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my
difficulty. You’re incredible! Thanks!
I’d like to thank you for the efforts you have put in writing this blog.
I am hoping to check out the same high-grade content from you later
on as well. In fact, your creative writing abilities has motivated me to get my very own site now 😉
My page – need to sell my house asap
abcslot link server internasional paling mantap
https://mazo.marinedasalud.es/CPMDI3YjJERjI=j
vermox canada cost can you buy vermox over the counter in usa vermox medicine
Heya! I’m at work surfing around your blog from my new iphone 4!
Just wanted to say I love reading through your blog and look
forward to all your posts! Keep up the superb work!
Hi there, just became alert to your blog through Google, and found that it is truly informative.
I’m going to watch out for brussels. I’ll appreciate
if you continue this in future. A lot of people will be benefited from your
writing. Cheers!
Битумовозы Новый Уренгой – Нефтепродукты, ГСМ
Gama Casino — это новейшее дополнение к миру онлайн-игр. Хвастаясь широким выбором игр, казино Gama может предложить что-то каждому – Gama casino 2022
What’s up friends, its impressive piece of writing regarding tutoringand entirely explained, keep
it up all the time.
Potential borrowers in eligible states can apply on-line
and benefit from fast funding.
Feel free to surf to my blog post: here
Hi there every one, here every person is sharing these
know-how, therefore it’s nice to read this website, and I used to visit
this blog every day.
I truly love your site.. Pleasant colors & theme.
Did you make this website yourself? Please reply back as I’m
planning to create my own website and want to know where you got this from or exactly what the theme is named.
Many thanks!
Ready to try a new vaping experience? Check out our selection of disposable vapes, offering a variety of flavors and strengths to suit your taste. From fruity to savory, we have something for everyone. Our disposable vapes are also a convenient and hassle-free option for those on the go. Try them out now and enjoy the satisfaction of high-quality products and excellent customer service.
Thanks for finally writing about > Eclipse – Formatter
e Save Action – Handerson Frota sell ugly houses
After I originally commented I appear to have clicked on the -Notify
me when new comments are added- checkbox and from now on whenever a comment
is added I get four emails with the exact same comment.
There has to be a way you are able to remove me from that service?
Thanks!
I desperately need a [url=https://synthroid.skin/]Synthroid 137 mcg coupon[/url] to afford my medication.
Hey there! I understand this is kind of off-topic but I needed to ask.
Does building a well-established website such as yours require a massive
amount work? I am brand new to operating a blog but I
do write in my diary on a daily basis. I’d like to start a blog so I will be able to share my own experience and
thoughts online. Please let me know if you have any kind of ideas or tips for
brand new aspiring blog owners. Thankyou!
darknet search engine url blacknet drugs [url=https://cypher-darkweb.com/ ]darknet market iphone [/url]
darknet markets deepdotweb current darknet market list [url=https://world-drugsonline.com/ ]darknet market alternatives [/url]
На сайте http://vivagifts.ru вы сможете заказать ручки с логотипом. Все они высокого качества и реализуются по доступной стоимости, а потому сделать приобретение смогут все желающие. В разделе также представлены и металлические, а также деревянные флешки. Минимальные сроки выполнения заказа. Гравировка выполняется за пару дней. Есть возможность оформить заказ всего за сутки после того, как он поступил в работу. Для выполнения заказа используется собственное инновационное оборудование. Оно позволяет браться за работу различного уровня.
Aw, this was a really good post. Finding the time and actual effort to create a very good
article… but what can I say… I put things off a lot
and never seem to get anything done.