Skip to main content

How should we treat virtual methods exposed in APIs

Cu cateva zile in urma mi s-a cerut sa investighez de ce nu functioneaza o aplicatie asa cum trebuia in urma unui upgrade de framework, iar cand am gasit cauza problemei am zis ca trebuie sa va zic si voua.
Un mic framework care era folosit definea o clasa de baza abstracta, care la randul ei continea cateva metode virtuale.
public abstract class FooBase
{
    public virtual void DoAction1()
    {
        ...
    }
    ...
}
Implementarea care era facuta in sismul nostru asta in felul urmator:
public class MyCustomFoo : FooBase
{
    ...
    public override void DoAction1()
    {
         // Some custom action
         ... 
    }
}
Problema la MyCustomFoo este ca metoda DoAction1() nu apeleaza metoda din clasa de baza. Asta nu ar fi nici o problema cat timp cel care a scris acest cod implementeaza aceasta functionalitate. Pe vechia versiune de framework, acest lucru era in regula, dar noua versiune schimba usor o functionalitate si are nevoie neaparat ca metoda din clasa de baza sa fie apelata.
Intrebarea care a aparut aici in cazul meu a fost: Cine este de vina?
Din unele puncte de vedere as spune ca dezvoltatorul care a implementat clasa MyCustomFoo. Acesta trebuie sa se asigure ca apeleaza si metoda din clasa de baza, pastrand vechia functionalitate.
Totodata metoda era marcata ca virtual, cea ce inseamna ca cel care marcato ca virtual permite persoanei care face ovveride sa schimbe modul de implementare a respectivei functionalitati. Dar sa nu uitam, ca in momentul in care face ovveride nu trebuie sa alterezi vechiul comportament.
Noua versiune de framework trebuia si i-a modificata in asa fel incat sa nu se altereze functionalitatea in nici un fel, dar unele modificari pot sa duca la unele schimbari si in clasele virtuale.
In acest caz noua versiune trebuie sa fie insotita si de un document cu modificarile la API care au fost facute.
Voi ce parere aveti? Intr-un caz de acest gen cine poarta vina este raspuzator pentru aceasta problema?

Partea a doua din aceasta discutie: http://vunvulearadu.blogspot.ro/2012/06/how-should-we-treat-virtual-methods.html.

Comments

  1. Cred ca ideea de "vina" nu isi are locul aici. Cind se face un design, se face in functie de ce anume se doreste in acel moment, nu ce s-ar putea schimba in viitor. Daca ceva se schimba, atunci este responsabilitatea celui care schimba sa modifice si designul.

    In cazul asta, metoda trebuie sa fie nevirtuala, ca sa execute mereu baza, dar care apeleaza in acea baza si o alta metoda care este virtuala. Patternul este deobicei sa termini numele unei astfel de metode in Override, deci DoAction1Override. Desigur, asta tine mai mult de code practices in cadrul proiectului.

    ReplyDelete
  2. Ca si Siderite eu consider ca e mai bine sa faci un DoSomethingCore drept virtual si restul codului DoSomething sa se execute indiferent de vointa clasei derivate. Pana la urma filosofia .NET e sa nu te bazezi pe buna intentie si atentia programatorilor ci sa te asiguri ca se face ce trebuie (vezi GC)

    ReplyDelete
    Replies
    1. Asta in cazul in care cei care expun API se gandesc la asta.
      Part 2 - http://vunvulearadu.blogspot.ro/2012/06/how-should-we-treat-virtual-methods.html

      Delete
  3. As zice ca daca era intr-adevar un 'framework' cel care a definit clasa de baza ar trebui sa se asigure ca a evidentiat foarte clar in documentatie (sau si mai bine printr-un naming fara ambiguitati) care e contractul care trebuie satisfacut de clasa respectiva si de cele derivate din ea - in felul asta cel ce face override va sti la ce se asteapta clientii acelei ierahii de clase.

    Intr-un framework odata stabilit acel contract va fi foarte greu de schimbat in viitor fara a introduce breaking changes (precum in exemplul de mai sus) - daca e doar ceva de uz intern, desigur nu mai e asa important.

    Intr-un framework, cand se face o metoda virtual, autorul trebuie sa se asigure ca cel ce face override ii e foarte clar ce se asteapta de la acel punct de extensibilitate - in astfel de cazuri cand functionalitatea din clasa de baza e "a must" se foloseste template method pattern, cum a zis si Andrei.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

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 …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…