Skip to main content

Could this be a good case when to use 'params'

In urma cu cateva saptamani am discutat putin despre keyword-ul params si cautam locuri unde acesta ar putea sa fie folosit cu un scop clar, nu doar de dragul de a il folosi. Zilele acestea am gasit un caz unde acesta ar putea sa isi gaseasca locul.
Sa presupunem ca scriem o metoda care genereaza semnatura unei metode pe baza. Numarul de parametrii a unei metode poate sa fie variat de la 1 la n si chiar 0. Din aceasta cauza pentru a putea sa acoperim cele doua cazuri ar fi nevoie sa avem ca si parametru o colectie de parametri care sa accepte sa fie si null.
public string GetMethodSignature(string methodName, List<object> parameters = null)
Acuma apar usoare probleme pentru cel care ne foloseste metoda. Pentru fiecare apel cand are unul sau mai multi parametri o sa fie nevoit sa creeze o lista de elemente.
myObj.GetMethodSignature( "FooAction" , new [] { param1 });
In acest caz, o implementare folosind params ne simplifica putin atat apelul cat si modul in care procesam datele:
public string GetMethodSignature(string methodName, params object[] parameters)
...
myObj.GetMethodSignature( "FooAction" , param1 );
myObj.GetMethodSignature( "FooActionNoParam");
Pentru cazul cand nu avem nici un parametru este de ajuns sa apelam metoda ca si mai sus, iar colectia noastra nu o sa aibe nici un element.
Cum vi se pare acest caz? Credeti ca in acest caz este folositor "params"?

Comments

  1. Depinde ce se intelege prin "metoda care genereaza semnatura unei metode pe baza" - daca e vorba de metode overloaded, acestea pot diferi nu doar prin numarul si numele parametrilor, ci si prin tipul lor - deci pot exista doua metode:
    FooAction(int a);
    FooAction(DateTime a);

    Altfel, varianta cu params e doar un mic sintactic sugar care usureaza munca programatorului - mai important mi se pare ca
    List parameters
    e destul de vag si nu sugereaza ce ar trebui pasat acolo fara a citi ceva documentatie/comments..

    In plus, daca in viitor cineva va vrea intr-o clasa derivata sa adauge un parametru intr-un overload al metodei respective, de genul:
    public string GetMethodSignature(string methodName, int newParam, params obj ect[] parameters)
    poate introduce un breaking change in codul existent.
    Deci as evita params intr-un framework/API public, dar no problems in interiorul unei aplicatii..

    ReplyDelete
    Replies
    1. Pe partea de breaking change in codul existent e un risc destul de mare daca expui o metoda in API ce foloseste params.
      Params in sine e un sintactic sugar, eu incercam sa vad poate sa fie util cu adevarat.
      parameters ar putea sa fie redenumit parametersMethodValue, poate asa ar fi mai usor de inteles ce reprezinta.

      Delete

Post a Comment

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...