7/7 Banking on Ruby - Share your thoghts/code


#1

Hi, I improved this project in OOP part II. I just wanted to get your guys opinion about how I code this, did I made a mistake or could I refactored it better? Thanks in advance.

class Account
  attr_reader :name, :balance
  def initialize(name, balance=100)
    @name = name
    @balance = balance
  end
  
  public
  
  def display_balance(pin_number)
    if pin_number == pin
      puts "Balance: $#{@balance}."
    else
      puts pin_error
    end
  end
  
  def withdraw(pin_number, amount)
    if pin_number == pin && amount < @balance
      @balance -= amount
      puts "Withdrew #{amount}. New balance: $#{@balance}."
    elsif amount > @balance
      puts "Insufficient funds"
    else
      puts pin_error
    end
  end
  
  def deposit(pin_number, amount)
    if pin_number == pin
      @balance += amount
      puts "Deposit #{amount}. New balance: $#{@balance}."
    else
      puts pin_error
    end
  end
  
  private
  
  def pin
    @pin = 1234
  end
  
  def pin_error
  	@pin_error = "Access denied: incorrect PIN."
  end
end

checking_account = Account.new("Mark", 500)
checking_account.display_balance(1234)
checking_account.withdraw(1234, 501)
checking_account.display_balance(1234)
checking_account.deposit(1234, 600)

class SavingsAccount < Account
end

savings_account = SavingsAccount.new("Jason", 500)
savings_account.display_balance(1234)
savings_account.withdraw(1234, 501)
savings_account.display_balance(1234)
savings_account.deposit(1234, 800)

#2

I can access balance without using the display_balance method.
savings_account.balance

You wrapped the balance and name variables using attr_reader which is good for encapsulation, but after that refer to those variables as balance and name not @balance and @name anymore.

The pin variable should be initialized at account creation imo.
It doesn’t make sense to have a default pin, especially if there is no set_pin method.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.