Ways to prevent redundancy of code within a class

I have created two classes that extend an abstract class:

   class SubstitutionTeacher extends SubstitutionAbstract {
      abstract _save();
    }

    class SubstitutionFree extends SubstitutionAbstract {
      public _save() {
      }
    }

    class SubstitutionSubject extends SubstitutionAbstract {
      public _save() {
      }
    }

Within the method save(), I have implemented specific behaviors for each subclass as follows:

  /* Class SubstitutionFree
    public _save() {

        const substitutionAdd: ISubstitutionModelTeacher = {
          lesson: this.substitution.lessonNumber,
          confirmed: true,
          subsDate: this.substitution.date,
          newTeacher: this.substitution.teacher
        };

        return this.replaceService.addSubstitution(substitutionAdd);
      }

 /* Class SubstitutionSubject
    public _save() {

        const substitutionAdd: ISubstitutionModelTeacher = {
          lesson: this.substitution.lessonNumber,
          confirmed: true,
          newTeacher: this.substitution.teacher
        };

        return this.replaceService.addSubstitution(substitutionAdd);
      }

It is evident that both methods share a common structure. To avoid duplication, we can extract this common part:

{ lesson: this.substitution.lessonNumber,
confirmed: true,
newTeacher: this.substitution.teacher
}

One approach to address this duplication would be to refactor the save() method and pass in this common structure as a parameter. However, this might compromise the abstraction principle.

Answer №1

Perhaps this snippet of TypeScript may not be valid, as I am still learning and not very proficient in it yet :)

However, your issue is not limited to TypeScript, so this may provide you with a concept on how such problems can be resolved.

You can create a method in SubstitutionAbstract :

class SubstitutionAbstract {

    // This method should be called whenever the object is needed instead of duplicating it
    // You can make it protected if TypeScript supports that
    public getMyStuff(param1, param2, param3, param4) {
        return { lesson: param1,
                 confirmed: param2,
                 newTeacher: param3,
                 subsDate: param4
               };
    }  
    // .....
}

In each subclass, simply call this method:

public _save() {
    const substitutionAdd: ISubstitutionModelTeacher = 
             getMyStuff(this.substitution.lessonNumber, true, 
                           this.substitution.date, this.substitution.teacher);

    return this.replaceService.addSubstitution(substitutionAdd);
}

If you do not require subsDate in some implementation, then pass null for that parameter in getMyStuff, which should not cause any issues. TypeScript typically checks types, so adjustments may be needed to ensure compatibility (e.g. returning something of type ISubstitutionModelTeacher).

Once again, this is likely non-functional code due to my limited experience with TypeScript, but it conveys the approach you could take.

Of course, there are other possible solutions, this is just one example.

Happy Coding :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue stating "Assignment error: Cannot assign type 'void' to type 'ReactNode'"

I'm attempting to execute the compatiblelist() function compatiblelist() { CompatibleDevicesAPI().then( response => {this.getCompatList(response)} ); } Whenever I try to call {this.compatiblelist()}, an error oc ...

What is the best way to handle .jsx files in my library bundling process with Rollup?

Currently, I am in the process of developing a component library using storybook and rollup. Here is the configuration file rollup.config.mjs /* eslint-disable import/no-extraneous-dependencies */ import peerDepsExternal from 'rollup-plugin-peer-deps- ...

A step-by-step guide on retrieving the present date and time using TypeScript

Details This is my first time creating a VSCode extension using TypeScript, and I am having trouble displaying the current date/time in an information message. My Attempts I have searched through VSCode key bindings for any references to date/time, as w ...

What is the best way to retrieve information from multiple pages of my REST API?

