OOP - Is it better to call functions from within other functions, or to have one big controller?

StackOverflow https://stackoverflow.com/questions/17081602

Question

I'm re-writing a fairly complex script that I created a few weeks ago. After showing it to a few people, they all agreed that I should break it up into smaller pieces (classes) that have a specific purpose, and SOLID object-oriented programming principles

As a self-taught programmer these concepts are pretty new to me, and I'm a little confused about how to best transfer data from one function/class to another. For instance, here is a simplified structure of what I'm building:

enter image description here

MY QUESTION IS:

Should I have a "controller" script that calls all of these functions/classes and passes the data around wherever necessary? Is this where I would put the for loop from the diagram above, even though it would work just as well as part of Function 1 which could then call Function 2?

Was it helpful?

Solution

Without a controller/service script you'll not be able to meet single responsibility principle in fact. Here's a high level design I'd implement if I were you.

FileRepository
Should expose a method to get a file. Let's name it GetFileById.

MongoDBRepository Methods for CRUD operations. Such as SelectById, SelectByQuery, Update, Create, Delete.

Object creation logic
If your createNewObj logic is simple it would be enough to move it to your object contructor so that your code looks like that: var newObj = new MyObj(json[i]); But if it's relatively complex maybe because you use some third party frameforks for validation or whatever you'd better create a factory. Then you could would look this way: var newObj = MyObjFactory.Create(json[i]);

Service/controller
Finally you'll need to implement controller/service object. Let's name it WorkService with a method DoWork which should handle all interactions between the repositories and other objects discribed above. Here's approximately DoWork should look like:

function DoWork(fileId){
  var json = fileRepository.SelectById(fileId);
  for(var i=0;i<json.length;i++){
     var newObj = new MyObj(json[i]);  // or calling factory method
     var dbRecord = MongoDBRepository.SelectByQuery(newObj.name, newObj.date);
     if(dbRecord){
       MongoDBRepository.Update(newObj);
     }
     else{
       MongoDBRepository.Create(newObj);
     }
  }
}

Please note it's just a javascript syntax pseudo-code. Your actual code might look absolutley different but it gives your a feeling of what kind of design your should have. Also I exmplicitly didn't create a repository objects inside DoWork method, think of the way to inject them so you meet Dependency inversion principle.

Hope it helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top