I'm new to programming, and In very many cases, i find myself torn whether i should copy paste code to make the program run faster, or gather methods by forcing the program to go through additional loops. I'll give you an example a bit like my current case:
solution1: (copypaste code)
button1.clickevent: saveValue1Method()
button2.clickevent: saveValue2Method()
button3.clickevent: saveValue3Method()
saveValue1Method()
{
doSomethingWithValue1()
buttonlabel.text = "you clicked a button";
doThis();
}
saveValue2Method()
{
doSomethingWithValue2()
buttonlabel.text = "you clicked a button";
doThis();
}
saveValue3Method()
{
doSomethingWithValue3()
buttonlabel.text = "you clicked a button";
doThis();
}
dosomethingwithValue1()
{
mylabel.text = 1;
}
doSomethingWithValue2()
{
mylabel.text = 2;
....
}
doSomethingWithValue3()
{
mylabel.text = 3;
....
}
solution2: (more program instructions)
button1.clickevent: saveValueMethod(1)
button1.clickevent: saveValueMethod(2)
button1.clickevent: saveValueMethod(3)
saveValueMethod(int i)
{
if (i == 1)
{
doSomethingWithValue(1)
}
if (i == 2)
{
doSomethingWithValue(2)
}
if (i == 3)
{
doSomethingWithValue(3)
}
buttonlabel.text = "you clicked a button";
doThis();
}
doSomethingWithValue(int j)
{
if (j == 1)
{
mylabel.text = 1;
...
}
if (j == 2)
{
mylabel.text = 2;
}
if (j == 3)
mylabel.text = 3;
}
Keep in mind this is just a simplified example, and doesn't necessarily make sense. In many cases i would have to loop through a lot of values, not just if 1,2 or 3.
Which concept is good coding?