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 partner and I stumbled over here from a different website and thought I might check things out.
I like what I see so now i am following you. Look forward to looking over your web page again.
darknet links dark web links
dark market 2023 darkmarkets
bitcoin dark web free dark web
Сайт https://2417.pro представляет собой портал с бесплатными объявлениями. Так вы сможете найти предложения на самую разную тему, включая транспорт, недвижимость, бизнес, работу, электронику, услуги, детский мир, моду и стиль. Вы сможете сами подать объявление, если необходимо что-то продать. Если в доме или гараже хранится ненужная вещь, то можно ее продать, ведь, возможно, она кому-то пригодится. Есть премиум объявления, а также срочные, когда товар необходимо продать оперативно. Среди всех вариантов вы обязательно найдете тот, который вам нужен.
It’s great that you are getting thoughts from this article as well as from
our discussion made at this time.
I’ve read a few good stuff here. Certainly price bookmarking for revisiting.
I surprise how a lot attempt you set to make one of these great informative website.
Feel free to visit my site: im reporting all your gmbs
darknet links darkmarket link
darknet market lists how to get on dark web
watch porn video
deep web links dark web market list
https://edpillsfd.com/# erection pills viagra online
I am regular visitor, how are you everybody? This piece of writing posted at this website is genuinely good.
my blog … importacion de embarcaciones
Jսst desire to say yoսr article іs as astounding.
The clearness in your рut up іѕ simply nice ɑnd i can suppose ʏoᥙ’re an expert
on tһis subject. Fine alߋng with үour permission allow me to grasp yoᥙr feed to stay սp
to dɑte ԝith drawing close post. Thаnks a mіllion аnd pⅼease carry
ⲟn tһe rewarding ԝork.
Also visit mу site … Canadian News Today
how to get on dark web darknet sites
http://rytmika-gdansk.pl/profile.php?lookup=24645
Hello it’s me, I am also visiting this web page regularly,
this web page is actually nice and the viewers are in fact sharing
pleasant thoughts.
onion market tor market links
dark web markets dark web link
buy dapoxetine 90mg orlistat order order xenical 60mg without prescription
Thanks for your personal marvelous posting!
I really enjoyed reading it, you will be a great author.I will make sure to bookmark your blog and will eventually come back sometime soon. I want to encourage you to ultimately continue your great writing, have a nice afternoon!
These are actually wonderful ideas in about blogging. You have touched
some nice things here. Any way keep up wrinting.
darknet market list dark web market
tor market dark markets 2023
Are you looking for a way to earn extra income while promoting health and wellness?
Look no further! Our affiliate program offers a generous 25% commission on every sale you refer to our site.
Join Top Affiliate Programs Now
https://yfind.net
новости Херсона сегодня
where to buy acticin
По ссылке https://yandex.ru/profile/137507524552 вы сможете найти всю исчерпывающую информацию, касающуюся свадебного агентства Kasla Wedding. Оно на профессиональном уровне занимается организацией масштабных торжеств. При этом продумывает все до мелочей, чтобы торжество прошло именно так, как нужно. Здесь вы найдете информацию про то, где находится это агентство. Есть фото и видео материалы, телефон для связи и другая дополнительная и нужная информация, которая поможет найти агентство.
I’m not certain where you are getting your information, but good topic.
I must spend a while finding out much more or figuring out more.
Thanks for excellent information I was looking for this information for my mission.
Howdy! I know this is kinda off topic however , I’d figured I’d
ask. Would you be interested in trading links or maybe guest authoring a blog post or vice-versa?
My blog goes over a lot of the same subjects as yours and I think we could greatly benefit from each other.
If you happen to be interested feel free to send me an e-mail.
I look forward to hearing from you! Excellent blog by the way!
Hi, I do think this is a great web site. I stumbledupon it 😉 I
am going to revisit once again since I book marked it.
Money and freedom is the greatest way to change, may you be
rich and continue to help other people.
darknet market best darknet markets
You really make it seem so easy with your presentation but I find this
matter to be really something which I think I would never understand.
It seems too complex and extremely broad for me. I’m looking forward for your next post, I’ll
try to get the hang of it!
Good day! I simply would like to offer you a huge thumbs up for the great information you’ve got
here on this post. I will be returning to your website for more soon.
Howdy! I know this is somewhat off-topic however I needed to ask.
Does managing a well-established website like yours take a
massive amount work? I am completely new to writing a blog but I
do write in my journal on a daily basis. I’d like to start a blog so I will be able to share my
experience and thoughts online. Please let me know if
you have any kind of suggestions or tips for brand new aspiring
blog owners. Thankyou!
I am regular visitor, how are you everybody? This piece of writing posted
at this web page is in fact nice.
Wow! After all I got a website from where I can truly get valuable information concerning my study and knowledge.
I was wondering if you ever considered changing the layout of your site?
Its very well written; I love what youve got to say.
But maybe you could a little more in the way of
content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 images.
Maybe you could space it out better?
dark markets 2023 black internet
where is the nearest place that sells kamagra jelly
deep web drug store tor markets
Good way of describing, and nice paragraph to take data concerning my presentation subject,
which i am going to present in college.
darknet seiten drug markets dark web
I like the helpful information you provide in your articles.
I will bookmark your blog and check again here frequently.
I’m quite certain I’ll learn plenty of new stuff right here!
Best of luck for the next!
dark web market list darknet links
deep web drug links dark market
I don’t even know how I ended up here, but I thought this post was great.
I do not know who you are but definitely you’re going
to a famous blogger if you are not already 😉 Cheers!
citalopram 40 mg coupon
dark web websites deep web drug store
Hi! I’ve been following your blog for a long time now and finally got the courage to go ahead and give you a shout out
from Lubbock Texas! Just wanted to tell you keep up
the good job!