Showing posts with label inheritance. Show all posts
Showing posts with label inheritance. Show all posts

Monday, September 15, 2014

Why Must I Be A Programmer in Love (with Inheritance)?


Why do I hate code inheritance so much? Possibly because no matter how much I pretend to hate it, it still seems to be my first instinct for extending class behavior. Which only makes me hate it more. Or at least pretend to.

Tonight's case in point comes from an unlikely source: the Karma configuration for one of the chapter projects in Patterns in Polymer. I am (slowly) working through each chapter standardizing on the dependencies and generated structure provided by eee-polmer-tests. One of the peer dependencies of eee-polymer-tests is Karma and eee-polymer-tests is kind enough to include a file with common configuration options.

I use those common configuration options in each Polymer project with a karma.conf.js that looks like:
module.exports = function(config) {
  var common = require('./node_modules/eee-polymer-tests/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    // Override common settings here...
  }));
};
OK, this is not classical class inheritance. This is typical JavaScript prototypical inheritance. My problem remains the same. I see a problem and I want to solve it by putting junk in the object doing the extending. Worse, once I start down that road, I begin inventing ways to make the inheritance smart.

While converting some old tests over to this new approach, I realized that I was missing two things: the html2js Karma preprocessor and the inclusion of HTML fixtures in the configuration. The fix is simple enough:
module.exports = function(config) {
  var common = require('./node_modules/eee-polymer-tests/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    // Override common settings here...
    preprocessors: {
      'test/*.html': 'html2js'
    },

    files: [
      'test/PolymerSetup.js',
      {pattern: 'elements/**', included: false, served: true},
      {pattern: 'bower_components/**', included: false, served: true},
      'test/**/*Spec.js',
      'test/*.html'
    ]

  }));
};
I have added the html2js preprocessor (I am also required to npm install karma-html2js-preprocessor --save-dev). I have copied the list of files from eee-polymer-test's common Karma configuration and added the test/*.html fixtures to the list.

And this is enough to trigger my Pavlovian inheritance response: “I should add preprocessors by default, I should change the mixin_common_opts() so that I can add the one entry to the list rather than copying and pasting, I should support special attribute that are added to existing values instead of overwriting them.”

Maybe this is why inheritance is so insidious. Because each of those things is small enough that they make sense. I would not be violating YAGNI—I would use them immediately. Each would legitimately solve a problem for me. So why not just give in? Why not just implement the configuration like this and be done with it?

There are at least two reasons. The first is a nagging sense that I would be in violation of POLS—that I (or someone else using this code) would find the inheritance confusing or non-obvious. The second reason is that I am jumping to implementation without really considering the problem.

And here's the problem. Here's my dirty little secret. I don't use fixtures in my Polymer testing. In my very first Polymer tests, I used them mostly as I was trying to understand how best to approach testing. The Polymer fixtures worked, but since then I have mostly dynamically created the elements right in my tests. So maybe this is a case of YAGNI after all. But it's not that I don't need the code—this is a situation where I don't need the solution.

As a nod to my struggles, I will likely add the list of files from the common configuration into the generated karma.conf.js as a comment. That way, if I do run into this again, I will have all of the information that I need right in the configuration file.

In the end, I nearly gave into my seemingly natural reflex to add some form of inheritance to everything. Thankfully, I was able to listen to my better nature. Maybe someday that will be my first instinct.


Day #184

Monday, May 27, 2013

Templates, Strategies, Factories and Dart

‹prev | My Chain | next›

I don't remember where I saw it, but I seem to recall that windowing systems are one of the few times in which regular inheritance actually works. Well, the dialog classes in the Dart version of the ICE Code Editor are kinda like a windowing system. Maybe regular inheritance will work with them...

All of the dialogs classes follow a similar structure. The constructor accepts an instance of the full-screen version of the editor and sets the same three instance variables. Each dialog has a menu item getter named el. This el is not the DOM element that contains the dialog, rather it is the menu item element that is inserted in the main menu. After that, there is a method that opens the dialog and one or more subsequent methods that perform an action for the dialog.

The OpenDialog class, which provides a dialog for opening existing projects, looks like:
class OpenDialog {
  var parent, ice, store;

  OpenDialog(Full full) {
    parent = full.el;
    ice = full.ice;
    store = full.store;
  }

