Recently i found myself fighting to come up with a “good” way to accomplish what i needed to code. I was dealing with logic to determine if something existed, and if the data was the same, if either condition was true i needed to update and then save changes.
I basically had the below.
function ( int id, int attributex, int attributey){
item x = null;
x = find(id);
if( x ==null){
item = new item();
item.attributex = attributex;
item.attributey = attributey
}else{
if(attribute x changed || attribute y changed){
item.attributex = attributex;
item.attributey = attributey;
}
}
Add(item);
SaveChanges();
}
So basically the problem was that i only wanted to update the DB if it DNE or if something changed, but i didn’t want to copy the SaveChanges, or Add logic inside the two else statements. So i tried a couple of different approaches, setting a Boolean if something changed, reorganizing logic. Until i realized what i was trying to do was wrong!
Basically there were two differn’t use cases. If it doesn’t exist i wanted to ADD it and then Save changes. But if it was an update, i simply just wanted to update it, and save changes. Before i was trying to add AND update for both cases, which logically was wrong.
Basically this made me think back to all the times when i had been fighting with something for a good amount of time, before realizing that the reason it was so complicated was because fundamentally it was wrong.
So i guess the reason i wasted your time, and all these words, was so next time you find something that is way too complicated, i want you to think about it and come to the conclusion: the reason it is soo hard, is because you have the wrong solution!.
Anything is possible, you just need to find the right way to acomplish your goal.
0 responses so far ↓
There are no comments yet...Kick things off by filling out the form below.