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://moscow.flamp.ru/firm/stolica_potolki_kompaniya-70000001068923239
magnificent put up, very informative. I wonder ᴡhy tһe οther specialists of this sector Ԁon’t realize tһis.
You sһould continue yoᥙr writing. I’m confident, үoս’ve a ցreat readers’ base ɑlready!
Μy web page … lotto
На сайте https://galaxyswapper.ru/ вы сможете получить доступ к скинам в игре Fortnite сейчас. Важным преимуществом портала является то, что ПО создают первоклассные разработчики, которые используют в своей работе уникальные технологии – они работают на результат. Сотрудники предпринимают все возможное для того, чтобы вам нравилось находиться на сайте, вы им активно пользовались и могли играть в любимые игры. Испытайте всю мощь на себе. Все, что вам необходимо – это просто скачать приложение и начать свою игру.
Thanks very nice blog!
best over the counter toenail fungus treatment: over the counter drugs – strongest over the counter painkillers
What’s up, after reading this awesome post i am too happy to share my know-how here with
friends.
Now I am ready to do my breakfast, when having my breakfast coming yet again to read further news.
Натяжные потолки столица отзывы
На сайте https://otvety-po-uchebe.blogspot.com/ вы сможете заказать курсовой проект у лучших и компетентных специалистов, которые отлично разбираются в конкретной теме. Специально для вас подберут такого сотрудника, который сделает все как нужно, правильно оформит курсовую, чтобы у вас ее быстро приняли. Вот почему если предмет вам не дается, вы испытываете с ним трудности, то скорей обращайтесь в эту компанию, где вам всегда помогут. Здесь никогда не срывают сроки, установлены доступные цены.
online pharmacy netherlands
best over-the-counter medicine for sinus infection: antibiotics over the counter – over the counter laxatives
I believe what you said was very reasonable.
But, what about this? suppose you added a little content? I ain’t saying your information is not good., however what if you added a title to possibly
get a person’s attention? I mean Eclipse – Formatter e Save Action – Handerson Frota is kinda
vanilla. You could look at Yahoo’s front page and watch how they create
post titles to get people to click. You might add a video or a related picture
or two to get people excited about what you’ve
written. In my opinion, it might make your
blog a little livelier.
Hi, I read your blogs regularly. Your humoristic style is witty, keep up the good work!
over the counter uti meds: best ed pills over the counter – pills like viagra over the counter
dexamethasone 2 mg dexamethasone price south africa dexamethasone 0.5 tablet price
I have to travel frequently and carrying modafinil otc has made a marked difference in my travel fatigue.
Hello my friend! I wish to say that this post is amazing, great written and come with almost all important infos.
I’d like to look more posts like this .
You’ve gotten the best online sites.
https://www.tv-slupsk.pl
нейросеть онлайн
I every time spent my half an hour to read this weblog’s
posts every day along with a cup of coffee.
Good ⅾay! Thiѕ is my first visit to yоur blog!
We агe a gгoup ߋf volunteers and starting a neԝ initiative in a community in thе same
niche. Your blog pгovided us beneficial іnformation tⲟ wⲟrk οn. Yoᥙ hɑve dοne a extraordinary job!
Mʏ site … lotto, Rubin,
Appreciating the time and energy you put into your blog and in depth information you offer.
It’s nice to come across a blog every once in a while that isn’t
the same unwanted rehashed information. Wonderful read!
I’ve bookmarked your site and I’m including your RSS feeds to my Google account.
Wow that was strange. I just wrote an incredibly
long comment but after I clicked submit my comment didn’t
show up. Grrrr… well I’m not writing all that over again.
Anyways, just wanted to say excellent blog!
Thanks for every other informative website.
Where else may jjust I amm getting that kind of information writtenn in such
a perfect approach? I have a venture that I am just now
opewrating on, and I’ve been on the glance out for such info.
Also visit my blog :: motoryzacja podkarpackie
Столица натяжные потолки отзывы
Hey very interesting blog!
Also visit my site; Cash For Houses
lipitor india lipitor generic over the counter lipitor
Hmm it appears like your website ate my first comment (it was extremely
long) so I guess I’ll just sum it up what I submitted and
say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything.
Do you have any points for beginner blog writers? I’d certainly appreciate it.
Thanks , I have just been looking for information approximately this subject for ages and yours
is the greatest I’ve discovered so far. But, what
concerning the conclusion? Are you certain in regards to the supply?
I blog frequently and I truly apprеciate yoսr
informatiߋn. Yoսr article һaѕ truly peaked my interest.
I will book mark уour website and keep checking for neᴡ infoгmation abօut once per wеek.
I opted in fߋr youг Feed tⲟⲟ.
Have a ⅼook at my blog; lotto (Bradley)
It’s truly a nice and useful piece of information. I’m happy that you just
shared this helpful information with us.
Please stay us informed like this. Thanks for sharing.
best over the counter dark spot remover: over the counter pill – over the counter drugs
Натяжные потолки столица отзывы
avodart 0.5 mg price in india
albuterol discount albuterol 0.42mg albuterol from canada
Way cool! Some very valid points! I appreciate you penning this post and also the rest of the site is very good.
Ищете надежного поставщика тяговых аккумуляторных батарей 48 вольт для вилочных погрузчиков? На сайте https://www.akb48v.ru/ вы найдете широкий ассортимент аккумуляторов различных брендов и ёмкостей, которые подойдут для любых задач. Выбирайте АКБ 48V и вы найдете лучшее соотношение цены и качества, а также надежность в работе и высокий уровень сервиса.
https://overthecounter.pro/# diuretics over the counter
It’s an remarkable article for all the online visitors; they will take advantage from it I am sure.
dapoxetine online canada dapoxetine tablets over the counter dapoxetine over the counter uk
аренда опалубки в МСК https://opalubkazdes.ru/
По ссылке https://vk.com/prodvizhenie_saytov_msk вы сможете воспользоваться такой услугой, как продвижение сайтов силами профессионалов и с использованием уникальных и инновационных технологий. Они сделают все необходимое для того, чтобы вывести ваш сайт в топ лучших и на первые позиции. И самое главное, что услуги оказываются по доступной стоимости, максимально оперативно. Для того чтобы связаться со специалистами компании, необходимо им написать в чат либо оставить заявку. Посмотрите список всех услуг, которые оказываются компанией.
I hardly drop comments, but i did some searching and wound up
here Eclipse – Formatter e Save Action – Handerson Frota.
And I actually do have some questions for you if it’s
allright. Is it just me or does it give the impression like some
of these comments appear like left by brain dead people?
😛 And, if you are writing at additional online social sites, I’d like
to keep up with anything fresh you have to post. Could you make
a list of every one of all your social sites like your twitter feed, Facebook page or linkedin profile?
Feel free to visit my web-site – Lift CBD Gummies Review
Thanks for sharing your thoughts about idn poker.
Regards
Without a Clomid sale, I’m not sure how much longer I’ll be able to fight.
Piece of writing writing іs alѕo a excitement, if you know after that ʏou cаn wrіtе otһerwise it is difficult to
write.
Also visit my homepage lotto
столица потолки отзывы
Hi everyone, it’s my first go to see at this web site, and paragraph is really fruitful in support of me, keep up posting these articles.
Leer resenas en online casinos en Chile aqui: mejor casino online
It’s remarkable in support of me to have a website, which is helpful designed for my
knowledge. thanks admin