  Element get el {
    return new Element.html('<li>Open</li>')
      ..onClick.listen((e)=> _hideMenu())
      ..onClick.listen((e)=> _openProjectsMenu());
  }

  _openProjectsMenu() { /* ... */ }

  _openProject(title) { /* ... */ }
}
OK, maybe this isn't the prototypical GUI windowing system, but it still seems worth exploring inheritance.

I can extract the common elements into a base class:
class Dialog {
  var parent, ice, store;

  Dialog(Full full) {
    parent = full.el;
    ice = full.ice;
    store = full.store;
  }

  Element get el {
    return new Element.html('<li>$menuLabel</li>')
      ..onClick.listen((e)=> _hideMenu())
      ..onClick.listen((e)=> open());
  }

  String get menuLabel;
  void open();
}
This forces me to define the menuLabel and open() methods in any of the sub-classes:
class OpenDialog extends Dialog {
  OpenDialog(full): super(full);

  get menuLabel => "Open";

  open() { /* ... */ }

  _openProject(title) { /* ... */ }
}
This saves me a bit of work and provides a nice template for all of the dialog classes in ICE. But the template pattern of inheritance is not the end-all be-all of object oriented programming.

One of the problems with this approach is that these dialogs are performing two functions: the menu item and the subsequent dialog that opens. An alternate approach would be to create a MenuItem class:
class MenuItem {
  var dialog;
  MenuItem(this.dialog);
  Element get el {
    return new Element.html('<li>${dialog.name}</li>')
      ..onClick.listen((e)=> _hideMenu())
      ..onClick.listen((e)=> dialog.open());
  }
}
A MenuItem is then solely responsible for serving as the thing that opens a dialog. The dialog, in turn, is then solely responsible for being a dialog:
class OpenDialog {
  String name = "Open";

  var parent, ice, store;
  OpenDialog(Full full) { /* ... */ }

  open() { /* ... */ }
  _openProject(title) { /* ... */ }
}
To put this all together, I have to inject the dialog into the menu item:
new MenuItem(new OpenDialog(this)).el;
This is a little more verbose than the original, combined menu item and dialog:
new OpenDialog(this).el;
Then again, this is the benefit of helper methods:
get _openDialog=> new MenuItem(new OpenDialog(this)).el;
This does have the advantage of being explicit about the menu item's strategy. In this case, it is perfectly clear that the strategy for this particular menu item is to create an open project dialog. I really like that approach.

That said, Dart affords me a few other options. I could add a factory constructor to the OpenDialog class:
class OpenDialog {
  String name = "Open";

  var parent, ice, store;
  OpenDialog(Full full) { /* ... */ }
  factory OpenDialog.menu_item(full) {
    var dialog = new OpenDialog(full);
    return new MenuItem(dialog);
  }

  open() { /* ... */ }
  _openProject(title) { /* ... */ }
}
This would make constructing objects a little more compact:
get _openDialog=> new OpenDialog.menu_item(this).el;
Now that I think about it, I could even return the DOM Element from a factory:
class OpenDialog {
  String name = "Open";

  var parent, ice, store;
  OpenDialog(Full full) { /* ... */ }
  factory OpenDialog.menu_element(full) {
    var dialog = new OpenDialog(full),
        menu_item = new MenuItem(dialog);
    return menu_item.el;
  }

  open() { /* ... */ }
  _openProject(title) { /* ... */ }
}
Then constructing a menu with a specific dialog strategy becomes:
get _openDialog=> new OpenDialog.menu_element(this);
I really like that. It is nice and compact. It conveys the meaning well. It also keeps the menu item and dialog responsibilities separate.

That said, there are drawbacks. If I opt for a Dialog template that really is just a dialog template, then I would need to define this factory constructor in each concrete class. I will sleep on the ultimate decision, but it is nice to have so many palatable options available to me.


Day #764

Saturday, February 11, 2012

Inheritance Grab Bag in Dart

‹prev | My Chain | next›

