isa424 isa424 - 11 months ago 43
Javascript Question

What is this kind of OOP approach called?

So I am fairly new to OOP and I've been trying to start Unit Testing my apps in whatever language. But I realized that testing requires a certain approach to designing your Classes with less dependencies. From what I've read I've come to conclusion that the thinner the class the better since responsibilities are delegated to other classes, the approach I am practicing right now.

So I've been playing with Typescript and wanted to create simple Money management app. By coding it what I wanted to learn is if the way I have designed these classes enable better design and testability overall. For example I have an Amount object with a function that accepts an object of type Money and returns its amount property.

Does it make dependencies less loose? Does this kind of approach even make sense to be implemented? (Hoping to hear different opinions from gurus of OOP. Constructive criticism is welcome!)

A paste bin with all the classes

Answer Source

By coding it what I wanted to learn is if the way I have designed these classes enable better design and testability overall

From a quick scan it didn't look like any of the classes instantiated other classes, and require the caller to instantiate and pass in their dependencies. IMO this is the KEY, most important first step to testable design, and is called Dependency Injection.

It allows for a test method to instantiate mock/stub objects, and call the functions they are testing. This is a powerful technique to remove IO from tests. Suppose you had an object that performs IO. If the object were to instantiate a DB driver directly then it would have a tight coupling to the DB client and a test would not be able to easily inject a stub or mock. If the class accepts an instance of a DB driver, or an interface for a DB driver, then a test can easily configure a stub driver which doesn't perform any IO. Your design looks to accomplish a similar thing.

A couple things come to mind:

  • Are Currency, and Amount necessary? They look to be unnecessary Money wrappers? It has the feeling of taking DI overboard.
  • While it looks like DI is accomplished some of the classes are tightly coupled:
    • Account requires Money
    • Money requires Account
    • Currency requires Money
    • Amount requires Money
    • Money requires Currency

From my experiences a tightly coupled design like this, would really make working with it, and extending it, difficult.