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.
It’s an remarkable post for all the internet users; they will get benefit from it
I am sure.
Check out the sweet pouches at Killa Cola Extreme.
My brother suggested I might like this web site. He was entirely
right. This post truly made my day. You can not imagine just how much time I had
spent for this info! Thanks!
First of all I would like to say great blog! I had a quick question which
I’d like to ask if you don’t mind. I was interested
to find out how you center yourself and clear your
head prior to writing. I’ve had a difficult time clearing
my mind in getting my thoughts out. I do take pleasure in writing however
it just seems like the first 10 to 15 minutes tend to be lost just
trying to figure out how to begin. Any ideas or tips?
Kudos!
buy baricitinib 4mg without prescription lipitor 80mg us buy atorvastatin 80mg without prescription
I am sure this paragraph has touched all the internet users, its
really really pleasant article on building up new web site.
baricitinib oral buy generic metformin 1000mg order lipitor 80mg online
I would like to thank you for the efforts you’ve put in penning this blog.
I’m hoping to see the same high-grade content from you later on as well.
In fact, your creative writing abilities has encouraged me to get my own blog now
😉
Check out the Killa-Cold Mint Extreme XXL at Killapods.eu.
Hi there just wanted to give you a quick heads up.
The words in your article seem to be running off the screen in Internet
explorer. I’m not sure if this is a formatting issue or something to do with browser compatibility but I thought I’d post to let you know.
The design and style look great though! Hope
you get the problem solved soon. Cheers
Dօ you have a spam problem on this site; I also am a bloɡցer,
and I was wonderіng yojr situati᧐n; many of us have deѵеloped some nice
procedures and we are lookijng to exchange strategies wit ᧐tһer folks, be sure to shoot me an emil if interested.
Ηere is my site :: crime
buy baricitinib online cheap where to buy lipitor without a prescription atorvastatin 40mg brand
Awesome! Its actually remarkable piece of writing, I have got
much clear idea on the topic of from this post.
Hey! Do you know if they make any plugins to help with
SEO? I’m trying to get my blog to rank for some targeted
keywords but I’m not seeing very good success. If you know of any please share.
Thanks!
payday loan
buy olumiant 2mg sale where to buy baricitinib without a prescription lipitor 40mg brand
https://med-pro-ves.ru/info/kak-vygodno-kupit-valyutu-v-banke
Ɗefinitely believe that which you stated.
Your favorite justification аppeareԁ to be on the internet tthe easіest thing to be aware of.
I say to you, I certainly ɡet ieкed while people consider
worries that they plainly do nnot kϳow about. You managed to hit the nail upⲟn the top as
well as defined out the whole thinbg withoht having ѕide effect , peole can take a signal.
Will likely be back to get more. Thanks
My blg post; breast
It’s great that you are getting thoughts from this paragraph as well as from our argument made at this place.
Инерционные катушки.
Ремни безопасности: заблуждения ценою в жизнь. Немного о статистике.
Если такие документы у Вас будут, то оспорьте указанный штраф.
Все без исключения автомобили оснащаются специальными механизмами и устройствами, призванными обеспечить безопасность пассажиров во время движения. Система безопасности в автомобиле делится на активную и пассивную.
Строгое соблюдение действующих требований безопасности обеспечит комфорт передвижения, спасет жизнь и здоровье людей, деньги и время.
https://genzer.ru/toplivnaya-sistema/pervye-avtomobili-na-benzinovyh-motorah/
ТР ТС 010/2011 «О безопасности машин и оборудования» разработан с целью установления на таможенной территории ЕАЭС единых обязательных для применения и исполнения требований к машинам и (или) оборудованию при разработке (проектировании), изготовлении, монтаже, наладке, эксплуатации, хранении, транспортировании, реализации и утилизации, а также для обеспечения свободного перемещения машин и (или) оборудования, выпускаемых в обращение на единой таможенной территории Таможенного союза.
5. При проектировании и производстве машины и (или) оборудования используются эргономические принципы для снижения влияния дискомфорта, усталости и психологического напряжения персонала до минимально возможного уровня.
За последние 10-15 лет автомобили стали в техническом плане намного сложнее, это факт, от которого уже не уйдешь. К бодьшому сожалению все новые и современные автотранспортные средства сегодня стало ремонтировать и обслуживать на много тяжелей. Но это не означает то, что в современном мире стало меньшее число людей, которые готовы на постоянной основе самостоятельно проводить такое техническое обслуживание своих автомобилей или их ремонтировать. Так же в нашей стране всвязи с существенным ростом автопарка, повсюду стали появляться как грибы различные автосервисные конторы, начиная например от простых гаражных сервисов и заканчивая самыми крупными автостанциями техобслуживания.
Обширная категория систем, в постоянном режиме участвующих в управлении автомобилем, корректируя или дополняя действия водителя. Что относится к активной безопасности автомобиля? В качестве основы можно выделить систему поддержки курсовой устойчивости (сохраняет заданную траекторию движения посредством динамической стабилизации), но к сегодняшнему дню этот комплекс значительно расширился и за счет узконаправленных дополнений:
Постановка транспортных средств на посты ТО должна осуществляться под руководством работника, назначенного работодателем ответственным за проведение технического обслуживания.
Please let me know if you’re looking for a article author for your site.
You have some really great articles and I feel I would be a good asset.
If you ever want to take some of the load off, I’d really like to write some articles for your blog in exchange for
a link back to mine. Please blast me an e-mail if interested.
Thank you!
Hеllo! This is my 1st comment һeere so I just wanted to give
a quick shout out and saay I really enjoy reading your posts.
Can you suggest any other blogs/ᴡebsites/forums that cover the same
subjects? Thank you!
Feel fгеe to surf to my web page beastiality
cheap olumiant 4mg metformin 500mg drug order lipitor 40mg pill
Experience the exhilarating freshness of Killa-Cold Mint Extreme XXL for a premium sensation like no other!
Inspiring story there. What happened after? Take care!
Hello outstanding blog! Does running a blog such as this
require a large amount of work? I’ve no knowledge
of computer programming however I had been hoping to start my
own blog in the near future. Anyway, should you have any recommendations or techniques for new blog owners please share.
I know this is off subject nevertheless I simply had to ask.
Thanks!
I like the valuable information you provide for your articles.
I will bookmark your weblog and test once more right here regularly.
I am quite certain I’ll learn many new stuff proper right here!
Best of luck for the following!
На сайте https://dolzhitov.ru/ вы сможете оформить обратный звонок для того, чтобы заказать производство каминов, печей, барбекю. Специалист только для вас разработает модель с учетом индивидуальных предпочтений и всего за месяц. В работе применяются уникальные и инновационные методики, высокотехнологичные материалы, которые помогут получить именно тот результат, который нужен. Звоните и заказывайте проект прямо сейчас. Жамьян Должитов сам вытачивает небольшие изделия из кирпича.
buy olumiant 4mg generic order atorvastatin 10mg pills generic atorvastatin 80mg
vps ssd nvme – vps ssd nvme, create vps
I like it when folks get together and share views. Great site, continue the good work!
Drugs prescribing information. Long-Term Effects.
viagra otc
All about drug. Get information here.
Very nice post. I just stumbled upon your blog and wished to say that
I’ve truly enjoyed surfing around your blog posts.
After all I’ll be subscribing to your rss feed and I hope you write
again soon!
olumiant 2mg canada atorvastatin oral purchase atorvastatin generic
strattera 2016
Hello, I log on to your blogs on a regular basis. Your story-telling style is awesome,
keep it up!
My web page; Elearnportal
darknet drug store deep web drug markets
generic baricitinib olumiant oral lipitor 80mg uk
https://repanutie.ru
I am looking for and I love to post a comment that “The content of your post is awesome” Great work!
buy baricitinib for sale order baricitinib order lipitor 40mg for sale
ampicillin pill 500mg
Medicine prescribing information. Short-Term Effects.
get norvasc
Some trends of medication. Get here.
What’s up, this weekend is nice for me, since this moment i
am reading this fantastic informative paragraph here at
my house.
I am extremely impressed with your writing skills and also with the layout on your blog.
Is this a paid theme or did you modify it yourself?
Anyway keep up the nice quality writing,
it is rare to see a great blog like this one these days.
I know this web site presents quality depending posts and extra material, is there any other website which provides these kinds of information in quality?
Excellent items from you, man. I have take into accout your stuff prior to and
you are just too great. I actually like what you have got right here, certainly
like what you’re saying and the best way by which you are saying it.
You make it enjoyable and you still take care of to keep it smart.
I can’t wait to learn much more from you. This is really a terrific website.
darknet markets best darknet markets
Hi there! This is my first comment here so I just wanted to give a quick shout out and
say I really enjoy reading through your articles. Can you recommend any other blogs/websites/forums that go over the same subjects?
Thank you so much!
Woah! I’m really enjoying the template/theme of this
website. It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance”
between usability and visual appearance. I must say you have done a fantastic job with this.
Additionally, the blog loads super fast for me on Safari.
Superb Blog!