How much work should the constructor for an HTML parsing class do?

前端 未结 19 1941
悲&欢浪女
悲&欢浪女 2020-12-23 09:55

How much work is it reasonable for an object constructor to do? Should it simply initialize fields and not actually perform any operations on data, or is it okay to have it

19条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 10:33

    Why not just pass the parser to the constructor? This would allow you to change the implementation without changing the model:

    public interface IParser
    {
        Dictionary ParseDocument(string document);
    }
    
    public class HtmlParser : IParser
    {
        // Properties, etc...
    
        public Dictionary ParseDocument(string document){
             //Do what you need to, return the collection of properties
             return someDictionaryOfHtmlObjects;
        }
    }
    
    public class HtmlScrapper
    {
        // Properties, etc...
    
        public HtmlScrapper(IParser parser, string HtmlDocument){
             //Set your properties
        }
    
        public void ParseDocument(){
             this.myDictionaryOfHtmlObjects = 
                      parser.ParseDocument(this.htmlDocument);
        }
    
    }
    

    This should give you some flexibility in changing/improving how your application performs without needing to rewrite this class.

提交回复
热议问题