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.363 Comments on “Eclipse – Formatter e Save Action

  1. 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!

  2. На сайте http://mebel.morekrim.com/kuhni вы сможете заказать качественную, добротную мебель. Для того чтобы воспользоваться услугой, необходимо позвонить по указанному телефону. Далее к вам на объект прибудет замерщик, который рассчитает стоимость проекта. В любом случае она будет выгодней, чем у конкурентов. На итоговую стоимость влияют следующие факторы: размеры мебели, цена фасадов, качество фурнитуры, а также то, из какого материала будет создана столешница. Ознакомьтесь с примерами работ на сайте.

  3. Article writing is also a excitement, if you be acquainted with afterward you can write or
    else it is complicated to write.

  4. 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.

  5. 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

  6. ทางเรา mothervaper ยังมี ผลิตภัณฑ์ บุหรี่ไฟฟ้า Pod System อื่นๆ ที่กำลังจะนำเข้ามา ให้ผู้ใช้ได้เลือกใช้อีกด้วย ไม่ว่าจะเป็น Infy Pod , Vmc Pod , Relx Bubble Mon ,
    Coga และอื่นๆ อีกมากมาย โดย น้ำยาบุหรี่ไฟฟ้า
    หรือ บุหรี่ไฟฟ้า พอตใช้แล้วทิ้ง ทุกรุ่น ล้วนแล้วแต่มี
    ราคาถูก แต่ให้คุณภาพที่ดีเยี่ยมทั้งนั้น อีกทั้งยังเป็นรุ่นยอดนิยมอีกด้วย

  7. 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.

  8. Качественные пластиковые окна Rehau в Санкт-Петербурге. Невский район! Установка окон. Ремонт окон. Москитные сетки. Собственное производство. Низкие цены! Мы творим комфорт в ваших домах. Установим качественные современные окна собственного производства длительного времени работы с гарантией. https://galereya-okon-spb.ru/

  9. 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.

  10. 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!

  11. 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.

  12. 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.

  13. 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!

  14. 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!

  15. And also, it’s easy to replace images to keep them on motif with the room’s ever-changing layout. This home design pattern is all about using items in brand-new, interesting and also unusual means. If you have a matching bedroom collection, think of relocating some of the items to the visitor area, dining room, or entrance. This look embraces organic products such as wool, cotton, silk, rattan and also clay in earth tones and warm neutrals. The days of using one metal finish everywhere in the house are gone. Rather, it’s currently really common to blend and also match steel coatings– not only in the kitchen and bathroom– yet throughout the home on surface areas like doorknobs, drape rods, lights, hinges, as well as much more.

    Choose top quality throws, paddings, and carpets that match the area. The very best means to make a place show up even more extravagant is to utilize tones that enhance each other. Choosing 2 shades as well as their differing tones will certainly guarantee this. For dependable color use, adhere to shades of black, white, or gray. This year is about making your residence really feel even more like your individual design with top notch items. The focus of this trend gets on top quality, much like our equipment.
    Contemporary Art Gallery Living Area
    Prior to signing up with GH in 2020, she was the digital editor at Elle Style. In her existing role, she discovers every little thing from style patterns as well as home trips to lifestyle product suggestions, including writing her regular monthly column, “What’s in My Cart.” This New York City apartment, crafted by Kati Curtis Layout, includes a tray ceiling that magnificently highlights the Sputnik world chandelier and also includes depth to the format. What’s more, the mix of light and dark hues produce a striking 3D effect. The luxe appearance isn’t concerning glam, glossy, mirrored, or glitzy spaces.

    What color of furniture is in for 2023? As we have actually talked about, natural materials such as wood, as well as natural, grounding color combinations with a concentrate on green, brownish and also cream tones will certainly be prominent throughout 2023, helping to establish a relaxing, and tranquil ambience.

    Similar to our very own individualities and quirks, work with awkward living-room designs and also not against them, to develop an unique room that doesn’t look like everyone else’s blueprint develop. And also if you’re looking to market your residential property, make your niche suggestions and recesses really shine by making them a statement attribute in your front room. These living room design concepts make sure to influence, and even if you do not replicate the room like-for-like, there’s something you can select as well as play regarding with as component of your next job. One easy method to change the appearance of your living-room is to go about enhancing it with interesting textiles through colorful vintage carpetings, area rugs, toss cushions, pillows, and also much more. As well as there’s no need to invest thousands of dollars on nice-looking textiles. Comb flea markets as well as vintage shops as well as see if you can resource an antique Turkish carpet cost a bargain or previously owned vintage carpets that are still in excellent condition.
    See All Exterior As Well As Garden Furnishings
    The use of a mural likewise broadens the room as it stops an expanse of the white wall making the room really feel blocky. If you want living space concepts that are instantaneously going to add something various to your area, choosing a couple of shades to repeat together is a terrific location to begin. Include texture underfoot, whilst zoning a seating area or relaxation edge with one of the very best carpet layouts that unites your scheme with an accent color. As revealed right here, try layering a smaller sized patterned design over a bigger all-natural distinctive carpet for an included layer of tactility. Add a sense of simple dramatization with a range of lighting fixtures and also candles that provide a space differing tones of light for the utmost in lavish living-room design concepts.

    Not just does this woven setup add some personality to this large area, but the variety of reflective rooms additionally helps bounce the light around ideal. ” Although recessed illumination is definitely not going anywhere, I assume that lights– even equally as ornamental pieces a lot more so than for illumination– will certainly be included right into property spaces,” she says. This area not just fills up on sofas at flooring degree but the interior designer has born in mind the upper quarters of the room also.

    Remember 80s decorating? Iconic 1980s interior designs and home accessories loveproperty.com – lovePROPERTY Remember 80s decorating? Iconic 1980s interior designs and home accessories loveproperty.com.

    A gleaming surface or a massive size can offer a high-style focus in the area. Select elevated drapes that are more comprehensive than your window to attain a lavish appearance. Mint & pink– For a suppressed combination with a calming result, pink and mint eco-friendly are ideal. Marian Parsons is the woman behind the well-known blog site and also social media brand Miss Mustard Seed. Marian and also her family members remain in the middle of a full renovation of their recently-purchased house as well as selected to mount glamorous brass hardware from Grandeur Hardware. A space by Timothy Corrigan blends materials like metal, timber, and also velour.
    Like Style & Interior Design? Follow Us
    Otherwise, it may make your living-room appearance chaotic, which totally defeats the function of developing a luxurious living-room interior decoration. For instance, you can integrate the soft qualities of velvet furniture with the grainy natural structure of a wood coffee table. By playing appearances off of each other, you’ll function to produce a sensation of deepness in your interior decoration that stimulates a brilliantly edited, varied mix. For example, modern minimalist design commonly integrates tidy lines, neutrals, and also black components; while maximalist design prefers split appearances, color, and also classic items. Nonetheless, we see both design perspectives accepting the use of all-natural materials, such as timber, stone, woollen, linen, and rattan, as well as numerous other trends on this listing. Before we enter the interior design patterns for 2023, as constantly, I recommend embellishing your home in a way that makes you feel excellent.

Deixe um comentário

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

*

Este site utiliza o Akismet para reduzir spam. Saiba como seus dados em comentários são processados.