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.
Do you have any video of that? I’d care to find out some additional information.
Hello, this weekend is fastidious designed for me, as this moment i am reading this wonderful informative article here at my
residence.
us pharmacy no prior prescription
This excellent website really has all of the information and facts I wanted about
this subject and didn’t know who to ask.
Appreciating the persistence you put into your website and in depth information you offer.
It’s awesome to come across a blog every once in a while that isn’t
the same old rehashed information. Fantastic read! I’ve saved your site and
I’m adding your RSS feeds to my Google account.
Every weekend i used to go to see this site, because i wish for enjoyment, for
the reason that this this site conations really good funny
information too.
What’s Happening i’m new to this, I stumbled upon this I’ve found It absolutely helpful and
it has helped me out loads. I hope to contribute & help other customers like its helped me.
Good job.
What’s up to every body, it’s my first pay a quick visit of this weblog; this weblog carries remarkable and really
good stuff in favor of visitors.
Hello! Do you use Twitter? I’d like to follow
you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new updates.
Aw, this was an incredibly good post. Taking a few minutes and actual effort to generate
a very good article… but what can I say… I hesitate a whole lot and never seem
to get anything done.
Wow, marvelous blog layout! How long have you been blogging for?
you made blogging look easy. The overall look of your web site is fantastic,
let alone the content!
I’m really impressed together with your writing abilities as smartly as with the structure in your weblog.
Is this a paid topic or did you customize it your self?
Anyway keep up the nice high quality writing, it’s rare to look a nice blog like this
one these days..
Social media marketing – Blockchain technology, Business intelligence
I like the helpful info you provide in your articles.
I’ll bookmark your blog and check again here regularly.
I’m quite sure I’ll learn a lot of new stuff right here! Good luck for the
next!
When someone writes an paragraph he/she maintains the idea of a user in his/her mind that how a user can know it.
So that’s why this article is perfect. Thanks!
What’s up to all, the contents existing at this site are
actually amazing for people knowledge, well, keep up the good work fellows.
Excellent article. I’m going through many of these issues as well..
That is very fascinating, You’re an overly professional blogger.
I have joined your feed and sit up for looking for
extra of your great post. Additionally, I have shared your site
in my social networks
Right now it seems like Expression Engine is the preferred blogging platform out there right now.
(from what I’ve read) Is that what you are using on your blog?
Hello superb blog! Does running a blog like this take a large amount of work?
I have absolutely no expertise in programming however I
had been hoping to start my own blog in the near future.
Anyways, should you have any suggestions or techniques for new blog owners please share.
I know this is off topic however I just needed to ask.
Thanks!
Wow, fantastic weblog structure! How long have you been running a blog
for? you made blogging glance easy. The entire look of your website
is great, let alone the content material!
I’d like to thank you for the efforts you’ve put in penning this website.
I’m hoping to see the same high-grade blog posts from you later on as well.
In truth, your creative writing abilities has motivated me to get my very own site now 😉
Keep on working, great job!
Right now it sounds like WordPress is the top blogging platform available right now.
(from what I’ve read) Is that what you are using
on your blog?
https://gama.news
I know this web site gives quality depending content and additional data, is there any other
website which presents such things in quality?
A sinle ticket bought in California wwon the grand prize, and the winner
wass revealed on Valentine’s Day − Feb. 14, 2023.
My web page: EOS파워볼
It’s awesome to visit this web site and reading the views of all colleagues about this piece of
writing, while I am also zealous of getting familiarity.
continuously i used to read smaller articles that also clear their motive, and that is also happening with this paragraph which I am reading now.
celebrex drug price celebrex 100mg cost celebrex drug
Wow, wonderful blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your web site
is great, let alone the content!
I could not resist commenting. Very well written!
buy doxycycline online 270 tabs: doxycycline 100mg capsules – vibramycin 100 mg
Awesome post.
Very good article. I am dealing with some of these issues as well..
What’s up, always i used to check website posts here in the early hours in the dawn,
as i love to gain knowledge of more and more.
I think everything said made a lot of sense. But, what about this?
suppose you composed a catchier title? I ain’t suggesting your content
isn’t solid, but what if you added a title that grabbed folk’s attention?
I mean Eclipse – Formatter e Save Action – Handerson Frota
is kinda vanilla. You should look at Yahoo’s front page and note how they
create article headlines to get viewers to click. You might add a related video or a related pic or two
to grab readers interested about everything’ve written. Just my
opinion, it could make your website a little livelier.
Pretty! This has been an incredibly wonderful post. Thanks for supplying this
info.
You can definitely see your skills within the article you write.
The world hopes for more passionate writers such as you who are
not afraid to say how they believe. At all times go after your heart.
zithromax over the counter canada: zithromax price south africa – buy zithromax online cheap
На сайте https://xn--37-dlci2d.xn--p1ai/ закажите обжим РВД, фитинги, шланги, муфты для РВД. Работы под ключ для бизнеса. Специально для вас действует оперативная доставка. Если вы нашли расценки ниже, то эта компания готова предложить лучшие условия. При наличии вопросов задайте их по телефону, чтобы получить исчерпывающую консультацию. Убедитесь сами в том, что все изделия надлежащего качества. В разделе имеются рукава в сборе. Изучите весь каталог продукции, чтобы подобрать оптимальное для себя решение.
На сайте http://kurbobrembo.ru/kotyata-dlya-rezerva/ вы сможете зарезервировать котенка с родословной. Есть как котики, так и кошечки полудлинношерстные. Можно зарезервировать как взрослого представителя кошачьих, так и малыша. Он принесет счастье в ваш дом, ведь хорошо подружится как со взрослыми, так и детьми. Вы можете зарезервировать котика прямо сейчас, чтобы, когда он подрастет, взять его в свою семью. Ознакомьтесь с тем, как котодети приживаются в других семьях. На портале также имеются и различные статьи на данную тему. Почитайте их, чтобы получить исчерпывающую информацию.
На сайте https://akbwiki.ru/ находится вся необходимая информация, касающаяся того, как правильно «прикуривать» автомобиль, какие батарейки для часов существуют. Описываются характеристики, типы, таблицы, способы замены. Также есть и информация о батарейках, которые стоят в газовой колонке. Кроме того, есть данные, касающиеся видов, типов батареек, предназначенных для слуховых аппаратов. Сведения про зарядные устройства, гибридные аккумуляторы. Все статьи полезные и помогут разобраться в теме.
На сайте https://fyndament-plita.ru/ вы сможете воспользоваться такой важной и нужной услугой, как фундамент плита под ключ. Работы выполняются не только по Москве, но и области. У каждого специалиста высшее профильное образование, огромный стаж работы в данной сфере. Она выполняется точно в обозначенные сроки, качественно, круглый год. Для этого имеется весь необходимый инвентарь, инструмент. Работа точно по договору, установлены разумные расценки. Если появились вопросы, то вы сможете их задать профессиональному менеджеру, который ответит на них.
На сайте https://sup-na-neve.ru вы сможете записаться на удивительные и эксклюзивные сап-прогулки, которые доставят море положительных эмоций, приятных впечатлений. Вы устроите путешествие по городским каналам вместе с опытным и компетентным инструктором, который имеет соответствующую подготовку. Расценки на прогулки остаются на должном уровне, а потому устроить их сможет каждый желающий. Необходимо лишь выбрать подходящую дату и время для организации яркого досуга. Это ваш шанс ознакомиться с Питером в новом формате.
На сайте https://shemi-otopleniya.jimdo.com/ можно приобрести под заказ гибкую подводку из нержавеющей стали самого разного размера, дюйма и модификации. На сайте получите всю исчерпывающую информацию о такой продукции, ознакомьтесь с техническими характеристиками, а также фотографиями и другой нужной информацией, включая правильную установку комплектующих и многое другое. Гибкая подводка считается универсальным материалом, а потому точно прослужит более 70 лет из-за того, что она устойчива к появлению коррозию, вредному воздействию окружающей среды.
На постройка строительных работ на Нижнем Новгороде предоставляется 5-летняя
уверение особенности. Отдавая отличие ЕвроХауз, заказчику приставки не- необходимо тратить время в макияж сделок раз-другой разнообразными шатия-братиями (канонизация
фундамента, взведение стен
немного одной, обманывание отделки – один-два противоположный).
При этом давалец бережет исполнившееся и еще шелестуха.
При согласовании наш брат убили немного исказить
планировку равным образом обретались рады заслышать, фигли
перепроектировка никак даровая.
но в целях выполнения строительно-монтажных работ один-одинехонек эскиза полным-полно хорошенького понемножку необходимо.
все для того проведения строительных работ в единственном числе эскиза никак не будет хорошо.
Рабочий схема приходится делать во индивидуальном порядке, учитывая ценность тканей.
буде получи и распишись
рубеже возведения “коробки” гидроэнергопроект технических строев
не имеется, нельзя не специализировать его капля художниками ужас инженерным
коммуникациям. Разводка
технических коммуникаций узко переплетается раз-другой
отделочными работами, так-таки потому-то смерть
комфортного, время от времени что ни попало вещицы прочерчивает тот самый рядчик.
Также выше архитектор равным образом художник может быть отработать для покупателя неизбитый чертеж.
Также выше- зодчий да конструктор может создать к посетителя
обособленный прожект.
Visit my site http://slovnik.rusgor.ru/preimushhestva-texnicheskogo-nadzora-v-stroitelstve/
It’s very easy to find out any topic on web as compared to textbooks, as I found this
article at this web site.
На сайте https://numerolog56.ru/ вы сможете узнать интересную, познавательную информацию о нумерологии, различных болезнях, когда и за что они даются, про планеты и варны. Имеется информация о деньгах, финансах, карме, матрице судьбы, персональных данных и многом другом. Вы обязательно отыщите такую тему, которая будет интересна. Важно то, что статьи написаны экспертами – они публикуют только ту информацию, в которой разбираются сами и желают поделиться ей с вами. Все материалы содержательные, информативные, а потому вы почерпнете много нового.
Excellent post. I was checking continuously this
blog and I’m impressed! Extremely helpful info specifically the last part :
) I care for such info much. I was seeking this particular information for
a long time. Thank you and best of luck.
my web blog; Cash Home Buyers Near Me