R
R
Roman2016-03-24 17:16:01
Java
Roman, 2016-03-24 17:16:01

What can be done to avoid violating the dependency inversion principle?

I have a java program here, the essence of which is to make a transaction between two bank accounts. Everything works, but the dependency inversion principle is violated. How to fix it?

class BankAccount
{
 private String AccountNumber;

 private double Balance;
 public BankAccount(String AccountNumber, double Balance) {
 this.AccountNumber = AccountNumber;
 this.Balance = Balance;
 }
 public void AddFunds(double value)
 {
 Balance += value;
 }
 public void RemoveFunds(double value)
 {
 Balance -= value;
 }
 @Override
 public String toString() {
 return "BankAccount{ " + "AccountNumber=" + AccountNumber + ", Balance=" + Balance + " }";
 }
}

class TransferManager
{
 public TransferManager(BankAccount Source, BankAccount Destination, double Value) {
 this.Source = Source;
 this.Destination = Destination;
 this.Value = Value;
 }

 private BankAccount Source;
 private BankAccount Destination;

 private double Value;
 public void Transfer()
 {
 Source.RemoveFunds(Value);
 Destination.AddFunds(Value);
 }
}

public class Bank {
    public static void main(String[] args){

    BankAccount from = new BankAccount("4321", 1200);
    BankAccount to = new BankAccount("1234", 200);
    System.out.println(from);
    System.out.println(to);
    TransferManager mymgr = new TransferManager(from,to,300);
    mymgr.Transfer();
    System.out.println(from);
    System.out.println(to);
 }     
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pi314, 2016-03-24
@Romzasin

More or less like this:

interface IBankAccount
{
 public void AddFunds(double value);
 public void RemoveFunds(double value);
}
...
class BankAccount implements IBankAccount
...
class TransferManager
{
 public TransferManager(IBankAccount Source, IBankAccount Destination, double Value) {
...

...etc. Everywhere to replace the direct dependence on the class on the dependence on the interface, because:
- The modules of the upper levels should not depend on the modules of the lower levels. Both types of modules must depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
(A class is a module, and an interface is an abstraction.)

S
sirs, 2016-03-24
@sirs

You probably do not quite understand what the dependency inversion principle is .
You don't use interfaces anywhere, everything is hardwired for you, for example, TransferManager can work with only one single type of BankAccount objects ....
PS Read about the code convention, because it's not easy to read your code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question