Why is the use of Dynamic something to be avoided?

Asked

Viewed 936 times

17

My company works with development, it is a company practice that all codes made are reviewed by another person before they are approved in pull request.

Usually my codes have only a few details to change, but this last time the reviewer commented on a code snippet where I used dynamic to assign the type of return in the method claiming that this is a bad practice and would not accept that PR so.

In the specific example it was in a method that could receive as many numbers as strings, concatenating the result in cases of string or summing in cases of numbers, so the output had kind that depended on the type of input.

So I got three questions:

  • Because the use of dynamic is considered a practice to be avoided?
  • There is something that can replace the use with the same effect?
  • Which case where the use of dynamic it is necessary?
  • 1
  • What was the use of Dynamic in your code?

  • @Leolonghi was in a method that could take both numbers and strings, concatenating the result in string cases or summing in number cases, so the output must have been something that was changeable.

  • 2

    @Peace this your method already seems to me a anti-pattern

  • @Tobiasmesquita do not know what is an anti-pattern, I will look for

  • 1

    interesting, I don’t know c#, but after looking at the answers below, I come to the conclusion that Dynamics is comparable to a javascript Feature where you can make an object without properties (var a = {}) and assign properties at runtime by making the.property or the['property']. From an object-oriented point of view, this is bad, because we’re assuming that an object is not typed and this kind of forces another programmer to have to read an entire piece of code to try to understand the definition of an object (and is still susceptible to misunderstandings).

  • 1

    @Paz https://answall.com/q/189442/101 I tried to answer as completely as possible, but I don’t know why people aren’t seeing this. there is something wrong or missing in my answer?

  • @bigown is much more complete than the answers I found on the web, in fact it seems to me a compiled of everything I found, really exceptional. + 1

  • @wryel 1) Your comparison with Javascript is mistaken and would be more comparable to "anonymous" types. JS has dynamic typing, the correct comparison would be with the variables and behavior of the objects. 2) The object is typed as dynamic, the value of the object that has different types.

    1. The code of a program must be written legibly, but favoring the programmer (and his probable incompetence) over the quality/result program (the result of the code) is a serious error! The program must be understandable to facilitate the maintenance of those qualified to do so. If the functionality was introduced, it is because it was necessary for certain objectives.
  • Imagine deserializing a polymorphic JSON without Dynamic.

  • @Edney but then we couldn’t use an anonymous Object?

  • Also, normally this restriction is an administrative issue, strong typing ensures that there will be no type error, since the code. In production it is undesirable to depend on Dynamic, but for debugging and development (when you have a more controlled environment) it is a very useful resource. Not to mention that Dynamic generates additional type resolution processing. I had teachers who condemned the use of goto, many see goto and already say it is spaghetti code, in c# it is difficult to make tail recursion without goto, it is more or less the same thing.

Show 9 more comments

4 answers

23


Never accept something that says a practice is good or bad, it serves nothing but for the person who said "impose" your will. If the person explains why it ceases to be a mere practice and becomes relevant information for you to make better decisions.

Because the use of Dynamic is considered a practice to be avoided?

It is not a bad practice, it should be used where it is needed. It should not be used where there is another better solution, as all language mechanisms.

dynamic basically turns off type checking and it’s your problem to access existing members in the object, if that’s what you need, use it.

Important additional reading. And also.

There is something that can replace the use with the same effect?

Depends on what you need. Identical effect no.

  • There are cases that can be used a object instead, generalizes the type, but does not turn off the type check, so you can only access the object, even if the object has other members. If you want to access these members you must make a cast. Not interesting in most cases, but useful in some rare cases.

  • Can use Generics (concept). Most of what you think about dynamic can be better solved with this mechanism much better.

  • If the only thing you want is not to type the data type then just use the var.

  • Use a Dictionary, syntax may not be the nicest, but it’s essentially the same semantics as dynamic gives and in several cases it becomes clearer what is doing.

  • Likely solution to your case: If it is a parameter of a method that can work with unrelated types you should use overloading and have different methods for different operations.

    From the comments seems to be the case. If it is the return, as there is no overload in this case have to create a method with a different name. If it returns different types it means that the methods are different. If it has if within the method to decide what to do, surely the solution is to create an overload of the method.

  • If you really just want to be able to receive objects from the same hierarchy it might be useful to just use polymorphism.

  • There are crazier solutions I won’t even mention.

Codes showing this.

Where the use of Dynamic is needed?

Whenever you have no control over the structure of the object.

It was created primarily for interoperability with external applications and codes such as WITH and other "dynamic" languages running on CLR.

Or it is used for objects that need to be structured (not only created) at runtime, for example creating a class based on a database table that you don’t know about (practical example). Another common example is to receive a JSON that you don’t know how it will come (practical example). But if you know the structure then you have no reason to use.

Another practical example.

It is not about taste, it is about need. In a static language it is not idiomatic to leave dynamic typing. Abuse of dynamic is something considered bad in C#. Use where is the best solution no problem.

  • 8

    "Never accept something that says a practice is good or bad, it serves nothing but for the person to "impose" his will. If one explains why it is no longer a mere practice, it becomes relevant information for you to make better decisions." I’ve seen many, many developers talk about "nuncas" and "evites" without knowing why besides "because it’s bad practice". It’s the famous pirate parrots.

