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

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.51EF 6.0.2VS2013
It seems that there …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.
publ…