What is the specific terminology or field of focus for this particular code type (non-adherent, non-standard)?

Is there a term for a module or library that is considered subpar because it deviates from standard behavior, especially implicitly?

For instance, in the file module.js, you may find the following code...

Object.assign = (x, y) => {
  // Instead, perform a deep copy...
}

...users of this module might be taken aback when Object.assign does not function as expected.

Furthermore, what field(s) of study does this concept fall under? I am interested in further reading on this topic.

EDIT: Updated to a more appropriate example

Answer №1

Monkey patching is the term used for this practice.

https://en.wikipedia.org/wiki/Monkey_patch

Your example of monkey patching is seen as malicious and is generally discouraged because it can break code that relies on Object.assign.

In the case of this specific example, a better alternative could be:

{
  let assign;
  [assign, Object.assign] = [Object.assign, function(dst, ...sources){
    if(sources.at(-1) === 'deep-copy'){
      return assign.call(Object, dst, ...sources.slice(0, -1).map(src => structuredClone(src)));
    }
    return assign.apply(Object, arguments);
  }]

}

const a = {};
const b = {prop:{test:true}};

Object.assign(a, b, 'deep-copy');

b.prop.test = false;

console.log(a);

Object.assignDeepCopy() may seem like a more concise and safer solution, but there is a risk of potential conflicts with future JavaScript additions...

Unfortunately, in cases involving Object.assign, there isn't a foolproof solution...

The recommended approach would be simply:

Object.assign(a, structuredClone(b));

It's worth noting that opinions vary on whether monkey patching is a good practice or not.

I personally appreciate monkey patching BUT:

  • Using monkey patching within your project is generally acceptable.
  • When implementing monkey patching, maintaining the default behavior while adding extra functionality is crucial.
  • If you are providing code for others to use (e.g., a framework, module, or library), then it's best to avoid monkey patching.

On the flip side,

Extending objects like Array.prototype could lead to complications:

  • You introduce Array.prototype.flat() to recursively flatten arrays before September 4, 2018.

  • Chrome 69 releases JS version of flat on September 4, 2018.

  • Your dependencies begin using JS flat.

  • Due to the overridden default behavior by your custom method, your application breaks and dependencies no longer operate as expected.

Compared to modifying existing methods through monkey patching:

JavaScript typically follows SOLID's open–closed principle, ensuring that behaviors of existing functions remain consistent.

Therefore, if you opt to monkey patch Array.prototype.find to support object filters like arr.find({id: 1}), it should continue to work reliably unless external factors introduce conflicting modifications to the same method.

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

Challenges faced when subscribing to global events in JavaScript

I have some questions about the JavaScript code snippet below: What does .events.slice(-1)[0][0] signify? Similarly, could you explain the purpose of nodes_params += "&ns=" + GLOBAL_EVENT + "," + start_from + ",-,-";? Could you elaborate on what is m ...

What is the best way to assign a random background color to a div element using an array?

I'm looking to spice up my div with a splash of color! I have an array filled with colors such as 'red', 'green', 'blue', and '#f00'. How can I randomly select one of these colors each time the div is rendered? ...

Is it possible to create models that can be used in both Node.js and angular without duplication

Currently, I am diving into the world of Node.js and Angular (part of a MEAN project) through an online course on Udemy. One challenge I have encountered is the need to create identical models for both the back-end and front-end (specifically with angular2 ...

Is there a way to access fields from an associated model within React components?

Is there a way to access fields from an associated model in React components within Rails? I have a listing model that I'm iterating through in a React component and retrieving all the fields for each record, including the ID of the associated model. ...

Detecting the physical screen size based on the user agent in PHP and JavaScript

Is it possible to accurately detect the screen size of mobile browsers using both javascript and php? Given how mobile devices come in all shapes and sizes these days, relying solely on pixels may not be enough. I'm looking for a method that can speci ...

Protractor never-ending cycle

In my previous question, I encountered an issue with clicking a button until it becomes disabled. Initially, the solution was as follows: var nextPage = function () { if (element(by.css('[ng-click="vm.nextPage()"]')).isEnabled()) { e ...

Correcting W3C validation issues is essential

I am encountering errors in my W3C validation process. Even though I have set <!DOCTYPE HTML> for my page, I continue to experience issues as shown in the image below. I have been trying to troubleshoot and resolve these errors without much success ...

Countdown timer feature and auto-submit function for your website's page

Currently, I am working on an online exam project that requires the page to be automatically submitted after 10 minutes, regardless of whether the user clicks on the submit button or not. Additionally, I want to include a countdown timer to display the r ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Best practices for managing jqGrid AJAX requests

Looking to create a more flexible solution in jqGrid by setting up a custom function for AJAX calls instead of hard-coding the URL in the definition. I've experimented with a few approaches, but haven't found one that perfectly mirrors the direc ...

What is the best way to create a new instance for each incoming HTTP request in NestJS?

While working with my API, I encountered an issue where the classes were not being destroyed after receiving a response. Currently, I am using nestJS, but when I tested nodeJS + expressJS, I also faced the same problem. The code I am using is as follows: ...

Discrepant functioning of window.location in Internet Explorer versus Chrome

I am encountering an interesting issue with a webpage that has 3 levels in its URL structure, such as example.com/1/2/3. The code snippet I am using is as follows: window.location.replace(""); When running this code in IE11, it navigates to example.com/1 ...

Using jQuery in an external JavaScript file may encounter issues

As a newcomer to jQuery, I decided to try writing my jQuery code in an external js file rather than embedding it directly into the head of the HTML file. Unfortunately, this approach did not work as expected. Here is what my index.html looks like: < ...

What is the best way to retrieve the slot object property in order to send it to a component for a specific data table row in Vuet

I have defined a vue data property as shown below: data() { orders: [], order: { order_id: null length: null, width: null, } } Additionally, I have implemented a vuetify data table structured like this: <v-data-table v-if=& ...

Vue component fails to register

In my current project, I am incorporating a custom component tag using Vue.JS. Although we have successfully utilized Vue.JS in past projects, the same approach isn't working this time. It seems like I must have overlooked something... After inspect ...

Upgrade your project from Angular 5 to Angular 9 using webpack

I want to share my experience, not ask a question! To upgrade dependencies in package.json: -Update all Angular dependencies to version 9 -Add these dependencies: "@angular-devkit/build-angular": "^0.900.4", "@angular-builders/cu ...

Get Angular events in the proper order

I am currently facing challenges with event handling in AngularJs. In my service, I send out events using the following line of code : $rootScope.$emit("FNH."+this.status, flowNodeHelper); When receiving the event in service "S1," I handle it as follows ...

A collection of dropdown fields sharing identical names but containing distinct IDs

I am looking to create an array of select fields with the same list of option values. The goal is to prevent a value that is selected in one field from appearing in another field. For example, if "a" is selected in the first field, it should not be avail ...

issue with node callback function - code malfunctioning

I have written a script in Node.js and Express to send an email after a SQL transaction is successfully completed! router.post('/',function(req,res,next){ sql.connect(config).then(function() { var request = new sql.Request(); ...

Leveraging the keyword 'this' within an object method in node's module.exports

My custom module: module.exports = { name: '', email: '', id: '', provider: '', logged_in: false, checkIfLoggedIn: function(req, res, next){ console.log(this); } }; I inclu ...