Writing JavaScript according to SOLID

前端 未结 5 1486
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 20:25

Have any one used the SOLID programming principle (or any of it\'s parts) while developing JavaScript?

I\'ve just started up on reading on it but can\'t seem to find any

5条回答
  •  故里飘歌
    2021-01-29 20:52

    This presentation: SOLID JavaScript In A Wobbly (World Wide Web) by Derick Bailey demonstrates how to use SOLID programming principles while developing javascript.

    He explicitly addresses the issue of interfaces in javascript several times. In javascript, interfaces are more of a convention, so it's up to you how to define them. You can write an empty object definition (think of it like an abstract class or an interface). Or you can rely on documentation for your protocols/contracts.

    At a more conceptual level, an object's method signatures implicitly define it's interface, so in javascript you can often get by with "duck-typing" and still adhere to SOLID. (!) Here's an example of the "interface segregation principle" from the presentation that demonstrates this:

    // Copyright 2014 Muted Solutions, LLC, and freely distributable and re-usable under the MIT License
    
    // JavaScript has no interface construct ...
    // sooooooo..... use inheritance instead? o_O
    
    // Rectangle
    // ---------
    
    function Rectangle(){}
    
    Rectangle.prototype.area = function(){
      return this.height * this.width;
    };
    
    Rectangle.prototype.setHeight = function(height){
      this.height = height;
    };
    
    Rectangle.prototype.setWidth = function(width){
      this.width = width;
    };
    
    // Square
    // ------
    
    function Square(){}
    
    Square.prototype.area = function(){
      return this.size * this.size;
    };
    
    Square.prototype.setSize = function(size){
      this.height = size;
      this.width = size;
    };
    

    This code and all of the rest of the example code from the talk is posted on GitHub: https://github.com/derickbailey/solid-javascript

提交回复
热议问题