I am a bit annoyed that there does not seem to be a way to pass a class name to a function in Dart. Even so, it is not a huge hardship. Instead of telling my comic book collection's super class the model class to use when creating records, I have to supply a function that creates the models:
class Comics extends HipsterCollection {
  Comics() {
    url = '/comics';
    model = (attrs) => new ComicBook(attrs);

    on = new CollectionEvents();
    models = [];
  }
}
Like I said, not a big. I would prefer to be able to treat the class name as an object that can be passed:
model = ComicBook;
Which the super class could use to construct object as:
class HipsterCollection {
  // ...
  modelMake(attrs) {
    new model(attrs);
  } 
  // ...
}
But neither passing a reference to a class works nor does trying to treat a variable as a class. At least not in Dart.

No matter, perhaps I can do other things to clean up my sub-class definition. First of all, the definition of the on and models properties surely does not need to be done in every sub-class of HipsterCollection. The first thing to try is defining a constructor in my super class:
class HipsterCollection<M extends HipsterModel> {
  var url, on, model;
  List<M> models;

  HipsterCollection() {
    print("[HipsterCollection]");
    on = new CollectionEvents();
    models = <M>[];
  }
  // ...
}
(I am retaining the generics type information from yesterday, if for no other reason than documentation).

And that works. Not only does my collection still populate, but my super-class-only print("[HipsterCollection]"); statement displays in the console output:


I was unsure that this would work. I more-or-less expected that, since my Comics sub-class defined its own constructor, that the super class constructor would not be evaluated. I do not see anything in the constructor section of the language spec about the subject, so I try out a simple case like:
class A {
  A() { print("A"); }
}

class B extends A {
  B() { print("B"); }
}

class C extends B {
  C() { print("C"); }
  C.special(c) { print(c); }
}

main() {
  var c = new C();
  print("==");
  var c1 = new C.special("whee!");
}
(try.dartlang.org)

In both cases, the super-class contructors in C's ancestor chain are invoked, so this seems at least consistent behavior:
A
B
C
==
A
B
whee!
With the on and models property definitions safely back in the HipsterCollection base class constructor, my Comics collection is looking down right sparse:
class Comics extends HipsterCollection {
  Comics() {
    url = '/comics';
    model = (attrs) => new ComicBook(attrs);
  }
}
Hrm... since I cannot assign a class to the model attribute like I can in Backbone.js, there is no need to define that model function constructor as a property or to do so inside the constructor. It makes more sense to define that as a static class method:
class Comics extends HipsterCollection {
  Comics() {
    url = '/comics';
  }

  static modelMaker(attrs) {
    return new ComicBook(attrs);
  }
}
Only that does not seem to work. Back in the base class, I try:
class HipsterCollection<M extends HipsterModel> {
  // ...
  static modelMaker(attrs) {
    print("[super.modelMaker]");
    return null;
  }
  // ...
  _handleOnLoad(event) {
    var request = event.target
      , list = JSON.parse(request.responseText);

    list.forEach((attrs) {
      models.add(modelMaker(attrs));
    });

    on.load.dispatch(new CollectionEvent('load', this));
  }
}
But the only messages that I see are from the static method in the super class. Reading through the spec, I see this is intentional:
Inheritance of static methods has little utility in Dart. Static methods cannot be overridden... Experience shows that developers are confused by the idea of inherited methods that are not instance methods.
Sigh. It sure is hard for a fella to communicate a constructor class from sub-class to super-class in Dart. In the end, I settle for an instance method:
class Comics extends HipsterCollection {
  Comics() {
    url = '/comics';
  }

  modelMaker(attrs) => new ComicBook(attrs);
}
Back in the HipsterCollection base class, I then declare this method as abstract:
class HipsterCollection<M extends HipsterModel> {
  // ...
  abstract M modelMaker(attrs);
  // ...
  _handleOnLoad(event) {
    var request = event.target
      , list = JSON.parse(request.responseText);

    list.forEach((attrs) {
      models.add(modelMaker(attrs));
    });

    on.load.dispatch(new CollectionEvent('load', this));
  }
}
I must admit it nice to have compile-time, or at least formal, mechanism to catch any method-not-defined-in-sub-class mistakes that I might make.

One last thing that could make the concrete class definition even smaller would be to define the url property in my sub-class definition rather than in the constructor:
class HipsterCollection<M extends HipsterModel> {
  var url, on;
  // ...
}

