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(...

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see...

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provi...