In defense of spaghetti code. *ducks*
-
There's spaghetti and there's spaghetti.
if (oldState == "state1" && newState == "state2")
{
}
else if (oldState == "state2" && newState == "state3")
{
}
else if .. else if .. else if .. else { }
// line 1000This may feel like spaghetti, but as long as your code reaches one or more if-statement sequentially and it's readable and you can follow it's not so bad. It's quite easy to refactor, should you ever want to.
public class StateClass
{
public static string oldState;
public static string newState;
}public class DifferentClass
{
//...
StateClass.oldState = "whatever";
StateClass.newState = "something";
//...
SomeControl.Text = StateClass.newState;
}public class AnotherClass
{
private object field1;
//...
private object field90;
//...
if (StateClass.oldState == null) throw new Exception("State not set.");
if (StateClass.oldState == "state1" && StateClass.newState == "state2")
{
SomePublicOrStaticVar = "";
}
else if (StateClass.oldState == "state2" && StateClass.newState == "state3")
{
}
else if .. else if .. else if .. else { }
// line 1000
//...
}Now it's going real spaghetti-like. You'll always have to wonder what will happen everywhere once you set or read either oldState or newState. Also, your code has to run in a specific order, but in different classes so it's not at all obvious or even logical. Not sure what SomePublicOrStaticVar does, but setting it or reading it at the wrong time is sure to mess up something somewhere. Having 90 private fields is also a huge strain on your cognitive abilities. Everything you do in such a class you have to wonder "will this mess up other methods that rely on this field?" Believe me, I know X| I've had code like this mess up Form1 because a user changed something on Form2 (which had no relation to Form1 whatsoever). To me, it mostly comes down to this, how many variables do you have to worry about at any given time and how visible are those variables among your different classes? Large code chuncks aren't the problem (although slicing them up can improve readability and maintainability). Lots of if-statements aren't a problem either, as long as they don't work on too many different (public) variables. When functions have their input and output and nothing else to worry about you can rewrite to your heart's contents if you wanted to and the function may remain a black box if it returns the correct output. I think you're good enough to go for the first spaghetti.
I don't think this is spaghetti code; it's just long and complicated. Spaghetti jumps all over the place and would obscure the actual logic far more than this example does (which is completely hypothetical. Not real world at all, by the way.) Last year I tried a challenge -- to rewrite a hangman game from the late 70's, which was written in an early dialect of BASIC with GOTOs and GOSUBs all over the place, into a modern language. The code was very short, barely a page of A4 when printed out. But to understand this very simple program, I had to print it, and draw lines all over it to work out the program flow, which took over an hour. Imagine if it went to more than two sides of paper! I found a line that was unreachable and would never be executed. Even the person who wrote it wasn't aware. Just a bit of structure, named procedures etc. simplified and clarified it enormously. But I suspect that what the OP is talking about is something a bit different from that. The code may have had a lot of IFs and branches, but writing it in a clear way with meaningful names, rather than abstracting it all to classes, may have been the right call in this instance. But do a reality check: give it to a colleague and see how long it takes them to figure out the flow and logic.
-
The worst type of spec is one that fails to address all scenarios that are important to a product's behavior. The developer must then ask the spec writer for clarification or decide what to do in such cases. If the flow diagrams cover all possibilities, they pass this key test. But yes, they should be simplified if possible. Reviews really help to avoid bad specs. Just as there are code reviews, there should also be spec reviews.
Robust Services Core | Software Techniques for Lemmings | Articles
The fox knows many things, but the hedgehog knows one big thing.Correct! So, we agree - it's your job to write good code (as well as you can, ofc) even if the specs are bad!
Eusebiu
-
I ran into an issue recently on a professional embedded project, and that was this: In translating the flow diagrams to code, there were so many conditions around state changes and such that my options were to either abstract the flow with some sort of generalized framework, or cook some spaghetti code. I chose the latter. Why? Simple. The actual effort if anything would be about equal, or favor the spaghetti approach. More importantly, progress remains visible with the spaghetti approach rather than the abstract flow framework which requires a lot of up front design and work without progress visible to the client. Finally, this is embedded code, where a rewrite is maybe a grand or two $USD, on the outside, assuming not a lot of reuse. It would cost at least half that to develop a simple framework, which might make things more maintainable, but questionable in terms of how effortlessly one can make changes (whereas maintainability is more about stepping away for a month and being able to pick it up again, mostly - or someone else picking up your code). It's all a matter of robbing peter to pay paul. The bottom line here is that while we may chase perfect code, and "best practices" that's not always the most effective technique for keeping the lights on. Flame away.
To err is human. Fortune favors the monsters.
may i please inquire the number of boxes in the flow chart . also the number of lines of code in the final product and the language . if the customer insists on spaghetti one must ask the precise type they prefer . for me it is fettuccini -Best
-
I ran into an issue recently on a professional embedded project, and that was this: In translating the flow diagrams to code, there were so many conditions around state changes and such that my options were to either abstract the flow with some sort of generalized framework, or cook some spaghetti code. I chose the latter. Why? Simple. The actual effort if anything would be about equal, or favor the spaghetti approach. More importantly, progress remains visible with the spaghetti approach rather than the abstract flow framework which requires a lot of up front design and work without progress visible to the client. Finally, this is embedded code, where a rewrite is maybe a grand or two $USD, on the outside, assuming not a lot of reuse. It would cost at least half that to develop a simple framework, which might make things more maintainable, but questionable in terms of how effortlessly one can make changes (whereas maintainability is more about stepping away for a month and being able to pick it up again, mostly - or someone else picking up your code). It's all a matter of robbing peter to pay paul. The bottom line here is that while we may chase perfect code, and "best practices" that's not always the most effective technique for keeping the lights on. Flame away.
To err is human. Fortune favors the monsters.
"assuming not a lot of reuse" is the fulcrum of this kind of decision. Efficiency is using the lowest effort that will get the desired result, so for low reuse, spaghetti is fine. Idk if I could force myself to do it, but then I've been known to use pen and paper, so there's that.
-
While I hear you, I do have one niggling nit to pick with your suggestion that comments *do* have zero impact if you mean they have zero negative impact on your codebase. They do. Comments are extra maintenance, and often get stale. They should be used as sparsely as possible and no sparser. For the most part, code should be self documenting. This is not as true in embedded where you often can't afford the necessary abstractions to express intent, such as using the STL algorithms everyone is familiar with. In the case of embedded comments tend to be more necessary.
To err is human. Fortune favors the monsters.
-
To me spaghetti code is basically like a messy room you don't clean up. Doesn't mean you need to make a framework, but ya know... at least make the bed.
Jeremy Falcon
Agreed, but there's a smell when you've got a lot of seemingly arbitrary conditionals and special case handling. I was assuming that the 'spaghetti' code described by codewitch was what you had left after you'd done cleanup and refactoring.
Software Zen:
delete this;
-
I ran into an issue recently on a professional embedded project, and that was this: In translating the flow diagrams to code, there were so many conditions around state changes and such that my options were to either abstract the flow with some sort of generalized framework, or cook some spaghetti code. I chose the latter. Why? Simple. The actual effort if anything would be about equal, or favor the spaghetti approach. More importantly, progress remains visible with the spaghetti approach rather than the abstract flow framework which requires a lot of up front design and work without progress visible to the client. Finally, this is embedded code, where a rewrite is maybe a grand or two $USD, on the outside, assuming not a lot of reuse. It would cost at least half that to develop a simple framework, which might make things more maintainable, but questionable in terms of how effortlessly one can make changes (whereas maintainability is more about stepping away for a month and being able to pick it up again, mostly - or someone else picking up your code). It's all a matter of robbing peter to pay paul. The bottom line here is that while we may chase perfect code, and "best practices" that's not always the most effective technique for keeping the lights on. Flame away.
To err is human. Fortune favors the monsters.
No reason to duck or put the fireproof suit on Honey. In many of our 'real' worlds, time and budget are real concerns, and we don't have the flexibility to create an RFP that rescopes and projects a timeline. It's nice to work in that world, but it's not what the client always wants. Had a case last week where a weird set of changes from an outside vendor (don't get me started on the level of their incompetence with 500+ employees) should have required adding a column to the client's DB and creating the framework and structure to handle the change. Into the thousands of dollars and major timeline. We have two weeks and nowhere near the budget. My colleague was panicking over redesigning everything correctly. I messaged him the meme of the dog with spaghetti on his head and said "time for a nice bowl of pasta". Not pretty at all, but done and in production, working fine. I do know why bird's "nests" look like spaghetti, lol. Your bottom line is 100% correct!
-
I've never been over budget. I also don't accept ridiculous schedules. You can have it fast, cheap, and / or good. Pick 2.
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
Hmm, not all of us live in that charmed world. Clients often have line of business needs that eclipse coding purity. They don't care about how it gets done, just that it works reliably. And purity != reliability. In existing codebases, it's often not a matter of bad planning or specs. Sure, we explain the 'do it right' piece, and at the end the result is about the same as me explaining to my dog we can't go for a walk because it's too cold; she still ends up at the door waiting.
-
jschell wrote:
dislike the claim that abstractions make anything better
True (in absolute), but in general they help. Indeed, if you just need to print to the standard output, you don't need abstractions (and you don't start with those, ofc) but as soon as some requirement changes that and you will want to do file, on screen, on some API, then abstractions will be better (than, IDK, local ifs, switch even local functions).
jschell wrote:
But don't do it 'just in case'
In general (again), you do it because you care about things like clean code, maintainability and avoid cases like 'only God and me knows... now only God'. :laugh: I've never heard anyone saying that it coded that beautiful/maintainable code 'just in case'... while I've heard a lot of times that the developers were not aware of some clean code principle or did not know how to really implement it.
Eusebiu
Hard to say. I've inherited code that was overly abstracted and it can be a dog to read. That said, it can be challenging up front to determine the correct level of abstraction. I have seen few perfect waterfall designs, most push agile to a new definition :) So, defensively you include the parts and pieces. I've gone back at the end and removed some since the flat procedure was clear, direct, and less code; and never called by anything else.
-
Jeremy Falcon wrote:
what a senior should know
In general, you are right! He is just arguing that in his very particular case it's better to break the rules (and by better he means time to deliver and money saved, not technical excellence or performance improvements). Unfortunately, he did not paint the entire picture - only the parts that supported his decision. Who knows?! Maybe in his very particular case the decision was correct.
Eusebiu
Sorry buddy, but I disagree. There are different levels of good design and for a one- or two-day job, you are 100% correct in the fact we don't have to go full on SOLID, RAII, etc. But that doesn't mean you don't do the basics of a decent structure that should be ingrained in our subconscious by now - especially if it's for work or pay. No senior should and I'd never hire one twice that thought otherwise. Also, there are factors that don't add up. If this quick project was so insignificant, there shouldn't have been a diagram in the first place. Nobody in the industry diagrams anything for a one-day job - nobody. And lastly, if you check out the entire post, you'll notice my points where entirely skipped over too. This whole thread was just clickbait over someone being bored.
Jeremy Falcon
-
may i please inquire the number of boxes in the flow chart . also the number of lines of code in the final product and the language . if the customer insists on spaghetti one must ask the precise type they prefer . for me it is fettuccini -Best
It's a screen flow diagram to be specific. There are 6 boxes on the main page loosely corresponding to the screens. There are about 11 lines connecting them in various directions. One trick with it, is it wakes and polls a server periodically, and goes to sleep until it's woken up by a user. That adds a bit of complexity. Another issue is that there are inactivity timeouts on each screen that drop you back to either the home screen or the sleep screen depending on where you are. Also there are 3 buttons and they are contextual, changing function depending on the screen you're on. Hopefully I've given you enough of the landscape that you can understand the issue. :)
To err is human. Fortune favors the monsters.
-
honey the codewitch wrote:
There is no justification for spending $1000 to possibly save $1000 down the road. It makes no sense.
This is not your decision to take; it's the clients/management/call it what you want. You cannot possibly know what's down the road. Ofc, we don't know your contributions - you might be a 10x developer! You don't need to feel insulted if someone says your decision is not of a senior developer - everyone makes mistakes and no one is always right! The thing is that some of the arguments are not adding up... I just wonder why you posted this knowing (because you 'ducked') that this is not common/best practice. Are you looking for validation? :) (you will probably find it from junior developers or some devs that know your project).
Eusebiu
Yeah, no it's my decision. The client gets deliverables, and projects designed to spec. I get to decide how to get there in the least expensive way possible, that delivers something robust and to spec. I am not a fan of micromanagement. I work for myself. And yes, I do know the cost of a rewrite, because I wrote the code.
To err is human. Fortune favors the monsters.
-
Ok, if you want to talk in $s, also post how much did you actually billed (I guess you have an hourly rate)? Then we would agree that it might be cheaper to keep writing spaghetti code. $1k for a full rewrite seems low at a glance... it's less than a working week (in some cases a 1MD)...
Eusebiu
It was about a day of work. That's typical for a lot of IoT codebases. You're dealing with kilobytes of RAM and very little room to store code. Projects don't sprawl - they can't.
To err is human. Fortune favors the monsters.
-
Something I overlooked yesterday is that you have a detailed spec in the form of these "flow diagrams". It's great when it's easy to see how code implements the spec. If that means spaghetti, so be it. Any blame then lies with the spec writer. :-D
Robust Services Core | Software Techniques for Lemmings | Articles
The fox knows many things, but the hedgehog knows one big thing.That was actually my precise calculus. :D
To err is human. Fortune favors the monsters.
-
It's a screen flow diagram to be specific. There are 6 boxes on the main page loosely corresponding to the screens. There are about 11 lines connecting them in various directions. One trick with it, is it wakes and polls a server periodically, and goes to sleep until it's woken up by a user. That adds a bit of complexity. Another issue is that there are inactivity timeouts on each screen that drop you back to either the home screen or the sleep screen depending on where you are. Also there are 3 buttons and they are contextual, changing function depending on the screen you're on. Hopefully I've given you enough of the landscape that you can understand the issue. :)
To err is human. Fortune favors the monsters.
it seems i do not understand as it seems i do understand . a state diagram comes to mind rather than a flow diagram though perhaps they are the same as i do not know for certain . the few times i utilized a state diagram i found the logic easy to understand .
-
I ran into an issue recently on a professional embedded project, and that was this: In translating the flow diagrams to code, there were so many conditions around state changes and such that my options were to either abstract the flow with some sort of generalized framework, or cook some spaghetti code. I chose the latter. Why? Simple. The actual effort if anything would be about equal, or favor the spaghetti approach. More importantly, progress remains visible with the spaghetti approach rather than the abstract flow framework which requires a lot of up front design and work without progress visible to the client. Finally, this is embedded code, where a rewrite is maybe a grand or two $USD, on the outside, assuming not a lot of reuse. It would cost at least half that to develop a simple framework, which might make things more maintainable, but questionable in terms of how effortlessly one can make changes (whereas maintainability is more about stepping away for a month and being able to pick it up again, mostly - or someone else picking up your code). It's all a matter of robbing peter to pay paul. The bottom line here is that while we may chase perfect code, and "best practices" that's not always the most effective technique for keeping the lights on. Flame away.
To err is human. Fortune favors the monsters.
Spagetti code (in my day) usually only meant the use of GOTO (which has been declared a cardinal sin since the 1970's). Heck I didn't know C had a goto until after 10 years of using it (c. 2003) But if you're coding in assembler, I think there's no way you can avoid it (I mean some fools use interrupts all the time, even some compilers, but that wastes a ton of clock cycles). BASIC, on the other hand, I have not touched since 1997 (Thank god too, I never could find a free Basic compiler then, Qbasic is crap)
-
I ran into an issue recently on a professional embedded project, and that was this: In translating the flow diagrams to code, there were so many conditions around state changes and such that my options were to either abstract the flow with some sort of generalized framework, or cook some spaghetti code. I chose the latter. Why? Simple. The actual effort if anything would be about equal, or favor the spaghetti approach. More importantly, progress remains visible with the spaghetti approach rather than the abstract flow framework which requires a lot of up front design and work without progress visible to the client. Finally, this is embedded code, where a rewrite is maybe a grand or two $USD, on the outside, assuming not a lot of reuse. It would cost at least half that to develop a simple framework, which might make things more maintainable, but questionable in terms of how effortlessly one can make changes (whereas maintainability is more about stepping away for a month and being able to pick it up again, mostly - or someone else picking up your code). It's all a matter of robbing peter to pay paul. The bottom line here is that while we may chase perfect code, and "best practices" that's not always the most effective technique for keeping the lights on. Flame away.
To err is human. Fortune favors the monsters.
I just looked at some code I wrote in 2009-ish because we had to enhance it. I don't think it technically is spaghetti code, but it twists and turns on itself enough to act like it. Here's the basic environment: * SQL & a binary file store values used in the calculations * COBOL does the calculations * Delphi is the middleman * C# is the UI But wait, the COBOL can't access the SQL to get those values, so the C# gets them and does all the same calculations as the COBOL, then passes just a few values to the Delphi. The Delphi combines everything via a client data set, then passes it back up to the C# one value at a time. Sometimes it passes values to the COBOL as well. COM is used 3 different ways during this process. Oh, and the same value frequently has different names in the 3 program languages, and some of the names are the same for different values. For example, SomeAmount in C# => SomeOtherAmount in Delphi, but SomeAmount in Delphi => ThisAmount in C#. It's a head-turner and headache-creator for sure.
Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere
-
It's a screen flow diagram to be specific. There are 6 boxes on the main page loosely corresponding to the screens. There are about 11 lines connecting them in various directions. One trick with it, is it wakes and polls a server periodically, and goes to sleep until it's woken up by a user. That adds a bit of complexity. Another issue is that there are inactivity timeouts on each screen that drop you back to either the home screen or the sleep screen depending on where you are. Also there are 3 buttons and they are contextual, changing function depending on the screen you're on. Hopefully I've given you enough of the landscape that you can understand the issue. :)
To err is human. Fortune favors the monsters.
Sounds very familiar territory.
-
jschell wrote:
dislike the claim that abstractions make anything better
True (in absolute), but in general they help. Indeed, if you just need to print to the standard output, you don't need abstractions (and you don't start with those, ofc) but as soon as some requirement changes that and you will want to do file, on screen, on some API, then abstractions will be better (than, IDK, local ifs, switch even local functions).
jschell wrote:
But don't do it 'just in case'
In general (again), you do it because you care about things like clean code, maintainability and avoid cases like 'only God and me knows... now only God'. :laugh: I've never heard anyone saying that it coded that beautiful/maintainable code 'just in case'... while I've heard a lot of times that the developers were not aware of some clean code principle or did not know how to really implement it.
Eusebiu
And if you don't have input/output streams? You have to read the key input directly from the hardware? Even have to debounce the keys yourself, because there's little or no hardware support? We already know (from CP articles) that Honey abstracts displays where possible. Embedded is different.
-
it seems i do not understand as it seems i do understand . a state diagram comes to mind rather than a flow diagram though perhaps they are the same as i do not know for certain . the few times i utilized a state diagram i found the logic easy to understand .
It is pretty much the same, just presented slightly differently. The screens are basically state transition "landings", the arrows, the transitions themselves. I wish I could just show you the diagram but I'm not at liberty to share it. It would make things clear. The actual logical flow isn't terrible, per se. But it folds back on itself some (due to inactivity of button presses, or otherwise navigating from screen to screen) There is a quirk that impacts all of the startup code, and that is the startup code must run on wake or on boot, with a different "start reason" associated with it. The machine otherwise has no indication to determine whether it was woken from sleep vs. powered on. It remembers nothing. Also, I have a watchdog timer in the code, for robustness - this is out of band, and what it does is it starts counting down, and if it reaches the end, it reboots. This is regardless of what else happens. The reason for that is to prevent a hang, not that my code hangs, but in production, who knows? So that's a separate flow on top of everything else. Basically what it amounts to is rather than one state machine, it's several state machines working in tandem. That's messier than what I'd like in an ideal world, but making it cleaner just wasn't going to pay for itself.
To err is human. Fortune favors the monsters.