views:

80

answers:

1

Hi All,

I wanted to ask,

If writing nested(deep) iteration loops (as shown in example) a bad practice (in OOPs)?

For example :

If i want to zip all files that in all Workspaces.
Given example classes are Workspace, Project , File

please ignore avoid syntax errors

for each Workspace workspace in WorkSpaces
 { 
     Projects = workspace.Projects; //any collection of projects
       {  
           for each Project project in Projects 
           {  
                   Files = project.Files//any collection of Files 
                   for each File file in Files
                   {
                        ....so on so forth
                         //SOMEWHERE Down the line 
                           do_something(f);  //ideally add file to zip  
                   }
           }
       }
}

//Note : nesting could go more deeper.
//Not the best example but hope it explains my intent.

*One more way is adding a zip function to each class Workspace,Project,File
and call that,but still the iteration would be needed?

Whats the best way to achieve the same in an more Object oriented manner?

Thanks All

+7  A: 

Well first of all I see nothing wrong with the for loops. If you want to do it in "purely" OOP just let all classes in the hierachy implement one interface IZippable for example. Then you can call:

foreach IZippable workspace in WorkSpaces
    workspace.zip();

and in the zip method

class Workspace implements IZippable {
   private List<Projects> projects;

   public void zip() {
       foreach IZippable project in projects 
           project.zip();
   }
}

And same to the end of hierarchy:

class Project implements IZippable {
       private List<Files> files;

       public void zip() {
           foreach IZippable file in files 
               file.zip();
       }
    }

.............................................

Petar Minchev
+1 for clarity.
Jas
+1 thx for the clarifications :) answer accepted
Amitd