Should const be outside function components in React.js? - reactjs

Some of my code got a review comment saying something like "move const outside the function to avoid redeclaration". This was a normal function component, something like this:
export default function someComponent() {
const someString = 'A string';
///...
}
I was confused about the idea of this causing a redeclaration, because it does not, I know that the record that holds the variables and constants belong to the scope, so it's not exactly that.
But then i remembered that typescript does not allows you to have a const inside a class, not sure about the reason or is this is related. But then ts added the readonly modifier in ts v2, so the confusion remains.
Should const be outside function components, or not?
I would love to know more opinions.

There are 2 sides to the coin. Firstly, in terms of clean code and readability, I strongly prefer local declarations like in your example. I would love using more nested functions as well.
However, in JavaScript, every time the function executes, the local definitions will be redeclared, even if they are constants or functions. So it's a trade-off. If the function is called many times, this becomes an overhead.
I think it would not be hard for a compiler like TypeScript's tsc or some other pre-processor to extract those definitions at compile time to have best of both worlds. But it's likely that they do not do this to remain fully compatible. I am not aware of such tools but would be interested if there are some.

Related

How to abstract things away in c without having a bunch of function parameters?

I've been messing around with SDL2 in c and was wondering how to abstract code away without using too many function parameters. For example, in a normal gameplay loop there is usually an input, update, render cycle. Ideally, I would like this to be abstracted as possible so I could have functions called "input", "update", "render", in my loop. How could i do this in c without having those functions take a ludicrous amount of parameters? I know that c++ kind of solves this issue through classes, but I am curious and want to know how to do this in a procedural programming setting.
So far, I can't really think of any way to fix this. I tried looking it up online but only get results for c++ classes. As mentioned before, I want to stick to c because that is what i am comfortable with right now and would prefer to use.
If you have complex state to transport some between calls, put that in a struct. Pass a pointer to that as the sole argument to your functions, out at least as the first of very few.
That is a very common design pattern on C code.
void inputstep(struct state_t* systemstate);
void updatestep(struct state_t* systemstate);
void renderstep(struct state_t* systemstate, struct opengl_context_t* oglctx);
Note also that it is exactly the same, if not even more (due to less safety about pointers), overhead as having a C++ class with methods.
this in a functional programming setting.
Well, C is about as far as you get from a purely functional language, so functional programming paradigms only awkwardly translate. Are you sure you didn't mean "procedural"?
In a functional programming mindset, the state you pass into a function would be immutable or discarded after the function, and the function would return a new state; something like
struct mystate_t* mystate;
...
while(1) {
mystate = inputfunc(mystate);
mystate = updatefunc(mystate);
…
}
Only that in a functional setting, you wouldn't re-assign to a variable, and wouldn't have a while loop like that. Essentially, you wouldn't write C.

use of any in typescript

