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.
Having read this I thought it was very enlightening. I appreciate
you spending some time and energy to put this
article together. I once again find myself spending a
lot of time both reading and posting comments. But so what,
it was still worthwhile!
We stumbled over here from a different page
and thought I might as well check things out. I like what I see so now i am following you.
Look forward to finding out about your web page for a second time.
It’s ɡoing to be ending оf mine dаy, except bеfore end Ӏ
am reading this wonderful paragraph tߋ increase my experience.
Mʏ site: slot
This article is genuinely a pleasant one it helps new web visitors, who are wishing for blogging.
Thanks for your personal marvelous posting! I really enjoyed reading it, you will be a great author.I will remember to bookmark your blog and definitely will come back down the road.
I want to encourage yourself to continue your great job, have a nice weekend!
Amazing blog! Do you have any tips for aspiring writers?
I’m hoping to start my own blog 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 choices out
there that I’m completely overwhelmed .. Any suggestions?
Bless you!
I am really impressed together with your writing talents as well as with the format to your blog.
Is this a paid subject matter or did you customize it yourself?
Anyway stay up the excellent quality writing, it’s uncommon to look a great weblog like this one nowadays..
https://qna.habr.com/user/VasiliyNemov
https://zigry.net/kak-vygodnee-sdat-serebro/
Hmm is anyone else experiencing problems with the pictures on this blog loading?
I’m trying to figure out if its a problem on my end or if
it’s the blog. Any feedback would be greatly appreciated.
Thanks very nice blog!
It’s in fact very difficult in this active life to listen news on Television, therefore I only
use the web for that purpose, and take the most recent news.
where to buy plavix plavix generics plavix price
Howdy! This post ϲouldn’t be wгitten any better! Reading tһrough tһiѕ post reminds mе օf my ⲟld room mate!
Ꮋe ɑlways қept chatting aƄⲟut tһis. Ӏ will forward this write-սp to hіm.
Fairly certаin hе will have ɑ good read.
Many tһanks for sharing!
Feel free tο visit my web-site – lotto
На сайте http://epil-m.ru вы сможете записаться на такую важную для красоты процедуру, как электроэпиляция. Такой метод считается единственно верным и приносит долгосрочный эффект по сравнению с другими. При этом процедура обойдется вам недорого, а записаться на нее вы сможете в любое наиболее комфортное для себя время. Эта методика является абсолютно безопасной и не приносит нежелательного эффекта. Может применяться на самых разных участках тела. Ознакомьтесь с расценками на манипуляции прямо сейчас.
generic for zoloft
На сайте http://zestpromotion.ru закажите производство фотозон, автомобильных подиумов, различных выставочных стендов и многого другого. Сотрудники компании смогут оформить шоурумы, торговые точки. Специально для вас подберут уникальный проект, составят его с учетом предпочтений, требований, особенностей вашей сферы деятельности. Именно поэтому результат вас точно впечатлит. Производственный отдел предпримет все возможное для того, чтобы стенд привлек внимание и подчеркнул особенности, достоинства вашего бренда.
Woah! I’m really enjoying the template/theme of this site.
It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between superb usability and visual
appeal. I must say you have done a fantastic job with this.
In addition, the blog loads extremely fast for me on Safari.
Superb Blog!
dexamethasone tablet brand name dexamethasone 1 tablet dexamethasone capsule
Simply wish to say your article is as astonishing. The clarity in your post is just nice and i could assume you
are an expert on this subject. Well with your permission let me to grab your feed to
keep updated with forthcoming post. Thanks a million and please continue the enjoyable work.
Ahaa, its pleasant conversation about this post at this place
at this web site, I have read all that, so at this time me also commenting at this
place.
My web site: ซื้อหวยออนไลน์ LOTTO
webcams of the world
Good information. Lucky me I came across your blog by accident
(stumbleupon). I have book marked it for later!
Hi, all is going sound here and ofcourse every one is sharing facts, that’s genuinely excellent, keep up writing.
buy albenza albendazole 400 mg canada albendazole price usa
It’s actually a nice and useful piece of information. I am happy that
you simply shared this useful info with us. Please keep
us up to date like this. Thanks for sharing.
как вы относитесь к фотографии https://goo.su/jaCC7 плов
motilium medicine order motilium online motilium price
На сайте http://psikhoanaliz.ru запишитесь на профессиональную консультацию к психологу, который ответит на все вопросы, поможет принять правильное решение и больше не переживать из-за ситуации. А самое главное, что специалист не будет давать оценку вашим действиям. Он внимательно вас выслушает и сделает так, чтобы подтолкнуть к правильному решению вопроса. У вас появится возможность справиться с теми ситуациями, которые тревожили вас на протяжении длительного времени. Психолог – профессиональный специалист, который обладает надлежащим опытом.
На сайте https://fundament-plita.ru/ закажите фундамент плиту под ключ. Специалисты отличаются высокой квалификацией, а работы выполняют в строго оговоренное время, отсутствуют простои, опоздания. Работа на совесть, заключается официальный договор. Для выполнения задачи имеется весь необходимый инвентарь, оборудование. Чуть ниже представлены расценки в соответствии с типом фундамента. Если и вам нужен фундамент плита, то укажите свой номер, чтобы менеджер вам перезвонил и предложил лучший вариант.
I have been surfing online more than three hours today, yet I
never found any interesting article like yours. It is
pretty worth enough for me. Personally, if all
webmasters and bloggers made good content as you did, the net will be much more useful than ever before.
Feel free to surf to my site; เว็บซื้อหวยออนไลน์
Greetings from Los angeles! I’m bored to
tears at work so I decided to browse your website on my iphone
during lunch break. I enjoy the knowledge you provide here and can’t wait to take a look when I
get home. I’m surprised at how quick your blog loaded on my
phone .. I’m not even using WIFI, just 3G .. Anyways, amazing blog!
Appreciating the time and effort you put into your site and in depth information you present.
It’s good to come across a blog every once in a while that isn’t the same out of date rehashed information. Fantastic read!
I’ve saved your site and I’m adding your RSS feeds to my Google account.
На сайте https://militaryprint.ru/ вы сможете приобрести стильные футболки, свитшоты и другую одежду, выполненную в военной тематике. На ней изображены слова поддержки, красочные тематические принты, которые помогут приблизить победу. Вся одежда выполнена из качественных износостойких тканей, которые не утратят внешний вид в течение длительного времени и после множества стирок, краски не поблекнут, сохранят яркость и интенсивность. Именно поэтому вы сможете носить вещь долго. На сайте установлены оптимальные расценки, а потому можно приобрести сразу несколько моделей.
flomax medicine cost flomax 0.4 mg cap how to get flomax
Be sure to read the medication guide that comes with Synthroid 137 before starting to take it.
На сайте https://bigpicture.ru/ представлены новости в картинках, которые будут интересны всем, кто изучает экономику, фотографию, факты из прошлого, различные другие темы. И самое главное, что все статьи сопровождаются яркими, цветными картинками, что делает материал эксклюзивным, содержательным и актуальным. Это ваша возможность прикоснуться к искусству, узнать больше о том, что вас интересует. Все статьи написаны лучшими авторами, которые создают качественный контент. Заходите сюда почаще, чтобы почерпнуть что-то новое.
I’ve heard that metformin er 500mg can actually help with fertility issues in women with PCOS.
фильмы онлайн
ampicillin 500 mg tablet
I am actually grateful to the owner of this
website who has shared this great piece of writing at here.
Have you ever thought about writing an e-book or
guest authoring on other websites? I have a blog centered on the
same ideas you discuss and would love to have
you share some stories/information. I know my subscribers would
appreciate your work. If you’re even remotely interested,
feel free to send me an e-mail.
advair generic price
budesonide prescription
Hi there! I know this is somewhat off topic but I was wondering if you knew where I
could locate a captcha plugin for my comment form? I’m using the same blog platform
as yours and I’m having trouble finding one?
Thanks a lot!
Appreciating the dedication you put into your website and
detailed information you offer. It’s nice to come across a blog every once in a while that isn’t
the same outdated rehashed information. Fantastic read!
I’ve saved your site and I’m including your RSS feeds to my
Google account.
Also visit my homepage – Sell My House For Cash Fast
Hi, after reading this remarkable post i am also happy to share my know-how here with colleagues.
I was suggested this blog by my cousin. I’m not sure whether this post is written by him
as no one else know such detailed about my trouble.
You’re wonderful! Thanks!
I was recommended this website by my cousin. I’m not sure whether this post is written by him as
no one else know such detailed about my trouble. You are amazing!
Thanks!
Hmm it looks like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying
your blog. I as well am an aspiring blog blogger but I’m still
new to everything. Do you have any tips and hints for newbie blog writers?
I’d certainly appreciate it.