0

I saw a code that is used in webapis .net core having. Since this class is created at one time. So how we can guarantee that multiple calls are isolated. Is this right approach. What are the problems here?.

Because of one api web request GetLocation was called with id =6 and some other values for _order object and for another api web request GetLocation was called with id =9.It happen at same time. So are these calls to method are isolated?

I'm not talking about DI or other separation

public static class Common
{
        
        public static Location GetLocation(long id, Order _order)
        {

        -- We create instance of our business classes and Data access layer
        --Inside here Database queries and buisness logic
        -- 
        }
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
user641812
  • 335
  • 5
  • 19
  • _"how we can guarantee that multiple calls are isolated."_ It depends on what do you mean by "calls being isolated" and actual implementation of `GetLocation`. – Guru Stron Mar 04 '21 at 08:21
  • As for this being right approach - the common pattern is to isolate this logic in some class implementing some interface and use this interface via [DI](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0) in your controllers. Still is it right or not can be debatable question. – Guru Stron Mar 04 '21 at 08:23
  • @GuruStron Please check I edit the question – user641812 Mar 04 '21 at 09:37
  • if there is no shared state used by this method then yes, this calls should be "isolated". – Guru Stron Mar 04 '21 at 11:59

1 Answers1

0

Main Query

In a hosted rest api can the common logic be encapsulated as static method, which is a shared method. Will it cause a trouble for multiple concurrent requests

Conditional Yes, this code is fine

A method whether static or non-static, is just a set of instructions / logic, which needs to executed. It doesn't have a memory of its own, it will be an issue only if there's a static / shared variable accessed in an unsafe manner without a lock and mutex, then it can lead to race condition / data corruption. Only thing is static method is loaded during initial class load and doesn't need an object to access but a class name. Using static method is though generally an anti pattern, its doesn't work with dependency injection, mocking frameworks and unit testing

In your case

You seem you be creating local variable to execute the business / data logic, which shall be fine. In fact shared variables need to be secured even in a non static method.

I am not a big fan of static method / static variables, since they can get embroiled in trouble easily with introduction of shared variable at later time and unsafe access by multiple threads / requests. I would recommend for a better design for the future extensibility and integration, convert to a non static method.

Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74