1

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:

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Gustav Vingtoft
  • 355
  • 2
  • 16
  • What coupling are you talking about? Coupling between packages or between classes in one package? In general, one should go for strong/high coupling of the classes that are in the same package and very low coupling between classes that are not in the same package. The design of the package structure is really important for maintenance. – deHaar Jun 20 '19 at 13:45
  • Maybe softwareengineering Stackexchange is better suited for this kind of question on design principles – tkruse Jun 20 '19 at 15:21
  • I tried to improve the formatting, but it seems like there is some code with your proposed idea missing at the end. – Laurenz Albe Jun 21 '19 at 07:54

1 Answers1

2

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 !

Prasobh.Kollattu
  • 1,665
  • 1
  • 22
  • 32