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.
Столица натяжные потолки отзывы
price of flomax 8 flomax flomax back pain
I’m gone to tell my little brother, that he should
also pay a quick visit this webpage on regular basis to obtain updated
from most up-to-date news.
Столица натяжные потолки отзывы
Good day very cool website!! Guy .. Beautiful .. Wonderful ..
I’ll bookmark your blog and take the feeds also? I am happy to search out
a lot of useful info right here within the put up, we’d like develop more techniques in this regard, thank you for sharing.
. . . . .
Also visit my site: 2002 ford explore
Hey! I just wanted to ask if you ever have any trouble with hackers?
My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due
to no back up. Do you have any solutions to stop hackers?
На сайте http://azimutpro.ru закажите рекламные подарки, качественную сувенирную продукцию: ручки с логотипом, различные красочные ежедневники, флешки, пакеты, зажигалки, брелоки и многое другое по доступным ценам. Все работы выполняются качественно, в соответствии с требованиями, нормативами. Если появились вопросы, то необходимо их задать менеджеру, который подберет для вас оптимальный вариант, подскажет, какую продукцию лучше приобрести, поведает о достоинствах, недостатках каждого вида.
Hi would you mind letting me know which web host you’re utilizing?
I’ve loaded your blog in 3 different internet
browsers and I must say this blog loads a lot quicker then most.
Can you recommend a good web hosting provider at a fair price?
Thanks, I appreciate it!
Aw, this was a very nice post. Spending some time and actual effort to
create a great article… but what can I say… I hesitate a lot and never manage
to get anything done.
Hey! I know this is kinda off topic but I was wondering if you knew
where I could locate a captcha plugin for my comment form?
I’m using the same blog platform as yours and I’m
having difficulty finding one? Thanks a lot!
I like what you guys are usually up too. Such clever work
and coverage! Keep up the good works guys I’ve included you guys to blogroll.
Cool + for the post
_________________
букмекерлік кеңсе сколковское тас жолы
Столица натяжные потолки отзывы
abc slot gacor hari ini buktikan sekarang
https://dpm-ptsp.gorontalokab.go.id/tintuc/ezyzpv
I will immediately grasp your rss as I can not in finding your email subscription link or
e-newsletter service. Do you’ve any? Kindly let
me recognize so that I may just subscribe. Thanks.
purchase prednisone canada
Useful info. Lucky me I found your web site unintentionally,
and I’m shocked why this accident did not took place earlier!
I bookmarked it.
Сайт https://video-camer.ru представляет собой интернет-магазин товаров, предназначенных для видеонаблюдения. Перед вами только качественная, надежная техника, которая работает точно и бесперебойно. И самое главное, что она представлена именитыми брендами, которые отвечают за качество товаров. В разделе имеется продукция для видеонаблюдения, автомобильные товары, а также металлоискатели, диктофоны, микрофоны, плееры и многое другое. Вся продукция реализуется по доступной стоимости.
Planet88 situs slot online gacor 2023
daftar dan menangkan jackpot jutaan rupiah
Daftar Sekarang :
https://be.plantoys.com/
fildena 150 for sale
Казино Gama Casino открыло свои двери в 2023 году, предлагая своим клиентам захватывающие и уникальные азартные игры онлайн – Gama casino com
Great blog right here! Additionally your web site lots up very
fast! What host are you the usage of? Can I
get your affiliate link on your host? I desire my site loaded up as quickly as yours lol
phenergan 25mg nz medicine phenergan phenergan coupon
اخبار جدید هواشناسی ایران و دانستنی های فیلم
بازی مرکب و اخبار ورزشی زنده پرسپولیس و اخبار فوری لردگان و اخبار حوزه سلامت مشهد
و خبرهای تازه جنرال دوستم
https://bookmarkspecial.com/story13600237/خبرهای-غور
На сайте https://zhana-credit.kz/ вы сможете воспользоваться услугами автоломбарда. Важным моментом является то, что оценка происходит по максимуму, при этом ставки минимальные. Нет необходимости составлять договор купли-продажи. Все сотрудничество осуществляется на максимально выгодных, прозрачных условиях. Кредиты под залог авто выдаются всего лишь за несколько минут. Не потребуется справка о доходах. Получить кредит очень просто. Для этого необходимо лишь оставить заявку, после чего менеджеры перезвонят вам для подтверждения.
Very soon this site will be famous amid all blog people, due to it’s fastidious content
For hottest information you have to go to see web and on the
web I found this site as a best website for most recent updates.
Hi, I think your website might be having browser compatibility issues.
When I look at your website in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping.
I just wanted to give you a quick heads up! Other then that, fantastic blog!
An intriguing discussion is worth comment. I think that
you need to publish more about this issue, it might not be a taboo subject but
generally people do not discuss such topics. To the next!
All the best!!
What’s up everyone, it’s my first go to see at this web page, and paragraph is truly fruitful for
me, keep up posting these content.
Feel free to surf to my web page: CashForHouses
I am curious to find out what blog system you are using?
I’m experiencing some minor security problems with my latest website and I would like to find
something more safe. Do you have any recommendations?
Hmm it appears ⅼike your website ate my fiгst comment (it was extremely lօng) ѕo I guess I’ll ϳust sսm it up ᴡhat I submitted and say, I’m tһoroughly
enjoying ʏour blog. І as wеll am an aspiring blog blogger ƅut Ι’m ѕtіll new to
the wholе thing. Do you have any tips and hints for
beginner blog writers? Ӏ’Ԁ realⅼy appreciate it.
my website: lotto
where to buy ampicillin 500mg
I believe people who wrote this needs true loving because it’s a blessing.
So let me give back and shout out on change your life and if you want to really findout?
I will share info about how to make passive income Don’t forget..
I am always here for yall. Bless yall!
Your style is unique in comparison to other folks I have read stuff from.
I appreciate you for posting when you have the opportunity, Guess I’ll just bookmark this page.
colchicine 0.6 mg without prescription colchicine 0.6 mg discount colchicine singapore
If you wish for to get a great deal from this paragraph then you have to apply these methods to your won blog.
Metformin 850 keeps my glucose levels in check, you know what I’m saying?
I am regular reader, how are you everybody?
This post posted at this web page is really good.
My website :: marital aids for men
Thank you a lot for sharing this with all people you really
realize what you’re talking about! Bookmarked. Kindly also consult with my site =).
We may have a link alternate agreement among us
Just wish to say your article is as surprising.
The clarity in your post is just nice and i could assume you are an expert on this subject.
Fine with your permission allow me to grab your RSS feed to
keep updated with forthcoming post. Thanks a million and
please continue the enjoyable work.
Hello, you used to write magnificent, but the last several
posts have been kinda boring… I miss your tremendous writings.
Past several posts are just a bit out of track! come on!
Feel free to visit my blog – Eden Skin Tag Remover
avana india
avana 2 generic avana avana usa
I’m also writing to make you understand of the fine encounter my
friend’s princess gained going through your webblog.
She came to understand some things, which include how it is like to possess a
great coaching heart to have others without difficulty
know precisely various hard to do topics. You really exceeded my expected results.
Many thanks for giving such important, safe, revealing and also cool tips about the topic to Julie.
vavada казино официальный сайт
Wow that was strange. I just wrote an extremely long comment but after I clicked submit my
comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say excellent blog!
motrin gel caps
buy viagra online
Excellent post. I used to be checking continuously this blog and I
am inspired! Very useful info specifically the final phase :
) I deal with such information much. I used to
be looking for this certain information for
a very lengthy time. Thank you and good luck.