What sets apart passing arguments to a function from utilizing variables at the class level?

As someone who is just starting out in the Typescript and Angular-2 world, my previous experience includes working with Java and Angular-1.5.

Imagine a scenario where there is a component class with several variables that need to be used across functions, either from a JSON response or generated after some calculations based on JSON data.

  1. Is it better to define these variables as class-level members like this:

    processFunction(){
        ....
        ....
        this.someVar = this.someService.getData();
        ....
        ....
        this.functionA(); //funcA needs this.someVar
        this.functionB(); //funcB needs this.someVar
    }
    
  2. Or should the variables be saved as function scope members and passed as arguments like this:

    processFunction(){
        ....
        ....
        let someVar = this.someService.getData();
        ....
        ....
        this.functionA(someVar);
        this.functionB(someVar);
    }
    

Which approach is the most suitable to follow?

PS: The provided code is a simplified version of a broader use case where multiple variables need to be defined as function variables (using let) and passed as function arguments.

In a Java context, the best practice would typically involve using class-level variables when more than 2 functions share variables.

I would appreciate suggestions specifically related to handling such scenarios in Typescript.

Answer №1

Adhere to the Law of Demeter

The Law of Demeter (LoD) or principle of minimal knowledge is a guiding principle for software development, especially in object-oriented programs. As a form of loose coupling, the LoD was introduced by Ian Holland at Northeastern University in late 1987. The essence of this guideline can be summarized in various ways:1

  • Each module should only have limited knowledge about other modules, specifically those that are closely related.
  • Modules should communicate only with their close acquaintances, not with unfamiliar modules.
  • Interact solely with immediate friends.

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

Numerous asynchronous requests

I'm trying to figure out why the application keeps making multiple ajax calls. Check out this directive: gameApp.directive('mapActivity', function() { return { restrict: 'A', link: function(scope, element, att ...

Error encountered while trying to eliminate array element

I have a project in the works that involves creating a page where users can filter suggestions and vote for their favorites. The screen is divided into 3 tabs: [Top Rated], [Newest], and [My Votes]. Upon loading the screen, a call to the database is made ...

Ldap.js: exploring nested searches

My current task involves using ldapjs to conduct a search where the filter is dependent on the outcome of a preceding search. ldapClient.search(base1, opts1, (err1, res1) => { res1.on("searchEntry", entry => { const myObj = { attr1: entr ...

Discover the most concise string within the array

Is there a way to determine the shortest string in a JavaScript array regardless of the number of elements it contains? I attempted using var min = Math.min(arr[0].length,arr[1].length,arr[2].length); to find the shortest string among 3 elements in an ar ...

Utilize React Native to continuously fetch and display data from this API

[React-Native] Seeking assistance on looping through JSON API for conditional rendering. As a beginner, I would greatly appreciate your guidance. Thank you. Find my code here: https://drive.google.com/file/d/0B3x6OW2-ZXs6SGgxWmtFTFRHV00/view Check out th ...

The values entered in the React form inputs are not displaying accurately

I'm currently working on a project that involves creating a form for tours. Everything seems to be working well, except for the issue of input values getting mixed up. For example: Actual output: { tourName: 'pune darshan', location: &apos ...

Employing jQuery's offset() method for scripting

Issue: The problem I'm facing is that after clicking on the label where the date should be entered, the calendar is not appearing as expected. I tried using a jQuery script to darken the background, but then the calendar is not displaying in the corre ...

Updating a Div on your webpage using a JQuery UI dialog: A step-by-step guide

I am currently trying to update my webpage from a JQuery UI dialog, but the code I have so far does not seem to be working. Any assistance or guidance would be greatly appreciated. function submit_new_site() { // These are the input text IDs on the ...

I'm currently working on building a form with the Angular framework, but I'm facing a challenge in displaying all the

I am having trouble with my Angular form as I am only able to display two fields when the page is loaded. Code snippet from Component.html: <div class="card m-3"> <div class="card-body"> <form [formGroup]="surveyFor ...

What are the differences between Modules and Typings in Typescript?

I have been searching far and wide for information on the variances between modules and typings in TypeScript, but I'm still struggling to grasp the concept. As a newcomer to TypeScript, could someone please provide a concise explanation of these diff ...

Exploring the utility of promise.race()

When it comes to promise, there are two main options that I am aware of: promise.all() promise.race() I have a good grasp on what promise.all() does. It runs promises simultaneously, and upon successful resolution, the .then method provides you wit ...

Sharing an angular app URL containing query parameters with multiple users

I am in need of a feature that allows me to transfer the filter settings on a page to another user. For instance, if I apply certain filters on a specific page, I would like to share the URL with those filters already applied to other users. ...

employing a modal to create an interactive form in Angular

I recently started delving into Angular and I'm aiming to develop a dynamic form that can create entries in my database with fields that vary based on a dropdown selection in the modal header. I've searched for solutions but only found help for c ...

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

Initiate a unidirectional ajax request

My WCF service has a slow processing time when called for the first time, but caches the results in HttpRuntime.Cache afterwards. To initialize this cache, I want to initiate a fire-and-forget ajax call from JavaScript. Currently, my page contains the fol ...

Transmit JavaScript code from ASP.NET

Trying to transfer JavaScript code built using String Builder on the server-side (ASP.NET) to the HTML page's JavaScript. Here is my approach: Utilizing a Master Page and an ASPX page structured like this: <asp:Content ID="BodyContent" ContentPla ...

Unlinking styles from the template in Vue.js

I have a unique situation where my template contains a <style> block that needs to be positioned near its corresponding div due to CMS restrictions. However, when I try to integrate Vue.js into the mix, it appears to strip out the style block and di ...

Is there a way for Playwright to utilize Apple Silicon instead of Intel Chrome on an M1 Mac device?

Recently, I made the switch from an older, less powerful Mac Mini to the high-performing Mac Studio with an M1 Max chip. Unexpectedly, my Playwright end-to-end tests have started running at a sluggish pace. Upon further investigation in debug mode, I not ...

When attempting to run the Angular build using the Azure Event Hub JS SDK, deployment fails to execute successfully

Whenever I test the project on my local machine with ng serve -o everything functions properly. However, after building it (either in dev or prod) and deploying it to either an Azure web app or a local server on my computer, I encounter the following ...

Ways to establish a minimum height for material cards using Material UI

I am facing an issue with a card that contains a nested table. The card expands and shrinks based on the size of the table inside it. I want to prevent the card from shrinking when the table has no data or just one entry. Instead, I need the card to mainta ...