Forem

Cover image for Objetos e Estruturas de Dados (Código Limpo: Que Bruxaria é Essa?!?! - Parte 4)
ananopaisdojavascript
ananopaisdojavascript

Posted on

3 2

Objetos e Estruturas de Dados (Código Limpo: Que Bruxaria é Essa?!?! - Parte 4)

Use getters e setters

O uso de getters e setters para acessar dados pode ser melhor que simplesmente procurar por uma propriedade em um objeto. Talvez você pergunte: "Por quê?!". Bom, aqui você vai ver uma lista desorganizada de motivos:

  • Quando você quer fazer mais do que obter a propriedade de um objeto, você não tem que procurar e mudar cada dado acessível na sua base de códigos.
  • Simplifica a inclusão de validações ao usar um set.
  • Encapsula a representação interna.
  • Facilidade de inclusão de tratamento de registros e erros no momento de obtenção e configuração.
  • Você pode fazer o carregamento lento das propriedades do seu objeto, vamos dizer obtendo-as de um servidor.

Não é recomendável:

function makeBankAccount() {
  // ...

  return {
    balance: 0
    // ...
  };
}

const account = makeBankAccount();
account.balance = 100;
Enter fullscreen mode Exit fullscreen mode

É recomendável:

function makeBankAccount() {
  // this one is private
  let balance = 0;

  // a "getter", made public via the returned object below
  function getBalance() {
    return balance;
  }

  // a "setter", made public via the returned object below
  function setBalance(amount) {
    // ... validate before updating the balance
    balance = amount;
  }

  return {
    // ...
    getBalance,
    setBalance
  };
}

const account = makeBankAccount();
account.setBalance(100);
Enter fullscreen mode Exit fullscreen mode

Faça com que objetos tenham membros privados

Esse feito pode ser alcançado por meio de closures (ES5 e versões anteriores)

Não é recomendável:

const Employee = function(name) {
  this.name = name;
};

Employee.prototype.getName = function getName() {
  return this.name;
};

const employee = new Employee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined
Enter fullscreen mode Exit fullscreen mode

É recomendável:

function makeEmployee(name) {
  return {
    getName() {
      return name;
    }
  };
}

const employee = makeEmployee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
Enter fullscreen mode Exit fullscreen mode

E aí? Gostaram? Até a próxima tradução! 🤗

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay