OOP Tight Coupling. When should I do it?

391 Views Asked by At

I've implemented two services. One that pulls data from a Country API and another that pulls data from a County API.

I like to keep my controllers clean, so I'm curious if it's a good idea to combine my services together instead of keeping them apart.

I'm not exactly sure what constitutes tight coupling and when it's appropriate or not.

Should I go down this route:

public async Task<IActionResult> Get(
        [FromQuery] double latitude, 
        [FromQuery] double longitude
    {
        var countryService = new CountryService();
        var countryData = await countryService.Get(latitude, longitude);

        var countyService = new CountyService();
        var countyData = await countyService.Get(latitude, longitude);

        return Ok(new Data(countryData, countyData);
    }

OR

public async Task<IActionResult> Get(
        [FromQuery] double latitude, 
        [FromQuery] double longitude
    {
        var combinedService = new CombinedService();
        Data combinedData = await combinedService.Get(latitude, longitude);

        return Ok(combinedData);
    }
2

There are 2 best solutions below

0
pid On

Tight coupling is an excellent idea when you sense cohesion on the domain level. In Eric Evans' book DDD the term Bounded Context is defined. Think about it this way: how much information/knowledge is shared between the two parts? If it's a relevantly high percentage you may as well couple them because they are already on the domain level. This also is affine to Larmans' GRASP definition of Information Expert.

More about this here.

0
user270576 On

First, make sure that you're talking about tight coupling between CountryService and CountyService, not a tight coupling between your controller and services.

The example you gave has tightly coupled services and controller, which is never a good thing. A clean controller would accept a service interface in its constructor, not do a new on a concrete implementation.

As to whether or not to combine CountryService and CountyService into a CombinedService, the decision is simple:

  • keep them separate if you have at least one client that uses only one of them, and not the other
  • press them together is all clients use them in combination