1

I have couple of files in my folder, some of them can be checked for integrity. I have a xml file which describes which files can be checked for integrity and their checksum.

In OOP, let's assume I have a class called File.

Then, I have a class called FileWithIntegrity which extends File.

I could create a class called FileWithoutIntegrity, but that will not be different from File class.

In this case, does it make sense to create an instance of File and use it as an object?

As far as I know, superclass should be abstract and they should not be instantiated. Am I wrong?

1 Answer 1

2

The general answer is to take it on a case-by-case basis. For some modelling tasks one can have hierarchies where base classes are usable. GUI related ones come into mind as a prime candidate. One has a Button class, which gives you a standard button. But one also has a SubmitButton class, which is derived from Button, and makes the button look all fancy, but still needs the behaviours of Button. So, it makes sense to use one or the other, depending on the circumstance, and not worry about NonSubmitButtons.

On the other hand, a hierarchy of connections classes for different databases would not allow such usage. You'd have your Connection class, which is derived by MySQLConnection, PostgresConnection etc. It doesn't make sense to construct a generic connection - just to work with one.

I think your case falls in the former, rather than the latter, case.


On the other hand, you could ditch the concept of a hierarchy of classes completely if the situation escalates. For example, if you'd want to represent archived files, files stored on remote servers, procfs style files etc, you'd need a pretty big hierarchy. If a file could be any of the above, you'd quickly have an unwieldy hierarchy - things like FileWithIntegrityAndOnARemoteServer looks quite bad. For cases like this, you can store the extra properties as actual properties of the class. For any one file, the properties are optional, but for files with integrity checks, the appropriate property is present etc. It's an instance of the composition over inheritance idea.

2
  • I was thinking about properties as well. You are right, maybe I am better off using properties instead of creating a separate class. Maybe different constructors? Feb 7, 2017 at 13:07
  • @TahnikMustasin yes, that sounds like a good approach to it. Or a factory of some sort. Feb 7, 2017 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.