Doubts about usability - var e functions - Javascript

Asked

Viewed 49 times

1

I came across a situation that until today had not occurred, my friend was coding and made the following block of code (only simulation)

function teste() {
  teste = true // Ele faz uma verificação
  if (teste) {
    teste2('verdadeiro')
  } else {
    teste2('falso')
  }

  function teste2(texto) {
    var element = document.getElementById('element');
    element.innerHTML = texto

  }
}
teste()
<div id="element">
</div>

I would take another approach:

function teste() {
  var testando = ''
  var teste = true // ele faz uma verificação
  if (teste) {
    testando = 'verdadeiro'
  } else {
    testando = 'falso'
  }
  var element = document.getElementById('element');
  element.innerHTML = testando
}

teste()
<div id='element'>
</div>

I’m not asking in terms of functionality, because the two approaches serve, but which is more appropriate and why?

  • I know I could use a ternary operator in this situation I mentioned but it follows with a few more checks and wanted to make as simple as possible the minification of the problem

2 answers

4


Generally speaking yours is simpler, so between the two, it’s what I would do because I prefer the Navalha de Ocam.

I’m not seeing reasons to do it the first way. But I could take a more real example. Artificial examples are complicated to establish what is good or not because they have no context, and context is all about deciding on the applicability of something. And not knowing this is the biggest problem of novice programmers (some program for decades and are still as newbies because they don’t like to learn, they just like to see results).

One reason to do it in the first way would be to name a routine, and that’s one way to avoid a comment explaining what it does. But it would only make sense if the function had an explanatory name, calling teste2() that’s not what it’s for.

I still find it exaggerated most of the time, and almost certainly in this case, because it’s small and the code there does something very standardized and it’s almost self-explanatory by itself. Not to mention that creating this function can worsen performance (I’m not saying because there may be optimizations), but it’s not the best reason to avoid creating the function.

If the function were generic and even received which element should take would make a little more sense, but I have my doubts if it would not be exaggerated. Either way, that would be another code. For this example I would not do the secondary function outside of it trying to keep the idea of the first code, even more if it keeps the name teste(). For another example the problem is different and the decision must be different. Then again, this is not the best reason to choose to do a generic function, this decision should look at other things to decide why.

In fact I can simplify, this example I would do so:

function boolPortugueseElement() {
    document.getElementById('element').innerHTML = true ? 'verdadeiro' : 'falso';
}

boolPortugueseElement();
<div id='element'>
</div>

I put in the Github for future reference.

When you simplify it tends to become easier to understand and it becomes less necessary to do other things. Some people don’t like it because they say it’s less readable. I don’t think this case is, legibility is subjective. Some say it makes it difficult for the intern, but the intern should be taught to program, not lower the bar for him. I look at this and understand perfectly what happens there. The codes of the question I took a long time to understand, especially the first one. But reinforcement that the lack of good names helped not understand.

It is best to give good names before any other concern.

I find it much more important to put the ; than this concern, because it can give problem. I do not understand why it took fashion of people not to use it more.

I think people create too many variables. I would create one to make it legible, but only if the name is too explanatory and the code it processes is complex, otherwise it’s just to complicate the code.

Although it had in the title, in the question even there was no clarity that wanted to know about the var. Never stop using the var, unless you prefer to use the let. So at this point the first code is wrong. Yes, it works, but it could present problems in another situation. Get used to always use the right way, just like I said about the ;, just because you may not use it in some situations, why not use it? What gain do you expect from not using it?

But I would put the var in the first code, I don’t know why it wasn’t put.

Behold What is the difference between variable declaration using Let and var?.

  • I understood and thank you for the ear tug, I will try a little later to put the real example to facilitate. But I love your approach, very didactic and explanatory!

2

This depends on the programmer and how clean you want your program to be, for example:

  • A function that checks a condition and updates a part of the HTML

In this case your approach would be the simplest and easiest to understand, I do not see the need to define a function within a function as your friend did simply to make a check and then call the method defined within himself, when you have few lines of code the thing is still easy to understand, but when the code gets complex the reading becomes more difficult, this comes into play make the refactor of the code as much as possible, ie each function does only what it was made to do, she should not know what things functions do and should not worry about defining other methods that exist only within herself. I do not believe there is a more suitable, there are good practices that the community tends to follow with the passage of time programming in a language, for your case for example my approach would be more like the example below in each need to update the HTML in more parts of the code.

function updateElement(elementId, innerHTML){
  let element = document.getElementById(elementId);
  element.innerHTML = innerHTML;
}

function teste() {
  // Dê preferência por usar let ao invés de var se a váriavel for local
  let teste = false;
  if (teste) {
    updateElement('elementId', 'verdadeiro');
  } else {
    updateElement('elementId', 'falso');
  }
}

teste();
<div id="elementId"></div>

Unless there is a specific reason, I think the right thing to do is to take a simpler approach that will help you understand your own code and help others as well if you are working in a group. That’s why there are programming principles like KISS (Keep It Simple, Stupid), which basically means: Keep it simple and stupid.

  • I fully agree with you. even your proposal is much leaner than the one I thought at first and simpler to follow. But does creating a var not have some external factors that impact on usability? For example, memory allocation, more time for processing and so on? I made a minimal example because the function is a little (much) bigger than that and I don’t know if it causes any impact to the end user. I know we don’t normally worry about it (I’m an example myself) but my application depends on quick and assertive answers, you understand?

  • I’ve never taken any performance test between using var and let, and I don’t believe it’s necessary, let was created to correct existing scope problems in variables defined with var, is a way to keep code cleaner and reduce the possibility of errors in runtime

  • Yes yes, as to that I understand. However my doubt would be about a Function or storage in var (or Let) for decision making. It may sound like a stupid question but it’s just that I’ve never really seen in all the years that I work with this particular situation.

  • If you have a function that has a return in Boolean, by convention you can add the same directly within the condition, example if(myBooleanFunction()), not that it will make much difference to the end user but it is simply a way to keep code simple and readable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.