Class Design – Is Passing Instances Through Several Layers Bad Practice?

class-designdesign

In my program design, I often come to the point where I have to pass object instances through several classes. For example, if I have a controller that loads an audio file, and then passes it to a player, and the player passes it to the playerRunnable, which passes it again somewhere else etc. It looks kind of bad, but I donĀ“t know how to avoid it. Or is it OK to do this?

EDIT: Maybe the player example is not the best because I could load the file later, but in other cases that does not work.

Best Answer

As others have mentioned, this isn't necessarily a bad practice, but you should pay attention that you're not breaking the layers' separation of concerns and passing layer-specific instances between layers. For instance:

  • Database objects should never be passed up to higher layers. I've seen programs using .NET's DataAdapter class, a DB-access class, and passing it up to the UI layer, rather than using the DataAdapter in the DAL, creating a DTO or dataset, and passing that up. DB access is the domain of the DAL.
  • UI objects should, of course, be limited to the UI layer. Again, I've seen this violated, both with ListBoxes populated with user data passed up to the BL layer, instead of an array/DTO of its content, and (a particular favorite of mine), a DAL class that retrieved hierarchical data from the DB, and rather than returning a hierarchical data structure, it just created and populated a TreeView object, and passed it back to the UI to be added dynamically to a form.

However, if the instances you're passing are the DTOs or entities themselves, it's probably ok.

Related Topic