0

I have just made a small online CAD demo for fun and learning. It is working perfectly for my intentions, but now I want to improve the code and I'm not sure of how to convert the current function-oriented code to Object Oriented. This is a small part of the code I have so far:

// DATA
var lines = [[]];
var circles = [{}];
var rectangles = [{}];

// Drawing functions
function drawLine(from, to){}
function drawCircle(center, radius){}
function drawRectangle(from, size){}

// Adding elements to the render chain
function addLine(e){}
function addCircle(e){}
function addRectangle(e){}

To get it Object Oriented, I can see two different ways. The first one is to group them by domain. This way there are many functions that can be reused within each of the classes:

var lines = [[]];
...

var draw = function(){
  var all() = function(){}
  var lines() = function(){}
  var circles() = function(){}
  var rectangles() = function(){}
  }

var add = function(){ ... }
...

The other one is to group them by type. This is the way I've read before about OO, since it's a representation of real world models and it's much more intuitive. The best part is that you have all the parts for the rectangle in the same small piece of code:

var rectangle = function(){
  var x, y, width, height;
  var draw = function(){}
  var add = function(){}
  }
...

Which one follows closer the best OO patterns?

Francisco Presencia
  • 8,732
  • 6
  • 46
  • 90
  • 2
    Shapes are things. Verbs are what those things do. Objects should be things that have verbs, not the other way around. – Niet the Dark Absol Oct 23 '14 at 12:52
  • What's the motive to make it object-oriented? What does that give you over what you have working now? – Mike Perrenoud Oct 23 '14 at 12:55
  • Javascript is not an object oriented language – meda Oct 23 '14 at 12:56
  • maybe the following answer can help: http://stackoverflow.com/a/16063711/1641941 – HMR Oct 23 '14 at 13:57
  • @NiettheDarkAbsol that's the answer I wanted, thank you. However, doesn't that go against MVC also? I mean, I could call it `painter.drawLines` instead of `draw.lines`, reversing the logic of it. – Francisco Presencia Oct 23 '14 at 17:47
  • @MichaelPerrenoud to put code together in a manner that is easier to understand by others and the future me. It also allows me to organize it for whenever it grows, so it doesn't become an entangled mess. – Francisco Presencia Oct 23 '14 at 17:49

1 Answers1

0

Caution, here, your methods are private:

var draw = function(){};
var add = function(){};

To make them public:

this.draw = function(){};
this.add = function(){};

Note: to respect strict pattern, ; is needed after a var set.

Else you can edit the prototype (better):

function Rectangle() {
  var x, y, width, height;
}
Rectangle.prototype.draw = function ();
KyleK
  • 4,643
  • 17
  • 33