Search code examples
dependenciesanti-patternscircular-dependency

Circular dependency between two methods in a class


I have a library class which contains two methods, say, Login() and NavigateToPage(). Now, in order to navigate to a page, the session has to be logged in. Also, to log in, one needs to first navigate to the login page. As of now, my workaround is :

Login()
{
   NavigateToPage(LoginPage);
   // log in and do validation stuff.
   // set IsLoggedIn to true for further methods (also for NavigateToPage() method.)
   IsLoggedIn = true;
}

NavigateToPage (PageType pageType)
{
    if (pageType == LoginPage)
    {
       // navigate to login page.
       return;
    }
    if (! IsLoggedIn) Login();

    // switch case for navigation to other page types.
}

This is sort of a psuedocode. The actual code has worked till now, without any problems. Still, I feel there is something wrong as it looks cyclic. I think there is something that can be done to improve the code and remove the cyclic dependency. Could someone suggest anything?

I had pretty much intended to make the question language and platform-agnostic. But I see that I couldnt explain it. Basically, the pages are independent of my class. The library that I am developing, takes a website and navigates its pages. I am just trying to automate the tasks in a website. So, the login page and other pages that I am talking about are in context of that website that I want to browse. The library automates that browsing. I hope I am clear now.


Solution

  • Using your existing pseudo logic, I will just refactor the code and introduce an explicit method for navigating to login page

    Login()
    {
       NavigateToLoginPage();
    }
    NavigateToLoginPage()
    {
       // navigate to login page.
       // log in and do validation stuff.
       // set IsLoggedIn to true for further methods 
       IsLoggedIn = true;
    }
    NavigateToPage (PageType pageType)
    {
        if (! IsLoggedIn) NavigateToLoginPage();
    
        // switch case for navigation to other page types.
    }