If I have to write a simple program (25-35 lines), should I divide it even further, in functions which have a few lines and get executed max. 2 times, or to put it all im one?
e.g. if I need to add and substract 2 angles, should I do everything in one function or write one which converts everything back (and forth) and one which does the actual adding/substracting, leaving main with only I/O (extra: should an angle be defined as a structure or to stick to ints, assuming it isn’t used anywhere else)?
My reasoning is that the code is clearer and that I find it easier to write as well, but apparently some people find it unnecessarily long and too complicated. I’m looking for “the right way”, preferably examples or experiences from job interviews. Obviously large real-world applications need to be modular, but what about script-like or programs that focus solely on one algorithm?
4
There is not a “right way”, you have to choose when “promote” a fragment of code in a method.
Usually it make sense create a new method:
- when your main method is too long, bloated or complex (code readability/maintainability)
- when that fragment is used two times or more (no code duplication)
- when that frament could be used from two methods or more (code reusability)
- when you need to use local variables (that are nearly useless in the main method)
This is heavily dependent on your situation at hand. You don’t give much surrounding context. Who are you writing this for? Is it a throwaway script to fulfil a specific need right now or do you intend for it to be used and maintained further on down the line?
If you’re writing it for yourself then you can do whatever you want, it’s only you that will be using it. Likewise if it’s a throwaway script it doesn’t really matter either since you’re not going to be using it in the future.
If you’re asking for ‘best practice’ or you’re writing this with the intention that you will maintain it/other people will use it, then it’s generally preferable to split code up into the smallest possible reusable chunks. This way it’s very simple to modify, add or remove steps to your code that you may end up needing in the future but currently can see no use for.
It’s a huge pain to have to rip up half of your code because you made certain assumptions a few months ago that no longer hold true. I, like many others I’m sure, learnt this lesson the hard way. It’s generally better to write code with as few assumptions as possible and craft generic methods which can be swapped out at any time while having to alter as little existing code as possible.
Do you use the exact same code that is more than one or two lines in other parts? split
Will you do it in the future? split