Difference between an instance of a class and a class representing an instance already?

后端 未结 6 2131
别跟我提以往
别跟我提以往 2020-12-30 01:47

I use Java as an example but this is more of a general OOP design related question.

Lets take the IOExceptions in Java as an example. Why is there a cla

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 02:20

    Option 1 has to list all known causes at declaration time.

    Option 2 can be extended by creating new classes, without touching the original declaration.

    This is important when the base/original declaration is done by the framework. If there were 100 known, fixed, reasons for I/O problems, an enum or something similar could make sense, but if new ways to communicate can crop up that should also be I/O exceptions, then a class hierarchy makes more sense. Any class library that you add to your application can extend with more I/O exceptions without touching the original declaration.

    This is basically the O in the SOLID, open for extension, closed for modification.

    But this is also why, as an example, DayOfWeek type of enumerations exists in many frameworks. It is extremely unlikely that the western world suddenly wakes up one day and decides to go for 14 unique days, or 8, or 6. So having classes for those is probably overkill. These things are more fixed in stone (knock-on-wood).

提交回复
热议问题