Is it best to make a refactored/service method public or private in Typescript?

Objective: I need to refactor a method in my component that is used across multiple components, and move it to a service class for better organization.

Context: The method in question takes a user's date of birth input from a profile form and converts it from DD/MM/YYYY format to MM/DD/YYYY format.

Inquiry: When relocating the method to the service class, should it remain public or should it be changed to private?

I have tried researching this topic, but the information is ambiguous. It seems like most suggest keeping it public unless it is exclusively used within the same class.

Current Implementation

Component:

let dobForDb = this.formatDateForDB("31/12/2019");

formatDateForDB(data: any): string {
        // Separate by '/'
        var array = data.split("/");
        let day = array[0];
        let month = array[1];
        let year = array[2];
        let dateString = month + "/" + day + "/" + year;
        return dateString;
    }

Refactored as

Component:

let dobForDb = this.serviceclass.formatDateForDB("31/12/2019");

Service Class:

public formatDateForDB(data: any): string {
        // Separate by '/'
        var array = data.split("/");
        let day = array[0];
        let month = array[1];
        let year = array[2];
        let dateString = month + "/" + day + "/" + year;
        return dateString;
    }

Answer №1

When you define a method in a service that you plan to utilize in a component, it must be declared as public. Otherwise, the method will not be accessible in other classes, such as the component class. Test it out for yourself: declare a method in a service as private:

private doSomething()

...and you will find that you cannot use it in a component where the service is injected.

Therefore, your methods should be public in this scenario.

It's important to note that in TypeScript, all properties and methods are public by default, making the public modifier unnecessary (whether or not to use it is a matter of personal/project conventions). Both of these methods are considered public:

doSomething() {}

public doSomething() {}

A method is only declared as private if its scope is limited to within the same class and not outside of it. This restriction includes usage in component templates: private methods and properties of a component class cannot be accessed in the component's template.

Answer №2

In Summary: Avoid using private/public unless for dependency injection purposes.

This topic tends to be subjective in nature. Personally, I prefer not to designate my properties and methods as public or private, except when it comes to dependency injection like this example:

constructor(private foo: FooService) { }

To me, there is no logical reason to make a property/method private, especially when dealing with setters and getters.

Since I utilize TypeScript for typing, the code becomes more organized and clearer without adding unnecessary keywords that just clutter the code base. Ultimately, what matters most is understanding what can be accessed within an application.

Instead, setting a property as readonly makes much more sense.

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

How to make a GET request to a Node server using Angular

I am currently running a node server on port 8000 app.get('/historical/:days' ,(req,res,next){..}) My question is how to send a request from an Angular app (running on port 4200) in the browser to this node server. Below is my attempt: makeReq ...

How to detach functions in JavaScript while preserving their context?

Can functions in JavaScript be detached while still retaining access to their context? For instance, let's say we have an instance of ViewportScroller called vc. We can retrieve the current scroll position with the following method: vc.getScrollPosi ...

Reacting to Appwrite events in a React Native environment

My React Native application encounters an error when subscribing to realtime events. The error message reads as follows: ERROR Error: URLSearchParams.set is not implemented, js engine: hermes. appwriteClient .subscribe( `databases.${APPWRITE_DATAB ...

Struggling to locate components in your React, Next.JS, and Typescript project? Storybook is having trouble finding them

I have set up Storybook with my Next.js, TypeScript, and React project. The main project renders fine, but Storybook is breaking and giving me the error message: "Module not found: Error: Can't resolve 'components/atoms' in...". It appears t ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Matching only the specified Records in an array of Typescript generic objects

Check out this demo: https://tsplay.dev/Nnavaw I am working with an array that has the following structure: Array<{ id?: string; text?: string; date?: Date; }> This conflicts with the current implementation: data: Array<Par ...

Utilize Angular-Material to showcase a tooltip when hovering over a form label

I am struggling to display a tooltip on a label. Is there an easy fix for this issue? <mat-form-field> <mat-label matTooltip="Please enter your E-Mail Address"> E-Mail <mat-icon>help_outline</mat-icon> < ...

Absent 'dist' folder in Aurelia VS2015 TypeScript project structure

After downloading the Aurelia VS2015 skeleton for typescript, I encountered an issue trying to run the Aurelia Navigation app in IIS Express. One modification that was made to the skeleton was adding "webroot": "wwwroot" to the top level of project.json. ...

Running unit tests using Typescript (excluding AngularJs) can be accomplished by incorporating Jasmine and Webpack

While there is an abundance of resources on how to unit test with Webpack and Jasmine for Angular projects, I am working on a project that utilizes 'plain' TypeScript instead of AngularJs. I have TypeScript classes in my project but do not use c ...

Encountering difficulty creating a new entity in NestJS with TypeORM due to the error message EntityMetadataNotFoundError

Hey, I've been encountering some issues with TypeORM. I'm attempting to add a new entity to my current project and here's what I did: I created a new entity import { Entity, Column, PrimaryGeneratedColumn, JoinColumn, OneToOne } from ' ...

The Angular Material Stepper ng-template is missing a defined context variable for custom icons which is causing

My endeavor involves leveraging an ng-template alongside the matStepperIcon property to customize Angular Material's matStepper icons. I am also aiming to transmit some data by utilizing ng-container and *ngTemplateOutlet, yet facing partial success. ...

Following the execution of the "ng build --prod" command in Angular 2, the functionality of ui

Utilizing an Angular program with a Node.js server and the ng serve command has been successful. However, when attempting to transfer this code to a shared Linux server and using XAMPP for compilation, an error was encountered: ng build --prod The error ...

The iframe is not large enough to contain all the HTML content

I'm encountering a problem with a website I'm currently developing - specifically, I am struggling to embed an HTML document into an iframe in a manner that fills the entire page. Additionally, I am utilizing Angular to retrieve the HTML document ...

The most recent version of Angular featuring the powerful Angular-anim

Currently, I am in the process of revamping an application that was initially developed using a combination of jquery, bootstrap, and kendo ui. Moving forward, the application will transition to an angular (2/4) and kendo framework. In the previous setup, ...

Is it possible to generate an array of strings from the keys of a type or interface?

Imagine a scenario where we have a type or interface defined as NumberLookupCriteria: type NumberLookupCriteria = { dialCode: string; phoneNumber: string; } or interface NumberLookupCriteria { dialCode: string; phoneNumber: string; } Is there a w ...

Creating components with SCSS files in an Angular library can be achieved by following a few simple

After creating an scss app and associating a library, I encountered an issue when trying to create components with .scss files inside the library. Angular automatically assigned a css file to the component created within the library. The application (name ...

TypeScript - creating a dynamic instance of a new class with a custom

Looking to dynamically create new class objects in a loop with customizable names? For example, having classes like "tree": export default class ParentClass { // ... } export default class Thomas extends ParentClass { // ... } export default cla ...

Angular 8 dropdown menu that closes when clicking outside of it

Hello, I am currently using the click function on the p tag. When a user opens the dropdown menu, I want to close it when they click outside of it in Angular. Here is the HTML code: <div class="select_cat"> <p class="cat_name" (click)="openC ...

Unable to retrieve headers from extended Express.Request type

Currently, I am attempting to enhance the Request in Express so that it accurately represents the structure of a query. My current approach is as follows: export interface TypedRequestQuery<T> extends Express.Request { query: T; } While this met ...

Troubleshooting why Angular2 is failing to load external styles in styleUrls

Currently in the process of developing an angular2 application and had envisioned being able to implement distinct styles for public content versus admin content. To my disappointment, it appears that Angular is not accommodating external styles that are l ...