Programming_Fundamentals

Using functions vs classes

Several factory design patterns use functions to generate classes, which comes with several advantages. In fact, most often factory functions are the way to go over factory classes, except for one scenario: checking state. Classes can contain state, while functions do not. This means that for scenarios like creating singletons (where you keep a reference to an object in state), use classes over functions

Programming_Fundamentals
0
Why is stack faster than heap?

  • There is no need for garbage collection on the stack. A variable is pushed once it is created, and then popped once the function returns. There is no complex logic required, so no garbage collector required to remove unused variables and so on

  • A stack variable is not shared among functions. So they do not need to be synchronized in multi-threaded scenarios, resulting in a performance gain in these scenarios

Programming_Fundamentals
0
Detecting cyclic loop in linked lists

Use the fast and slow pointer to detect loops in linked lists.

Slow pointer: increase by 1 for every iteration Fast pointer: increase by 2 for every iteration

If a loop exists, both pointers will eventually meet up in the same position

Programming_Fundamentals
0
Weak vs Strong References

Weakly referenced variables are eligible for garbage collection Strongly referenced variables are not eligible for garbage collection

Programming_Fundamentals
0
Recursion caveat: stack overflow

Recursion runs the risk of running into a stack overflow due to a potentially large amount of function calls. Each function call needs to save it's state in the stack... so too many functions and limited memory is a recipe for an overflow

Programming_Fundamentals
0
OOP: Composition over inheritance

(a.k.a. composite reuse principle). Prefer composition (i.e. a class containing an instance of another class) over inheritance (i.e. "extends" or similar)

Think in terms of what an object can do as opposed to what an object is: "HAS A" vs "IS A"

Benefits are more flexibility, easier thought processing and longer-term stability of objects

Programming_Fundamentals
0