I have an angular 1.4 project on typescript, the project is getting bigger and bigger and our team is really tired of interfaces that we have declared (so that all objects are typed, in comparison to any)
I'm asking if this is a good idea or not? I chose typescript because I wanted to have a typed project, should I drop the interfaces or not?
You can get by without using interfaces and going with any, but in the long term you are probably going to regret it. If your team is sick of the interfaces you've created, I would put time in fixing those instead of abandoning them. There is a significant argument around if typed languages reduce the number of errors found in code. Personally, I think they do.
What I've found with typed languages is that it helps remove stupid mistakes we all make, and this clears up our time to focus on actual logic problems in code. Not everyone agrees with me on this, but I will always pick a type language over a non typed one, especially if the team is used to dealing with languages like Java or C#.
Interfaces can be very helpful if used properly.
If you are just doing this....
IFoo { ... }
Foo implements IFoo { ... }
Then they will not help as much as they do in other typed languages (C#/Java). Because the type checking in TypeScript is dependent upon the properties on the object and NOT on the declared type. This is because you can simply write this...
MyCtrl (foo: Foo) { ... }
//instead of
MyCtrl {foo: IFoo) { ... }
This will not hinder unit testing in any way since as stated above the type checking is based upon properties and not declarations.
There are cases when interfaces can be quite helpful, for instance a common use case is when defining an object as a parameter...
doSomething (options: ISomethingOptions) { ... }
There is no harm in creating interfaces for everything, you just need to determine what level of typing works best for your team.

Which of these functions is more testable in C?

I write code in C. I have been striving to write more testable code but I am a little
confused on deciding between writing pure functions that are really good for testing
but require smaller functions and hurt readability in my opinion and writing functions
that do modify some internal state.
For example (all state variables are declared static and hence are "private" to my module):
Which of this is more testable in your opinion:
int outer_API_bar()
{
// Modify internal state
internal_foo()
}
int internal_foo()
{
// Do stuff
if (internal_state_variable)
{
// Do some more stuff
internal_state_variable = false;
}
}
OR
int outer_API_bar()
{
// Modify internal state
internal_foo(internal_state_variable)
// This could be another function if repeated many
// times in the module
if (internal_state_variable)
{
internal_state_variable = false;
}
}
int internal_foo(bool arg)
{
// Do stuff
if (arg)
{
// Do some more stuff
}
}
Although second implementation is more testable wrt to internal_foo as it has no sideeffects but it makes bar uglier and requires smaller functions that make it hard for the reader to even follow small snippets as he has to constantly shift attention to different functions.
Which one do you think is better ? Compare this to writing OOPS code, the private functions most of the time use internal state and are not pure. Testing is done by setting up internal state on a mock object instance and testing the private function. I am getting a little confused on whether to use or whether to pass in internal state to private functions for the sake of "testability"
Whenever writing automated tests, ideally we want to focus on testing the specification of that unit of code, not the implementation (otherwise we create fragile tests that will break whenever we modify the implementation). Therefore, what happens internally in the object should not be of concern to the test.
For this example, I would look to build a test that:
Executes the test by calling outer_API_bar.
Asserts that the correct behavior of the call using other publicly accessible functions and/or state (there must be some way of doing this, as if the only side effect of calling outer_API_bar was internal to this unit of code, then calling this function could not impact your wider application in any way, and essentially be useless).
This way, you are able to keep the fact that you use functions like internal_foo, and variables like internal_state_variable as implementation details, which you can freely change when refactoring your code (i.e. to make it more readable) without having to change your tests.
NOTE: This suggestion is based on my own personal preference for only testing public functions, and not private ones. You will find much debate on this topic where some people pose good arguments for testing private functions being a valid thing to do.
To answer your question very specifically pure functions are waaaaay more 'testable' than any other kind of abstraction. The more pure functions you can include, the more testable your code would be. As you rightly mention, this can come at the cost of readability, and I am sure there are other trade offs to consider. My suggestion would be to aim for more pure functions and look for other techniques that would allow you to compensate on the readability side of things.
Both snippets are testable via mocks. The second one, however, has the advantage that you can also check the argument of internal_foo(bool arg) for an expected value of true or false when the mock for internal_foo() is invoked. In my opinion, that would make for a more meaningful test.
Depending on the rest of the code that we don't know, testing without mocks may be more difficult.

What is the reason for assigning this to a locale variable without a callback?

As far as I know assigning this to a variable is used within callbacks where the this scope may change. But digging through the ExtJS source I found it used in all sorts of functions but not always. So is there any reason that I would assign this to a local variable beneath the scope or is the ExtJS source just struggling with different developer styles?
#kevhender pointed me to the right sencha forum thread where evan has given a very good explanation.
It's only for the size. And here's a example:
function doA() {
var me = this;
me.a();
me.b();
me.c();
me.d();
me.e();
me.f();
me.g();
me.h();
me.i();
me.j();
me.k();
me.l();
}
function doB() {
this.a();
this.b();
this.c();
this.d();
this.e();
this.f();
this.g();
this.h();
this.i();
this.j();
this.k();
this.l();
}
Compressed we get:
function doA(){var a=this;a.a();a.b();a.c();a.d();a.e();a.f();a.g();a.h();a.i();a.j();a.k();a.l()}
function doB(){this.a();this.b();this.c();this.d();this.e();this.f();this.g();this.h();this.i();this.j();this.k();this.l()};
It adds up.
According to that we should
NOT use a local var if we use this only up to three times
function doA(){var a=this;a.a();a.b();a.c();};
function doB(){this.a();this.b();this.c();};
and use it if we use this more often then three times
function doA(){var a=this;a.a();a.b();a.c();a.d()};
function doB(){this.a();this.b();this.c();this.d()};
There are a few reasons for this, the most significant being that using a local variable will save a few bytes during compression of the files. It may not seem like much for a small bit of code, but it can add up a good bit over time.
There is a long thread at the Sencha forums talking about this very issue: http://www.sencha.com/forum/showthread.php?132045.
As you've correctly stated this is sometimes used in places where the scope might change.
There are cases where you want to do the same to make sure there are no scoping issues.
Other than that, the devs sometimes just assign this to a variable out of habit more than out of necessity.

GCC function attributes vs caching

I have one costly function that gets called many times and there is a very limited set of possible values for the parameter.
Function return code depends only on arguments so the obvious way to speed things up is to keep a static cache within the function for possible arguments and corresponding return codes, so for every combination of the parameters, the costly operation will be performed only once.
I always use this approach in such situations and it works fine but it just occurred to me that GCC function attributes const or pure probably can help me with this.
Does anybody have experience with this? How GCC uses pure and const attributes - only at compile time or at runtime as well?
Can I rely on GCC to be smart enough to call a function, declared as
int foo(int) __attribute__ ((pure))
just once for the same parameter value, or there is no guarantee whatsoever and I better stick to caching approach?
EDIT: My question is not about caching/memoization/lookup tables, but GCC function atributes.
I think you are confusing the GCC pure attribute with memoization.
The GCC pure attribute allows the compiler to reduce the number of times the function is called in certain circumstances (such as loop unrolling). However it makes no guarantees that it will do so, only if it think it's appropriate.
What you appear to be looking for is memoization of your function. Memoization is an optimization where calculations for the same input should not be repeated. Instead the previous result should be returned. The GCC pure attribute does not make a function work in this way. You would have to hand implement this.
I have one costly function that gets called many times and there is very limited set of possible values for the parameter.
Why not use a static constant map then (the arguments' can be hashed to generate a key, the return code the value)?
This sounds like it might be solved with a template function. If all if the known parameters and return values are known at compile-time, you could perhaps generate a template instance of the function for each possible parameter. Essentially you'd be calling a different instance of the function for each possible parameter. Not sure it would be any easier than the static cache you've already implemented, but might be worth exploring.
Check out template metaprogramming. The concepts are similar to 'memoization', suggested by JaredPar, even using the same introductory example of a factorial function. It might be appropriate to say that these kinds of templates are compile-time implementations of memoization.
I dont like to reopen old threads, but there was a particularly offensive comment here:
"templates are for dealing with different types, rather than different values of the same type"
Now, take a simple template factorial implementation:
template<int n> struct Factorial {
static const int value = n * Factorial<n-1>::value;
};
template<> struct Factorial<0> {
static const int value = 1;
};
The template parameter here is an integer, not a typename.

Resources