Bogomip
Bogomip

Reputation: 435

Reusing complex code in Typescript//Angular

I am writing an application which has physical simulations on it. Each simulation differs in the physics and what gets drawn to a canvas, but not in generalized things such as:

etc... i.e. there are many parts which are done exactly the same in every simulation, but I current have that same code in each simulation. This adds up to 300-400 repeated lines of code in every simulation, obviously bulking my app up really well.

An example of the simulation, and parts which are controlled by reused code and part which are written specifically for this simulation

I want to take all of the general functions which deal with these non-simulation-specific issues and put them in another file, which is then loaded alongside each simulation. Changes in the common file affect all of the simulations which use it.

I have made a demo stackblitz of the problem. This is not the actual app, that's big, but a demo of what my code currently looks like and why I want to change it. The foods have specific things for them, but also general functions which are the same in each component.

For the record I have tried:

I have not been able to make any of them work, as the variables and function names are not happy working together as they would be if they were all under the same class. I recognize that my not making them work is reflective of my current skill level, not that they shouldn't work.

I did not try making the functions static as I read on another stackexchange answer that can cause problems down the line. I want the best solution really.

Upvotes: 1

Views: 293

Answers (1)

Aram Khachatrian
Aram Khachatrian

Reputation: 399

From the source code I saw on your stackblitz extending a base class looks like a good option because most of the properties and method repeat in all simulation components. Optionally, you can make your base class abstract, to make sure child classes provide some values for required properties and implementation for required methods.

Further analysis of the real project sources may revile additional options such as:

  • Creating TS file with utility methods. These utilities may be used in simulation-specific methods.
  • Dividing html into smaller reusable pieces.
  • Re-using SCSS in the form of mixins, global classes or SCSS files.

See example code on stackblitz.

Upvotes: 1

Related Questions