Bring Arguments Back to Angular

I keep seeing this mistake. Angular components define variables and functions. But I think it is an issue when arguments are not defined for the functions and the component variables are being mutated directly in the functions. Looks like this:

So in that component we have an editData function that takes no arguments. It relies on this to glue the variables to the context. It gets the job done, but it is a little too lazy. This is considered an impure function. We cannot know reliably what is going to happen to our data.

AngularJS gave us created a bad habit. Written in the days of MVC, we had controllers where we happy attached our view data to an object. AngularJS passed that object to the view, and we were happy to let two-way data binding take care of the rest.

The gist here shows attaching functions and our data to our vm object (view model). But this got us in a bad habit because when we wanted access to our data all we did was type vm.data and there it was. For whatever reason this lead to a wide scale pattern of not using arguments for functions and access the data on the view model.

Well this needs to go. Next time you write a component function, use arguments. This really seems so simplistic, but there is a lot of code out there relying on this. While this feels obvious to write about, the ease in which Angular allows this with component “global” values makes this mistake so easy.

The scenario that cause me to write this post went like this; we had a service that retrieved data for a table. The service also handle paging and sorting on the server. The component had a function that called the service and set the return value equal to the data value that was bound to the grid. The issue is that the component function had no arguments. I relied on passing the this variables straight to the service. Two big issues come out of that. The function is not pure and the function is not testable. Impure functions take more effort to understand, and because internal state drives the function, the call cannot be mocked.

In summary, component functions in Angular need arguments all the time even if they only rely on component this values. AngularJS may have made us too relaxed in how we think about attacking our data to the view. Angular’s class structure also makes it far to easy to write this kind of code. Use arguments. If executed properly you will have nice, testable, pure functions. That is a good thing.

If you found this helpful at all please hit the button . It helps this post reach more people.

I post on twitter about new article here. I would also really enjoy hearing any response. Just leave them below!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.