Thursday, July 1, 2010

Is it logical to over-ride static members?

The Java language (or C#) does not allow static members of a class to be over-ridden. But what if there is a language that does?

Let us say that there is a class written in a hypothetical Java-like language
class DataSource{

  DataSource(Data data){
    this.data = data;
  }

  @override
  static Data getData(){
    return createFormData();
  }
  
  static <T extends Datasource> create(){
    Data data = getData();
    DataSource ds = new DataSource(data);
  }
}

Let us pretend that this language allows static members to be overridden
class GridDataSource
extends DataSource{
  GridDataSource(Data data){
    super(data);
  }

  @override
  static Data getData(){
    return createGridData();
  }
  
  static GridDataSource create(){
    Data data = getData();
    GridDataSource ds = new GridDataSource(data);
  }
}

You want a static method because you want it to be callable without instantiating the class, but you also want any derivative class to be expected to provide the method getData() as well as the factory method create(). For certain derivative classes you wish to over-ride getData() and for others you don't. Therefore, you need to consistently expect the method getData() to be present.

A so-called "OO purist" might say - this is not OO, redesign your algorithm to fit into OO constraints.

Forgive me a million times to be on the offensive - but first of all, who gets to be anointed an "OO purist" and secondly with what authority would such an anointed Chosen One pronounce that this isn't OO other than the few academic papers might have been read?

There should be absolutely nothing wrong with a programmer's preference as long as it is maintainable and extensible with the least of efforts. If a programmer finds this style of programming eases maintenance and extensibility - so be it. So, no debate about if this style of programming is good or bad.

The question to be answered is - is this logical or topologically sound?

At first purview, we could say that this is illogical.
  1. Since the addressability of static members depend on the extension of the class, why don't you just make them class members rather than static members?
    Wrong answer - the factory method has to be static and, therefore, any method it calls has to be static.
  2. The actual implemented class is not known until a class is instantiated.
    Wrong answer - that is due to the constraints of language's run-time architecture.
  3. We would have to implement virtual references in the language and that would defeat the purpose of efficiency of having static members.
    Wrong answer - the run-time efficiency of static members is a side effect/benefit. The main reason for having static members is to be able to address those members without class instantiation.
  4. Having virtual references designed to treat such a feature at run-time decreases run-time efficiency.
    Should the definition of OOP be constrained by the architecture of CPUs rather than linguistic topology? Why, processor makers could pander to virtualization, executable bit, etc and surely they could accommodate a little bit more? However, doesn't C# already have delegates? What about the planned implementation of closures in Java?

Such a feature is easily implemented with C# delegates, which would answer whether it is topologically possible to implement over-rideable static members. End of dispute.
class DataSource{

  delegate Data GetData();
  GetData getDataFuncton;

  // "static constructor" is run when class is loaded
  static DataSource(){
    getDataFuncton = new GetData(getData);
  }

  DataSource(Data data){
    this.data = data;
  }

  static Data getData(){
    return createFormData();
  }
  
  static <T extends Datasource> create(){
    Data data = getDataFuncton();
    DataSource ds = new DataSource(data);
  }
}

With this question settled, there should not be any more excuse not to allow contracting static members in an interface.

9 comments:

  1. if you feel in need of overriding a static method, i would say that your design is just poor.

    Actually in my world static methods are taboo. it has to be really a very good reason behind.

    Straightforward solutions could be the singleton pattern or even better the dependency injection pattern.

    ReplyDelete
  2. La Nike Air Max Mujer se ha convertido en una locura internacional durante mucho tiempo.
    En los últimos tiempos, muchas marcas han lanzado su colección de Camisetas Nba 2018.
    Hay tanto camisetas caras y camisetas baratas, especialmente la Camisetas Nba Baratas.
    Con el número creciente de fanáticos locos, la Camisetas Nba no solo está pensada para los jugadores.
    Las tiendas de deportes pueden querer Comprar Camisetas De Futbol.
    Para las tiendas, puede comprar Camisetas De Futbol Baratas de China y otros países a bajo precio.
    Estos Camisetas De Futbol Baratas están hechos a medida y diseñados para dar el mejor ajuste.
    La mejor forma de Comprar Camisetas De Futbol es buscar en nuestra auténtica tienda en línea.

    ReplyDelete
  3. Michael Kors Outlet Online was a huge success there and became very well known. The designer Kors then branched out into accessories including Michael Kors Handbags Clearance. He never lost focus on his American chic styling. Some of his most notable collections include the Michael Kors Totes, Michael Kors satchel and the Designer MK Outlet and Michael Kors Outlet Online Store.

    No one has to know that they are cheap Ray Ban Sale UK and no one will know unless you tell them. Each of the cheap designer Ray Ban Sunglasses Sale UK carries the signature brand on the lens to let you know that you do have authentic designer Cheap Ray Ban Sunglasses UK.

    tags: Cheap Oakley Sunglasses UK,MK Outlet

    ReplyDelete
  4. Ce sac cartable Michael Kors est si universel qu'il pourrait plaire à tout le monde. Dans cet article, je vais essayer de passer en revue les caractéristiques principales et les éléments qui distinguent ce sac à main des autres.

    tags:Bolsos Michael Kors Rebajas,Bolsos Michael Kors Baratos,Bolsos Michael Kors El Corte Ingles

    L’extérieur de ce fourre-tout Michael Kors est un cuir métallisé de laiton froncé et froncé. Si vous connaissez les sacs à main Michael Kors, vous savez que ce cuir sera doux et souple. Les deux grandes poignées supérieures sont attachées au sac avec quelques centimètres de chaînes dorées, puis les moitiés supérieures des bretelles présentent le même cuir couleur laiton.

    tags:Bolsos Michael Kors Baratos,Michael Kors Örhängen

    La diversité des couleurs et la taille utilisable de ce sac le rendent parfait pour un usage quotidien. Les poches intérieures ne manquent pas pour aider à garder les choses en ordre. Il y a des endroits parfaits pour votre téléphone ou votre Blackberry. Le zip top empêche les malfaiteurs de saisir votre sac dans un bar et aide également à contenir tout ce qui se trouve à l'intérieur lorsque vous courez pour créer ce train.

    tags:Windguru Longchamps,Longchamp Soldes Destockage,Pronote College Longchamp

    ReplyDelete