r/learnprogramming • u/Temporary-Warthog250 • Apr 05 '22
Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them
Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.
Someone else who reads yours and does understand it, try to explain it to them to help them learn
14
105
u/NewInHere__ Apr 05 '22
recursion, just... recursion
71
u/dkToT Apr 05 '22
Basically a function that will call itself until a certain criteria or situation is satisfied. Once it is satisfied, the result will be returned to the parent function call all the way back to the top. This will help with clean code but only if you know your functionality follows a certain pattern.
A great example of this is the fibonacci series and why it was used in alot of early interview questions. The fib(n) is equal to fib(n-1) + fib(n-2). With recursion you can use this pattern to do the calculation for fib(n-1) and fib(n-2) where fib(n-1) = fib(n-2) + fib(n-3) and fib(n-2) = fib(n-3) + fib(n-4), etc....
Super useful and clean if you now the exact pattern and expectation (traversing a tree, etc..) of what you are building but I personally don't see this used often.
7
→ More replies (6)15
u/TheTomato2 Apr 05 '22
To add on to this, recursion, at least for me, was confusing because sometimes it's taught before they teach you how or what the main stack in program works/is. It's really simple once you learn its just the same function calling itself and pushing another instance on to the stack and then using returns to unwind the stack. That's all recursion is. It's also makes it easy to understand why probably shouldn't use it unless the problem really begs for it.
→ More replies (1)101
u/Emerald-Hedgehog Apr 05 '22 edited Apr 06 '22
Alright. Imagine you got a steak and you wanna cook it well done. It's needs to be cooked 5 minutes for that.
Function CookSteak(š„©)
{
Ā Ā š„©.CookedMinutes += 1Ā Ā If (!š„©.IsWellDone()) { return CookSteak(š„©) }
Ā Ā else { return š„© }
}Does this help?
49
u/KrafDinner Apr 05 '22
I'm not sure if it helped the asker or not, but it's a fantastic explanation... and steak... mmmm
→ More replies (6)36
u/WarWizard Apr 05 '22
Why not just call this function BurnSteak() or MakeSteakInedible()
:D
14
u/_Personage Apr 05 '22
function cookShoeLeather()
Yeah, that was the last time I made any sort of meat for the person who called my meat tacos that :(
12
u/MyHomeworkAteMyDog Apr 05 '22 edited Apr 06 '22
Just to add, here are the elements of a recursive algorithm:
A base case, when the algorithm returns an answer without further recursion.
A recursive call, to a smaller subproblem closer to the base case.
A way to accumulate the recursive solutions
20
u/AlSweigart Author: ATBS Apr 05 '22
I just got done writing an entire book on recursion.
Recursion is tricky, but mostly it's just poorly taught. The main thing that instructors fail to talk about is the call stack. It's the invisible data structure that automatically handles where the execution should return as you call and return from functions.
Once you know that, and you can see that local variables are local to the function call and not just to the function, it becomes a bit easier to see how recursive functions work.
It's tricky though, because you can't point to the call stack in your source code. Without having that explicitly pointed out, recursion just seems like magic. But it isn't magical or somehow more powerful: *literally anything you can do with recursion you can do without recursion by using a loop and a stack. It's just that recursive algorithms use the (unstated, hidden) call stack as their stack.
(I always get people saying, "some things do require recursion" and, no, they don't require it. Here's a non-recursive Python implementation of the famously recursive Ackermann function, and it has the same output as the normal recursive one.)
It's fine to have difficulty with recursion though; recursion is overrated and often a terrible way to write code. The times when recursion is useful is for problems that involve a tree-like structure and some sort of backtracking (maze solving, tower of hanoi, etc). Otherwise, iterative code is much simpler and I think some programmers just use recursion because it makes them feel smart.
→ More replies (2)6
u/flank-cubey-cube Apr 05 '22
To add on to your last paragraph, recursion also incurs some overhead and isn't the most efficient way to do things. Each function called recursively gets added to the stack frame, and if you have an *extremely* large tree structure, you'll get a stack overflow. The exception to this is if you are able to optimize for tail recursion, because than the compiler will be able optimize it to a loop.
9
u/AlSweigart Author: ATBS Apr 05 '22
Yes, but I always hold off on performance claims until I run code under a profiler. I've had some recursive code end up being faster than an iterative version. (Not sure how that happened.)
Also, to be specific, the stack overflow happens if you have an extremely deep tree. Like, it could be a linked list (which is basically a unary tree) that is a couple thousand nodes long. If you had an extremely large but shallow tree, you won't have a stack overflow.
And many interpreters/compilers don't have tail call optimization, including the main ones for Python, JavaScript, and Java. I hold the opinion that tail call optimization should never be used.
All recursive functions can be implemented iterative using a loop and stack. If you are doing tail recursion, it's because your recursive algorithm doesn't require the call stack. So iteratively you can implement it as a loop and a stack without the stack, so why not just use a loop? Often times you have to mangle the code and decrease readability to make it tail recursive, so I'd just go with a simple loop every time.
I can't think of a tail recursive function that wouldn't be improved by just using a loop.
→ More replies (1)→ More replies (16)4
u/EdenStrife Apr 05 '22
It's just calling a function from within itself.
It's sometimes easier and makes more sense than doing a loop.
9
u/KimPeek Apr 05 '22
There is high risk of introducing memory leaks if you use recursion where you should use a loop. They are not interchangeable. CS recursion, compared to mathematical recursion, requires more than a function calling itself. Recursion requires a base case, a decomposable problem (size-n problem), a defined subproblem (size-m problem), and the construction of the solution for the size-n problem from solutions to size-m problems.
→ More replies (9)
28
u/NYCnative339 Apr 06 '22
Irrelevant comment but these are the posts I enjoy, not the fucking classic āhOw LoNG tO lEaRN pRoGraMmiNgā
→ More replies (1)6
17
23
u/Sakin101 Apr 05 '22
Javascript
22
u/Temporary-Warthog250 Apr 05 '22
Lol literally. I never understood JavaScript. Itās all just⦠wtf
45
Apr 05 '22
It's like someone sat down and made a language in a week and then we just used it forever. Insane.
16
u/David_Owens Apr 05 '22
Other way around. They made a language over a few decades, so it became a Frankenstein's Monster of ideas and features from different eras.
10
u/AlSweigart Author: ATBS Apr 05 '22
(For those who don't get the joke, Brendan Eich was tasked to create a scripting language for the Netscape web browser and wrote what became JavaScript in ten days. Though some say this "ten days" story is exaggerated/misleading.)
→ More replies (1)0
4
Apr 05 '22
[removed] ā view removed comment
7
u/Olemus Apr 05 '22
Arrow functions are becoming more popular in other languages as well C# for example uses them quite a bit nowadays
14
u/TangerineX Apr 05 '22 edited Apr 05 '22
I think people take Javascript to be way more complicated than it needs to be. In javascript, there's really 4 things to think about
"primitives", or various values. These are strings, numbers, and booleans
Arrays, which are just an ordered list of things
Objects, which is a map of key: value pairs, which are all primatives.
Functions, which take some input, and turn it into something else
Basically EVERYTHING in javascript is built off of these concepts. If you understand these, you've understood 90% of javascript.
Surprisingly, I've learned more about Javascript by learning Typescript instead, which gives a more opinionated way of using Javascript in a way that makes a bit more sense. It's also become the standard for writing stuff in many frameworks, such as Angular and React.
→ More replies (2)→ More replies (1)5
u/AlSweigart Author: ATBS Apr 05 '22
First thing to understand about JavaScript: it's one word, with capital-J, capital-S.
It's not important, except if you write on a resume that you have 3 years experience with "Javascript" or "Java Script", it kind of calls into question how familiar you are with it.
But otherwise, it's a silly detail and I don't bother correcting people about it. Unless you are writing a JavaScript book and misspell it on the cover.
188
u/famrob Apr 05 '22
Big O. Iām quite far in the CS program at my school but the professor who tried to teach me big O was just absolutely horrible at it, so it went in one ear and out the other
166
u/tzaeru Apr 05 '22 edited Apr 05 '22
Big O basically tells how much time or space a function needs when its input grows in size.
For example, consider this algorithm:
function(int n): counter = 0 for (i = 0; i < n; i++) for (j = 0; j < n; j++) counter++ return counterIf
nis 1, what's the number returned? It's 1*1 = 1. There was 1 increment operation done.If
nis 4, what's the number returned? It's 4*4 = 16. There were 16 increment operations done.So you see the algorithm's time complexity grows by n^ 2. Big O notation is a way of expressing this; we can say that the time complexity is O(n2 ).
You can simply get the time complexity by counting the number of operations in the function and comparing how that number changes depending on the size of the input.
O(log n) is one very common time complexity and one example of an algorithm with O(log n) time complexity is searching a sorted array with binary search. The reason it's log n is that in each step, binary search splits the search space in two; so with input with size of 8 there are at most 4->2->1 or 3 steps, while with input size of 16 there's at most 8->4->2->1 or 4 steps.
4/3 = 1.33.. and log(16)/log(8) = 1.33..
→ More replies (2)94
u/Rote515 Apr 05 '22
Although this comment is true, i donāt think it gets to the heart of BigO, the most important part of bigO is that itās a time complexity estimation more than an exact time complexity which your examples do not show. For example a 3N + 2N + 2N2 algorithm has a bigO of N2 as we drop the constants and only use the fastest growing term, because as N gets large it ends up being the only term we care about from a complexity point of view.
24
u/XilamBalam Apr 05 '22
Yes, it's looking how the function "behaves at infinity" (asymptotic behaviour).
→ More replies (2)→ More replies (2)5
u/MaxwellCE Apr 06 '22
What if the algorithm is N² + N³? Could we say that has a big O of N³, or is the N² component non-negligible?
→ More replies (1)57
u/Rote515 Apr 05 '22 edited Apr 05 '22
BigO is super straightforward if you have a decent understanding of algebra. The general gist of it is that in computer science we only really care about the fastest growing term for time complexity, so for example if I have a function that is solved in the following number of steps. N+N2 where N is the size of the input, the the BigO time complexity is N2 since thatās the fastest growing term. The reason we care only about the fastest growing term is because when N gets very large thatās the only term that will really matter. For instance in the above equation if our input N is a list of 10,000 integers, well 10,000 operations is trivial for a modern processor, but 10,000*10,000 is not, that can take actual time to complete.
Thereās a bit more to it than that, but that is the basics of BigO
Edit: one last thing, BigO is very useful but it doesnāt tell the whole story of time complexity, itās a good way to understand the basics as N gets very large, but it can be misleading in certain algorithms. For example the equation 10000000n + n2 for the number of steps to complete an algorithm is still O(n2) time complexity, but because the first term has a super large constant itās till likely not the most efficient solution depending on what youāre solving, there might be a case where an algorithmic n + n3 is better if n never gets very large for example even thought itās O(n3) which is generally a very bad time complexity.
→ More replies (5)6
11
u/AlSweigart Author: ATBS Apr 05 '22
I always recommend Ned Batchelder's 2018 PyCon talk How Code Slows as Data Grows to explain big O in technical-but-approachable terms in under 30 minutes.
→ More replies (7)6
u/Marvsdd01 Apr 05 '22 edited Apr 05 '22
I'm not that good on explaining things, and I assume you're not asking "how to calculate an algorithm's memory or time complexity" - as Big O is directly related to that. So, in that case... When you ask "what is the Big O of an algorithm?" you are asking "how does my algorithm perform in the worst scenario possible?" If you think about a sorting algorithm, you can put the "worst case scenario" as the case where you try to sort a very large amount of numbers, for example. In this case, if this sorting algorithm would, for the sake of the explanation, have a Big O notation of O(n*log(n)) in terms of time spent running it, you're saying that the algorithm makes that amount of operations to complete the task of sorting an array. The "n" in the expression is a general representation of the size of the array, in this case. In most cases, you don't need an exact calculation of the algorithm's complexity, so we use an approximation.
Edit: spelling errors
5
u/Marvsdd01 Apr 05 '22 edited Apr 05 '22
Just so I can add a little more... Let's say you have two sorting algorithms: one performs at O(n2) in the worst case scenario, and other performs at O(n * log(n)). If you explode the size of the array you're sorting, then the difference between those two algorithms become very clear in terms of time spent sorting/number of operations needed to sort the array (as, mathematically, n2 is bigger than n * log(n)). That's the basic idea of using Big O notation (or any complexity notation, actually). If we want to check how two algorithms perform in terms of operations done or memory spent, it would be impractical (or sometimes impossible) to run these algorithms simultaneously and/or in the same running conditions to be able to compare them. Then we use a mathematical expression (complexity notation) so we can generalize performance of code in a way that we don't depend on computers to actually run it, and still can tell how this code is better or worse than another one.
Edit: the text became italic when I used an *
→ More replies (4)
255
u/ICantPCGood Apr 05 '22
Dynamic Programming, itās just recursion with notes about what youāve done already?
We covered it in a class with the only teacher Iāve ever truly called ābadā and then every teacher after just assumed we all knew it š. Could never really grok it on my own or figure out how to apply it.
292
u/procrastinatingcoder Apr 05 '22
It generally refers to keeping a table of previous results, and re-using those for your next calculations. It's nothing special, and I find the term "dynamic" in dynamic programming to be the most misleading thing ever personally.
157
Apr 05 '22
It was deliberately misleadingly named so the researcher could continue funding or something like that.
Itās a shame as the basics are simple to grasp.
14
u/tv_head__ Apr 05 '22
Got any source ? (if you don't mind my asking)
→ More replies (2)115
u/TheAtro Apr 05 '22
I spent the Fall quarter (of 1950) at RAND. My first task was to find a name for multistage decision processes. An interesting question is, "Where did the name, dynamic programming, come from?" The 1950s were not good years for mathematical research. We had a very interesting gentleman in Washington named Wilson. He was Secretary of Defense, and he actually had a pathological fear and hatred of the word "research". Iām not using the term lightly; Iām using it precisely. His face would suffuse, he would turn red, and he would get violent if people used the term research in his presence. You can imagine how he felt, then, about the term mathematical. The RAND Corporation was employed by the Air Force, and the Air Force had Wilson as its boss, essentially. Hence, I felt I had to do something to shield Wilson and the Air Force from the fact that I was really doing mathematics inside the RAND Corporation. What title, what name, could I choose? In the first place I was interested in planning, in decision making, in thinking. But planning, is not a good word for various reasons. I decided therefore to use the word "programming". I wanted to get across the idea that this was dynamic, this was multistage, this was time-varying. I thought, let's kill two birds with one stone. Let's take a word that has an absolutely precise meaning, namely dynamic, in the classical physical sense. It also has a very interesting property as an adjective, and that is it's impossible to use the word dynamic in a pejorative sense. Try thinking of some combination that will possibly give it a pejorative meaning. It's impossible. Thus, I thought dynamic programming was a good name. It was something not even a Congressman could object to. So I used it as an umbrella for my activities.
ā Richard Bellman, Eye of the Hurricane: An Autobiography (1984, page 159)
→ More replies (3)14
u/ICantPCGood Apr 05 '22
Oh, that actually sounds similar to how I would describe it. I guess Iāve just been over complicating it in my head. Thanks!
→ More replies (5)9
88
u/AlSweigart Author: ATBS Apr 05 '22
(Heh, I just got done writing an entire book on recursion.)
YEP. Famously, the name "dynamic programming" is meaningless. The guy behind DP named it that because he wanted to do math research for RAND but the Secretary of Defense hated "research" projects and wouldn't fund them. Though other people say this story isn't actually true.
Dynamic programming falls into two categories. The first is, as you noted, just recursion but specifically the kind of recursive problems that have overlapping subproblems. For example, recursive Fibonacci has a problem where you keep solving the same thing over and over again:
fib(6)is equal tofib(5) + fib(4), which is equal to(fib(4) + fib(3)) + (fib(3) + fib(2)), and so on until the base case wherefib(1)andfib(2)are 1. But notice you're solvingfib(3)multiple times. These are the overlapping subproblems. The return value never changes, so why not just use a little memory to remember the calculation after doing it once and just re-use that result? This form of caching is specifically called memoization (not memorization). Dynamic programming is recursive algorithms that use memoization to handle their overlapping subproblems.Merge sort and quicksort are recursive algorithms, but you don't have any repeat recursive calls there so there are no overlapping subproblems.
The other part of DP is tabulation, which is where you effectively start from the base cases and build up to the big problem you want to solve, storing results in a table in memory to help you solve things. For fibonacci, you're starting from the first two numbers 1 and 1 and building up the the nth number.
These are called "top-down dynamic programming" and "bottom-up dynamic programming". Note that there's no such thing as "top-down recursion" and "bottom-up recursion": all recursion is top-down and "bottom-up" recursive algorithms don't actually have recursive function calls and aren't recursive.
→ More replies (1)4
u/ICantPCGood Apr 05 '22
Thanks! Thatās super helpful. I could recall that there was two approaches but had a hard time distinguishing between them. Also the naming history is good to know because I was definitely trying to read in to the name and figure out what was dynamic about Dynamic Programming which lead to a lot of frustration.
30
u/MyHomeworkAteMyDog Apr 05 '22 edited Apr 05 '22
I think of DP as a bottom up approach while recursion is top down. The typical example is the computation tree of a Fibonacci sequence, Fib(n)=fib(n-1) + fib(n-2). Calling fib(n) this way requires 2n fib() calls, many of which are repeated computations. But with DP, you start bottom up, computing and storing fib(0), fib (1), fib(2), ā¦, fib(n-2), fib(n-1), fib(n) in a table. Each next fib call is solved in constant time, using the values previously stored in your table. This lets us avoid recursively recomputing down to the base case for each fib call. With DP, you start with the base case of the recursion and generate the values up to the starting value. This way you can get an answer to Fibonacci(n) in linear time rather then exponential.
7
u/kupiakos Apr 05 '22
Recursion with memoization would get you the same answer with the same number of
fibcalls, it's just a different approach7
u/faceplanted Apr 05 '22
You're missing one detail though, using dynamic programming prevents you blowing the stack trying to get to the very first lead in the tree to memoize it, dynamic programming, what with the way it works upwards and uses iteration doesn't have that problem.
35
u/Lynx2161 Apr 05 '22
Its recursion with a hash map of previous results nothing fancy
→ More replies (10)21
u/the_last_ordinal Apr 05 '22
I usually describe it as "Recursion plus memoization" and I think that's really all it is.
Memoization is a fancy term for notes about what you've done already
6
u/faceplanted Apr 05 '22
The name is meaningless like everyone has said, but the idea is to optimise recursive problems where parts of the recursion tree repeat themselves, and to start from the leaves of the tree rather than the root. So if you know there's only like 9 possibilities for the base case repeated a trillion times you can just work out those 9, and then work out the parents from those, until you get to the top of the tree, basically shaving off 99% of the tree by precalculating the repeated parts.
The reason it's not "recursion with memoization" like some people are saying is that it's specifically designed to remove the risks of recursion, if you use recursion with memoization, you can blow the stack before you ever get to a leaf to memoize it, with dynamic programming you start at the bottom and use iteration so you don't have that problem, and since as I mentioned there might be only like 9 leaf nodes you can limit your memory usage to a similar number of entries.
4
u/rashnull Apr 05 '22
Yes! This! These meaningless buzz words like āmemoizationā and ādynamic programmingā should be taken to the backyard and shot with a bazooka!
3
u/perpetualeye Apr 05 '22
Yes but the important part is identifying optimal substructure and overlapping subproblems. Once you get that then DP is just that, recording stuff.
5
u/pigeon768 Apr 06 '22
Dynamic Programming, itās just recursion with notes about what youāve done already?
Yes. That's literally all it is. It's hard if you overthink it. It's easy if you don't think about it too much.
Honestly it's a lot easier if you delete the term "dynamic programming" from your memory banks and just think "that thing where you turn a recursive definition of a thing into a non-recursive algorithm to do the thing".
Consider the Fibbonaci sequence. It's got this nice recursive definition: F(n) = F(n-1) + F(n-2); F(0) = 0; F(1) = 1.
So you write the code to do that:
int fib(int n) { if (n <= 1) return n; else return fib(n-1) + fib(n-2); }the trouble is that if you run this for even moderate values of n, it takes for freaking ever to run. (go ahead, try it) The trouble is that fibonacci does not have a "simple" nested structure. As you go downwards recursively, it branches outwards.
Dynamic programming is the pile of all the different methods you might use to improve the runtime. For instance, if you do this:
#include <map> int fib(int n) { if (n <= 1) return n; static std::map<int, int> s; if (const auto it = s.find(n); it != s.end()) return it->second; return s[n] = fib(n-1) + fib(n-2); }...you've done dynamic programming.
If you do this:
int fib(int n) { int a = 0; int b = 1; for (int i = 0; i < n; i++) { int tmp = a + b; b = a; a = tmp; } return a; }...you've done dynamic programming.
Here's the important bit: Dynamic programming is an idea, not an algorithm. There is no set of steps to start with a recursive definition and end up with a realizable algorithm. I've just given you a recursive definition of the Fibonnaci sequence and shown you two totally different algorithms that might fall out of applying "dynamic programming" to the recursive definition.
2
u/mugen_kanosei Apr 05 '22
Here is a video you can watch on the subject. https://youtu.be/oBt53YbR9Kk
2
u/Piyush_2002 Apr 06 '22
Wait dynamic Programming is recursion and here i was getting tensed thinking it's something hard to learn and procrastinate
→ More replies (1)2
u/No_Fold9999 Apr 06 '22
Okay despite all the comments about being a recursive computation algorithm being true. There is a little more to it. I did my Phd. Mainly with respect to dynamic programming.
The fundamental idea of dynamic programming comes from optimization or optimal control. Stating roughly that an optimal trajectory can be splitted and sub trajectory need to be optimal itself. Otherwise the total trajectory was not optimal to begin with. Now this fact is used to construct a recursive solution process, since we now know that we can process a problem iteratively. Moreover it can be used to compute an approximate solution to the Hamilton Jacobi Bellman equation ( PDE) which describes many many processes such as traffic, objects in images etc. So in general there is a little more to it if you study where it originated from.
90
u/hehehuehue Apr 05 '22
What actually is DevOps? I get that it's a methodology but how does Docker and Kubernetes relate to DevOps? What even is Kubernetes and how does it work?
81
u/DevDevGoose Apr 05 '22
Forget technology like Docker and K8s. DevOps is the recognition of how software should be created and run. In the past (and still in backwards companies), development teams "built" software and then handing it over to operations teams to run. This creates a conflict where development teams want to introduce change whereas operations teams want to stop change and keep things stable. This conflict is not good for getting the most out of software.
DevOps is the cultural shift aimed at bringing these 2 viewpoints together and harmonising them for the overall benefit of the software.
As more companies have shifted away from projects and into products and there are org structures that incorporate ideas like Platform Engineering type teams, technology like Docker and K8s have come around to help streamline the process of getting working software into production safely and consistently.
It is common for companies and individuals to not really grasp what DevOps is and so co-opt the term and create job titles related to technology.
→ More replies (2)6
u/painted-biird Apr 05 '22
This is kind of in the same vein, but what is the difference between virtualization- ie using VMware to run Red Hat on my Mac- and virtualized containers Ć la Docker and Vagrant? Iām so confused about this (yes, Iām a total noob- only studying Unix/IT since December), because as I understand you can spin up an OS in Docker and Vagrantā¦
→ More replies (3)15
u/Avastz Apr 06 '22
Docker was born from the thought process of people famously saying "well it works on my machine...why don't we just ship them my machine." And they did.
Think of it as their name/logosake, shipping containers. Whatever is inside the shipping container is shipped off somewhere else, then eventually delivered, everything (theoretically) still enclosed and safe inside. That's what's going on, except it's software and the necessary pieces of an OS and other dependencies to get that software to work.
24
u/kneeonball Apr 06 '22 edited Apr 20 '22
This is a long post but kind will explain the basics of DevOps history at a high level.
If you take the original purpose of DevOps, it's not a methodology, but a culture. In companies that build and deploy some sort of software, there are traditionally two major groups at play on the tech side of things.
Developers - the people who are building the code
Operations - the people building and maintaining the hardware, networks, server infrastructure, etc.
Waterfall
When things were mainly waterfall you'd have a process that looks something like this:
The business would get an idea
They'd talk to some business analysts to get the requirements written down
Those requirements would get handed off to developers and they'd try to relay the requirements correctly
Developers develop the application(s)
Developers throw their app over the imaginary wall to operations and say "Here, run this in a test environment"
Operations tries to figure out how to run it, and often isn't involved in the planning process
Testers would test, and send bugs back to Dev
Dev would try to fix bugs
Deadline would come up, and developers would throw it over the wall again and say we need to run it in production
This process is full of siloed teams that are operating independently of each other and all have different goals. Developers would get mad at testers, testers would get mad at developers, operations would get mad at developers, developers would be mad at business analysts not relaying requirements right, there was plenty of blame to go around in most cases. Basically, after several months to a year or two, you'd go from idea, to deployment into production and all of these teams have barely collaborated.
There were all kinds of things that could be done better. Devs would manually deploy, operations would make network changes or patch servers and break the applications, there was mostly (or all) manual testing, so bugs would get introduced or reintroduced constantly.
Agile
The Agile Manifesto came along and we started trying to change the way we work, and it was effective at getting business analysts, developers, and testers all working together on the same team, but there was still a divide between the development and operations teams in most cases.
DevOps
Along came DevOps, which at its heart is a culture of collaboration between Development and Operations groups. They don't have to be on the same team. You don't even have to have someone called a DevOps engineer, and you don't have to be working with Docker or Kubernetes to be a DevOps organization. What it really boils down to is breaking down silos and collaborating earlier in the process.
This collaboration lead to operations helping development early on in the process with designing something that can run efficiently and effectively, and development could help with operations problems. In the past, someone manually did updates on each and every server by logging in, running the update, and checking it worked after. Maybe they got to the point where they were writing a script to do it, but it was still tedious. With Dev and Ops collaborating, this is where more automated tools came in.
Big DevOps concepts
You had automated server provisioning with tools like Terraform. No more manually building each server, or running a script to do it. Write some code for the configuration, and the tool will know how to build the server or resource for you.
You got automated configuration management tools like Puppet, Chef, Ansible, SCCM, etc. Define a configuration for a server, and let the tool automatically set the configuration on t he server for you without you ever having to log in and touch it. An added bonus, what if someone logs in and manually changes the config in an undocumented way? Well, the tool will reset it, making sure it always matches what you intended via code.
You got automated build tools, like Jenkins. No more pushing code, deploying, and hoping it works. You can automatically run tests and build the application every time a code change is pushed, in a standard way defined by how you configure it on the server. No more "The build for production only works with Bob's configuration on his machine for some reason." or anything like that.
You have automated deployment tools, like Octopus, Harness, Azure DevOps, etc. (lots to list here). Gone are the days of manually remoting into a server and copying and pasting the build artifacts over to the server.
You got better monitoring tools. Ops would generally have to figure out how to monitor the application (Application Performance Monitoring) and server, but with a DevOps culture, came tools like Prometheus (server monitoring), Data Dog, New Relic, AppDynamics, DynaTrace, etc.
Docker and Kubernetes
Then we figured out running apps inside of containers was nice, and then we had so many running in containers, that we needed to better orchestrate those, and along came Docker Swarm and Kubernetes (Kubernetes won obviously). If you think of a virtual machine and how it relates to a real machine (where we're virtualizing hardware to run multiple servers on the same set of hardware), I like to think of containers / Docker as virtualizing the Operating System. You package all the dependencies of your application with the application, so that as long as you deploy to a server that has the Docker Engine (or whatever container engine you want) on it, the app will run. In the past, this was a hard task as you had to have someone go and install all the tools necessary for running the application manually on each server. Later, we had Configuration Management tools to help with this some, but it was still a pain.
Kubernetes came along from the need to better manage all of these containers. Instead of running a single app on a single virtual machine, or several on a virtual machine, Kubernetes allows you to take an inventory of your entire data center you want added to the Kubernetes cluster, and Kubernetes can help you with running containers on your servers. In the past we had to manually decide where each server would go, where each app would run, set up all the networking for it, etc. With Kubernetes, we just tell it we want to run x instances of this container, and we want to increase the number of instances if the load on them gets too high, and Kubernetes figures out where to run them for you. In the past, if you decided you probably would need 4 servers to run your application in production, and then your app was more popular than expected, you now have to get another virtual machine ready with the right OS, give it an IP on the network, add it to the load balancer pool, deploy your app to it, and hope you did everything right so it would run. With Kubernetes, it just adds another instance wherever it thinks is best and you don't have to touch a thing.
Then you can take it a step further and go from plain old Kubernetes to a Service Mesh with something like Istio, linkerd, Consul Connect, etc.
Why the term DevOps has become bastardized
All of these tools came from a collaboration between Dev and Ops. Instead of solving their own problems separately, they solved problems together and we have vastly improved the way we build and ship software in the past 5, 10, 15+ years.
The companies that started doing this collaboration and coming up with these tools and talking about them at conferences would get other companies who weren't as good at tech wanting to do them. They'd see a company doing automated deployments as part of their DevOps culture, and that company would say "I want a DevOps engineer to build automated deployments for us." It's kind of bastardizing the core of the DevOps movement, because usually what these companies do is take two silos, Dev and Ops, and add a 3rd silo and call it DevOps. The whole idea is to remove silos and work together, not add another silo, but it is what it is. The DevOps engineer has been created and it's usually a term for someone who does release automation engineering, or infrastructure automation engineering (or both). In a perfect world, we'd still consider all of these Ops jobs separately, but companies that don't know any better use DevOps as a catch-all term for trying to improve what they do without solving the real problem to begin with.
This was a high level overview of a lot of concepts, and most of them probably won't make sense right away, but take it one piece at a time. Listen to some talks like what I have linked below and you'll start to get a better grasp on it. The guy in the video is coming at it from an Ops perspective mostly as he runs operations teams, but does a great job of explaining the dynamic of why a DevOps culture is helpful.
https://www.youtube.com/watch?v=qLUt6bwNnks
TL;DR: DevOps is a culture, not a methodology, but companies that don't know what they're doing have created the term DevOps engineer and think it's a thing that you do because they aren't good at building software. So even though a DevOps engineer shouldn't exist in theory, it does and it could mean a lot of different things.
Edit: Sorry for any small mistakes or anything, was late at night when I typed this.
→ More replies (2)8
u/truechange Apr 05 '22
I'm not really a devops guy but I think it's really just a general term of how moderm server admin and deployment stuff is being done today. Docker is the most popular containerization tech used these days that's used to deploy web apps, and, Kubernetes is used to manage multiple docker containers. You don't really need this to deploy stuff unless you're scaling real big.
→ More replies (5)3
u/SquarePixel Apr 06 '22
DevOps is the idea that development and operations should not be separate. Part of realizing this is to describe everything as code: the software, the infrastructure, the process. When you do this it enables new ways of working where you can have these incredibly tight feedback/iteration cycles (that were previously considered āimpossibleā) where itās no longer unusual for developers to bring new features to production on a daily basisāa true embrace of āagileā.
There are many ancillary benefits too, such as onboarding new developers; the sometimes multi day ordeal of āsetting up a new dev environmentā can be fully automatic. There is much more to DevOps obviously, but this is how I like to distill it.
133
u/shawntco Apr 05 '22
Wtf is a monad, functor, etc
96
u/Servious Apr 05 '22 edited Apr 06 '22
IMO these things are best understood through the lens of Haskell's
Maybetype.Very simply, a
Maybe Intfor example can be eitherJust 5orNothing. At its most basic form, it can be used with pattern matching. For example here's a haskell function that adds 2 to a Maybe if it's there:add2 :: Maybe Int -> Maybe Int add2 (Just n) = Just (n + 2) add2 Nothing = NothingYou can see we had to use pattern matching to "unwrap" the actual value of the maybe so we could add 2 to it. This is pretty inconvenient and pretty annoying especially if you're trying to do something more complex than simply adding 2. That's where
Functorcomes in.
Functorallows you to apply a function to the value inside the functor and get back the modified functor by using thefmapfunction. Here's what that definition looks like:fmap :: Functor f => (a -> b) -> f a -> f bThis definition is a bit complex so I'll break it down. This is saying "fmap is a function which is defined for any
Functorf. This function accepts a different function fromatob; and a functor containing ana; and returns a functor containing ab."aandbcan be any type. What makes something a functor at the very base level is whether or not this function is defined. You can think about it like mapping over a list in any other language because that's exactly whatfmapis defined as for lists.So in our
Maybeexample, we can use it like so:add2 :: Maybe Int -> Maybe Int add2 x = fmap (+ 2) x -- or add2 x = (+ 2) <$> x -- <$> is just an infix version of fmap; same exact function.Much more convenient, and as an added bonus it looks a bit more like regular function application (in haskell anyway).
We're not quite to monads yet because there's a step between
FunctorandMonadand that's calledApplicative. Instead of starting with the (somewhat confusing) definition, let me pose a question: what if I have a function with more than one argument that I want to passMaybes into? Like what if I wanted to add twoMaybevalues together? That's the problem applicative solves.With functors we can do:
(+ 2) <$> xBut with an applicative instance we can do:
(+) <$> maybeA <*> maybeBthe result of which will be a
Maybecontaining the result of adding the two values inside. If either of theMaybevalues areNothingit will come out asNothing. And this pattern is extendable for more than just two arguments as well. For example:functionWithManyNonMaybeArguments <$> maybeA <*> maybeB <*> maybeC <*> maybeDSo to quickly summarize: functors allow you to apply a function to the inside of one "wrapped" value (like
Maybe). Applicatives allow you to apply a function of many arguments to many "wrapped" values. Now, here's where we get to monads. Here's a situation you might be in:someFn :: a -> Maybe c someMaybe :: Maybe aHow would you feed that
someMaybevalue into thesomeFnfunction? You might guess to usefmapfrom functor, but let's look at what would happen:fmap someFn someMaybe fmap :: Functor f => (a -> b) -> f a -> f b -- so in this case fmap :: Functor Maybe => (a -> Maybe c) -> Maybe a -> Maybe (Maybe c) -- so fmap someFn someMaybe :: Maybe (Maybe c)Oof, double-wrapped
Maybe; That's not right. This is the problemMonadsolves with thebindfunction or>>=operator. The correct code for this would be:bind :: Monad m => m a -> (a -> m b) -> m b -- again, >>= is just an infix version of bind; exact same thing. someMaybe >>= someFn :: Maybe cAlso worth noting that for something to be a
Monadit must also beApplicativeand for something to beApplicativeit must also be aFunctor. So all monads are also applicatives and functors.Sorry if you don't know any Haskell because this is pretty complex and very haskell-focused, but I kinda figured you wouldn't be asking these questions without a passing familiarity with some haskell. Feel free to ask any questions; I love talking about this stuff!
19
u/teito_klien Apr 05 '22
This is by far one of the best explanations of functors, applicative and monads, Iāve ever read.
Thanks a lot !
17
u/FiveOhFive91 Apr 06 '22
This is by far the first explanation of functors, applicative and monads, Iāve ever read.
→ More replies (5)5
Apr 05 '22 edited Apr 05 '22
This is a really clear explanation, so thank you for writing it. I hadn't understood fmap or bind at all before this, and I had seen them used a lot, but they ended up being a lot simpler than I anticipated. I still have a few questions though, and because you said questions are welcome, I'll ask:
I looked up the difference between
(<$>)and(<*>), and it looks like this is the type signature difference (the top I just copied from your comment).fmap :: Functor f => (a -> b) -> f a -> f b (<*>) :: Functor f => f (a -> b) -> f a -> f bWhy is (<*>) an applicative and fmap a functor? Also, you said that fmap deals with monads like Maybe, but the type signature looks like it deals with functors applied to some type a and some type b. Am I misinterpreting it?
→ More replies (3)33
u/WhoTouchaMySpagoot Apr 05 '22
Thereās a vid on youtube by brian beckman. Itās called donāt fear the monad
21
5
u/ExtraFig6 Apr 05 '22 edited Apr 05 '22
Start with functor.
If you tell me programming languages you're familiar with i can give you code examples
If you've used a function like map or for each, you've probably used functors.
A functor has two parts. It does something to types, and it does something to functions between those types.
For example, list. What does list do to types? It gives you a new type called list of ___. So
int => list<int> string => list<string> list<int> => list<list<int>>Now what about functions? Well, you can map functions across a list. So if you have a function
f : A -> BYou can map it
list-map(f) : list<A> => list<B>By doing f to each element in the list, returning the result.
Optional/maybe/nullable is also a functor. You can think of it as being a list that can only have 0 or 1 element.
What does map do? If you've used an Elvis operator, it's like that. If the input is null, just return null. Otherwise, do the function.
→ More replies (3)→ More replies (10)2
31
Apr 05 '22
Advanced algorithm analysis and probabilistic algorithms (Las Vegas and Monte Carlo algorithms). First one because i find the subject boring and the second, because i struggle with probability theory and stochastic processes.
66
u/procrastinatingcoder Apr 05 '22
Pohl Ira has a great way of vulgarizing the Monte Carlo algorithm, or well, the general idea behind it. So I'll just be re-using his explanation.
Let's say you were playing a game of chess. You want a computer to do "optimal" moves. So you try to calculate every possible game. This whole thing goes out of control very fast. It's trivial for the first few moves, there's not that many options, but it multiplies very very fast.
Two little concepts:
The question changes to "What's a good move". We'll define a "good move" as a move that gives you more chances of winning than losing.
If two people of identical skill level play, you'd expect that over a thousand or ten thousand games, the victories would be split 50/50 roughly.
Now, identical skill level can mean both masters or... both complete and utter idiots. So let's say the computer plays both sides of the game, but instead of calculating anything, it plays completely randomly . So both sides play completely randomly, which is an "identical skill level". Where over a thousand games, you'd have roughly 500 wins and 500 loss for each player.
How does this help us? Well, let's say that instead of playing completely randomly, the computer plays completely randomly EXCEPT the first move. Which is always the same for one of the players. If that player "wins" more than a rough 500/500, then you could assume that move gave some sort of advantage to that player. And the more skewed it is, the "better" the move.
And while calculating every possibility is incredibly demanding, playing randomly is very easy for a computer.
So the computer just does exactly that. It picks a "first move", does a thousand games, sees if it wins or loses more. Then it tries another "first move", and does that for a bunch of them, then it takes the one that seems the most "advantageous".
So nothing is set in stone, everything is random, you have no idea why it works, but your algorithm gives you a "good move".
In general though, Monte Carlo just talks about trying and experiment multiple times, and using those results to make a decision of some kind. In a trivial way, you could roll a 6-sided dice 1 million times. And then if you were to bet on the next number, just pick the one that had the highest count when you did your experiment.
Note that the dice might seem not to make sense, all sides are equals. But think on it for a second, are all dices perfect what if it was slightly worn, and that it had a very very very small imbalance that gave a bit bigger odds that it would land on a particular side. Testing it with a million rolls would give you a good idea, which is also easier than trying to do a perfect physics simulation of the die.
As for heuristic algorithms in general, I think the primality test is a fairly easy one to understand, but I've already written a wall of text here.
6
22
u/Herpnasty11 Apr 05 '22
Quantum computer as a whole lol
17
u/faceplanted Apr 05 '22
For a non quantum explanation, quantum computers basically make one specific matrix operation O(1) so if you can convert your problem into one of those, you can speed up operations that that could normally take effectively forever on a conventional machine.
This is why cryptography is considered in danger if quantum computers become powerful, certain encryption algorithms rely on computers not being able to do certain operations quickly with large inputs, but we've shown that you can map those problems onto that operation quantum computers are good at. So rather than taking a billion years to decrypt, your message could take seconds/minutes/hours, even days would be far too fast, you need it to take millennia.
→ More replies (1)6
u/hehehuehue Apr 05 '22
WIRED has a really good video on this
TLDW: Imagine a coin spinning constantly and not landing on either heads or tails, compared to binary where a coin MUST be either heads or tails.
6
u/evinrows Apr 05 '22 edited Apr 05 '22
But how do you solve a problem with that technology?
I know the answer is "something something every combination of people solutions at the same time," but at some point you have to collapse the quantum state. So how/when do you do that such that you get useful information back?
8
u/DONT_HACK_ME Apr 06 '22
You use algorithms that slightly change the system (but not collapse it) so that when you do measure the system, collapsing it, the correct solution is much more probable to be found than the incorrect solution.
Then you run the algorithm several times to verify what the correct solution was.
3
u/TangerineX Apr 05 '22
You can think of computers like marbles flowing through a large marble contraption. At the end of the contraption, there are several buckets. If your marble can flow through the contraption and land in some of the specific buckets, then we consider the program to return "true" and if not, the program returns "false".
Now instead of a bucket, what if it just leads to the start of another marble contraption. This is the basis of how functions work, we feed the results of functions into each other.
Now consider the case where we don't know exactly which functions we should use, or what data we should use to get our results. Imagine a scenario where the only thing we can do is try a huge number of combinations. In our marble example, we have a ton of input locations, and we have to find the right one to drop it.
So quantum computing is fast because what it allows us to do is simulate dropping the marble into all (or at least a lot) of the start location at once. Sure, a lot of them will fail, but we're only interested in the ones that succeed.
This is very very simplified explanation of how quantum computing as a whole, and I'm sure you can read more into it
→ More replies (1)2
u/LaChapelleAuxSaints Apr 05 '22 edited Apr 06 '22
There's a computerphile video covering this quite intuitively. It only covers the superposition aspect of it though but since it is one of the hardest concept to grasp, the way he explained it helped quite a bit.
→ More replies (2)
19
Apr 05 '22
Casting and upcasting in Java :/
→ More replies (2)18
u/procrastinatingcoder Apr 05 '22
All dogs are animals, not all animals are dogs. Logically you can go one way, not the other.
More specifically, I'm not sure of what bytecode gets generated for the JVM, but as far as C++ and a few other compiled languages go, what "inherited" classes do is just "copy" the inherited code with their own code right beside it. So you can always refer to something you copied, but you can't generate the missing pieces afterwards.
→ More replies (1)
15
u/rhett21 Apr 05 '22
OOP. Currently taking DSA in C++, always confused what's an object, and when does an object get promoted to OODesign.
16
u/lurgi Apr 05 '22
There's no real promotion.
An object in most languages is first a way of bundling up data and functions that operate on that data in a handy way. That's encapsulation. Usually you also have a way of saying "These things are a lot like these other things, but they have extra stuff, too". That's sub-classing. Finally, you typically have a way of hiding some details from the people who are using your class/object. The sorts of inner workings that they don't need to know about, but you, the author of the class, do need. That's information hiding.
It's not exactly clear why this is so useful when you are working on small programs. Then again, just about everything works with small programs. You can use goto all over the place but everything is small enough that you can grasp the whole thing. A lot of programming techniques are about managing complexity as programs grow.
Anyway, what is a class? Typically, classes are nouns. They are things. These things "do stuff".
Imagine you are making a Connect 4 game. What are the "things" in the game? Well, there's a Board. That's a start. The board contains a bunch of Pieces (these could be classes, but probably aren't complex enough to merit it). What sort of things does the Board do? How about playing a piece? We could just put the piece at the specific location, but it's better if we tell the Board "Player 1 is dropping a piece on column 2" and let the Board work out where it goes from there. We can also ask the Board "Did anyone win?".
The nice part is that all the game logic is bundled up in the Board class rather than being scattered everywhere.
→ More replies (4)3
u/TangerineX Apr 05 '22
I recommend reading Design Patterns: Elements of Reusable Object-Oriented Software (you can find PDFs online). While objects and services and classes make up the basis of OOP, there are larger meta-structures that help you understand how to actually write code in an OOP environment. Design Patterns are sort of like bigger patterns of code that a lot of other engineers have gone through and realized are applicable very often. Learning about design patterns really helps understand how OOP works, and how to write better OOP.
For each design pattern, it's important to understand the following
What problems it seeks to solve/when to use the design pattern
Why is the design pattern helpful? How does it work?
How to implement the design pattern.
14
u/Sedowa Apr 05 '22
I'm reading through stuff about virtual functions and class pointers to them and I've found I just don't understand why it has to be so complicated. Seems it would be a lot easier to just avoid using them and code around it but maybe there's a performance reason for it.
Same with lambda functions. It was explained to me as being a function that just gets run once so doesn't need a fancy definition but seems to mostly just make readability harder for not a lot of gain. Once again this could just be a performance thing and maybe it helps with larger applications rather than the smaller ones used in teaching material.
It's hard to wrap my mind around the point of it all.
→ More replies (8)
14
Apr 05 '22
linked lists bruh i cannot get it rn
→ More replies (8)2
u/tastes-like-chicken Apr 06 '22 edited Apr 06 '22
Let's start with pointers, they're fundamental to the concept of a linked list. A pointer "points" to some location in memory. It isn't actually the thing that it points to, but it holds the memory address of that thing. Pointers can get a bit complicated as you read more about them but just remember that they point to a memory address where something is located, and you can access that something by dereferencing the pointer.
Now we'll talk about arrays, since it will help you understand why linked list are useful. Arrays are stored contiguously in memory. This means that if you have an array with 5 elements, you need 5 blocks of memory that are side-by-side to store that array. More info on that can be found here if you need more explanation. Just remember that arrays are stored contiguously, so they require a chunk of memory large enough to store each element side-by-side.
What if we don't want to store our data contiguously? Enter linked lists. Linked lists are like arrays in that they store a "list" of data. Unlike arrays, the elements in a linked list can be stored non-contiguously, meaning they don't have to be side-by-side in memory. This is because of pointers. Each element in a linked list, referred to as a Node, stores a piece of data and a pointer to the next element. That way, we can "connect" all of the elements in the list, so that you can get from the first element, to the second, and so on.
Why not just use an array? One of the tricky things about (non-dynamic) arrays is that it's expensive to delete elements, insert elements into the middle of the array, or resize the array because you essentially need to copy the old elements into a new array or write over the existing elements. With linked lists, deleting nodes only requires removing data and rearranging pointers. You also don't ever need to resize a linked list, as nodes can be added anywhere in the list by rearranging pointers. The downside is that you can't access a particular element as quickly as an array, because you have to traverse through each element starting at the head (or tail) node. Also inserting at the end of the list is expensive as you have to traverse the entire list, while inserting to the end of an array happens in constant time.
How are linked lists implemented? There are many ways, but typically you would create a Node object using a struct or class, and that object would hold one variable for the data and one Node* pointer to point to the next node. The list itself could be another class that contains a head Node, which is used to access all other elements in the list.
Hopefully that helps!
12
Apr 05 '22
I donāt understand for what Docker is used or in what projects I should use it
20
u/TheNintendoWii Apr 05 '22
Docker is used when you have something that needs a special environment. Letās say itās a Python project that needs a lot of packages. Instead of installing everything on each machine you have it on, you build a Docker image with all packages installed, so you can run that and everythingās set up. It also separates the program from the host machine, adding security.
13
u/littletray26 Apr 05 '22
Containerisation allows you to package up your application and all its dependencies into a deployable module / package that runs in its own container
It means you don't have to worry about the configuration of a target environment - your app runs identically, everywhere.
Docker is one of the more popular container solutions / engines.
→ More replies (3)7
u/truechange Apr 05 '22
If your app is dockerized, it will run in any server/host that supports docker. So whether your app needs Nodejs, PHP, Python, whatever, any docker host will run it.
10
u/Brafaan Apr 05 '22
Abstract class vs interface class, and when to use them and why.
10
u/SavvyPlatinum Apr 06 '22
Put simply.
Interface is just a structure that a class has to follow. The interface might say "a class needs to have an Add method and a Subtract method", but the interface doesn't implement the methods. It allows you to define the name, inputs and output type of methods in the class without implementing them. It's up to the class how to implement it. It's useful if you'd like multiple classes that do the exact same thing but in different ways, then you can use an interface to force them to share the structure.
An abstract class is just a normal class, but you can't instantiate them. You can leave the implementations empty (similar to interface), but you can also implement some methods. If you do, any class that inherits this abstract class will also inherit the implementations. It allows you to share implementation of methods between some classes if you know those implementations will be the same.
A class can both implement an interface and inherit an abstract class at the same time.
Feel free to DM if you'd like it explained in more detail.
→ More replies (9)→ More replies (1)3
u/Rote515 Apr 05 '22
What language are you using? Iāve never head an interface called a class before. In C# though an Abstract class is a skeleton parent class that outlines how every child class will look. It can also implement functionality, that child classes can use. Beyond that each class can only inherit from a single abstract class.
Interfaces donāt implement functionality, they just define the functionality, you can also have many of them.
→ More replies (2)
10
u/IceCattt Apr 05 '22
No matter how many times I see it explained, dependency injection still baffles me.
7
u/toastedstapler Apr 06 '22
so first off let's write a non DI solution:
class UserGetter { DataBase database = new DataBase(); List<User> getLoggedInUsers() { List<User> users = database.getUsers(); return users.stream().filter(user -> user.loggedIn).collect(Collectors.toList()); } }now if we want to test this class we've introduced an awkward situation - we need a database in order to run any tests as the class is auto instantiated on creation. if we go for a DI approach:
class UserGetter { DataBase database; public UserGetter(Database database) { this.database = database; } List<User> getLoggedInUsers() { List<User> users = database.getUsers(); return users.stream().filter(user -> user.loggedIn).collect(Collectors.toList()); } }we can now subclass
DataBaseand make a classTestDataBaseclass TestDataBase extends DataBase { public List<User> getUsers() { return List.of(new User("james", true), new User("jenny", false)); } }and in our tests we can test our class with the mocked database connection so we can supply our own custom test data without requiring a database for running unit tests
TestDataBase t = new TestDataBase(); UserGetter u = new UserGetter(t); assertEq(u.getLoggedInUsers(), List.of(new User("james", true));3
2
u/lionhart280 Apr 06 '22
Luckily I made a blog post for this topic because it comes up so often, enjoy!
https://blog.technically.fun/post/dependency-injection/dependency-injection-part-0/
PS, this blog post helped me nail a job interview. On the phone portion they asked me if I could explain DI and I was like "Wait, hold on, I have an entire blog post that does exactly that, can I just give you my blog address?"
They were like, "Oh! Wow! Aight, absolutely" haha
16
u/tube32 Apr 05 '22
Constructors and why are they important.
Same about setters and getters. What's the point of declaring a variable private only to allowed to access them via public methods?
Dependency injection
15
u/door_of_doom Apr 05 '22
These are all really good questions, and I don't feel like the answers you have gotten so far are adequete.
Interestingly, all of your questions fall into a really interesting realm of programming that concerns itself with "validity," or whether or not data is in a "valid" state.
What does it mean for something to be ain a "valid" state? Well imagine if you got a bill for your internet, and it was missing a few crucial things: It is missing important things, like the due date or the balance due. These are all critically important things for a bill to have, but your bill doesn't have them. This bill is not a valid bill. Bills have to state how much is due and when it is due.
Invalid states are really scary for programmers: Something that you generally don't want to have to do when programming a function is to manually validate all if your input, every single time. Some languages do require you to do this, but some languages give you tools to make it so that you don't have to.
This is where many languages try to give you the tools to design your code to make it "Easy to do the right thing, and hard to do the wrong thing." We generally want it to be easy for our data structures to be in a valid state, and hard/impossible for it to be in an invalid state.
So, consider a constructor: A constructor is a way of defining the bare minimum that an object requires in order to be considered valid. To use our previous example in a very silly way, if the only way to create a
Billobject is to call theBillConstructor, which has the paramatersfloat amountDueandDateTime dueDate, it would be nigh impossible to ever create aBillthat doesn't have anamountDueor adueDate.(There are other ways of achieving this, for example, the Builder pattern, but we won't go into that right now)
Now, whenever you are writing a function that includes a
Billas a paramater, you don't need to verify whether or not is currently has adueDate, you can know that it is always guaranteed to have one, as it is impossible to create one without it.Getters and Setters follow similar thinking: Many times, we don't want to give complete and unfettered access to our underlying data structures, because then it might be possible to invalidate the underlying data. For example, what if some bozo goes out and tries to set the
dueDateof ourBilltoNULL?NULLis not a valid due date, so instead of allowing them to have direct access to theDueDatefield of ourBillClass, we ask them to use thesetDueDatefunction. We can then add validation logic to oursetDueDatefunction that throws errors if they every try to do something illegal like set thedueDatetoNULL."But what if I don't need any validation logic?" You might ask. "Do I still need to use Getters and Setters?" The answer is basically "Technically no, but you might hate yourself later if you don't use them." While you might not think you need any validation now, you might change your mind later. And if you do change your mind, it is a lot easier to add validation logic to a function that already exists, rather than to create a brand new function and ask everybody to stop doing things the old way and start doing things the new way. What could have been a completely invisible improvment to your library is now a breaking change that negatively effects everybody downstream. By using Getters and Setters everywhere, you are future-proofing yourself against possible breaking changes down the road.
Dependency Injection is a pretty controversial topic, to be honest. First off, (and this applies to the constructors, getters, and setters too) in no way shape or form is it "needed." It is more a style (or framework) for programming that has certain pros and cons.
Put simply, think of Dependancy Injection as a different way of thinking about Constructors.
When we talked about Constructors before, we made it so that our Object class needs to define what it needs in order to be valid, and then whenever we have code that intends to create one of those objects, it needs to take it upon itself to provide everything that the new instance of the class is going to need. in our
BillExample, that means that whenever you want to create a newBill, you need to be ready to provide a validamountDueanddueDateWhat Dependancy Injection does is provides you with a (metaphorical) machine that knows and understands what Classes need in order to be instantiated (their dependancies), so if you want an instance of something (like a Bill), you can simply ask your Dependency Injection framework to provide one for you; it will analyze the dependencies of what you asked for, see if it knows how to generate those dependencies, and "inject" them into the instance, providing you with a new, neat, and (most importantly) valid instance of that class.
What people generally don't like about DI is that it starts getting really magical. The idea is that once you have wired up all of the dependencies and taught the DI framework how everything works, you can just ask it for an instance of something and it will just magically make one for you. It obfuscates things that some people don't really like being obfuscated. That "magic" can be both a blessing and a curse.
Anyway, even though this was a long-winded comment, it really was just a brief overview of these topics. If you have any followup questions, I'd be happy to answer.
→ More replies (3)5
u/AlSweigart Author: ATBS Apr 05 '22
Constructors are the code that set up (i.e. initialize) the member variables (i.e. the state) for new objects.
Say you have a
Rectangleobject withwidthandheightmember variables. It has a constructor where you set up this info when you create the object, like:Rectangle foo = Rectangle(5, 10);Then later you can call thearea()andperimeter()methods of this object and they return50and20, respectively.If you didn't have to specify this in the constructor (like, you could just call
Rectangle foo = new Rectangle();then this puts you in a situation where callingarea()andperimeter()would have to raise an exception, because the width and height of the rectangle are unspecified. If you forgot to write code to catch this exception, then the unhandled exception crashes the entire program.Forcing you to specify this info right from the start of the creation of the object can prevent bugs later on.
2) You want to have setters and getters because they can also run some code to do some checks before they get or set a member value.
For example, say you have $500 in a bank account and this is represented by a
BankAccountobject'sbalancemember variable being set to500. The rest of the program counts on this member variable always being positive, and there can be unknown bugs if it becomes negative for some reason.When you withdraw some amount of money (specified by an
amountvariable), you can runssomeAccount.balance -= amount;. But ifamountis600, this code setsbalanceto-100. At some point later, this cause a bug and it's hard to trace the cause back to thissomeAccount.balance -= amount;` code.The solution is to add a
set()method to theBankAccountclass which raises an exception if you try to withdraw more than what's in the account. Even if this exception goes unhandled and crashes the program, it "fails fast" and you immediately know when a problem has occurred.But you still have a problem because
balanceis still public and can be modified by code anywhere. What you need to do to prevent this is makebalanceprivate and only changeable by other classes through a setter method.Here's the confusing part: in Java, from the start we often create a bunch of public boilerplate getters and setters for every member variable, and make the member variables private. So you have a bunch of
getBalance()andsetBalance()methods forbalanceand every other member variable. But they all look likepublic getBalance() { return this.balance; }so we ask "why do we need this getter?"The reason is because if you force everyone to use getters and setters from the start, if you later need to add in some logic or checks to the getters/setters, you can just add that code. If you didn't have getters and setters (e.g. writing code that directly modifies
balance) then you'd have to write those checks and go through your entire code base to change everything to use getters and setters. This is such a common headache, that IDEs usually just set up these generic setters and getters. But they're so generic and don't do anything but, well, get and set that people wonder why we even have them.I like how Python avoids this by having properties: you can directly modify a value like
someAccount.balance = 200and if you need to add logic or checks later, you turnbalanceinto a property that calls a setter method you create, and200is passed to it. You can turnbalanceinto a property and you don't have to rewrite any of thesomeAccount.balance = 200code.3) Oof, this is too big of a topic for me to write here.
→ More replies (5)2
u/Longjumping_Round_46 Apr 05 '22
I don't know how much you know about OOP, so I'll try to keep it simple.
Say you have a class that represents a real world object.
public class Person { }Classes can have data members and functions.
public class Person { public string name; public int birthYear; public void IntroduceYourself() { Console.WriteLine("Hi, my name is {name}, and I was born in {birthYear}"); } }With constructors, when you create (instantiate) a new class, you can set the date members right then and there.
public class Person { public string name; public int birthYear; public void IntroduceYourself() { Console.WriteLine("Hi, my name is {name}, and I was born in {birthYear}"); } public Person(string name, int birthYear) { this.name = name; this.birthYear = birthYear } }And when you want to create a class:
Person terry = new Person("Sir Terry Pratchett", 1948); terry.IntroduceYourself();
8
u/ruffles_minis Apr 05 '22
I just cant quite fathom lambdas. I've tried to understand but to no avail
11
u/plastikmissile Apr 05 '22 edited Apr 06 '22
You know what functions are, right? That's what lambdas are essentially. They are functions. They have a weird syntax, but in the end of the day they are nothing more complicated than functions. But here's the kicker, many languages these days have taken a page from functional languages and are now treating functions the same way they treat data. Those functions are packaged as lambdas. So you know how functions can take numbers and strings as inputs and outputs? Well now they can take lambdas as inputs and outputs as well.
Let's see how that looks like. I'll be using C#, but the concept is the same everywhere. Let's say we have a class that has an internal value. I'd like to have a method that does operations on that internal value with a value that I provide. The old way of doing it would be something like:
public class Something { private int internalValue; public int Add(int x) { return internalValue + x; } public int Multiply(int x) { return internalValue * x; } }Looks good. It works. But say, I decided I wanted to add subtraction and division as well. Then some annoying customer wanted to add something even more complex that involves more than one operation. In the old way, we would have to keep adding different methods.
Now let's see how we might tackle this the functional way:
public class Something { private int internalValue; public Something(int value) { internalValue = value; } public int Math(int x, Func<int, int, int> function) { return function(internalValue, x); } }So now we have a new method that we called
Mathand it has an argument of typeFunc<int,int,int>. That basically means it expects that argument to be a function that takes twointvalues and outputs anintin return. This one method will replace the 'Add' and 'Multiply' methods from the old solution, as well as any others we can think of (as long as they just take two values with the first one being the internal value). And here is how use it:var something = new Something(); var addResult = something.Math(5, (a,b)=> a + b); var multiplyResult = something.Math(5, (a,b)=> a * b); var subtractResult = something.Math(5, (a,b)=> a - b); var complexResult = something.Math(5, (a,b)=> Math.Pow((a + b) * b, a));See how powerful that is?
→ More replies (2)→ More replies (1)4
u/Putnam3145 Apr 06 '22
For the vast majority of purposes, you can just think of them as functions without names.
7
u/ManadaTheMagician Apr 05 '22
Linker, the linker is just magic
2
u/__Fred Apr 06 '22
As there is no answer here, yet:
You mean, the linker as a part of creating an executable program?
AFAIK there are multiple steps if you compile a C program with multiple source files. You parse it, you translate it to assembler or directly into binary machine code. Then you have multiple "object"-files for each source file and then the linker combines them together.
I imagine he just concatenates them to each other and then he would also have to adjust the addressses of references to any memory location. Maybe there is a complicated algorithm here that you don't understand.
→ More replies (1)
7
u/SwishArmyKnife Apr 05 '22
Linked lists have been one thing I canāt grasp. One, I donāt think I understand why sequential traversal would be preferred over sequential access. Two, the code for navigating to each new one just doesnāt make sense to me. I feel like I end up looking at it like every 2 months and nothing new sticks or clicks.
→ More replies (8)11
u/MrSloppyPants Apr 05 '22 edited Apr 05 '22
Linked lists are just a data collection that points to the next one in the list. It can also point to the previous one in the list if it is a "doubly" linked list.
Where linked lists are useful is the speed with which you can perform insertion of items into the list. With an array, an insertion at any place but the end is at worst an O(n) operation because all the elements of the array must shift to accommodate the new item. Whereas inserting into a linked list is just changing the pointers of the items you are inserting between. At best it's an O(1) operation, constant time regardless of the size of the list.
→ More replies (4)
7
13
u/Silent__Note Apr 05 '22
Static (I'm beginner in Java)
6
u/EdenStrife Apr 05 '22
Static means you can access a function on a class without creating an instance of the class.
So for example the Math class. You want to be able to do arithmetic without creating a Math object in memory to do it for you.
11
u/ThatWolfie Apr 05 '22
https://www.reddit.com/r/learnprogramming/comments/twuf18/-/i3hzf6v this dude explains it well.
static functions are functions that do not need the state of the object. so if your method doesn't use
thisat all, it can be and should be (in most cases) static.static methods don't require you creating an instance of an object either.
→ More replies (1)3
u/Emerald-Hedgehog Apr 05 '22 edited Apr 06 '22
In very short with a class as example:
As soon as the program starts, a Class with the static prefix is instantiated. If you want to use a static Class it doesn't need to be instantiated (no new Class() needed, you can just use that class because it's already there from the beginning).
Just try it and experiment with it, that makes it much easier to understand. Here's what you can try for example:
There's more to it than static classes, you can also just have static variables for example. A normal class can have static variables.
Image you have a Class 'Person' with the static int 'personsBornCounter'. Now imagine in the constructor of the Person Class, you increase this variable by one. You can call this variable on any person and all will return the same number.
Pseudo code:
Class Person { Static Int personsBornCounter = 0 Constructor() { personsBornCounter += 1 } }Now create person a b and c and call the personsBornCounter on all of them - it should be 3 on all of them!
Also sorry for the lack of formatting, I'm on my phone.
Edit: Formatting
6
u/just_ninjaneering Apr 05 '22
Iterators and it's types(CPP) And what is a namespace exactly?
→ More replies (1)
6
u/oakskog Apr 05 '22
Transformation matrixes... If I have a 2D array of numbers, representing an image, and I want to rotate it say 30 degrees, I can use a transformation matrix? How?
8
5
u/ExtraFig6 Apr 05 '22
This is a linear algebra topic. I recommend familiarizing yourself with linearity and basis vectors. That will give you the tools to understand this
2
u/CozyRedBear Apr 05 '22
A simple 2D rotation matrix multiplies the X and Y components of a vector to produce a new set of coordinates. Unless as an exercise, you often don't have to derive these matrices yourself for spatial transforms. Though if you actually multiply out a point by a valid rotation matrix, you will find that it will have had the effect of rotating that point around the origin.
It's pretty easy to imagine a scaling transform which simply multiplies each vector component by 2. Any point at the origin remains at the origin and any point off the origin is scaled by a factor of two. A translation matrix simply adds to each component.
Rotation matrices involve trigonometry and are more complex in higher dimensions. A 2D rotation matrix is very simple to derive as the 3B1B video will show.
2
u/__Fred Apr 06 '22
If you multiply each y-component by 2, you stretch the image in y-direction. If you multiply x with -1, you would flip it on the x-axis. Makes sense?
You can do both things at once, if you multiply each vector in the (2D-)image with an appropriate matrix. I'm too lazy right now to figure out which that would be. Matrix * vector, is another way to write a system of equations.
Whatever transformation a matrix does to the origin vectors (0, 1) and (1, 0), it also does to the other vectors.
5
u/SlyHolmes Apr 05 '22
Pointers made me quit C++ and programming. Any chance anyone has any good resources/videos explaining them?
5
u/ruat_caelum Apr 06 '22 edited Apr 07 '22
So Let's look at "low level memory"
In computer hardware we have a "register" in the CPU it can hold 32 bits or 64 bits (depending on the architecture of the CPU.) Some are 8 bit, etc.
If we have a 32 bit computer we can fit 32 bits of information ONLY.
4 GB is the theoretical maximum of memory (ram) you can use with a 32-bit OS
Why?
So why can we not use 8 gigs or 16 gigs of ram in a 32 bit computer? Because the computer cannot access the rest of that memory.
Why not?
Each "memory location" in Ram has an address. 0 is the first
32 bitsEDIT 8 bits/1byte of memory in ram. Then 1 or 0000000000001 is the "2nd" address which also hold32 bits8 bits of information, but these are offset so if we counted from the beginning we would have 8-15 (address location)Eventually our 32 bit REGISTER can reach the LAST ADDRESSABLE memory location at 11111111..11111 (thirty-two 1's)
232 = 4,294,967,296, which means a memory address that's 32 bits long can only refer to 4.2 billion unique locations (i.e. 4 GB).
Okay so what does that have to do with pointers!
In the very low level CPU all that is happening is data is being moved from somewhere TO BE ACTED ON, and then moved somewhere else (possibly back to the same place it came from.)
to move data from memory location 0, we us a pointer to say to the CPU "copy 8 bits from memory location 0 to register A"
The "pointer" is pointing at the
32 bits8 bits that start the first32 bits8 bits of memory (because we asked for position 0)Now the DATA held in those first 8 bits could be anything. Our program is going to move the DATA from that LOCATION to the REGISTER and say Add 3 to it (just as an example of something to do to the data.)
Pointers then "grew" from this very low level concept into something greater in terms of programming, but in general it is all the same: There is an ADDRESS and a VALUE IN THAT ADDRESS
so a pointer to a class is just an ADDRESS or LOCATION of that class in memory, and a pointer to an INT is just a LOCAITON of SIZEOF(INT) in memory, etc.
When we use an ARRAY what we are doing by saying X[0] is really POINTING to a memory location that holds a specific size, (so if X was defined as INT then it holds that many bytes, or CHAR then that many)
So the easiest place to understand pointers is arrays.
If I say Int array x[] = [1,10,90,2]
The VALUE of x[0] == 1
The "pointer" to the value is x[0] which is just a location
the value (currently) is 1.
If I made a program that does x[0] = x[0]+x[1]
The program can run as many times as it wants. X[0] and x[1] will always be pointers but the VALUE (at least at x[0]) will change as the programs moves forward while the pointer stays the same.
EDIT I mistakenly said the memory address (which is 32 bits) would access 32 bits of memory. It does not it accesses 1 byte or 8 bits of memory. So while the address is 32 bits wide the size of the memory at that addess is not 32 bits, but instead 1 byte/8 bits.
→ More replies (4)2
u/inaruslynx2 Apr 05 '22
I could give you a run down of what they are. C++ is not very high above machine languages. It allows for hardware control. Part of hardware is memory. Memory is addressed. There is a lot of addresses in modern machines. With a pointer you are able to save the address of a variable.
Now why would you do this? When you pass a variable into a function c++ creates a spot in memory for this copy variable. If you change the value of this copy, the original is unaffected. If you pass in a pointer in and use the address, if you change the value, you change the original variable and not a copy.
This is useful if you don't want to return a whole lot of variables in the function.
9
u/rashnull Apr 05 '22
āFunctional programming has no side effectsā Neither does OOP if you code it not to!
4
u/tedharvey Apr 05 '22
It's like when you have two study guides. One for math and one for English. One guide will have math formulas and one will have grammar rules. There's nothing stopping you from study math and writing math formulas in your English book and vice versa. Same thing with programming functionally. When doing functional programming with a functional language, the standard library are geared toward not having side effects in your code. And it's not just about reducing side effects, the standard library will have many functions that assist you when following this workflow which non functional language will lacks since most will not be programming in that style.
→ More replies (8)2
u/warlaan Apr 06 '22
One of the reasons OOP is so popular - because it's easy to define strictly functional or strictly procedural programming, but with OOP you can just write code that is formally object oriented but effectively functional (when everything is immutable) or procedural (when you just put everything into one class).
Interestingly the guy who coined the term OOP (Alan Kay) also created the programming language Smalltalk, and judging by the standard library of Pharo Smalltalk it is usually written in an almost functional style.
He is also famous for saying that when he came up with the term he did not have C++ in mind (which goes the exact opposite direction).
8
u/Patrickstarho Apr 05 '22
Ceaser Cipher. I get your supposed to shift each character by n but the whole modulus thing makes no sense to me. I remember I did the problem and wrote it out 10 times. 2 weeks later I was stuck again
9
u/CatatonicMan Apr 05 '22
Modulo is like an analog clock. It goes in a cycle from 1 to 12, then back to 1 again.
So if you're at 11 and add four hours, you'd count 12, 1, 2, and end at 3.
A Caesar cipher is like that, except it has 26 letters instead of 12 numbers.
→ More replies (3)3
u/Rote515 Apr 05 '22 edited Apr 05 '22
Modulo has to do with math in discrete finite sets rather than our traditional thinking of math done under infinite sets. So if we have a problem 2+x(where x is an integer) with no modulus then we are working with all integers both positive and negative from -infinity to infinity. If on the other hand we have the same problem mod 10, then weāre only working with numbers 0-9, a discrete set rather than the infinite set, as any equation mod 10 will always be 0<=x<10 as our function is divided by 10 at the end and the answer is the remainder after the division.
Understanding this, and discrete math in general is really helpful in programming as a lot of what we do is donāt over finite sets.
→ More replies (3)
10
u/Alexrai123 Apr 05 '22
Assembly language. What. The. Fuck. 50 lines to transform 'a' to 'A'.
11
u/MrSloppyPants Apr 05 '22
All higher level languages are compiled down to assembler and then machine code. Assembler is almost exactly how the CPU actually executes code. A CPU has no idea what a Python statement is, a CPU needs to know the specific OpCode of the instruction you wish to execute, what data needs to be pushed into the appropriate registers, where the stack pointer is, where the instruction pointer is, and more. Taking a compiler course to understand how computer instruction sets actually work is very beneficial
→ More replies (1)3
u/shine_on Apr 05 '22
Computers, deep down inside, can only do a handful of simple things. They can fetch a value from memory, they can store a value in memory, they can add two numbers, they can check if the result of the last operation was zero, things like that. Although they can do these things extremely quickly, it's very tedious to write a large amount of code in this way. Higher level programming languages were invented as a means to make large programs more understandable to us humans, but ultimately every line of C or Java or Python is translated to several lines of assembly language, because that's what the processor understands.
2
u/flank-cubey-cube Apr 05 '22 edited Apr 05 '22
For your specific example, I'm not sure why the following wouldn't work. Also, this is assuming you're using an array of chars as the string. Another reason is if we used a string constant, we wouldn't be able to actually modify the string. For our example, we will be using the following the C function.
#include <stdio.h> int main() { char str[] = "abc"; str[0] = "A"; }Arrays in assembly just look like local variables, but contiguous. The other thing note worthy is that the first element of the array will be at the topmost position in the stack. In other words, it will be be closes to the stack pointer (rsp in our case).
push rbp ;function prologue mov rbp, rsp ; function prologue sub rsp, 0x20 ; allocating space for local variables mov [rbp - 20], 97 ; moving 'a' (ascii representation) to the top most ; point in the stack - str[0] = 'a' mov [rbp - 18], 98 ; 'b' into str[1] = 'b' mov [rbp - 10], 99 ; 'c' intro str[2] = 'c' ; To change the value, the value at str[0], we need to modify what's at ; [rbp - 20] mov [rbp - 20], 65 ; 'A' is 65 - changing 'a' to 'A' add rsp, 0x20 ; function epilogue ret ; function epilogueSome diclosure -- this isn't exactly what you'd see. You'd probably see a string defined from another section moved into somewhere on the local stack. But what's happening is essentially the same.
The hardest part about assembly is actually not the code like your comment suggests, it's the compiler quirks (Different ABIs and optimization wizardly) and the linker/loader magic that makes it hard.
2
u/nannerz_ Apr 06 '22
Im literally taking a break from programming in assembly to scroll through Reddit lmao. But Iām doing it for a class (my last programming class of college!) and probably wonāt ever do it again
→ More replies (1)→ More replies (2)2
u/otr_trucker Apr 06 '22
IMO, to understand assembly you first need to understand how a cpu works. A simple CPU has little internal memory areas called registers. These registers are only a few bits long. An 8 bit cpu would only have a register that is 8 bit long. Some registers may be able to be paired together to get double the space. The cpu can move data into and out of the registers. It can also preform some logical operations on certain registers (add, sub, AND, etc) and store the results. The cpu knows what to do based on machine code that is the program. Machine code is simply a series of 1s and 0s. One of the registers is called a program counter (PC). The PC register holds the memory address for the next instruction. A cycle of operation would be for the cpu to put the value of the PC register onto the address bus then load the value found at that address into an instruction register. It would then increment the PC then use the value in the instruction register to turn on or off control lines that cause the cpu to preform an operation according to that value.
Now we get to assembly. Assembly is just a step away from writing code in machine code. Instead of writing 1s and 0s you get to use a little bit easier to read code like MOV or ADD. But you are still talking to the CPU on its most primitive level. To preform an operation like ADD, you must first tell it to get a value from memory and put it in a register. Then you have to get another value from memory and put in another register. Now you can add the 2 registers together. Then you have to move the result from its location back into memory. A higher level language would handle all those steps for you but in assembly you have to do it all yourself.
To complicate things different cpus will have different registers and they will different commands. So when you talk about assembly, you generally would need to talk about which cpu you are talking about. An Intel cpu would be different from an ARM cpu and thus the code will be different for each.
At this point you are probably wondering why anyone would use assembly. The reason is that the closer you get to machine code the more power you have over your program, but the more work you have to put into it. Python is very easy to code in when compared to assembly. But python has rules about how you do things, and for the vast majority of your coding that is fine. But a python program will be larger in memory and will run slower than an assembly program that does the same thing. For a program that is to be run on a top of its class gaming PC, this isn't a problem. But, when you are looking at an embedded system, you are usually looking at limited resources and you may not have the space or speed necessary to use python. You can do things in assembly you can't do in python.
I've always thought that python is like riding around in a chauffeur driven car. C++ is like driving the car yourself. With assembly, you first have to build the car before you can drive it.
I suggest you watch Ben Eater's YouTube series on building an 8bit cpu on breadboards to get a better understand of how a cpu works.
1
6
u/Historical_Wash_1114 Apr 05 '22
I'm getting decent at programming and I have no idea what anyone is talking about with RESTFull APIs.
2
u/lionhart280 Apr 06 '22
Usually used for handling data over HTTP(S), usually websites but anything can use it.
RESTful primarily just means it adheres to the HTTP spec for requests, which is just a header on the request specifying its "type", the main ones are "GET", "PUT", "POST", "DELETE"
There's more but those are the main ones people use.
There's supposed to be specific rules that any URL that accepts a POST should also return the same thing back from a GET on the same endpoint.
IE if I POST <data> to
mywebsite.com/some-endpoint/11a23f1, then I call a GET on the same endpoint I should get the same <data> backA lot of people don't adhere to that... there aren't exactly internet police going around demanding you adhere to the rules, but its good practice.
At its core though is the expectation that your endpoints are idempotent.
If I call "GET" on <endpoint> 10 times in a row (without anyone else doing anything to modify the data at the same time), I should get the same value back.
And if I repeatedly POST to the same endpoint over and over, it shouldn't change anything after the first.
Aside from that its just a way of defining a bunch of URLs people can utilize to interact with your application
3
Apr 05 '22
Interfaces.
I get that it's used for inheritance, but I cant quite wrap my head around when or why you'd need to write one.
5
u/CatatonicMan Apr 05 '22
Interfaces are effectively a contract that tells you what a thing does (at minimum). They allow old code to use new code.
Say I have an Animal interface that defines a method Eat - I'm making a guarantee that all Animals can Eat, and that calling Eat on an Animal - any Animal - is a valid thing to do. If it can't Eat, it's not an Animal.
If I later create a Cat that inherits from Animal, I know the Cat can Eat, because it's an Animal and Animals can Eat.
The crucial bit is that I can write code that takes an Animal - Feed(Animal), say - and that code will work on anything that inherits from the Animal interface.
I can Feed(Cat) because Cat is an Animal. I don't need to know anything more about the Cat. I can Feed(Dog), because Dog is an Animal, too. Feed(Snake). Feed(Tortoise). Feed(Alpaca).
Years later, someone I've never met can make their own Animal (Lobster) and my code will have no problems working with it.
→ More replies (1)4
u/door_of_doom Apr 05 '22
An improvement that I'd like to make to this answer: We generally don't call it inheriting from an interface, we generally refer to it as implimenting an interface.
Cat doesn't inherit the Animal interface, it implements the Animal interface.
→ More replies (4)3
u/door_of_doom Apr 05 '22
Think of the Java Interface
List. (https://docs.oracle.com/javase/8/docs/api/java/util/List.html)It talks about a lot of things that can be done to a
List. You can add things to a List, remove things from a list, perform actions against each element of a List, etc. There are a LOT of things that can be done to Lists!But get this: It is impossible to actually create a "List" in Java, because a "List" is just an interface; It's just a contract defining a wide variety of possible lists that one might want to create. In order to actually create a
List, what we need to create is something that implements the List interface. The most commonly usedListimplementation isArrayList, which is anArraythat conforms to theListinterface.So if I make a function called
ListPrinterthat accepts aListas a parameter and prints out all of its contents, I can declare any valid implementations ofListas my parameter, and I can easily accept anArrayList,LinkedList,Stack,Vector, or any other implementation of theListinterface as a parameter of my function, and I'll be able to work with all of them equally well because they all implement the same method names that I need in order to do what I need to do: Print out their contents.
3
u/LaChapelleAuxSaints Apr 05 '22
Dynamic Programming. It's simply storing values into memory, like cache? Idk, but the way it was taught was so convoluted I still have no idea what the matrices are for or about.
→ More replies (2)
3
3
Apr 05 '22
Object Oriented Programming (Java)
Iām pretty new to this concept and I am still trying to learn it but right now it makes absolutely no sense to me.
3
u/inaruslynx2 Apr 05 '22
The way I understand it is you are creating something that represents an object like take a car. There are many cars. There are different makes and models. You can make a class that holds all of this info. Then make one car and track it's status.
So you could make 1 car that's a Honda accord. Then track its speed, lane, and gears. Then make another car of whatever and do the same. That's what oop allows.
→ More replies (1)2
u/Coding_Cactus Apr 05 '22
Here's a link to a comment I made a while back on OOP
I'll try to make a shorter one here if you don't want to read that one.
Take this string:
string aSampleString = "Test12345";If you wanted to know the length of that string how would you do it?
SampleString.length();Ok, easy, but what if we made a new string?
string aTotallyDifferentString = "LoremIpsum"Well, we'd do the same exact thing.
aTotallyDifferentString.length();The reason is because a string in Java is a class. To not add too much, it's a collection of properties and methods that can be inherited so that you don't have the same method typed out a thousand times and also to ensure that the underlyfing functionality doesn't deviate.
Then take that and apply it to totally made up class.
class FingerGun { string Shoot() { return "Bang!" } }Now, what do you think is gonna happen if I make two new classes from that one?
class LeftHand extends FingerGun { public string HandName = "Left"; } class RightHand extends FingerGun { public string HandName = "Right"; } /*This is just an example, ignore the horrid syntax mistakes*/ LeftHand Lefty = new LeftHand(); RightHand Right = new RightHand();Based on the above example, this should do exactly what you expect it to:
Lefty.Shoot(); Righty.Shoot();They both extend from FingerGun so they both have the Shoot() method. No need to re-create it on both of them unless they need to function differently from there.
→ More replies (1)
3
u/Nerdz2300 Apr 05 '22
Pointers. I still dont understand them. They are used a fair amount in embedded code as well. I just dont get it.
Also unions (not the labor kind).
→ More replies (4)2
3
u/rustybladez23 Apr 06 '22
I'm pretty newbie to programming. And I find pointers really hard right now
2
u/Mundosaysyourfired Apr 06 '22
Pointers are special variables that store memory addresses instead of actual values.
2
u/LavenderDay3544 Apr 05 '22
Tree balancing
3
u/0xonox0 Apr 05 '22
Tree balancing is supposed to make tree operations (such as searching, inserting, or deleting) truly O(log(n)). You could have unbalanced trees (think just a linear tree where each node only has a left child) where the tree operations will just morph into a O(n) operation. If we balance the tree the height of the tree will decrease and since tree operations depend on the height, they will also be more efficient on balanced trees. There are various algorithms to make a tree balanced such as AVL trees to red black trees to multiway search trees; imo it's just better to watch a video on this than my trying to explain it to you in a reddit comment but the main goal of this algorithm is to make trees more balanced.
TLDR: Balanced trees lead to more efficient tree operations
→ More replies (7)
2
Apr 05 '22
What is deployment? I could never understand the purpose of Docker.
10
u/tzaeru Apr 05 '22
Consider a typical web application. It runs on a particular server. That server needs particular software to support the application.
Let's say your application needs Python version 3.6 and Postgres version 10.
You can manually install those on the server, but you would have to do that again for each server where you run your application.
Containerizing an application is a way of bundling the dependencies together. Instead of running your application on a server that already has the required components installed, you run your application as a Docker container which already has the required dependencies. So the server you host your application on doesn't need to know about Python or Postgres; It only needs to know about Docker. Docker takes care of all the dependencies required by your application.
This also makes it easier for you to run multiple applications with incompatible dependency requirements. Perhaps you have another application that requires Python 3.7 and Postgres 11. You could install those on the same server, but you would need to run the Postgres instance in a separate port and you may run into trouble with where Python3 points to. But if this application is also bundled in a Docker image, it doesn't matter - you just run that Docker image and again it takes care of the dependencies.
→ More replies (5)3
u/Gamithon24 Apr 05 '22
Does this mean dependencies aren't shared between Dockers. Meaning the same dependency can be installed on the same machine multiple times?
→ More replies (1)3
u/HecknChonker Apr 05 '22
When you write code you need it to run somewhere so users can access it. This used to mean buying a computer that sits in your office and runs your code, but eventually large companies set up data centers with many computers and they let other people run their code there.
But different apps need different configurations. And sometimes you want to run many copies of the same app, and when you make a change you want to update all of them with that same change. Pushing out those changes is called a deployment, as you deploy code to a bunch of servers.
Docker helps in automating this process. You can set up your application to build a docker image, and that image can run in a data center that someone else manages. The docker image contains an operating system, your code, and any required dependencies your code needs.
2
Apr 05 '22
When you program something in your machine, it has some configuration right? Operational system, language version, frameworks and libraries version, etc.
That might work fine, but it's useless if other people can't access the software you wrote. So you need to "upload" that program to a server. However, you need to make sure this server also has all the same versions and tools that are needed.
In a very simplified way, Docker is a set of rules that define those settings. So it says what's the OS running the application, if there are frameworks and libraries, what version is running there? What's the database?
With that, you can have a team of developers using the same tools and versions for everything, making sure the application will work in any machine following those rules.
2
u/dizzyflames Apr 05 '22
Recursion is weird to me. I kind of understand it but still feel like I don't. You give me a recursion problem and I won't know if it works until I compile it even if it's a pretty basic problem but I still somehow get it working even if I don't know how I did it.
→ More replies (6)
2
u/Spudboy4800 Apr 05 '22
Shared memory, especially in systems (mmap, shm_open etc)
→ More replies (1)
2
u/consciousCog13 Apr 06 '22
Iāve still never heard a concise definition of an API. Iāve built them, modified them, taken entire courses on them. Iām still just like āitās aā¦bunch of methodsā¦that let you access dataā¦and stuffā¦ā
→ More replies (1)2
u/AlotOfReading Apr 06 '22
You pretty much have it. An API is a collection of things you can call to pass or receive data and the set of rules around how to use them. Often the "things" are functions, but it's perfectly reasonable to talk about APIs made up of things that aren't strictly functions like HTTP endpoints.
2
u/BenardoDiShaprio Apr 06 '22 edited Apr 06 '22
Memory consistency. People explain the theory, but I dont understand the actual implementation, as in, how would adding an atomic with acquire differ from release, at the hardware level.
→ More replies (1)
2
u/nomoreplsthx Apr 06 '22
C++ initialization semantics. Move constructors, copy constructors, initialization lists, the whole shebang. It's wildly different from the way object initialization works in any other language.
2
u/chrischin-a Apr 06 '22
when i was taking data structures and algorithms back in the fall, i never really understood how a binary search tree can be balanced
it didn't help that i was going through a rough ass time and couldn't concentrate without breaking down every other hour
2
u/Pollomonteros Apr 05 '22
Seems like Git uses "snapshots" to store the different changes in files, and I am wondering how is that different from just saving a copy of each file ? Like if I have 3 files and only 2 change in a version,how is that different from 1 of them remaining the same while the other two are deleted and replaced by the new versions ? I am aware that Git has an "history" of changes in each file,but how can it have such an history without running out of space in their servers ?
6
u/CatatonicMan Apr 05 '22
Delta compression.
Git has one full copy of the file. For subsequent versions, it only stores what changed.
It can reconstruct any particular version of the file by starting at the original and layering on all of the future changes.
2
u/Gamithon24 Apr 05 '22 edited Apr 05 '22
I might be wrong about how this works but I'll give it a go.
Instead of saving:
Filev1:
"Hello"
Filev2:
"Hello"
"World"
Git saves:
Filev1:
+"Hello"
Filev2:
+"World"
Git just remembers the added or removed line. Saving the redundancy of saving an entire file each time.
2
u/R_I_N_x Apr 05 '22
How to find the correct answer to a question asked by a professor when I've never been taught it. For example, finding out if the given number is a prime number; how am I supposed to find out questions such as that without looking up the answer?
5
u/TheNintendoWii Apr 05 '22 edited Apr 05 '22
You have to use what you know; What is a prime number? Only divisible with 1 and itself.
How do you know number x is divisible by y? In Python x % y == 0
How can you make a loop counting up to x (excluding x and itself)? In Python for i in range(2, x):
Then use that to combine everything:
def isPrime(number: int):
Ā for divisor in range(2, number):
Ā Ā if number % divisor == 0:
Ā Ā Ā return True
Ā return False # Will only happen if no divisor was found
2
u/GoodTimesFastFingers Apr 05 '22
Curried functions. I've read definitions before and the code made sense but I don't understand why you would ever need one, and I could not tell you what a curried function is if I had to.
→ More replies (2)
2
Apr 05 '22
At a really intro level, I wouldāve said for loops. I just didnāt feel that materials you encounter when learning informally REALLY explain this concept in rigorous and complete ways.
→ More replies (7)
1
1
1
Apr 05 '22 edited Apr 05 '22
The first time I saw this in JavaScript. Recursion was confusing as well and I had a buddy explain it to me. I appreciated the Computerphile explanation greatly.
1
u/RenewAi Apr 05 '22
Recursion: A function that calls itself and stops calling itself when a certain condition is met, then somehow does a magic wrap up backwards thing that does all the calculations.
The last bit of recursion has stumped me for years. It just doesn't work with my brain for some reason.
3
u/AlSweigart Author: ATBS Apr 05 '22 edited Apr 05 '22
I just got done writing a book on recursion. The reason it's mystifying to you is most likely because the tutorials/instructors who taught it didn't explicitly bring up the call stack.
First: A stack is one of the simplest data structures in computer science. It's like a list, but you can only add or remove things to and from the end of the list. We say you "push" data onto the end (or top) of the stack and "pop" data off the top of stack.
Second: Function calls aren't one-way. When you call a function, the program automatically and behind the scenes your program notes where the execution should return to when the function call returns. This data is called a frame object, and frame objects are pushed to the top of the call stack when a function is called and popped off the top of the stack when the function returns.
So if you have a function
a()that callsb()that callsc(), this is how your program knows that whenc()returns, it should go back tob(), and whenb()returns, it should go back toa(). Here's a brief Python program:def a(): print('Start of a()') b() print('End of a()') def b(): print('Start of b()') c() print('End of b()') def c(): print('Start of c()') print('End of c()') a()When we run it, notice it goes A-B-C-C-B-A:
Start of a() Start of b() Start of c() End of c() End of b() End of a()This is why stacks are called a LIFO or last in, first out. The last thing pushed to the stack is the first thing popped off it.
When we call
a(), a frame object (I'll call it a) is pushed to the top of the stack, then whenb()is called a frame object (I'll call it b) is pushed and becomes the new top of the stack. Thenb()callsc()which creates a c-frame object to push to the top of the stack. Whenc()returns, the c-frame object is popped off, then whenb()returns, the b-frame object is popped off, then whena()returns the a-frame object is popped off and the call stack is empty and our program is back in the global scope, outside of all functions. (Or, if you're in a program written in C which has amain()function, returning frommain()means the program terminates.)One thing to keep in mind: the execution is always in the function call at the top of the stack. This is why when
c()returns tob(), the c frame object pops off and the old b frame object under it is now at the top.It's a bit confusing because the call stack handled behind the scenes. You can't point to a place in your source code where the call stack is. It's either automatically handled by the interpreter or the code for it is added to your program by the compiler.
Now, if you have a recursive function, the function is calling itself. So the call stack has frame objects for the same function but that's okay because remember that the frame objects represent function calls and not functions. Say we have a factorial function:
def fact(n): if n == 1: return 1 else: return n * fact(n - 1)When we call
fact(3), a new frame object (I'll call it fact-3) is popped to the top of the call stack and the execution enters thefact()function. This ends up runningreturn n * fact(n - 1), but before it can do that, it needs to callfact(2).A new frame object (I'll call it fact-2) is created and popped to the top of the stack. This is just like
a()callingb(), except in this case a and b are the same function: it'sfact()callingfact().Here's the other thing that trips people up: each frame object stores a separate copy of the local variables. Rather than think of the local variables like
nas local to the function, they are actually local to a specific function call. This means there are multiplenvariables: in the fact-3 frame objectnis set to3and in the fact-2 frame objectnis set to2. They have the same name, but these are two separate variables storing two separate values.This is a major point of confusion for people learning recursion. Seriously, people are always thrown off because when you look at the code, you only see one
nvariable and it's easy to overlook the fact that there's actually onenvariable for each function call. This is why recursion looks like magic: you expectfact(5)to do 5 x 4 x 3 x 2 x 1 but all you see isn * fact(n - 1)and people don't know where the full multiplication is taking place.Anyway,
fact(2)has to callfact(1)(creating a fact-1 frame object), which returns1. When it returns, the fact-1 frame object is popped off the stack. Now we're back in the previous call tofact(), but it's the fact-2 frame object wherenis set to2. Thereturn n * fact(n - 1)now looks likereturn 2 * 1becausefact(n - 1)returned1and the localnvariable is2.This makes our
fact(2)call return2 * 1, that is,2, and the program (automatically, behind the scenes) pops off the fact-2 frame object and the execution returns to thefact()function again, but in the context of the fact-1 frame object where the localnvariable is (and always has been) set to3. This time thereturn n * fact(n - 1)is reallyreturn 3 * 2. So thisfact(3)function call returns6and pops the fact-3 frame object off the call stack.There's nothing left on the call stack at this point, so the program continues running code from whatever point in the global scope called
fact(3)and thatfact(3)function call has evaluated to6.As for where the 3 x 2 x 1 is taking place, the flow control of
fact()is simple enough that we can substitute the function calls with that call'sreturnstatement:fact(3) | V (3 * fact(2)) | V (3 * (2 * fact(1))) | V (3 * (2 * (1))) | V 6→ More replies (1)2
u/tube32 Apr 05 '22 edited Apr 05 '22
The best way to imagine recursion is like the movie inception.
Let us consider a recursive function to print from 0 to any given number (n)
1) def function(n): 2) if n==0: #base condition 3) print(0) 4) else: 5) function(n-1) #recursion 6) print(n) 7) returnLets first understand the function line by line.
Function declaration, pretty straightforward.
Checks if n is equal to 0 (will explain what a base condition is later)
If second line is True, then print 0
Else
Call the same function, BUT with n-1 as the parameter.
print the current value of n
Return (end of function)
Now say user inputs the value of n as 3.
The function first checks if n==0, which gives false since n=3, so the code moves to the else block.
Now what does the else block say? The else block says call the same function again, but with value 2 (n-1).
The code thinks to itself, "Huh, weird but sure whatever" and proceeds to do so. So now we're back to line number 1, except this time its
function(2).Now one more time at line 2 it checks if n==0, and it gives false so we move to the else block. The else block says, okay since we're here, lets call the bad boy once again with n=1.
The same process repeats for n=1 as well and the function is called for n=0.
Now the magic happens, the if statement at line 2 evaluates to True! The compiler is overjoyed as it was waiting to enter the if block. It finally enters the if block and asks the code, what do I do now? At line 3 the code says, since you have managed to make it so far, go ahead and print(0) on the screen. The compiler happily obliges and moves forward. This time, it skips lines 4 and 5 since the if block was executed and goes directly to line 6, which is a simple return statement.
Now where does the compiler emerge? It emerges back at line 5 BUT for when n=1. Now that its back it goes to line 6 and displays the current value of n (right now 1). Then on to line 7 where the the function ends for n=1.
Where does it emerge now? Again at line 5 but for n=2. Proceeds to follow the same steps as above.
Then finally we're back to line 5 for function(3) what the user originally called, where the function terminates.
A base condition is what tells a recursive function " so hey listen, if this condition is met, just do so and so and return a constant value, DO NOT call yourself again". Without a base condition a function will keep on calling itself repeatedly (equivalent of an infinite loop)
>somehow does a magic wrap up backwards thing that does all the calculations.
>>Now where does the compiler emerge? It emerges back at line 5 BUT for when n=1.
This is the magic backwards part, after the base condition is met, functions start coming out and proceed with the rest of the code, like in this case they continued from line 6.
I am afraid I have over complicated it, recursion is best understood with a visual representation. I hope you atleast got something out of it, I am not so good with explaining stuff over text :/
→ More replies (2)→ More replies (3)2
u/Technologenesis Apr 05 '22 edited Apr 05 '22
I'm gonna use this recursive addition function as an illustration:
func add(unsigned_int a, unsigned_int b): if a == 0: return b return add(a-1, b) + 1So you seem to understand the concept of a base case; in this situation, the base case is
a == 0. Ifais zero, the function doesn't recur; if it's not, it recurs in a way that ensuresawill eventually be zero, at which point the function will stop recurring. So imagine callingadd(3,4). The calls will happen in this order:add(3,4) add(2,4) add(1,4) add(0,4)That's where we hit our base case. Now, this final call will return
4; but obviously 3+4 is not 4. This is where the "magic backwards wrap-up" happens, only it's not magic. The program simply remembers what calculation needs to be done at each stage because you told it in the return value. So, starting at the bottom, we work our way back up:add(0,4) returns 4; add(1,4) returns the result of add(0,4)+1 which is 5 add(2,4) returns the result of add(1,4)+1 which is 6 add(3,4) returns the result of add(2,4)+1 which is 7*EDIT: accidentally mistyped add(3,4) as add(1,4) above
We've reached the top, and now we have our answer. The wrap-up works because the program remembers where it was when it moves from function to function.
add(1,4)callsadd(0,4), for instance, but the program remembers that once it has the result fromadd(0,4), it still has to add 1 to it before it has the result foradd(1,4).→ More replies (3)
1
1
u/CodedCoder Apr 05 '22
Big O, like I understand what it does, but for the life of me have such a hard time figuring out how to use it. Every book I tried, just seems so technical and dry.
2
u/Sasquatch_actual Apr 06 '22
I can't stand using books for stuff like this.
The most simple way to learn time complexity stuff is to code up some simple demonstrations.
The trick to this is using ridiculously large datasets.
If your dataset has 10 numbers in it, anything you do is going to complete nearly instantly after you click run.
Make an array with 500 million integers in it.
Try some constant time operations. They happen instantly.
Try some linear time operations. Search for 50k random integers between 0 and 500 million. That's going to take a while (minutes) to complete. Print out a timestamp before and after that process, see how long it takes.
Do the same thing again. But this time use binary search in logarithmic time. It'll blow your mind how fast it is. A few seconds maybe.
Play with each time complexity with large enough numbers to make a difference. Some may never finish,
Look at your data structures, and their different complexity for different operations. Think how loading half a billion items would be fast or slow.
Any operations that's making you iterate over that entire length of half a billion you'll feel it, when you try it.
→ More replies (4)
1
Apr 05 '22
Recursion and complex forms of it. And I donāt know how to break down Problems to best utilise recursion.
1
u/tv_head__ Apr 05 '22
Generics. Our teacher mentioned them but this was a class about JavaFX ( I've been using java for 3 years now as a hobby ) But it was something optional to learn about. I've heard this term thrown around in go-lang convos but never made the effort I suppose.
154
u/Keith_Hotdog_Cowboy Apr 05 '22
Great idea for a post OP. I'm going to bookmark this one.