class Comics extends HipsterCollection {
  var url = '/comics';
  modelMaker(attrs) => new ComicBook(attrs);
}
Unfortunately, that does not work as I receive the following error:
Internal error: 'http://localhost:3000/scripts/Collections.Comics.dart': Error: line 7 pos 7: field 'url' of class 'Comics' conflicts with instance member 'url' of super class 'HipsterCollection'.

  var url = '/comics';
      ^
Hunh? Why is that a "field"? I really intended it to be the instance member. Trying this out in the most simple case seems to actually work:
class A {
  var foo;
}

class B extends A {
  var foo = 'bar';
}

main() {
  var b = new B();
  print(b.foo);
}
(try.dartlang.org)

That works just fine, printing out the value of "foo" from the sub-class. Reading through the spec proves of little help. It seems to use field and instance variable more-or-less interchangeably. It does distinguish in places between field and getter, but there is a difference between instance variable and getter as well. There is no discussion in the spec on redefining an instance variable in a sub-class, though the super-class's instance variables are definitely available to the sub-class:
The instance variables of a class C are those instance variables declared by C and the instance variables inherited by C from its superclass,
Since Dartium and try.dartlang.org are unable to agree, and since redefining does not work in Dartium, I am forced to stick with assigning the instance variable in the constructor. Unless...

I do not expect this work, but what if I define a getter in the sub-class?
class Comics extends HipsterCollection {
  get url() => '/comics';
  modelMaker(attrs) => new ComicBook(attrs);
}
I am somewhat surprised, but that does work. It even works in the simple try.dartlang.org case.

I suppose that I can convince myself that this ought to work. In Dart, instance variables have implicit getters/setters. Therefore, I ought to be able to override those getters and setters. I thought I came across something in the spec that prohibited this, but it was probably just something like: "It is a compile-time error if a class has both a getter and a method with the same name". That does not apply in this case because I am overriding the implicit getter with an explicit getter.

This is a nice, compact format, but the problem, of course is that my url= setter would update the value of the url instance variable but have no effect on the url getter which is now hard-coded. In this case, this is not a big deal because the URL in a client-side MVC framework rarely needs to change. So, back in the base class, I again have an abstract method, this time a getter:
class HipsterCollection<M extends HipsterModel> {
  var on;
  List<M> models;

  abstract M modelMaker(attrs);
  abstract String get url();
  // ...
}

class Comics extends HipsterCollection {
  get url() => '/comics';
  modelMaker(attrs) => new ComicBook(attrs);
}
That will work just fine.

In the case where I need an implicit getter and setter, I will have to stick with assigning the instance variable in the constructor. Or hope that the noted behavior is a bug that will eventually be addressed.

That was quite the tour of the world on inheritance in Dart. At this point, I think I have a good handle on it. Well, maybe not that good, but hopefully enough to justify moving on to another topic tomorrow.


Day #293

Wednesday, February 8, 2012

Stupid Sub-Class Tricks in Dart

‹prev | My Chain | next›

I have model, view and collection base classes factored out of my Dart web application. I have a minor issue that I would like to see if I can resolve tonight. When I add a model to my collection, I would like to have it show up in the UI. Currently I have the add-from-form bit working, but I have to refresh the page ot actually see the new record.

In order for this to work, I will need a create() method on the collection class. The create() method will create a new record and add it to the collection. Adding it to the collection will, in turn, generate an "add" event for which the collection view can listen and do its thing. I have some of the parts necessary for this, but not all.

First up, the create() method:
class HipsterCollection {
  // ...
  create(attrs) {
    var new_model = model(attrs);
    new_model.save(callback:(event) {
      this.add(new_model);
    });
  }
  // ...
}
Nothing fancy there. I create a new model with the model function constructor, then save it. My model class already supports an optional callback that is used here to add the newly created model to the collection.

As for the add() method, I add the model to the models property (which is a simple array) and then dispatch an 'add' event:
class HipsterCollection {
  // ...
  add(model) {
    models.add(model);
    on.add.
      dispatch(new CollectionEvent('add', this, model:model));
  }
  // ...
}
With that, I need to modify the view class to allow a collection to be injected into it. I start in the view base class:
class HipsterView {
  var model, el, collection;

