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

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 provided a too