0

I am creating a project that defines the following class:

class BankAccount {
 constructor(balance=0){
   this.balance = balance;
 }

 withdraw(amount){
    if(this.balance - amount >= BankAccount.overdraftlimit){
      this.balance -= amount;
    }
  }
}

BankAccount.overdraftlimit = -500;

My question here is about the definition of the property overdraftlimit

Is this the best way to define let's call a global property? Or should be better to define it inside the constructor like

this.overdraftlimit = -500;

Thank you!!

5
  • 2
    that depends on your domain. can different bank account have different overdraftlimit? should a bank account be able to mutate it? Commented Aug 17, 2019 at 1:19
  • thanks for responding. No, another bank account cannot mutate it, and there will be different bank accounts with different overdraftlimits Commented Aug 17, 2019 at 1:21
  • if the overdraftlimit is not part of any specific instance, then it make sense to be defined as part of the class itself. otherwise make that part of your instance state. Commented Aug 17, 2019 at 1:22
  • I personaly would set this property in the constructor with a default value and create setter and getter for it Commented Aug 17, 2019 at 1:24
  • ok, so I understand that if it is defined as part of the class is independant of the instance and any instance can not mutate it. Commented Aug 17, 2019 at 1:25

1 Answer 1

3

If the overdraftlimit is shared across all the BankAccount, then go with the static propriety.

BankAccount.overdraftlimit = -500;

If every BankAccount have their own overdraftlimit, it should not be part of the class, but part of the single instances.

 constructor(balance = 0){
   this.balance = balance;
   this.overdraftlimit = -500;
 }

this way you could also change overdraftlimit without affecting other BankAccount.

Sign up to request clarification or add additional context in comments.

2 Comments

ohhh, ok I got it. Declare it as a static property makes that this property can be shared by all the instances. If one change it, it will affect the other instances. As you was saying part of the class not of the instance. That is what you mean right? Great explanation
yeah, that's it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.