POCO's, DTO's, DLL's and Anaemic Domain Models

后端 未结 3 2000
执念已碎
执念已碎 2021-01-30 14:52

I was looking at the differences between POCO and DTO (It appears that POCO\'s are dto\'s with behaviour (methods?))and came across this article by Martin Fowler on the anaemic

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 15:18

    Personally I don't find those Anaemic Domain Models so bad; I really like the idea of having domain objects that represent only data, not behaviour. I think the major downside with this approach is discoverability of the code; you need to know which actions that are available to use them. One way to get around that and still keep the behaviour code decoupled from the model is to introduce interfaces for the behaviour:

    interface ISomeDomainObjectBehaviour
    {
        SomeDomainObject Get(int Id);
        void Save(SomeDomainObject data);
        void Delete(int Id);
    }
    
    class SomeDomainObjectSqlBehaviour : ISomeDomainObjectBehaviour
    {
        SomeDomainObject ISomeDomainObjectBehaviour.Get(int Id)
        {
            // code to get object from database
        }
    
        void ISomeDomainObjectBehaviour.Save(SomeDomainObject data)
        {
            // code to store object in database
        }
    
        void ISomeDomainObjectBehaviour.Delete(int Id)
        {
            // code to remove object from database
        }
    }
    class SomeDomainObject
    {
        private ISomeDomainObjectBehaviour _behaviour = null;
        public SomeDomainObject(ISomeDomainObjectBehaviour behaviour)
        {
    
        }
    
        public int Id { get; set; }
        public string Name { get; set; }
        public int Size { get; set; }
    
    
        public void Save()
        {
            if (_behaviour != null)
            {
                _behaviour.Save(this);
            }
        }
    
        // add methods for getting, deleting, ...
    
    }
    

    That way you can keep the behaviour implementation separated from the model. The use of interface implementations that are injected into the model also makes the code rather easy to test, since you can easily mock the behaviour.

提交回复
热议问题