0

In the following code for a custom HttpClient, I found a method take takes an interface and writes to it as if it was an object with properties:

public async Task<T> GetAsync<T>(ICacheContext cacheContext = null) {
    try {
        T result = default(T);

        // check if value is cached
        if (cacheContext != null) {
            result = await GetResultFromCache<T>(cacheContext);        
            if (result != null) {
                cacheContext.IsDataFromCache = true;
                return result;
            }
        }

I'm a bit confused by cacheContext.IsDataFromCache = true;. Why would you set the property of an interface? Isn't that something you'd do to the object implementation of said interface?

8protons
  • 3,591
  • 5
  • 32
  • 67
  • 2
    `cacheContext` is an implementation of `ICacheContext` it is an object not just an interface – JSteward Nov 11 '20 at 01:07
  • 1
    `Isn't that something you'd do to the object implementation of said interface?` That is _literally_ what that code is doing. – mjwills Nov 11 '20 at 01:36

2 Answers2

1

Probably it receives an instance that implements ICacheContext as regards to polymorphism of OOP

for instance

ICacheContext cacheCtx = new CacheContextImpl()  // Class which implements ICacheContext
Chin Shuu
  • 51
  • 1
  • 2
  • 9
1

By referencing the interface instead of the concrete class, you can easily swap out implementations of your interface without having to change every method that references your object. In the code example, if there were three implementations of ICacheContext that all need the method, using the interface allows them to all use the same method. Otherwise you would need to create three GetAsync methods with a different signature for each implementation.

Another reason you would use the Interface in your method signature instead of the base class, is to enforce good coding practices - if the method only needs the ICacheContext properties of your base class, using the interface stops you from using other properties/methods of your implementation (maybe CacheContextImplementation.cs also handles logging or configs or something that you don't want handled in the 'GetAsync' method), restricting yourself to the interface forces you to be more OOP friendly.

Also, technically, the code isn't setting the property of the interface. It's setting the property of the implementation, using the mask of the interface.

Hope this helps, and makes sense

The Lemon
  • 1,211
  • 15
  • 26