Search code examples
javaloose-couplingcouplinggrasp

Improving my code with loose coupling or high coupling if any?


I want to improve my code using GRASP by creating an even lower coupling to my code. In my example I'm not sure whether I'm making lower coupling at all, and if I'm making loose coupling instead of high coupling?

I'm making my project using Spring boot. In my admincontroller I'm handling two classes: RestaurantcardService and ContentsectionService (from my service layer). Both these classes have implemented interfaces called I_RestaurantcardService and I_ContentsectionService.

The code looks like this:

public class AdminController {
RestaurantCardService restaurantcardService;
ContentsectionService contentsectionService;
public AdminController (){
    this.restaurantcardService       = new RestaurantCardService ();
    this.contentsectionService       = new ContentsectionService ();
}

Now my question is:

If I implement the interfaces for RestaurantCardService and ContentsectionService as the data types for the attributes instead of the classes themselves, wouldn't the coupling go down, because we could implement the interface in another variation of RestaurantCardService and ContentsectionService?

Then it would look like this:


Solution

  • This this highly coupled code. You have hard-coded your dependencies in the class itself.It will make the class difficult to unit test.

    Good approach should be get dependencies via constructor and should have interface for each services.

    eg: -

     public class AdminController {
                private final RestaurantCardService restaurantcardService;
                private final ContentsectionService contentsectionService;
                public AdminController (final RestaurantCardService rcs,final ContentsectionService  css){
                    this.restaurantcardService       = rcs;
                    this.contentsectionService       = css;
                }
    
     AdminController  ac = new AdminController (new RestaurantCardServiceImpl(),new ContentsectionServiceImpl());
    
    
                so for unit testing you can pass mock services;
    
                for intance:
    
    
        AdminController  ac = new AdminController (new MockRestaurantCardServiceImpl(), new MockContentsectionServiceImpl());
    

    Enjoy coding !