19

Basically, it should not be avoided. You have to know as use and when wear. This story of being "good practice" or "bad practice" is, mostly, a trick used to impose rules without having to base what you’re saying.

Because the use of dynamic is considered a practice to be avoided?

Only those who told you this can answer this question. But it is very likely because, using dynamic, everything is solved at runtime and not compilation, so it is much easier to do some nonsense and end up breaking the execution of the application.

Switching kids, you simply "throw away" one of the great advantages of static languages which is to know beforehand all the (possible) existing members of an object.

A small example:

dynamic pessoa = new { Nome = "jbueno" };
var n = pessoa.nome;

This code compiles normally, but bursts an error at runtime because the property nome does not exist in pessoa.

There is something that can replace the use with the same effect?

If by "effect" you mean dynamism: the answer is no. And if this is really necessary I would even tell you that you’re probably using the wrong language.

For other cases it is possible to give you some tips knowing the real need. Citing all possibilities is unfeasible.

Which case where the use of dynamic it is necessary?

It depends a little. It is necessary whenever you cannot know beforehand the structure of the object.

A real example would be to request a webservice whose return may have two completely different structures.

It is very likely that there are other cases where it is most useful. I find it difficult that the creation of this resource has been to solve cases like this example.

{ "sucesso": "true" };
{ "erro": "Algo deu errado" };
  • 2

    Can you explain why downvote so I can fix the answer?

  • 4

    The author of the noted negative could clarify the reason?

  • @Andrefigueiredo I think it was for no reason at all. Anyway, I tried to revise the answer and found nothing wrong. If you find anything you can let me know.

  • your examples would be appropriate for the use of "Anonymous", since they are unnamed objects.

  • @Andrefigueiredo I don’t understand. What do you mean by "Anonymous"? Anonymous types can only be created at development time.

  • For that very reason, dynamic pessoa = new { Nome = "jbueno" }; would not be a good use for your already quoted compilation error, which would be caught if it were defined as var pessoa = ..., since as far as the example goes, you don’t need it as dynamic for interoperability.

  • I would like to record that your reply was extraordinary, but the reply of the bigown user was chosen as correct by including the solution for my case as well. Thank you so much for your help!

  • 1

    Quiet. I didn’t try to solve your problem because I don’t know what it is.

Show 4 more comments

8

Asking why a feature is something to be avoided is like asking why the use of a tool should be avoided. And you’ll never hear anyone ask you something like "why should I avoid using star key".

The use of a feature is only a bad practice when it is used as the right solution to the wrong problem, and vice versa.

In your case, it seems to me from the comments that you want to use the dynamic to vary the return format of a method, according to the input. This is bad practice because:

  • ensures that every new type of feedback you have to deal with increases the complexity of the code and its analysis;
  • C# is a strongly typed language - but when using dynamic as you propose, you create a point in the system in which the determination of a type becomes difficult.

Talk to your reviewer and try to understand his vision, because he may still have a different understanding of the understanding of each person who answers here.

7

More a different perception.

By its nature the dynamic can be used for purposes other than your goal. So it is bad practice to use it when there is clearly a better alternative available. And what is the "best alternative"? That’s where prohibition comes in "it’s bad practice to use it".

But because the dynamic does it exist then? It is "one more" mess of . NET team?

The answer begins to be drawn once you know the type dynamic was introduced in the. NET 4.0 upgrade package. More precisely, as part of Dynamic Language Runtime (DLR).

Well, then it was introduced in a late version of . NET, so it’s not something legacy. Definitely to supply something. Here comes the old presumption that we must have good arguments to get into a big fight.

The guy dynamic overcome the lack/difficulty of . NET interoperability and simplify complex codes, among them:

  • Interoperability with implementations of several dynamic languages in . NET (Iron), such as Ironruby, Ironpython and Ironscheme, although they are abandoned or outdated at the present time;

  • Interoperability with objects WITH, how to omit multiple type conversions and passing empty parameters (Missingvalue) - ex.: Office libraries;

  • Handling Complex Types without creating multiple custom classes, such as XML and JSON. Ex.:

    public getFullName(String json){
        dynamic data = JObject.Parse(json);
    
        return String.Join(" ", new string[] {
            data.results.info.name.first, data.results.info.name.last
        });
    }
    
  • Alternative to the use of Reflections complexes.

  • As return or function parameters, where polymorphism does not apply.


But it’s good to note that he should be avoided in several cases, the most common being:

  • conversion leak between data types;
  • conversion leakage from/to reusable or business-relevant classes;
  • alternative to polymorphisms, mainly to unify overload methods;
  • alternative to static type variables, strongly typed, solved at compile time, but not of implicit type or unnamed types, i.e., all that is not declared as <tipo> <nome_var>;, mainly replacing anonymous types (var a = {"b": 1}; -> dynamic a = {"b": 1}).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.