开发者

Validation C# constructor object null dispose

开发者 https://www.devze.com 2023-04-11 11:59 出处:网络
I am new to object oriented prog in c#.So kindly bear me. I dont want to create object, if this.OrderCost() is more than 10000.00.How to drop this object. Is it correct to do validtion here. What is t

I am new to object oriented prog in c#.So kindly bear me. I dont want to create object, if this.OrderCost() is more than 10000.00.How to drop this object. Is it correct to do validtion here. What is the best possible way.

 public Bank(string开发者_如何学Python bankCode, string bankName)
    {
        this.bankCode= bankCode;
        this.bankName= bankName;


        if (this.orderCost() > moneyInBankAccount)
        {
            MessageBox.Show("Order amount exceeds the money in bank account.");
            this. = null;  // <--what to do here.
        }
    }


Validation of this type shouldn't been done in the constructor of the object. Instead it should be done in the method that is performing the action you intend to perform.

So, if you are attempting to deduct the money from the bank account to pay for an order you would perform the validation in the "Withdraw" method.


Except in several very rare circumstances that are not applicable here, if a constructor returns, it either returns the constructed object or it throws an exception.

So, to avoid construction of an object that would be invalid, you should throw an exception. Or you could create a method that returns null is the object would be invalid and create it otherwise.

Also, you shouldn't deal with the UI in the domain objects, so don't show that message box there.


It is not possible to "assign" to this or somehow else prevent the constructor from doing its job. You can either throw exception or somehow else indicate, that the newly created object is invalid.

EDIT
You can also create a static method, that will return a Bank object if your conditions are met, or return null otherwise.


Here is nothing new than other answers. Just to show how you can do it.

public class Bank
{
    public Bank(string bankCode, string bankName)
    {
        if (ConditionNotMet) throw new SomeException("");
        .....
    }
}

or

public class Bank
{
    private Bank(string bankCode, string bankName)
    {
    }

    public static Bank Create(string bankCode, string bankName)
    {
        if (ConditionNotMet) return null; //or throw Exception
        return new Bank(string bankCode, string bankName);
    }
}

If you are not convinced try to read the "I" of test class

public class Test
{
    public int I=0;
    public Test()
    {
        I=666;
        throw new Exception("No you can't read");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号