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.
Hi there i am kavin, its my first occasion to commenting anyplace,
when i read this piece of writing i thought i could also make comment due to this brilliant article.
I am sure this post has touched all the internet viewers, its really really pleasant article on building up new website.
Натяжные потолки столица
plavix generic canada generic plavix usa plavix 5 mg
It’s very easy to find out any topic on net as compared to
textbooks, as I found this post at this web site.
На сайте https://www.rupixel.ru вы сможете абсолютно бесплатно подобрать роскошные лицензионные фотографии от лучших фотографов, которые делают снимки на профессиональном уровне. Самыми популярными запросами на этом сайте являются: цветы, люди, растения, напитки, еда. Кроме того, имеются и избранные изображения. Скачивайте их на свое устройство, чтобы использоваться на свое усмотрение. Все они представлены в отличном качестве и высоком разрешении. Здесь снимки находятся в огромном количестве.
This web site certainly has all of the information and facts I wanted concerning
this subject and didn’t know who to ask.
Very quickly this web page will be famous among all blogging and site-building people, due to it’s good posts
Heya superb blog! Does running a blog similar to this require a lot of work?
I’ve no expertise in computer programming however I was hoping to start my own blog soon. Anyway, if you have any ideas or tips for new blog owners please share.
I know this is off topic but I simply had to ask. Many thanks!
cheapest antibiotics: cheapest antibiotics – buy antibiotics for uti
https://firms.city/russia/stolica-potolki
Hi friends, how is all, and what you desire to say on the topic of this paragraph,
in my view its really awesome in support of me.
dapoxetine 60 mg price in india dapoxetine pills dapoxetine otc
zoloft 25
whoah this weblog is fantastic i really like reading your articles.
Stay up the good work! You already know, a lot of individuals are hunting around for this information,
you can aid them greatly.
I got this site from my friend who shared with me regarding this website and
now this time I am visiting this web page and reading very informative articles at this place.
I think the admin of this web page is genuinely working hard in favor
of his web site, as here every material is quality based stuff.
where to buy fildena fildena 200 fildena 50 mg price in india
I believe people who wrote this needs true loving because it’s a blessing.
So let me give back and with heart reach out change your life and if you want to really
findout? I will share info about how to become a millionaire Don’t forget..
I am always here for yall. Bless yall!
столица потолки
Great blog! Do you have any suggestions for
aspiring writers? I’m planning to start my own website soon but I’m a little lost on everything.
Would you advise starting with a free platform like WordPress or go for a paid option? There are so many options
out there that I’m totally confused .. Any tips?
Thank you!
На сайте https://profobus.ru/dizayn/ вы сможете ознакомиться с курсами по дизайну. Перед вами 35 лучших из них. Еженедельно информация о заведениях обновляется, вносятся дополнения для того, чтобы вы быстрей сориентировались в выборе и записались на занятия. Почитайте более подробную информацию о каждой школе, чтобы иметь представление о том, как она выполняет обучение. В каждой компании преподают лучшие учителя с огромным опытом. У всех школ разный интервал обучения, а потому вы обязательно подберете то, что вас устроит.
thanks, interesting read
_________________
депозитсіз ресейліктерге арналған казино
В последние годы 3D-печать использовалась для производства всего, от зданий до предприятий и даже транспорта. Сейчас Дубай собирается выпустить дебютную в мире мечеть, напечатанную на 3D-принтере.
Как сказал главный инженер Департамента по делам ислама и благотворительной деятельности правительства Дубая, сооружение вместит 600 верующих и займет 2000 кв.м. на двух этажах. Выполнен он будет из бетонной смеси, выполнение хотят запустить к концу года и закончить в начале 2025 года.
IACAD не стал называть организацию, которая будет отвечать за строительство.
Для строительства зданий при помощи 3D-принтера нужны огромные агрегаты для печати, на которые запрограммирована проектная информация. Выдавливают строительный материал из насадки, наращивая конструкцию слоями. Подавляющее большинство конструкций, выполненых на 3D-принтере, сделаны из бетона, но можно печатать и с помощью иных материй, например из глины.
Дубай планировал стать мировой столицей 3D-печати, и в 2018 году он запустил стратегию, согласно которой к 2030 году 25% эмиратного строительства будет выполнено при помощи 3D-печати.
В 2019 году он провозгласился рекордсменом мира по самой большой структуре, напечатанной на 3D-принтере, — зданию муниципалитета Дубая (высотой 9,5 метра и площадью 640 квадратных метров), а также здесь находился первый в мире офис, созданный 3D-печатью, и научная лаборатория дронов, созданная при помощи 3D-печати.
Однако новые сооружения, произведенные 3D-печатью, появляются по всему миру. Парки и целые кварталы, как, например, проект New Story в Табаско, предоставляющий дома семьям, живущим в бедности.
Организация 3D-печати готовится строить на поверхности Луны. Она является сторонником модернизации сферы стройки с помощью таких технологий, как 3D-печать.
Новость опубликовал портал bigrush.top
I could not refrain from commenting. Well written!
Great post, you have pointed out some wonderful points,
I likewise think this is a very superb website.
Stop by my web site – Utopia Skin Tag Remover Price
Quality content is the main to be a focus for the people to pay a quick visit the site, that’s what this web site is providing.
Do I really have to purchase Synthroid every month, can’t I just buy a year’s supply or something?
At tһis mⲟment I am goіng to do my breakfast,
wһen haᴠing my breakfast coming again to rеad additional news.
Μy webpage lotto
потолки столица
Its like yοu read mу mind! Ⲩou sеem to қnow
so muϲһ about tһis, ⅼike you wrote tһe book in it or sоmething.
I think thɑt you coᥙld do ѡith a few pics to drive tһe message һome a Ьіt, but other than that, this is magnificent blog.
Аn excellent гead. I ѡill ⅾefinitely bе bɑck.
Take ɑ looҝ at my web-site lotto, Rosita,
Generally I don’t learn article on blogs, however I wish to
say that this write-up very pressured me to check out and do
so! Your writing style has been amazed me. Thank you, quite nice article.
My brother recommended I might like this website. He used to be totally right.
This post truly made my day. You can not believe simply how a lot time I had spent for
this information! Thank you!
tretinoin prices
На сайте https://alfa-divan.ru/ можно приобрести диваны, кресла напрямую с фабрики. Это позволит получить мебель высокого качества и по привлекательной цене. Диван будет готов в течение 2 недель. Это доступно за счет отлаженных процессов, а также линейного производства. Все диваны отличаются броским и стильным дизайном, привлекательным внешним видом. Они создаются из качественных и надежных материалов, которые не утратят внешнего вида долгое время. Вы сможете воспользоваться бесплатной доставкой, сборкой, подъемом.
purchase valtrex online cost of valtrex generic valtrex daily use
My doctor said the success rate for 50 mg Clomid is around 45 percent.
triamterene hctz 37.5 25
http://overthecounter.pro/# over the counter blood thinners
It’s actually a cool and useful piece of info.
I’m happy that you simply shared this useful info with us.
Please keep us up to date like this. Thank you for sharing.
my blog post: Total Rx CBD
Столица натяжные потолки
На сайте https://stroy-m2.ru/ закажите такие важные услуги, как косметический, капитальный, дизайнерский ремонт. Позвонив по телефону, можно заказать ремонт офисных, жилых помещений. Компания отремонтировала более 350 квартир в Нижнем Новгороде. Для начала необходимо получить консультацию от специалиста, а затем будут произведены замеры, составлена смета. В обязательном порядке заключается договор, работы выполняются согласно ему. Опыт работы каждого сотрудника такой, что он может браться за любые работы.
order zoloft uk
Woah! I’m really loving the template/theme of this blog.
It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between superb usability and visual
appearance. I must say you’ve done a great job with this.
Additionally, the blog loads super fast for me on Internet explorer.
Excellent Blog!
This article presents clear idea designed for the new users of
blogging, that really how to do blogging.
Feel free to surf to my page; slot gacor 4d
Hi, i think that i saw you visited my site so i came to “return the favor”.I’m trying to find things to improve my website!I
suppose its ok to use a few of your ideas!!
This piece of writing offers clеar idea fⲟr the neԝ viewers
οf blogging, that іn fɑct hⲟw t᧐ ⅾo blogging.
Here is my web-site lotto
I am sure this piece of writing has touched all the internet viewers,
its really really pleasant post on building up new blog.
Hello There. I found your blog using msn. This is
a really well written article. I’ll be sure to bookmark it and
come back to read more of your useful info.
Thanks for the post. I will definitely return.
flomax 4mg cost flomax 4 mg capsule flomax prescription online