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

前端 未结 19 1920
悲&欢浪女
悲&欢浪女 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:26

    You should try to keep the constructor from doing unnecessary work. In the end, it all depends on what the class should do, and how it should be used.

    For instance, will all the accessors be called after constructing your object? If not, then you've processed data unnecessarily. Also, there's a bigger risk of throwing a "senseless" exception (oh, while trying to create the parser, I got an error because the file was malformed, but I didn't even ask it to parse anything...)

    On second thought, you might need the access to this data fast after it is built, but you may take long building the object. It might be ok in this case.

    Anyway, if the building process is complicated, I'd suggest using a creational pattern (factory, builder).

提交回复
热议问题