tags:

views:

58

answers:

2

When including a class that returns objects of another type, I'm not sure of the best practice when importing the class file for the returned object type. So, if all three classes are in separate files:

class file A imports class file B
class file B imports class file C
class B returns an object of type C to class A

should class A also import class C in order to be more explicit, or is it alright to assume that class C has been imported by class B, and indirectly by class A?

+1  A: 

I think this is language and implementation specific.

I know in C++, if you do a #include, that's as good as doing a copy and paste of the file it is #including. So when you do that you're essentially bringing in any imports... as long as it doesn't clash with the entities in the namespace it should be fine. Just make sure that each *.h file you have has a #pragma once or that #ifndef section to it.

In Java, you'll have to be explicit. From my personal experience it will require declaration of all types been used. Not sure about the backend but at least my IDE complains, which I believe comes straight from javac.

jghost
that makes sense. In this case, I am thinking about require_once in PHP.
jmans
+1  A: 

IMHO, from OO design standpoint (not that I am any good), as long as class A doesn't need to know anything specific about class C, you don't need the import (of a module, not text). This can happen e.g. when class A depends on object of class/interface D, which will be returned by B (from factory method) which will be object of class/interface C, which extends/implements D. That is the point of factory method design pattern - brake dependency between created objects concrete class and its needed interface.

Gabriel Ščerbák
Right, but I am actually trying to get at something more basic than that. When the programmer knows that they can rely on a library included by another file, is it reasonable not to reference that third library in the code in question? This does create a bit of a dependency, but probably a reasonable one.
jmans
When you rely on dependency through another file, that dependency might be broken behind your back unless you make it explicit.
Gabriel Ščerbák