How to organize objects and methods?

I guess this is a very broad topic and I dont expect any right answer, but I am not sure how to approach it.

I have followed many tutorias fulls of barking dogs and similar. But once I decided to start my very own projects I realized sometimes it is not really clear.
Obviously the methods and objects have to be designed depending on how they are going to interact with each other, but I am lost with so many posibilities…

For example, today I started writing a to-do app… I created a class Entry (content) and a main class Book as (container)

Once the entry object is created, it has to be added to the book object. But… where should that method be? in the Book class or in the Entry class?

I am having that sort of questions and I am not sure how and where can I learn.

Oh my amazing to-do list is here in case anyone is curious.
It doesnt have comments but it is very basic and self explanatory.

Should the entry class be aware of any meta-functionality? Not really, no.

The Book class should have the ability to add/edit/remove entries, sure. It should be aware of its own descendants. It’s a logical move, as it manages them.

Entries themselves, however, shouldn’t know about each other. Generally, a good form might be the DOM: event bubbling works. When an event (add/edit/delete) happens at the entry level, it should notify the Book, which takes the appropriate action.

It’s a great discussion, and there is no one and only right answer. For me, I think about problems like this in very tight terms:

  • Encapsulation - isolate each entity as tightly as possible, so that it knows only what it NEEDS to know to do its job.
  • Delegation - many little parts, each given a specific subtask, allows management parts up the heirarchy to rely on them to do their job.
  • Communication - those little parts, which we trust to do their job, are completely self-contained, but we can listen to what they say, and we can tell them what to do.
1 Like

You don’t necessarily need to attempt that kind of pure class-based OO kind of programming in JS; it allows you to easily program with verbs rather than nouns, eg:

function addEntryToBook(book, entry) {
1 Like

True, @DanCouper – its a matter of approach. I can’t say I’m a purist, but I have really gotten behind the object oriented nature of JS, for those who are ready for it.

From the perspective of encapsulation, being able to poke into the book object to add entries is messy. What happens if, at some point, the mechanism book uses for storage changes? Now I need to dig around for any other code that might poke into its guts.

Personally, I prefer to have the book handle its own adding and editing, passing that content into the entry and let that handle ITS own editing.

As was said right off, there is no “right way”. Simply what works for each of us.

1 Like