代码之家  ›  专栏  ›  技术社区  ›  MatthewMartin muthu

何时调用base.method()以及base.method()中应该包含哪些代码?

  •  3
  • MatthewMartin muthu  · 技术社区  · 15 年前

    在下面的示例中,派生类的编写器应调用base.add()。如果它发生在第一个,基可以执行一种代码。如果最后发生,基可以执行另一种逻辑(参见示例)。我似乎不可能两全其美。简单的解决方法是完全停止调用基方法,因为基将永远不知道它是在第一个、最后一个或中间被调用还是在两个!

    面向对象的处理方法是什么?我应该停止将代码放入基方法,因为我永远不知道前置和后置条件吗?

    编辑:目标是拥有一个执行CRUD操作的业务对象类。重复的代码将移动到基类。例如,在添加记录之前检查业务对象的ID是否为0,并在保存之后检查业务对象的ID是否为>0。

    namespace StackOverFlowSample
    {
        class BusinessObjectBase
        {
            private bool _isNew;
            private int _id;
            public virtual void Add(string newAccount)
            {
                //Code that happens when subclasses run this method with the 
                //same signature
    
                //makes sense if base is called 1st
                if(_isNew && _id>0) throw new InvalidOperationException("Invalid precondition state");
    
                //makes sense if bae is called 2nd
                if (!_isNew && _id == 0) throw new InvalidOperationException("Invalid post condition state");
            }
        }
        class BusinessObject : BusinessObjectBase {
            public override void Add(string newAccount)
            {
                //doesn't make sense, because base will need to be called again.
                base.Add(newAccount);//pre validation, logging
    
                //Save newAccount to database
    
                //doesn't make sense, because base has already been called
                base.Add(newAccount);  //post validation, logging
            }
        }
    }
    
    3 回复  |  直到 15 年前