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.

32.460 Comments on “Eclipse – Formatter e Save Action

  1. На сайте https://www.goodly-studio.com/ вы сможете приобрести панно изо мха, спилов, растений, а также изысканные композиции из стабилизированных цветов. Есть часы изо мха с подсветкой, композиции в кашпо и многое другое. Все композиции выполнены из качественных, антиаллергенных и полностью безопасных материалов, а потому не представляют собой никакой опасности. Почитайте отзывы клиентов о работе. Все они положительные и как нельзя лучше олицетворяют работу дружного коллектива.

  2. We have hacked your website handersonfrota.com.br and extracted your databases. This was due to the security holes you had in your your site/server which have gained us remote control of everything that was on the server.

    Our team is mostly interested in customer, administrative, and employee information which we have extracted through your databases once we got remote control over the server. It still needs to be sorted out but it will be well-organized once finished. First, we will be going through the emails/sms information and contacting the recipient how you held in disregard about their information being exposed to a hacking group when you could have stopped it. This would be detrimental to your personal image with these relationships with these people. Lastly, now that we have information not only will we be monetizing off it with our methods but made public or sold to other people that will do whatever they wish with the information also after we are done.

    Now you can put a stop to this by paying a $3000 fee (0.11 BTC) in bitcoin. You can find our address by visiting https://www.blockchain.com/explorer/addresses/btc/3Hg8FLvfn1TtkziJWmXT7AcE8AmR3Ujket where you can copy and paste the address or scan the QR code. We will be notified of payment which we will then delete the information we have obtained, patch the hole in the site/server which we got in and remove you from any future targeting in the future. You have 72 hours in doing so after viewing this message or the series of steps will commence. You can obtain bitcoin through such services such as paxful.com or do a search on bing.com

  3. After looking into a handful of the blog articles on your web page, I really like
    your way of writing a blog. I saved as a favorite it to my bookmark
    website list and will be checking back soon. Please check
    out my website too and let me know how you feel.

    Look at my web-site; Skin Biotix MD Reviews

  4. Definitely imagine that which you stated.
    Your favorite reason seemed to be at the web the simplest
    thing to have in mind of. I say to you, I definitely get irked at the same time as people consider concerns that they plainly
    don’t recognize about. You controlled to hit the nail upon the highest and outlined out the entire thing without having side
    effect , other folks can take a signal. Will probably be
    again to get more. Thank you

  5. excellent issues altogether, you just won a logo new reader.

    What may you recommend in regards to your put up that you simply made some days ago?
    Any certain?

  6. Таможенное оформление товаров из Китая – ASIANCATALOG

    Китайские производители отлично знают, что коммерческие грузы в Россию транспортируются двумя методами, с учетом официального таможенного оформления и серой схемой, еще известной как карго. В чем отличие между этими несколькими видами импорта и к тому же на какие трудности нужно сконцентрировать внимание при экспорте груза из Китая силами продавца.

    Законное таможенное оформление грузов из Китая – это таможенное оформление которое проводиться соответственно с таможенным законодательством ЕАЭС и к тому же защищенной законодательством Российской Федерации.

    Недостоверное таможенное оформление (карго) носит большие риски утраты груза, уязвимо перед законом и к тому же не имеет правомерных документов.

    Учитывая то, что Российская Федерация придает отдельное внимание таможенному оформлению, востребованность недостоверного таможенного оформления (карго) снижается. Вместе с тем, в случае если товары из Китая будут привезены на территорию России без задержки, грузополучатели столкнуться с непростой ситуацией нереальности предстоящей продажи, включительно и сбыта товаров на основных маркетплейсах России. Вот почему мы предлагаем участникам внешнеэкономической деятельности выбирать официальное таможенное оформление и не использовать серое таможенное оформление.

    Кроме того, в случае отправлении товара из Китая в ключевые города и рынки России следует сконцентрировать внимание на вопросы логистики.

    Специалисты по таможенному оформлению ASIANCATALOG оказывают поддержку малому и среднему бизнесу России и СНГ при импорте товаров из Китая, выступая в роли поставщика осуществляют таможенное оформление товаров из Китая c предоставлением официального пакета коммерческих документов для дальнейшей реализации на внутреннем рынке и оказывают услуги по таможенному оформлению китайских товаров на основе договора услуги таможенного оформления, при экспедировании товаров из Китая под подписанный внешнеэкономический контракт клиента.

    Таможенное оформление товаров из Китая – это профессиональный вид деятельности ASIANCATALOG, гарантирующий безопасность и за короткий срок прохождение таможенного оформления с уплатой таможенных пошлин. Мы оказываем услуги таможенного оформления товаров юридическим лицам и также физическим лицам, являющимися резидентами России и СНГ.

  7. I think that is among the such a lot important information for me.

    And i am satisfied reading your article. However should observation on few common things,
    The web site style is great, the articles is actually great : D.
    Excellent process, cheers

  8. Fascinating blog! Is your theme custom made or did you download it from somewhere?
    A theme like yours with a few simple tweeks would really make my blog shine.

    Please let me know where you got your theme.
    Many thanks

  9. Have you ever thought about including a little bit more
    than just your articles? I mean, what you say is fundamental and all.

    But think of if you added some great graphics or videos to give your posts more, “pop”!
    Your content is excellent but with pics and video clips, this
    site could definitely be one of the very best in its niche.
    Superb blog!

  10. На сайте https://palitra24.ru/ вы сможете приобрести все для того, чтобы оказать профессиональные услуги маникюра и педикюра. В разделе вы найдете топы, гель-лаки, фрезы, насадки, различное оборудование, инструмент, жидкости, кисти, все для дизайна. Ознакомьтесь с хитами, которые популярны среди профессионалов. Регулярно интернет-магазин проводит распродажи, действуют акции, а потому в это время вы сможете осуществить более выгодную покупку. Здесь всегда действуют выгодные цены, а доставка осуществляется в минимальные сроки.

  11. На сайте https://xn—-otbfkgdah1a8b.com.ua/ представлена стильная, модная, качественная оптика, которая подходит для создания привлекательного имиджа, яркого стиля. Имеются варианты как для мужчин, так и женщин. Все очки брендовые, высокого качества, а потому прослужат долгое время, обрадуют внешним видом. Регулярно в интернет-магазине появляются новинки, с которыми необходимо ознакомиться и вам. Очки имеют оправу разной формы: квадратную, круглую. Есть и разноцветные детские модели, которые понравятся малышам самого разного возраста.

  12. Code Age Commanders sold 37,000 units in its very first week
    oof release in Japan, a solid start for a new frannchise business;
    debuting at number 2 in the charts behind Draagon Baall Z:
    Budokai Tenkaichi. If you want earning prizes from the tournament, then you can swiftly staft
    by logging into your 1xBit account or producing a new
    account if yyou are new to the platform. Jungle is the one placement that doesn’t have actually aan assigned lane;
    they’re intended to level up by killing the monsters in the jungle and afterwards
    make murder attempts on opponent champs in lane.
    While other video games in Play ‘n GO’s expandng profile
    take a more reasonable method, this one iss evocative preferred social mobile games like The Sims
    as well as Farmville. Virgin Radio operation in prwp work for tthe
    sale of the station properties tto TIML; this additionally causedd the closzure of Virgin Radio Groove
    as a non-core terminal in the portfolio. The Cash Vandals port device also has the ever-handy Autoplay function that lets youu spin between 10 and 100 successive rotates, inn
    addition to a Quickspin function which enables you to rltate the reels
    at double the typical speed.

    Online slots how to win – RAJAWIN

  13. Сайт http://board.ruputeshestvie.ru/ представляет собой туристическую доску объявлений, где вы сможете воспользоваться услугами, а также заказать авторскую экскурсию от гида, забронировать жилье, гостиницу, а также отель в России. После того, как вы опубликуете объявление, то его увидят миллионы, оно привлечет внимание потенциальных клиентов. Особенностью портала является то, что все объявления дублируются в социальных сетях. Вы можете ознакомиться с последними объявлениями, которые будут вам любопытны.

  14. Hey! This post couldn’t be written any better! Reading through this post reminds me of my good old room mate!
    He always kept chatting about this. I will forward this
    article to him. Fairly certain he will have a good read.
    Thank you for sharing!

  15. My relatives every time say that I am killing my time here at web, except I know I am getting know-how all the time by reading thes pleasant
    content.

  16. SINAGA123: DAFTAR SITUS JUDI SLOT ONLINE GACOR TERBAIK
    DI INDONESIA

    Judi slot online di Sinaga123 telah menjadi pilihan yang populer bagi
    banyak penggemar permainan kasino di Indonesia. Situs ini menawarkan berbagai
    macam permainan slot yang menarik dengan tampilan grafis dan suara yang memukau.

    Salah satu keuntungan utama bermain judi slot online di Sinaga123 adalah kemudahan aksesnya.
    Anda dapat mengakses situs ini dari perangkat apapun yang terhubung ke
    internet, seperti laptop, tablet, atau smartphone.
    Selain itu, Sinaga123 menyediakan aplikasi mobile yang dapat diunduh secara
    gratis untuk memudahkan akses kapan saja dan di mana saja.

    DAFTAR JUDI ONLINE GACOR TERBAIK DI INDONESIA

    Di tahun 2023 ini, Tentu saja beberapa situs judi online kini sudah menghadirkan sistem 1 akun yang bisa
    bermain semua jenis permainan judi yang dihadirkan dalam 1 situs tersebut, selain game judi slot anda juga bisa menikmati berbagai macam
    judi online lain seperti :

    1. Judi Slot Online
    2. Sportbook
    3. Live Casino
    4. Togel

    BAGAIMANA CARA BERMAIN JUDI SLOT ONLINE AGAR BISA MENDAPATKAN MAXWIN

    Permainan judi slot online adalah salah satu permainan yang sangat populer di kalangan pemain di seluruh dunia,
    salah satunya di Indonesia. Permainan ini sangat mudah dimainkan dan menawarkan peluang besar untuk memenangkan hadiah uang yang besar.
    Jika Anda ingin memaksimalkan kemenangan Anda saat bermain judi slot
    online di situs Sinaga123, berikut adalah beberapa tips yang dapat membantu:

    1. Pilih mesin slot yang tepat
    Pilihlah mesin slot yang sesuai dengan preferensi Anda dan pastikan untuk memeriksa persentase pembayaran mesin slot
    tersebut. Anda juga dapat mencoba bermain di mesin slot dengan jackpot progresif, yang akan memberikan hadiah uang yang lebih besar jika Anda berhasil memenangkan jackpot.

    2. Pelajari strategi bermain yang tepat
    Pelajari strategi bermain yang tepat untuk mesin slot yang Anda mainkan. Ini termasuk memahami cara
    kerja mesin slot, peluang pembayaran, dan kombinasi pemenang yang
    mungkin muncul.

    3. Bermain dengan sabar
    Bermain judi slot online membutuhkan kesabaran dan keberuntungan. Pastikan anda jangan terburu-buru pada saat bermain dan emosional agar tidak mengalami kekalahan.

    4. Bermain dengan fokus
    Bermain judi slot online membutuhkan fokus dan konsentrasi yang tinggi.
    Jangan terganggu oleh hal-hal di sekitar Anda atau oleh perangkat lain saat
    bermain. Dengan anda bermain dengan fokus Anda dapat membuat keputusan yang lebih
    baik dan berpeluang untuk memenangkan hadiah besar.

    5. Bermain dengan teman
    Bermain judi slot online dengan teman dapat meningkatkan pengalaman bermain Anda.
    Anda dapat bertukar pengalaman dan strategi, serta
    memotivasi satu sama lain untuk mencapai kemenangan yang lebih besar.

    BAGAIMANA CARA MEMBUAT AKUN DI SINAGA123

    Sinaga123 adalah situs judi slot online terpercaya yang menyediakan berbagai
    permainan kasino online, termasuk slot online.
    Untuk memainkan permainan di situs Sinaga123, Anda perlu membuat akun terlebih dahulu.

    Berikut adalah langkah-langkah cara membuat akun judi slot online di Sinaga123:

    1. Kunjungi situs Sinaga123
    Pertama-tama, kunjungi situs Sinaga123 melalui perangkat komputer atau ponsel
    Anda. Pastikan Anda menggunakan koneksi internet yang stabil untuk memastikan pengalaman bermain yang lancar.

    2. Klik tombol “Daftar” atau “Register”
    Setelah Anda masuk ke situs Sinaga123, cari tombol “Daftar” di
    halaman utama situs. Klik tombol tersebut untuk memulai proses pendaftaran akun.

    3. Isi formulir pendaftaran
    Setelah Anda mengklik tombol “Daftar”, Anda akan diarahkan ke halaman formulir pendaftaran SInaga123.
    Isilah formulir tersebut dengan informasi pribadi Anda yang valid, seperti nama lengkap, nomor telepon.

    4. Verifikasi akun Anda
    Setelah Anda mengisi formulir pendaftaran, Anda akan menerima email verifikasi dari Sinaga123.
    Akun Anda sudah siap digunakan.

    5. Lakukan deposit
    Setelah Anda berhasil membuat akun di Sinaga123, langkah
    selanjutnya adalah melakukan deposit. Pilihlah metode
    pembayaran yang tersedia di situs tersebut, seperti transfer bank atau dompet elektronik.
    Setelah melakukan deposit, Anda siap untuk memainkan permainan judi slot online di
    Sinaga123.
    https://slot-sinaga12344332.pages10.com/sinaga123-l-slot-sinaga123-l-sinaga123-gacor-l-sinaga123-slot-l-daftar-sinaga123-54135263

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

*

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.