  HipsterView([this.model, this.el, this.collection]) {
    if (this.el is String) this.el = document.query(this.el);
    this._initialize();
  }
  // ...
}
Here I am making use of Dart's very nice "generative constructors" with optional parameters. The constructor HipsterView([this.model, this.el, this.collection]) does just what one would expect: assign this.model if a model parameter is supplied, assign this.el if el is supplied, etc. That is, I could assign the model and collection properties of a HipsterView object with the following:
new HipsterView(model: model_object, collection: collection_object);
That is definitely nice. Except I do not want to create a HipsterView, I want to create a object that sub-classes a HipsterView like the AddComic view:
#import('HipsterView.dart');

class AddComic extends HipsterView {
  // ...
}
Back in my main() entry point, I do this like this:
#import('Collections.Comics.dart', prefix: 'Collections');
#import('Views.Comics.dart', prefix: 'ViewsFIXME01');
#import('Views.AddComic.dart', prefix: 'ViewsFIXME02');

main() {

  var my_comics_collection = new Collections.Comics()
    , comics_view = new ViewsFIXME01.Comics(
        el:'#comics-list',
        collection: my_comics_collection
      );

  my_comics_collection.fetch();

  new ViewsFIXME02.AddComic(
    el:'#add-comic',
    collection: my_comics_collection
  );
}
(the ViewsFIXME01 and ViewsFIXME02 prefixes are a reminder to fix these once a Dart bug has been fixed).

Unfortunately, this does not work. When I load the page, I get the following error:
Internal error: 'http://localhost:3000/scripts/main.dart': Error: line 15 pos 3: invalid arguments passed to constructor 'AddComic' for class 'AddComic'
  new ViewsFIXME02.AddComic(
  ^
Ugh. It seems that I cannot rely on the constructor definition in my base class. Instead, I have to reproduce the same constructor signature in my sub-class:
class AddComic extends HipsterView {
  AddComic([collection, model, el]): super(collection:collection, model:model, el:el);
  // ...
}
Ew. I am not a fan of that. It seems that, if I do not define a constructor in my sub-class, all that Dart does for me is forward an empty sub-class constructor to super() (without arguments). If I want anything more sophisticated, I have to manually transcribe the parameters list like this.

Unfortunately, my trouble does not end there. In my sub-class, I need to perform some post-instantiation initialization:
class AddComic extends HipsterView {
  AddComic([collection, model, el]): super(collection:collection, model:model, el:el);

  void _initialize() {
    print("sub initialize");
    el.on.click.add(_toggle_form);
  }
  // ...
}
In my base class, I had defined my constructor to invoke the _initialize() method:
class HipsterView {
  var model, el, collection;

  HipsterView([this.model, this.el, this.collection]) {
    if (this.el is String) this.el = document.query(this.el);
    print(this.el);
    this._initialize();
  }

  void _initialize() { print("super initialize"); }
  // ...
}
But when I load the page, I am not seeing my "sub initialize" message—I only see "super initialize". I can get this working by declaring _initialize() as an abstract method and removing the function body, but then I have to define _initialize() in all sub-classes. I want this to be an optional thing.

It seems crazy that I cannot access the _initialize() method from the super class. And, after much fiddling, I find that I can access the sub-class's method, but only if it is public. That is, if I remove the underscore from the method name:
class HipsterView {
  var model, el, collection;

  HipsterView([this.model, this.el, this.collection]) {
    if (this.el is String) this.el = document.query(this.el);
    print(this.el);
    this.post_initialize();
  }

  void post_initialize() { print("super initialize"); }
  // ....
}
If I then define post_initialize() in the sub-class:
class AddComic extends HipsterView {
  AddComic([collection, model, el]): super(collection:collection, model:model, el:el);

  void post_initialize() {
    print("sub initialize");
    el.on.click.add(_toggle_form);
  }
  // ...
}
Then I finally see the "sub initialize" message. More importantly, on-click handler is again working.

I think that is enough for one night. I hope to complete the dynamic UI add tomorrow. It was a bit rough today, but I got myself pretty close. I am none too sure about Dart's requirement to explicitly support the super class's parameters. I am definitely not a fan of not being able to access an over-ridden private method from the super class (this seems like a bug). I am a fan of the optional generative constructor format. And, since I made progress in my MVC framework, I will count tonight as a win.


Day #290