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.
magnificent publish, very informative. I wonder why the opposite experts of
this sector don’t understand this. You must proceed your writing.
I am sure, you’ve a huge readers’ base already!
Below the present law, undergraduate or graduate students who stay in Korea on a
D-two visa are permitted to work up too 30 houhrs a
week.
Also visit my web blog 란제리알바
مطالب روز دوست و دانستنی های قدیمی و اخبار فرهنگی امروز و خبرهای فوری طلوع نیوز و اخبار تامین اجتماعی هرمزگان و خبرهای لحظه به لحظه
ایران
https://webookmarks.com/story13805727/اخبار-علمی-ترسناک
Good answer back in return of this question with
firm arguments and explaining the whole thing
concerning that.
my web-site: free Printable november calendar
furosemide dosage
magnificent post, very informative. I wonder
why the other specialists of this sector don’t understand this.
You must proceed your writing. I’m confident, you have a
huge readers’ base already!
На сайте http://mebel.morekrim.com/kuhni вы сможете заказать качественную, добротную мебель. Для того чтобы воспользоваться услугой, необходимо позвонить по указанному телефону. Далее к вам на объект прибудет замерщик, который рассчитает стоимость проекта. В любом случае она будет выгодней, чем у конкурентов. На итоговую стоимость влияют следующие факторы: размеры мебели, цена фасадов, качество фурнитуры, а также то, из какого материала будет создана столешница. Ознакомьтесь с примерами работ на сайте.
Although nasty smells are not recognized to wake one up from rest,
a pleasurable smell can aid relax us.
http://indianpharmacy.pro/# online pharmacy india
Nice post. I learn something new and challenging on sites I stumbleupon everyday.
It will always be exciting to read through articles from other writers and practice something from their web sites.
https://zehnenoandinsh.ir/مهریه-چه-نوع-حقی-است/
Keep on working, great job!
https://indianpharmacy.pro/# india pharmacy
http://indianpharmacy.pro/# indian pharmacy paypal
Hey very nice blog!
Article writing is also a excitement, if you be acquainted with afterward you can write or
else it is complicated to write.
We are a bunch of volunteers and starting a brand new scheme in our community.
Your web site offered us with valuable info to work on. You have done a formidable activity and our entire community
can be grateful to you.
After I initially left a comment I appear to have clicked on the -Notify me when new comments
are added- checkbox and from now on every time a
comment is added I recieve 4 emails with the exact same comment.
Is there a means you can remove me from that service?
Cheers!
Also visit my blog post: Truth CBD Gummies
Thanks very interesting blog!
Amazing! Its actually remarkable paragraph, I have got much clear idea
on the topic of from this paragraph.
ทางเรา mothervaper ยังมี ผลิตภัณฑ์ บุหรี่ไฟฟ้า Pod System อื่นๆ ที่กำลังจะนำเข้ามา ให้ผู้ใช้ได้เลือกใช้อีกด้วย ไม่ว่าจะเป็น Infy Pod , Vmc Pod , Relx Bubble Mon ,
Coga และอื่นๆ อีกมากมาย โดย น้ำยาบุหรี่ไฟฟ้า
หรือ บุหรี่ไฟฟ้า พอตใช้แล้วทิ้ง ทุกรุ่น ล้วนแล้วแต่มี
ราคาถูก แต่ให้คุณภาพที่ดีเยี่ยมทั้งนั้น อีกทั้งยังเป็นรุ่นยอดนิยมอีกด้วย
Because your teeth’ roots are close to your nasal sinuses,
you can feel tooth discomfort because of swollen sinuses.
Hi there! Someone in my Myspace group shared this website with us so I came
to give it a look. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers!
Terrific blog and excellent style and design.
можно играть
I was suggested this blog by my cousin. I’m not sure whether this post is written by him
as nobody else know such detailed about my problem.
You’re incredible! Thanks!
buy cheap levaquin without rx
Качественные пластиковые окна Rehau в Санкт-Петербурге. Невский район! Установка окон. Ремонт окон. Москитные сетки. Собственное производство. Низкие цены! Мы творим комфорт в ваших домах. Установим качественные современные окна собственного производства длительного времени работы с гарантией. https://galereya-okon-spb.ru/
online pharmacy india india pharmacy mail order indian pharmacy paypal
A person necessarily help to make significantly posts I would state.
That is the very first time I frequented your website page and up
to now? I surprised with the research you made to
make this actual post incredible. Magnificent task!
My web page – sell My house Online for free
This is my first time go to see at here and i am actually pleassant to read
everthing at one place.
Hi there colleagues, its enormous post on the topic of educationand fully explained,
keep it up all the time.
Hello! Someone in my Myspace group shared this website with us so I came to
check it out. I’m definitely enjoying the information. I’m book-marking and will be tweeting
this to my followers! Excellent blog and excellent design.
Planet slot terbatas dan melampauinya calim hadiah akmu
sekarang
planet88
furosemide in mexico
У большинства не дает покоя вопрос, на счет https://www.dandy-o.com/hello-world/#comment-3787
A Youtube search will show numerious videos of the Rotovac procedure at
work.
india pharmacy india pharmacy mail order india online pharmacy
http://indianpharmacy.pro/# indian pharmacies safe
Hiya! Quick question that’s totally off topic. Do you know
how to make your site mobile friendly? My website looks
weird when browsing from my iphone. I’m trying to find
a template or plugin that might be able to fix this problem.
If you have any recommendations, please share. Thanks!
buy medicines online in india india pharmacy mail order indianpharmacy com
I loved as much as you will receive carried out right here.
The sketch is attractive, your authored material stylish.
nonetheless, you command get bought an edginess over that you wish be delivering the following.
unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this hike.
lisinopril price walmart
whoah this weblog is great i like studying your posts.
Stay up the good work! You already know, lots of individuals are searching round for
this information, you could aid them greatly.
how to purchase over the counter generic robaxin from canada
We absolutely love your blog and find the majority of your post’s to be just what I’m looking for.
Does one offer guest writers to write content for yourself?
I wouldn’t mind producing a post or elaborating on most of the subjects
you write regarding here. Again, awesome web site!
Howdy just wanted to give you a quick heads up and let
you know a few of the pictures aren’t loading properly.
I’m not sure why but I think its a linking issue. I’ve tried it in two different
internet browsers and both show the same
results.
Here is my web page: renovation contractor penang
Thanks for your personal marvelous posting!
I really enjoyed reading it, you could be a great author. I will make sure to
bookmark your blog and will often come back later on. I want to encourage you continue your great work,
have a nice weekend!
clindamycin 300 mg tablets price
Thanks for finally writing about > Eclipse – Formatter e Save
Action – Handerson Frota < Liked it!
Great post. I will be dealing with a few of these issues
as well..
I am actually thankful to the owner of this
web page who has shared this wonderful paragraph at at this time.