Tried to work with recursion, ended up with spaghetti code

Viewed 100

thank you for reading my question (the first part is just an introduction about my project so you can just skip it if you want)

First some background: On my way on learning how back-end web development works, I ended an with a project idea, an Web-forum (like phpBB, Invision community or vBulletin) but from scratch, meaning using just PHP (for the back-end).

The first thing that I did was to read on the web and trying to get my head around the MVC (Model-View-Controller) design pattern and to my surprise I successfully implemented that with my limited knowledge about OOP (Object Oriented Programing) and some interesting design patterns inside the book written by the GoF, at least implemented it the way I understood it.


The "system? layout?" that I implemented looks something like this:

  • Category: Contains one or more Forums
    • Forum: Contains the list of Subforums and the list of Threads / Topics under that Forum
      • Subforum : Contains the list of Subforums and the list of Threads / Topics under that Subforum.

So one Subforum can have it's own subforums, and so on and so on.

Hopefully if I explained that the right way you can see why recursion is implied here.

So now the problem:

I tried to implement a "system? algorithm?" that uses recursion to find how many threads / topics and posts under that those threads a specified forum or subforum have under it, why recursion? Because I want all the threads / topics under all the subforums under that forum, but because those subforums can have their subforums it needs to take into account all the threads / topics and the posts under all the those subforums and so on and so on. Hope I got it right.

After some thinking I ended up with 6 functions ( and here begins the spaghetti code ) Hope that the function's name's are self-explenatory;

function getThreadsIDs($forumID, $isSubForum); // returns a list of the IDs of JUST the threads under the specified forumID
function getSubForumsIDs($forumID, $isSubForum); // returns a list of the IDs of JUST the subforums under a specifed forumID
function getPostsIDsByThreadID($threadID); // returns a list of all the ID's of the posts under a specified threadID
function getNoTotalPostsIDsByForumID($forumID, $isSubForum); // returns a list of ALL the posts IDs under a specified forumID

//Recursive functions
function recursivePostNumber($forumID, $isSubForum); // recursively returns the total number of posts under a specified forumID
function recursiveThreadNumber($forumID, $isSubForum); // recursively returns the total number of threads under a specified forumID

The problem with this approach is that my code is entangled and messy, is there any better way to resolve this kind of solution?

0 Answers
Related