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://iserial.net/ представлены популярные, а также редкие сериалы, новинки, с которыми необходимо ознакомиться и вам. Они идеально подойдут для совместного просмотра, а также после работы, если хочется немного расслабиться и получить позитива. Все фильмы в отличном качестве, без надоедливой рекламы и с хорошим звуком. Именно поэтому понравятся большинству. Вы обязательно найдете то, что посмотреть сегодня или завтра. Все фильмы поделены на категории, чтобы вы быстро определились с выбором.
I started taking roaccutane isotretinoin last week and my skin is already improving.
https://2gis.ru/moscow/firm/70000001068923239
Hi there I am so glad I found your weblog, I really found you by accident, while I was searching
on Aol for something else, Nonetheless I am here now and would just
like to say thanks for a fantastic post and a all round exciting blog (I
also love the theme/design), I don’t have time to read it all at the minute but I have bookmarked
it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please
do keep up the excellent work.
Wһat і ⅾo not realize іs actualⅼy hοw you аre now not гeally
a lot more neatly-appreciated tһan you may be right now.
Үou arе so intelligent. Yoս know tһus significantly
relating t᧐ this subject, poduced me personally
ƅelieve іt fгom numerous numerous angles. Itts ⅼike women and men dоn’t seem to be
interested unless it’s somethіng tto do with Woman gaga!
Your personal stuffs nice. At аll time deal witһ iit up!
Feel feee tօ surf to my web page :: web site
Hey there! Would you mind if I share your blog with my
twitter group? There’s a lot of folks that I think would really appreciate your
content. Please let me know. Cheers
This info is invaluable. When can I find
out more?
У многих вызывает чрезвычайное беспокойство такая тема, как https://fideleschristianschool.com/fideles-forward-capital-campaign/
На сайте https://krasnodar.climateon.ru/ вы сможете купить в городе Краснодар кондиционеры и климатическую технику с доставкой и установкой. У нас в наличие все типы систем кондиционирования и вентиляции от оконных и мобильных кондиционеров до мульти-сплит, мульти-зональных (VRF/VRV) и полупромышленных систем.
I constantly spent my half an hour to read this weblog’s posts all the
time along with a cup of coffee.
Hi there to every body, it’s my first pay a quick visit
of this blog; this weblog contains awesome and really fine data in support of readers.
Hello this is kinda of off topic but I was wondering if blogs
use WYSIWYG editors or if you have to manually code with HTML.
I’m starting a blog soon but have no coding know-how so I wanted to get guidance
from someone with experience. Any help would be greatly appreciated!
Can I buy Metformin over the counter without a doctor’s prescription in the UK?
отзывы потолки столица
You have made some good points there. I checked on the web for
more info about the issue and found most people will go
along with your views on this site.
I like the valuable invo you provide in your articles.
I’ll bookmark your blog and check again heree regularly.
I’m quite sure I will learn lots of new stuff right here!
Good luck for the next!
https://promobanger.com/
If some one needs expert view concerning blogging
after that i advise him/her to go to see this webpage,
Keep up the nice work.
What i don’t realize is in truth how you are now not actually much more
well-favored than you may be right now. You’re very intelligent.
You understand thus significantly in relation to this matter, produced
me in my view believe it from so many varied
angles. Its like women and men don’t seem to be fascinated unless it’s one thing
to accomplish with Girl gaga! Your individual stuffs excellent.
All the time handle it up!
very good
_________________
betdaq букмекерлік компания
biaxin tablets biaxin for uti biaxin costs
Your style is unique compared to other folks I have read stuff from.
Many thanks for posting when you have the opportunity, Guess I’ll
just bookmark this web site.
Levothyroxine ordering online is a convenient and time-efficient way for patients to maintain a consistent medication schedule.
Столица натяжные потолки отзывы
buy acyclovir 800 mg
Thank you a lot for sharing this with all of us you actually recognize what you’re speaking about!
Bookmarked. Please also discuss with my website =).
We may have a link change agreement between us
Натяжные потолки столица отзывы
If you wish for to improve your experience simply
keep visiting this site and be updated with the most up-to-date news update posted here.
Игра в пасьянсы https://solitairepauk.ru может быть отличным способом для расслабления и снятия стресса. Вот несколько причин, почему это может быть так:
– Улучшение концентрации внимания: Игра в пасьянсы требует сосредоточенности и внимательности, поэтому это может помочь забыть о проблемах и переживаниях, сосредоточившись на игре и улучшив концентрацию внимания.
-Создание позитивных эмоций: Игра в пасьянсы может создавать позитивные эмоции, когда игрок видит, как карты соединяются и решается головоломка. Это может помочь улучшить настроение и снять напряжение.
-Улучшение моторики и координации: Пасьянсы требуют множества движений рук, что может помочь снизить напряжение в мышцах и улучшить координацию движений.
-Уменьшение чувства одиночества: Игра в пасьянсы может быть хорошим способом заполнить свободное время и занять ум, что может помочь снизить чувство одиночества и уединения.
-Релаксационный эффект: Игра в пасьянсы может создавать ритмичные движения и звуки, что может помочь создать релаксирующую атмосферу и снизить уровень стресса и напряжения.
В целом, игра в пасьянсы может быть отличным способом для расслабления и снятия стресса, особенно когда игрок находится в тихом и спокойном месте и может сосредоточиться на игре.
I really like your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone
to do it for you? Plz reply as I’m looking to construct my
own blog and would like to find out where u got this from.
appreciate it
whoah this blog is great i like reading your articles. Keep
up the great work! You understand, many persons are hunting around for this info, you could
aid them greatly.
Also visit my web page; how to sell My house fast for cash
finasteride 5mg drug finasteride where to get propecia
I was recommended this blog by means of my cousin. I’m not certain whether or
not this post is written by way of him as no one else recognize such special about my trouble.
You are incredible! Thanks!
Столица натяжные потолки отзывы
Казино Gama — это отличный вариант для игроков любого уровня благодаря впечатляющему выбору игр и щедрому приветственному бонусу – Гама казино официальный зеркало рабочее
An impressive share! I have just forwarded this onto a friend who had been doing a little
homework on this. And he in fact ordered me lunch
due to the fact that I found it for him… lol. So let
me reword this…. Thanks for the meal!! But yeah, thanx for spending some time to talk about this topic here on your website.
Here is my web page: Sell My Ugly House Fast
Undeniably believe that which you said. Your favorite justification appeared to be on the internet the simplest thing to be aware of.
I say to you, I certainly get irked while people consider worries that they plainly don’t know about.
You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people could take a
signal. Will probably be back to get more. Thanks
I always used to study article in news papers but now as I am a user of web
so from now I am using net for articles, thanks
to web.
sildalis canada sildalis 120 generic sildalis
Столица натяжные потолки отзывы
brand name ampicillin capsule
Remarkable! Its truly awesome post, I have got much clear idea concerning from this article.
На сайте http://utmmetki.store/ вы сможете получить руководство по UTM меткам. Вас ожидают правильные метки, а также генератор. Для того чтобы воспользоваться сервисом, необходимо ввести URL адрес, определиться с источником трафика и другими параметрами. Следует ввести как обязательные, так и необязательные параметры. Далее останется лишь скопировать полученный результат. Все максимально просто. В статье рассказывается обо всех нюансах, которые будут вам важны. Необходимо их учесть в своей работе.
I couldn’t refrain from commenting. Very well written!
No matter if some one searches for his vital thing, so he/she
wants to be available that in detail, therefore that thing is maintained over
here.
Canadian pharmacy Lasix has helped me maintain my health for years.
столица потолки отзывы
zoloft 200 mg pill
На сайте https://kitt-nn.ru/ вы сможете заказать спецодежду рабочую, а также для занятий охотой, туризмом, рыбалкой. Все изделия отличаются безупречным уровнем комфорта, безопасности, выполнены из современных, надежных материалов, которые невосприимчивы к агрессивным факторам внешней среды. В разделе вы также найдете СИЗ, медицинскую одежду, а также средства для защиты рук. Ознакомьтесь со всем каталогом изделий, чтобы сделать правильный выбор. Обязательно ознакомьтесь с прайс-листом для того, чтобы заказать все, что вам необходимо.
atarax 10 mg cost atarax generic brand atarax buy