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.
proscar 5mg canada proscar cost proscar bph
We are a bunch of volunteers and opening a new scheme in our community.
Your website offered us with useful info to work
on. You have done an impressive task and our entire group shall be grateful to
you.
Quality posts is the crucial to interest the viewers to pay a quick visit the web page, that’s what this web page is providing.
Greetings! I know this is somewhat off topic but I was wondering which blog platform
are you using for this site? I’m getting fed up of WordPress because I’ve had problems
with hackers and I’m looking at alternatives for another platform.
I would be fantastic if you could point me in the direction of a good platform.
Αt this time it sounds liқe Drupal іs tһe top blogging platform օut
tһere right noԝ. (from ԝhɑt I’ve read) Is that what you’re uѕing on your blog?
Feel free tо visit my site casino (Wilda)
cefixime 200 mg
Unquestionably believe that which you said. Your favorite
justification appeared to be on the internet the
simplest thing to be aware of. I say to you, I
definitely get annoyed while people consider worries that they plainly do not know about.
You managed to hit the nail upon the top and defined out the whole
thing without having side effect , people can take a signal.
Will probably be back to get more. Thanks
Hello There. I found your blog using msn. This is a really well written article.
I’ll make sure to bookmark it and return to read more
of your useful information. Thanks for the post.
I’ll certainly comeback.
https://valenzuela-coleman.blogbright.net/vliianie-konditsionirovaniia-vozdukha-na-kachestvo-sna
When I originally commented I clicked the “Notify me when new comments are added” checkbox and
now each time a comment is added I get four emails with the same comment.
Is there any way you can remove people from that service?
Cheers!
This page certainly has all the information I wanted about this subject and didn’t know who to
ask.
I must thank you for the efforts you’ve put in penning
this website. I really hope to check out the same high-grade content from
you later on as well. In truth, your creative writing abilities has motivated me to get my own blog now 😉
Also visit my site selling ugly Houses
cialis tablets purchase cialis 120 generic tadalafil australia
I am actually thankful to the owner of this web site who
has shared this enormous piece of writing at at this time.หลักการเล่นสล็อตออนไลน์
На сайте https://agropedia.ru/ представлена вся исчерпывающая и нужная информация, касающаяся различных сортов фруктов, яблок. Здесь рассматриваются самые разные виды: Прикубанское, Приисковое, Приземленное, Президент, Престиж, Предгорное и другие. Имеется вся исчерпывающая, полезная информация, включая описание сорта, места произрастания деревьев и многого другого. Есть информация, касающаяся того, как ухаживать за вишней, грушей, крыжовником, смородиной, чтобы получить богатый урожай.
So within your sales and marketing communications, by asking questions that
may allow you to know, but in an discreet way like – how does one put
on your hair?|In the highly discreet way like – how will you use nice hair, though
What’s up i am kavin, its my first time to commenting anyplace, when i read this article i thought i could also make comment due to this brilliant post.
I was extremely pleased to discover this web site.
I wanted to thank you for ones time just for this
wonderful read!! I definitely loved every little bit of it and i also have you book
marked to check out new things in your site.
My website: Saxenda Coupon
what is the generic name for cleocin
Heya i am for the first time here. I found this board and I find It really useful & it helped me out
much. I hope to give something back and aid others like you helped me.
Аsking questions ɑrе really fastidious tһing if уоu аre not understanding аnything
entireⅼy, howeveг this article ցives pleasant
understanding yet.
My site football betting (Elane)
Hey very nice blog!
sildalis tablets sildalis without prescription where to buy sildalis
Nice post. I used to be checking continuously this blog and I’m inspired!
Very useful info specially the final phase 🙂 I care for such info a lot.
I was looking for this particular info for a long time. Thank
you and good luck.
YG
ed pill: over the counter erectile dysfunction pills – over the counter erectile dysfunction pills
Avoid purchasing modafinil without prescription from untrustworthy sources.
Excellent site. A lot of helpful info here.
I’m sending it to a few buddies ans additionally sharing
in delicious. And certainly, thank you on your effort!
Сайт https://xn--90ahgpppejw8df.xn--p1ai/ представляет собой доску бесплатных сельскохозяйственных объявлений как от компаний, так и физических лиц. Для того чтобы подобрать оптимальный вариант, необходимо определиться с категорией, а также регионом. Далее система в автоматическом режиме начнет поиски. На сайте имеются самые разные рубрики, включая «Куплю», «Продам», «Услуги агро», «Каталог». Кроме того, имеется колонка с последними объявлениями, где продают сульфат аммония, семена люцерны, суданской травы, пастбищные травосмеси и многое другое.
This site was… how do you say it? Relevant!! Finally I’ve
found something which helped me. Cheers!
Also visit my blog post: Buy Ozempic Online Mexico
colchicine cost
This post will help the internet people for building up new webpage or even a weblog from start to end.
На сайте https://arbolitotpetrovicha.ru/ вы сможете приобрести арболитовые блоки от производителя. Компания использует исключительно проверенные, качественные и экологически безопасные материалы. Арболит является надежным, качественным, прочным материалом, который прослужит долгое время и обрадует своими безупречными эксплуатационными свойствами. В нем идеальным образом сочетаются все важные характеристики камня, а также дерева. Вся продукция реализуется по привлекательным ценам, с быстрой доставкой.
What are the advantages and disadvantages of a small business loan?
Also visit my site ezloan.io
ทางเราจำหน่าย relx Infinity ,
relx Bubble Monn ,
Infyy Pod ต้องขอบอกได้เลยว่า kschill.com เป็นตัวแทนหลักอย่างเป็นทางการในไทย ที่ใหญ่ที่สุด และเป็นเจ้าเดียวกับ RELX
THAILAND สินค้าทุกแบรนด์ ทุกรุ่น เราได้ทำการคัดสรร บุหรี่ไฟฟ้า ที่เป็นหนึ่งในนวัตกรรม ช่วยเลิกบุหรี่
ที่มีประสิทธิดีเยี่ยม และช่วยได้จริง มาให้ลูกค้าได้เลือกใช้ โดยสินค้าทุกชิ้นของเรา สั่งตรงจากโรงงาน
Pretty nice post. I just stumbled upon your blog and wanted to
say that I have truly enjoyed browsing your blog posts. In any case I will
be subscribing to your rss feed and I hope you write again very
soon!
Thanks for finally talking about > Eclipse – Formatter e
Save Action – Handerson Frota < Loved it!
888 Casino delivers whaat you would expeect from a international oon the net gambling powerhouse.
my website :: click here
Thanks for sharing your thoughts about flat rate merchant services.
Regards
It’s not my first time to pay a quick visit this web site, i
am visiting this website dailly and obtain fastidious information from
here all the time.
Please let me know if you’re looking for a article writer for your weblog.
You have some really good articles and I think I would be a good asset.
If you ever want to take some of the load off, I’d really like to write
some content for your blog in exchange for a link back to mine.
Please blast me an email if interested. Thank you!
I think this is among the most vital information for
me. And i’m glad reading your article. But want to remark on some general things,
The site style is perfect, the articles is really nice :
D. Good job, cheers
Medication information for patients. Drug Class.
levaquin order
Everything trends of drug. Read now.
https://te.legra.ph/Preimushchestva-okonnyh-kondicionerov-05-08
Hmm it appears like your website ate my first comment
(it was super 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 the whole thing. Do you have any tips for first-time
blog writers? I’d certainly appreciate it.
I am not sure where you are getting your info, but great topic.
I needs to spend some time learning more or understanding more.
Thanks for fantastic info I was looking for this information for my mission.
all the time i used to read smaller content that
as well clear their motive, and that is also happening with this article which I am reading
now.
albuterol 0.63 mg albuterol for sale albuterol 2
I think you have remarked some very interesting points, appreciate it for the post.
my site … Gloful Skin Serum
I blog quite oftgen annd I really apprecate your information. This
reat article haas truly peaaked my interest.
I will bookmark your website andd kep checking foor neww
informaion about once a week. I opted in foor your
RSS feed as well.