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.
phenergan australia otc phenergan generic otc cost phenergan 25 cost
where to buy cordarone
top ed drugs: buy erection pills – ed treatments
I love your blog.. very nice colors & theme. Did you
make this website yourself or did you hire someone to do it for you?
Plz reply as I’m looking to construct my own blog and
would like to find out where u got this from.
kudos
https://edpills.pro/# ed pills
Thanks to my father who informed me about this weblog, this blog is really amazing.
Thanks on your marvelous posting! I definitely enjoyed reading it, you may be
a great author. I will be sure to bookmark your blog and will often come back at some point.
I want to encourage you continue your great writing,
have a nice evening!
Leer resenas en popular casinos en Chile aqui: casino lanea
служба вскрытия замков в квартире https://vskritie-zamkov-moskva24.ru/
I am genuinely thankful to the owner of this web
site who has shared this impressive paragraph at at this time.
If some one desires expert view concerning blogging afterward i advise him/her to pay a quick visit this weblog, Keep up the nice work.
Have you ever thought about creating an e-book or guest authoring on other blogs?
I have a blog based on the same ideas you discuss and would love to have you share some stories/information. I know my audience would value your work.
If you are even remotely interested, feel free to shoot me an e mail.
ยินดีต้อนรับเข้าสู่ครอบครัว โคตร
KS ทางเรายินดีให้บริการตลอด 24 ชั่วโมง
Kardinal Stick เทคโนโลยีใหม่ล่าสุดในปี 2020 ด้วยดีไซน์ที่หรูหรา
ใช้งานง่าย เหมาะแก่การใช้เป็นตัวเลือกในการเลิกบุหรี่ที่ดีที่สุดในตอนนี้ ?
Amazing! Its genuinely remarkable article, I have got much clear idea on the topic of from this post.
Enjoyed looking through this, very good stuff, thank you.
My website; Beam Box Mini Bug Zapper Review
how to take doxycycline
Unquestionably believe that which you said. Your favorite justification seemed to be on the internet the easiest thing to be aware of.
I say to you, I certainly get irked while people think about worries that they just do not know about.
You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could
take a signal. Will probably be back to get more. Thanks
Thanks very nice blog!
Also visit my web page sell my home fast for cash
https://edpills.pro/# п»їerectile dysfunction medication
I am really enjoying the theme/design of your web site.
Do you ever run into any web browser compatibility issues?
A number of my blog visitors have complained about my website not working correctly in Explorer but looks
great in Safari. Do you have any solutions to help fix this issue?
На сайте https://poiskgid.ru/ ознакомьтесь с честными, информативными обзорами, которые касаются металлоискателей. Рассматриваются самые разные модели, включая их характеристики, настройки, а также функции и многое другое. Кроме того, опубликована важная информация, которая обязательно потребуется вам, если планируете покупку такого оборудования либо интересуетесь данной темой. Здесь находится огромное количество информации, статей, которые регулярно обновляются.
I am not sure where you’re getting your information, but great topic.
I needs to spend some time learning much more or understanding more.
Thanks for great information I was looking for this information for my mission.
buy viagra online
I know this if off topic but I’m looking into starting my own blog and was curious
what all is required to get setup? I’m assuming having a blog like
yours would cost a pretty penny? I’m not very web savvy so I’m not 100%
certain. Any tips or advice would be greatly appreciated.
Cheers
На сайте https://bort3302.ru/ вы сможете выбрать и приобрести борта на Газель, Соболь. Ознакомьтесь с их техническими характеристиками прямо сейчас. Это позволит подобрать наиболее подходящий под ваши параметры и цели покупки вариант. Но если вы не смогли определиться с вариантом, то воспользуйтесь квалифицированной помощью сотрудников. Они помогут подобрать то, что будет работать еще очень долго. Есть возможность воспользоваться специальным поиском для того, чтобы найти то, что нужно.
Hey very interesting blog!
продажа квартир в сочи
Howdy! This is my first visit to your blog! We are a collection of volunteers
and starting a new project in a community in the
same niche. Your blog provided us beneficial information to work on. You have done a outstanding job!
Что делать, если украли гос
номера с авто? номера на скутер – утром обратился,
через 2 часа привез курьер домой.
nearby gym for ladies
No matter if some one searches for his required thing, thus he/she wishes to be
available that in detail, so that thing is maintained over here.
how to buy generic levaquin pill
Thanks designed for sharing such a pleasant thought, article
is fastidious, thats why i have read it completely
https://genius.com/officesalmon60
acyclovir 400 mg cost
It is perfect time to make some plans for the future and it is time to be happy.
I’ve read this post and if I could I wish to suggest you few interesting things
or tips. Maybe you could write next articles referring to this article.
I want to read even more things about it!
https://raft22.ru/
vermox pharmacy usa generic vermox cheap vermox tablets where to buy
When someone writes an post he/she keeps the thought
of a user in his/her mind that how a user can understand it.
So that’s why this piece of writing is great. Thanks!
where can i buy cheap cialis where can i buy cialis uk average cost of 20mg cialis
I need to know more about the side effects of drug metformin before taking it.
Buying clomiphene for sale online saved me a lot of money.
most trusted online pharmacy certified canadian international pharmacy testosterone canadian pharmacy
lisinopril calming
Write more, thats all I have to say. Literally, it
seems as though you relied on the video to make your point.
You clearly know what youre talking about, why throw away your
intelligence on just posting videos to your blog when you could be giving us something enlightening
to read?
generic lexapro canada how to order lexapro online generic lexapro india
Greetings! This is my first comment here so I just wanted to give a quick shout out and tell
you I really enjoy reading through your blog posts. Can you recommend any
other blogs/websites/forums that go over the same subjects?
Thank you!
Also visit my web-site … Reventia Skincare Serum
Howdy, i read your blog occasionally and
i own a similar one and i was just wondering
if you get a lot of spam responses? If so how do you protect against it, any plugin or anything you can suggest?
I get so much lately it’s driving me mad so any assistance is very much appreciated.
buy silagra 100 silagra tablet buy silagra
Thanks for sharing your thoughts. I really appreciate your efforts and I am waiting for your further post
thanks once again.