Recently, I integrated a search engine into my application and now I need to gather all the data available for a particular resource, such as all the posts made by a user. The response I receive from my API looks something like this: { "count": 2, ...

Uploading Boolean Values from Switch Input (React/Typescript)

I'm facing an issue while trying to post the state value of a switch input toggle control. Whenever I use the submitRecommendation() function through a button click, I encounter a JSON parse error: Cannot deserialize instance of `boolean` out of START ...

Selecting an option using a radio button

I have a scenario where I need to navigate to different pages based on the radio button selection after clicking the "Recovery" button. recovery.component.html <div> <div class="form-check"> <input value="t ...

Incorporating Moralis into Ionic Angular with TypeScript

I'm currently developing an app using Ionic Angular (TypeScript) that will be compatible with both Android and iOS devices. I've decided to incorporate the Moralis SDK to establish a connection with the Metamask wallet. Here's a summary of ...

Utilize the type correctly within a React Higher Order Component

Having some trouble with types while using an HOC. The following is the code snippet for the HOC: export interface IWithLangProps { lang: ILang; } const withLang = <T extends object>(Comp: React.ComponentType<T>): React.ComponentClass ...

Encountering an issue with the nativescript-carousel due to tns-platform-declarations

While constructing a nativescript carousel using the nativescript-carousel plug-in, I encountered an issue when running tns build android. The error message reads as follows: node_modules/nativescript-carousel/index.d.ts(1,22): error TS6053: File 'D: ...

How can I apply a custom class in Angular 2, similar to jQuery's

I've been having trouble with a very basic task... I need to assign a class to a <div> when I click on a button. After hours of searching online, I still haven't found a simple solution and all the examples I come across are too complex for ...

What is the best way to handle errors that occur asynchronously without using promises in order to respond to those specific errors?

I have searched for answers but none seem to directly address my specific question. My current usage involves the pattern shown below: class A { getLocation() { return Promise.reject(2222222) } async a() { try ...

Exploring the process of obtaining dynamic table row information by clicking a button in a table using TypeScript

I am currently working with a dynamic table that has a button in each row. When the button is clicked, I need to retrieve the data from that specific row. I attempted to use the (click) event binding on <tr>, but the output I received was undefined. ...

Navigating the flow of data between the view and model in Angular can be a complex task

After using Angular (version 5.2) for a few months, I've come across a situation where I feel like I might be overlooking an obvious solution. The issue I'm facing involves manipulating data between the view and the model. For instance, in my pr ...

Strict type inference for the number data type in TypeScript

I am interested in inferring the number type within this function: type Options = { count: number }; function bar<C extends Options>(options: C): C['count'] extends 3 ? 'x' : 'y' {} bar({ count: 3 }) // x bar({ count: ...

Angular service is continuously throwing the error message "NullInjectorError: No provider for anotherService"

I recently built a basic Angular service and encountered an issue. @Injectable() export class someHandler { constructor( public anotherService: anotherService, ) {} ... The problem arises when I try to use this service in a component, as ...

What is the correct method for adjusting the filterPredicate in Angular materials?

Having trouble overriding the filterPredicate in my table with phone numbers and states. The filtering is working, but there's a bug where results for "UNASSIGNED" show up when I filter for "ASSIGNED". Can someone assist me with the correct syntax for ...

When should I schedule the execution of the .spec and .po.ts files in Protractor?

Curious about TypeScript and Protractor: I have a couple of basic helper functions stored in a shared.po.ts file within my Protractor suite. These functions are triggered by the third it() in my .spec file - meaning they are not immediately called upon ru ...

Angular 2 ngSubmit triggers unexpectedly on occasions when it is not supposed to

Currently, I am working on developing an Ionic 3 application with Angular 2 and TypeScript. In the app, there is a form that is responsible for sending data to our server. The issue I am facing is that whenever I click on the following button: <butto ...

The function using the React Hook "useState" is not a React function in TypeScript

Issue arises when attempting to use the useState hook within my component. While I can successfully define props on both Container and Continer.Element, encountering errors when trying to invoke Hooks inside Container.Element. const Container: React.FC&l ...

Using AngularFire2 to manage your data services?

After diving into the resources provided by Angular.io and the Git Docs for AngularFire2, I decided to experiment with a more efficient approach. It seems that creating a service is recommended when working with the same data across different components in ...