Programming pattern / architectural question

前端 未结 6 1412
生来不讨喜
生来不讨喜 2021-02-10 13:50

I am currently working on a project where I have a BankAccount entity for some other entity.

Each bank account as a reference to a bank entity, an account number and opt

6条回答
  •  无人共我
    2021-02-10 14:14

    I would use some form of Inversion Of Control.

    To be specific, I would have an interface called IIBANValidator. The various means of validating the IBAN should implement that interface. For example:

    interface IBANValidator {
        Boolean Validate(string iban);
    }
    
    class SqlBanValidator : IBANValidator {
    
        public bool Validate(string iban) {
            // make the sql call to validate..
            throw new NotImplementedException();
        }
    
    }
    

    Then, I would have a method in my BankAccount class which accepted an object that implements IIBANValidator and the IBAN number and was structured like (not optimized by any stretch):

    Boolean SetIBAN(IIBANValidator validator, String iban) {
      Boolean result = false;
      if (validator.Validate(iban)) {
        Iban = iban;
        result = true;
      }
    
      return result;
    }
    

    At this point your BankAccount class would not have to have a dependency on your validators, you could swap them out at will, and ultimately it's very clean.

    The final code would look something like:

    BankAccount account = new BankAccount();
    account.SetIBAN(new SqlBanValidator(), "my iban code");
    

    Obviously at runtime you could pass any validator instance you wanted.

提交回复
热议问题