32 Reasons WHY TS IS BETTER Than Go

  Рет қаралды 250,834

ThePrimeTime

ThePrimeTime

Күн бұрын

Пікірлер: 559
@roccociccone597
@roccociccone597 Жыл бұрын
As so often is the case... The guy in the article tries to write TS using Go. If you want to write TS then use TS. Go is great but not if you treat it like TS.
@ryangamv8
@ryangamv8 Жыл бұрын
No immutable variables tho. Tf is up with that
@roccociccone597
@roccociccone597 Жыл бұрын
@@ryangamv8 yeah sometimes it would be nice. Constants can cover some of those cases but since they're compile time constants they're not the same unfortunately. It would be nice if they introduced that eventually.
@gilbertovampre9494
@gilbertovampre9494 Жыл бұрын
Or any other language, I’m tired of people trying to write Java, C++, JS and other stuff in Go. You look at the code, you see the mess, you think “this looks like this person is trying to write in X language”, and than you go check their background and as it turns out, in their previously job they were writing in X language, you can see it right through it.
@cranberry888
@cranberry888 Жыл бұрын
​@@gilbertovampre9494how Go style different from x language?
@gilbertovampre9494
@gilbertovampre9494 Жыл бұрын
@@cranberry888 like, when I see "IRepository", "IClient", etc. or getters and setter for everything and everywhere, named "GetThis", "GetThat", they all came from some OOP language like C# or Java. When I see too much reflection or Generics, they probably came from JS, and so on. I might be wrong, I'm just stating about my own experience, and to this day it was never wrong. It's just minor things that give up their background.
@dryr-mp4pp
@dryr-mp4pp Жыл бұрын
I've written a lot of code in both. I like the simplicity of Go, for sure. Fewer ways to shoot yourself in the foot...kind of. There are just fewer choices to make in Go, which can be a good thing. TypeScript is more like Scala. It can support about any paradigm you'd like to use. There are 10 ways of doing anything. You can easily over engineer a problem by adding layers of generic inheritance or something like that. Then, there's the layers of configuration. Not all TypeScript is the same. Max strict TypeScript, in practice, ends up looking much different than minimally strict TypeScript. The point about no union/sum types is really important. Not everyone uses these features, but once you start using patterns like tagged unions, everything starts to look like a tagged union problem. The simplest example is an Option type, which you can't make yourself in Go today.
@Tresla
@Tresla Жыл бұрын
Option types are possible in Go, using Generics. They're just not as nice to work with, compared to a language like Rust which has very powerful pattern matching. Go Generics, at least in their current state, are very basic/underpowered. You could argue that that's perfect for Go, but I'd have to disagree. If you're going to add a feature like Generics, you can't half-ass it. type Option[T any] struct { Some T Valid bool }
@derschutz4737
@derschutz4737 Жыл бұрын
The difference is that Scala is half decent.
@anon-fz2bo
@anon-fz2bo Жыл бұрын
​@@Treslahey thats a creative way to implement an optional type. but having it as a struct vs a enum just feels wrong like u mentioned. since an optional can only have 2 states, it makes more sense to abstract it as an enum, which u cant do in go unfortunately since enums in go are just untyped uints.
@Tresla
@Tresla Жыл бұрын
@@anon-fz2bo I wholeheartedly agree. Go's lack of a truly generic enum type is one of its sore spots.
@PamellaCardoso-pp5tr
@PamellaCardoso-pp5tr 2 ай бұрын
The whole thing about optional type is you staying inside the Maybe/Option monad and delegating the error handling to the monadic structure. No need for a enum or some shit like that, thats just a neat sprinkle on top of your chocolate milk, but the chocolate milk itself doesnt need it to be delicious.
@bitmasked
@bitmasked Жыл бұрын
Go's error handling is amazing because it keeps it as part of the control flow. Exceptions are the bane of new and "mature" codebases alike, especially within a 20 mile radius of any junior engineer.
@ThePrimeTimeagen
@ThePrimeTimeagen Жыл бұрын
i hate exception handling with try catch
@OnFireByte
@OnFireByte Жыл бұрын
Go error handling is better than ts for sure, but most of the time i just wish they do something like rust that wrap error in Result enum, or at least have some syntactic sugar like “?” operator in, again, rust
@thewarsawpakt
@thewarsawpakt Жыл бұрын
@@ThePrimeTimeagen thoughts on elixir/erlang error handling?
@jarvenpaajani8105
@jarvenpaajani8105 Жыл бұрын
​@@ThePrimeTimeagen except in zig
@KevinCaffrey
@KevinCaffrey Жыл бұрын
The biggest gap in Go error handling imo is the lack of a “must use” annotation like Rust has. If a function returns only an error, it can be easy to accidentally forget to check for error.
@Speykious
@Speykious Жыл бұрын
As a Rust programmer, the one thing I dont like in Go's error handling is that you can still technically access the value even if there's an error. You get both the error and the value at the same time returned. In Rust you're guaranteed to only get one or the other thanks to ADTs.
@krux02
@krux02 Жыл бұрын
It has been repeated 1000 times. Yet as a go programmer, it doesn't bother me, or cause any bugs. I had to get used to it, sure. But after that it's just smooth sailing.
@Tresla
@Tresla Жыл бұрын
​@@krux02 The issue is that it CAN cause bugs. Not to mention, not every function follows the rule of "if it returns an error, the value should be regarded as invalid". And it's not always clear without reading through all of a function's documentation (io.Reader is a perfect example of this). I've been programming primarily in Go for the past 7 years, and can say with confidence that Rust's way is just plain better.
@johnyewtube2286
@johnyewtube2286 Жыл бұрын
"as a ___" why do people feel the need to state they are writing as something or other? Is it just readit brain?
@deformercr6680
@deformercr6680 Жыл бұрын
​@@johnyewtube2286it helps the reader gain perspective about where someone might be coming from.
@SimonBuchanNz
@SimonBuchanNz Жыл бұрын
​@@johnyewtube2286because it informs you of why they're saying the thing they're saying? You might have had a point if you saw "as a hair dresser, I think roundabouts are better than lights"
@adambright5416
@adambright5416 Жыл бұрын
arrays are values, slices are pointers to an array. append returns a copy of a pointer to the same array; BUT if underlying array grows because of append, it will create a new underlying array and return new pointer to new array.
@jonasstrmsodd6352
@jonasstrmsodd6352 Жыл бұрын
I think I just like Go now. The whole try-catch blocks in TS is a nightmare, and I'm fairly sure it nudges you towards just "YOLO: Hope it doesn't fail".
@ntrrg
@ntrrg Жыл бұрын
25. A slice is a portion of an array (which may be the whole array if you do x := [5]int{0, 1, 2, 3, 4}; s := x[:]). They work on top of the array you slice. Mutating a slice element (s[0] = 5), will mutate its backing array (x[0] is also 5 now), and those changes will be reflected on any slice from that same array, if you need a copy, you have to use the builtin copy functiom or make a copy manually (for loop and copy to new slice with a different backing array, for example). Slices are passed as copy, but it doesn't mean you will get a full copy of its elements, you just get a copy of the slice data structure, which is a struct { length, capacity int, data uintptr }, but data is still a pointer, so if you do s[0] = 0 inside a function, it will mutate its backing array. If you pass s to a function, and do s = s[1:], s is now [1 2 3 4] in the function scope, but it will still be [0 1 2 3 4] outside the function. I actually find it quite easy to understand, and I am pretty stupid, its like any user defined data structure would behave when it is used as argument in Go. There are some other rules like appending to a slice with not enough capacity, but once you know the rules about slices, it is easy and makes sense. P.S. having unmutable data structures in Go is not possible, you can make copies, but mutating it is not a compile error.
@a-yon_n
@a-yon_n Жыл бұрын
It took me a very long time to understand slice and yet I don't think I have fully captured it. Currently I see it as a view of the underlying array, when we cut a slice, we just create a new view of the same array, so manipulate one of the views will affect all the other views. It's so silly that Go designed it this way, make something very simple so hard to understand.
@ntrrg
@ntrrg Жыл бұрын
@@a-yon_n I think sometimes we overcomplicate some concepts, in simple words, arrays are static arrays and slices are dynamic arrays.
@Nenad_bZmaj
@Nenad_bZmaj 8 ай бұрын
You have to be careful when appending to a slice within a function, if you want to observe that change in the caller function. If the capacity is exceeded, the slice inside the function will start pointing to a new array which is a copy of the old array but with double capacity. The original array remains unchanged and at the same old address, at which your outside slice points to. Thus you won't see the change. In that case pass the pointer-to-slice, instead of the slice. It points to the address of the slice header, not of the array, and so any change within a function works on the slice residing in the caller. Also consider this: you pass the instantiated but empty slice 'a' to a function which should populate it, and suppose your function makes slice 'b' with some elements, or calls another function whose return value is equivalent to slice b. And you just assign: a = b or a = g(...) (function g returns a slice). Now, slice 'a' inside the function (and, of course, inside the function that slice can have a different name i.e. the name of the parameter, but we tend to use the same names for arguments and parameters) - points to the underlying array of b, but the slice a in the caller still points to the same empty array as before. In that case, also, pass the pointer-to-slice to the function parameter and assign like this: *a = b, since by 'a' now you call a pointer variable, so you deference it to get to the slice header in the caller. And now slice in the caller points to the underlying array of b. You didn't have to copy each element in a loop. Also use *a = append(*a, c...) when appending inside the function, slice 'c' to slice a in the caller and you are not absolutely sure that you won't exceed capacity at runtime.
@kidus_f1
@kidus_f1 Жыл бұрын
I'm wondering how Melkey could have a Go course on Frontend Masters when he doesn't know how slices work, it's basic stuff
@MassimoLuna-o4r
@MassimoLuna-o4r 3 ай бұрын
I love getting a new perspective on things, although I don't think you are always right about everything. I feel like it takes great courage to stand in front of this many people and state you opinion and I admire you for it. - No matter if it is factual or aligns with my views. Thank you. Keep it up :)
@Daniel_Zhu_a6f
@Daniel_Zhu_a6f Жыл бұрын
function overloading is a good alternative to OOP and object.verb(subject) notation. overloaded function call is essentially pattern matching on a tuple of types. so it's a good option to have
@vitiok78
@vitiok78 Жыл бұрын
The main problem of this article is that the author just wants to write Typescript code using Go. This is the stupid idea that doesn't work with any programming language. You just need to learn how to write idiomatic Go and most of those "problems" won't even appear in your project.
@elevationsickness8462
@elevationsickness8462 Жыл бұрын
Doesnt it give you inspiration. Anyone (with the right connections) can become a journalist these days
@gmdias0_
@gmdias0_ Жыл бұрын
makes sense
@anon-fz2bo
@anon-fz2bo Жыл бұрын
for real, the nil pointer arguement is dumb, u just have to remember to check if its nil. which if u write c/c++ you should already be comfortable with.
@vitiok78
@vitiok78 Жыл бұрын
@@anon-fz2bo I think he meant that in Go interface that contains nil is not nil. For example: var i *int // initializes to nil var something interface{} = i fmt.Println(something == nil) // prints false That's why it is very bad to write your own error type that implements error interface. Because it won't be nil when you return it
@voskresenie-
@voskresenie- 28 күн бұрын
I've worked with so many of these people when a company I used to work at adopted go. Not only were people not writing idiomatic go, they couldn't even be consistent about what language they _were_ writing via go - java, C++, python, and others. It was a nightmare for the few of us who actually had learned go properly and weren't just angry at the language over it not being a different language.
@CheefCoach
@CheefCoach Жыл бұрын
26: Slice is a reference to some array. Length of slice is how many elements are in slice, and capacity is the length of the array that is point to. If somebody is using antipattern in go that sliceb = append(slicea, something) than sliceb can be either pointer to slicea or copy of slicea+something. If slicea is on full capacity, than go will create new array with larger capacity and put sliceb there, but it won't move pointer to slicea to the new array.
@Gusto20000
@Gusto20000 Жыл бұрын
It helps to remember that append is “value semantics mutation API”.
@LusidDreaming
@LusidDreaming Жыл бұрын
Just a quick PSA, accessing JS object fields by variable is a security vulnerability if that field can be defined by user input.
@aimanbasem
@aimanbasem Жыл бұрын
by the same token, indexing a list with a variable is also a vulnerability, isn't it?
@LusidDreaming
@LusidDreaming Жыл бұрын
@@aimanbasem if there is no bounds checking, which i believe there is in JS. But in C there is no bounds checking so if an array can be indexed arbitrarily (or even just access OOB), there are ways for a user to take control of the program and start trying to execute OS commands with whatever access the program was given. This is also why you should assign specific users/roles to processes and never run them as root unless absolutely needed
@Kane0123
@Kane0123 Жыл бұрын
Watched a few of Melkey’s videos recently, seemed to have a fairly reasonable opinion on most things… where is he on the Theo-Prime scale?
@gastrader9993
@gastrader9993 Жыл бұрын
An absolute beauty. Best of both worlds
@ejazahmed4609
@ejazahmed4609 Жыл бұрын
He seems like a junior in comparison. I don't know about his qualification but that's the impression I get.
@antonpieper
@antonpieper Жыл бұрын
Can you elaborate on the Theo-Prime scale?
@orelweinstock
@orelweinstock Жыл бұрын
Theo gg is a startup hacker developer productivity focused get stuff out the door Prime is a high scale optimal code, ergonomics freak, elite coder
@joseandkris
@joseandkris Жыл бұрын
Actaully a good comparison
@oakley6889
@oakley6889 Жыл бұрын
Functional overloading exists in alot of langs, and its quite useful. Im pretty sure c++, java, a good handful of functional langs, etc Its good if you have some optimisation that uses a lookup table or premade collection that needs to be searched, if its created before, it can be passed in, or the function does it itself
@tokiomutex4148
@tokiomutex4148 Жыл бұрын
The only thing function overloading is good at is making the code more confusing, change my mind!
@Ryuuzaki145
@Ryuuzaki145 Жыл бұрын
​@@tokiomutex4148 with proper naming, I'd disagree. The method "String.toString()" in C# has many overloaded methods that still does exactly what the function means, the algorithm just is different depending on what data type is converted into a string. Building multiple constructors is also great, but you could argue we could simply create an empty constructor first then chain set properties to accomplish the same goal (such as " New Object().property1 = value .property2 = otherValue .property3 = value3; ) I find that function overloading only makes sense in OOP though. In Go, it would feel weird, kind of out of place
@atiedebee1020
@atiedebee1020 Жыл бұрын
​@@tokiomutex4148and they cause name mangling...
@edoga-hf1dp
@edoga-hf1dp Жыл бұрын
Function overloading can be good for optional arguments or handling of same functionality for different types
@tokiomutex4148
@tokiomutex4148 Жыл бұрын
@@edoga-hf1dp Until someone modifies the code and a different definition of your function ends up called, good luck debugging it!
@yapet
@yapet Жыл бұрын
About your "zod competitor" idea. Instead of doing a build step which will codegen validators, you can use the "new Function()" pattern to generate code in runtime. It’s the same approach that fastify uses to generate fast json serializers / deserializers given json schema definitions.
@majorhumbert676
@majorhumbert676 Жыл бұрын
This idea was already implemented. Look up "Typia"
@davidsaint8866
@davidsaint8866 9 ай бұрын
for point 7, I think it's better in GoLang, as they can pass variables that don't exist in your struct. What I do in that scenario is create a function, loop through the filters and have a swith case statement that handles the supported properties, and a default. It's a bit more work, but it ensures the integrity of the system is not compromised.
@sinom
@sinom Жыл бұрын
Golang's value errors would be nicer or they instead were some result return type with monadic operations on it
@Entropy67
@Entropy67 Жыл бұрын
Agree but you get some interesting freedom with what it is right now 🤔
@Qrzychu92
@Qrzychu92 Жыл бұрын
​@@Entropy67you don't have to use the monadic things everywhere
@OzzyTheGiant
@OzzyTheGiant Жыл бұрын
I don't want to resort to whataboutism but C has the same thing, if I recall correctly, and yet no one bats an eye
@thinhle462
@thinhle462 Жыл бұрын
For number 7 and your example, i would use json instead of map. In number 14, we could utilize struct and pointer to construct a optional value parameter or u can say dto
@codeChuck
@codeChuck 7 ай бұрын
@ThePrimeTimeagen, your point is very valid! If function signature in ts accepts a union type of arrays, it will be a runtime error in js! So, before pushing something into an string[] array, you should check for argument type to be a string with typeguard: ```ts if (typeof arg !== 'string') return; ```
@LusidDreaming
@LusidDreaming Жыл бұрын
This whole article is basically saying "I don't know how to program if I don't have the full set of TS features."
@ivanjermakov
@ivanjermakov Жыл бұрын
This whole article is basically saying "I like dynamically typed languages"
@UxerUospr
@UxerUospr Жыл бұрын
Not just TS, but the JS frameworks and sundry other packages he must use. Apples != Oranges
@teejaded
@teejaded Жыл бұрын
For me, less language features means when I have to read your shitty code (don't be mad, all code is shitty) I don't have to spend as long figuring out what the fuck you were doing.
@maximiliandollinger4804
@maximiliandollinger4804 Жыл бұрын
A slice is a descriptor of an array or part it. It holds the length, capacity and the pointer to the starting item in the array. The descriptor is passed by value. If you pass a slice and change the length or capacity, nothing will happen outside the current scope. There is an article on the go dev blog.
@chrism3790
@chrism3790 Жыл бұрын
To me, a telling sign that someone is inexperienced in programming (or that they're using the wrong tool for the job) is that they complain about error handling being cumbersome. It tells me that they haven't been bit in the ass enough times to realize that handling errors is orders of magnitude less painful than dealing with run time bugs and crashes. Go's approach to errors might not be elegant, but try/catch is 100 times worse, because it gives programmers a responsibility they're usually are too lazy to handle.
@felixjohnson3874
@felixjohnson3874 Жыл бұрын
I'd rather the program fail than clobber itself or anything else
@zhamed9587
@zhamed9587 Жыл бұрын
It turns out that it's easy to mistakingly ignore or overwrite errors in golang. I've worked on large golang code bases, and I've seen this issue many times. It's a mediocre and badly designed language at the end of the day.
@sergisimon9620
@sergisimon9620 11 ай бұрын
I still feel like errors should be sum types, like in Rust with Result or Either with Haskell. That being said, I'm 100% on having error handling as values and that the compiler forces you to know that something can error.
@refusalspam
@refusalspam 4 ай бұрын
Why not use Checked Exceptions like in Java. If they made it so that you had to either eat the exception or declare that your function also throws it, then the compiler can always inform you if you missed handling any error.
@chrism3790
@chrism3790 4 ай бұрын
@@refusalspam Yep, many languages have this. Rust, for example.
@bcpeinhardt
@bcpeinhardt Жыл бұрын
IME people use function overloading to 1. create a function that works on a couple different types instead of using full blown generics and 2. mimic default arguments (shorter signatures pass nil as arguments to longer signatures and the longest signature actually does the thing). At least that's what I use it for when I'm writing Java. It's fine but certainly not my favorite. Elixir's pattern matching based overloading is fabulous though, would be interested to see what it might look like in a strongly typed language.
@Nenad_bZmaj
@Nenad_bZmaj 8 ай бұрын
#26 - slices are NOT messy if you first read the language specifications. A slice holds three numbers: memory address, len and cap. The first one is a pointer to an allocated array. That address is the VALUE of the slice. In assignments to other slices/new slices, as any other value, it is copied, thus the memory address of the underlying array is copied. Therefore, all slices derived from one slice point to the same array UNTIL YOU CHANGE their value. Example. a := []int{1,2,3}. There is an array holding 1,2 3 and some more space where you can append new elements. Now, b:= a. b points to the same array. c:= b[1:] . c points to the same array but starts at index 1 of b, so it represents 2, 3 elements. e :=c[1:]. e represents element 3, because it starts from index 1 of c. You can't retrieve the leading elements, i.e 1, 2 (as you can with tailing elements), but you still have slice a if you need them. But let's have d:= []int{1,3,5.7}. This points to another array. Now lets assign: c = d[:len(d)-1]. Since value of d (memory address of the second array) is assigned to the value of c, c NOW DOESN'T POINT TO THE FIRST ARRAY but points to the second array and represents numbers1,3,5 , but last element is sliced away by slice operation. You can retrieve it: c= c[: len[d)]. Just as with x:=3 , x changes its value when you assign x=7. A slice behaves the same way, only its value is some memory address. Now, his objection was (probably) this: When you pass a slice to a function as value (it is still reference to an array, and thus light-weight), and use the builtin append function to append the receiver var inside the function, if the slice capacity is exceeded, Go runtime will copy the ARRAY to a new location but with a double size (new cap = 2*(old cap + num of appended elements).Of course, the value of slice inside the function changes: it now points to this new array. The slice in the caller still points to the old array and thus that array is not appended beyond its capacity. In order to obtain the wanted result in this case, don't pass a slice to the function, pass a pointer to slice. The receiving parameter points to the slice header on the stack of the caller function, and whatever you do with it affects that slice header, and that one, as any slice, is always pointing to its underlying array on the heap, no matter if that one was copied to another place in memory (at least until you change the value of the slice). OR, return the slice from the function, and you don't have to use pointer to it. But if your function parameter ap received &a (a being some slice from the caller), and then the function did this: *ap = c (c being some other slice pointing to a different array), then you changed the value of a from within the function, and now a points to that different array. This is perfect for populating a slice from some function that spits out the slice, all at once, and you don't have to copy element by element, UNLESS you want, for some reason, to have exactly the old array repopulated and you care about the address. In that case you wouldn't use *ap = c, but builtin copy function: copy(*ap, c). The copy function copies all elements to the underlying array of a, and the value of a (the address of that array) is not changed. In fact, in this case, you can pass a (not pointer to it) and do: copy(a, c) in the function, and you don't have to return a.
@redpillsatori3020
@redpillsatori3020 Жыл бұрын
58:40 - Another complaint about Go: "Slice/capacity gotcha with pass by value/reference" What are they talking about here? ChatGPT: Ah yes, the good ol' Go slice behavior. What's funny is that people get caught in a kind of cognitive dissonance with Go slices. They look and act like dynamic arrays from other languages but have some unique behavior that can make you pull your hair out if you're not careful. A slice in Go is actually a lightweight data structure that wraps around an underlying array. It contains a pointer to the array, the length of the slice, and its capacity. While arrays are passed by value (meaning a full copy is made), slices are header values that get copied, but they still point to the same underlying array. Here's a gotcha: ```go func main() { original := []int{1, 2, 3} modified := original modified[0] = 9 fmt.Println(original) // prints [9, 2, 3], not [1, 2, 3]! fmt.Println(modified) // prints [9, 2, 3] } ``` You modified modified, but original also changed. Why? Because both slices share the same underlying array. Here's another one related to capacity: ```go original := []int{1, 2, 3} newSlice := original[:1] // newSlice is now [1], right? newSlice = append(newSlice, 4) fmt.Println(original) // prints [1, 4, 3] Surprise! ``` Wait, what? You only modified newSlice, why did original change? This is because the underlying array had enough capacity to accommodate the new value. append doesn't always create a new array; it reuses the existing one if it can. It's efficient but can lead to confusing behavior if you're not careful. This can really trip you up if you're not aware of it, especially if you come from languages like Python or JavaScript where you don't usually have to think about these things. But once you understand it, it's incredibly powerful because you can do very efficient array manipulations without a lot of extra memory allocations. So, the advice here is: Know what you're dealing with. Understand the slice header and its relationship with the underlying array. If you need a true copy, make one explicitly.
@nodidog
@nodidog Жыл бұрын
As someone who actually has a couple of years experience with Go, there is NO WAY that this blogger does. They're not even aware of a lot of the basic functionality and idioms. Yikes that they felt confident enough to write an article and share it online 😂
@rosehogenson1398
@rosehogenson1398 Жыл бұрын
go doesn't have a "dynamic array type," it has the append() function append() writes the new value in place if the capacity is large enough, otherwise it makes a copy
@Josh-hv4wo
@Josh-hv4wo 7 ай бұрын
Typia allows for runtime validaton of TS objects using TS types/interfaces. Write an interface. Validate some incoming json against it. Beautiful. All the other runtime validation libraries have you operate kind of backwards to that.
@ShadoFXPerino
@ShadoFXPerino Жыл бұрын
Try catch is desired because solving all your problems at one place is a ludicrously attractive proposition. The bigger the problem space, the more attractive it becomes.
@cosmicspice9477
@cosmicspice9477 5 ай бұрын
In rust it is not feasable to have a `struct Hello implements Greeter {}` kindof deal, because at any moment, foreign code can implement their traits on your types, breaking this neat model. The best solution is rust-analyzer's hints, that write `2 implementations` above the definition
@NowHereUs
@NowHereUs Жыл бұрын
Slice is a reference to the underlaying array. Many slices can be constructed from one array. When you update slice your array gets updated. Similarly when you update array your slice may get updated if it has the range from the updated area of array. It is simple..
@manofqwerty
@manofqwerty 8 күн бұрын
We lazy error in Azure Functions a lot. Try catch generic exceptions on the main function, log the exception, cleanup and exit. This makes sense though because C#, like JS, can throw almost anywhere.
@josefnymanmuller374
@josefnymanmuller374 Жыл бұрын
Your Zod competitor already exists, it's called Typia. It does types => validation, types => json schema, types => protobuff schemas.
@justsomerandomguyman
@justsomerandomguyman Жыл бұрын
io-ts existed before both and did the same.
@joejoesoft
@joejoesoft Жыл бұрын
Overload isn't just "generics", but it's the main usage pattern. You can use overload for optional parameters, default values, and for function wrapping (did I miss a usage?). The Quicksort example of "sort" in this video is a good example of function wrapping. Another good example is when you have the data of an item in a collection, but your API wants the index of that data. Just overload the function name with a version that does the index lookup and calls "wants and index" version. I'd rather the LSP/IDE do the work than having a bunch of similarly named functions with suffixes like ByValue/ByIndex/ByNameAndIndex/Etc in the name. It's just a poor duplication of the parameter signature information. This is assuming a typed language, of course. I don't have to write a bunch of logic code to test if the signature is valid, don't have a monolithic parameter list, create a wrapper struct/object, or use a vague undefined parameter array.
@Sz4mar
@Sz4mar Жыл бұрын
😊
@rosehogenson1398
@rosehogenson1398 Жыл бұрын
Does an LSP actually help you with function overloading? rust-analyzer never gives me a helpful result on a .into() call
@joejoesoft
@joejoesoft Жыл бұрын
@@rosehogenson1398 The most helpful part is that you don't have to pick from a list of function names and don't have to mentally translate a variable to a type. These actions clear your short-term like a GOTO statement. You have the tools auto-complete the function name and you plug in your variables that you already had in mind. Breaking mental flow is in the top 5 reason for why users hate a feature - especially in UI design.
@AScribblingTurtle
@AScribblingTurtle Жыл бұрын
35:42: A Slices capacity describes how many elements it can potentially hold, before the Memory manager needs to reallocate and copy it somewhere else. Until you exceed the capacity of the slice (with something like append()) The Slice stays bound to the initial array and does not use memory of its own (using the array instead) As soon as you exceed the capacity, the slice and its content are copied to a new memory location. (Thus becoming independent and creating memory, that needs to be handled by the GC) When creating a slice from an existing Array, The Slices capacity is the "arrays length" - "the slices start index". If you create two slices, from the same array and they overlap, it is possible to change one slice's values by manipulating the other slices's data. (Since both slices would share the same memory locations) 56:42 : Dang it, I should probably continue watching before writing comments. Slices are not jus sugar though. Arrays are always static. Aka an Arrays capacity is always its length and that length cant change. Slices are more what you would expect from a PHP or Javascript Array. Meaning a dynamic length and no control over where in memory it lives. A Slice can be both a ref or copy (Depends on context) . Initially it is a ref. If you exceed the capacity, it becomes a copy.
@iojourny
@iojourny Жыл бұрын
Holy shit, 1 hour. Lets go
@avi7278
@avi7278 Жыл бұрын
yeah let's go. what your name?
@CapsAdmin
@CapsAdmin Жыл бұрын
I've never used go but from the looks of it the error handling reminds me somewhat of a common Lua convention. The standard library is like this. Opening a file is like local file, err = io.open(...), then you can do local file = assert(io.open(....)) if you want to "panic" when opening a file. It also has something a bit like throw catch but it's handled by doing local ok, f_or_err = pcall(function() local f, e = io.open(...) if e then error("LOL") end return f end) I feel like its downside is that you have to drill res,err everywhere and it can get a bit cumbersome sometimes. Sometimes it's nicer to just throw an error and catch it at the top, at least if it's all your own code. If you remove try catch and throw in javascript and just did return [result, new Error("uh oh")] around in a "tuple", is that the same thing as golang? Or am I missing something?
@DeepDarkier
@DeepDarkier 2 ай бұрын
yeah, but you would be creating an array everytime (not that creating arrays/objects everywhere is uncommon in js [see react])
@LusidDreaming
@LusidDreaming Жыл бұрын
I will say Omit type is nice for DTOs. Like I can say this DTO is the whole object except the DB generated ID, and now any time I modify the object my DTO mirrors it.
@mage3690
@mage3690 Жыл бұрын
Oh, _that's_ what that is? Just a slice of a struct? Why isn't that a thing?
@LusidDreaming
@LusidDreaming Жыл бұрын
@@mage3690 the only thing that is a little frustrating is the type hint will always just show Omit instead of the whole object, but it really is a really convenient feature otherwise. And it makes refactoring things easier. When you update a class, you don't have to update all the partial DTOs and you don't even have to modify much code unless the code specifically access a field that was changed.
@kowalkem
@kowalkem Жыл бұрын
Why not use struct embedding?
@oninoni
@oninoni Жыл бұрын
As a C++ / Assembler / HDL Engineer: This is literally the programmer equivalent of First World Problems :D
@YTCrazytieguy
@YTCrazytieguy 3 ай бұрын
22:30 Correction: In rust if you have a struct that implements two traits, they're both in scope and you're calling a method with a name that both traits have, you'll need to fully qualify the method call or get a compile error.
@adamsribz
@adamsribz 11 ай бұрын
Bro the CaPiTaLIZAtion thing is great. I hate having to write public on every single var to to export it
@andrewnleon
@andrewnleon 8 ай бұрын
I use try catch a lot in c# and it has helped me in capturing specific errors as well presenting the error to the user. I used it most though when handling data calls and bindings. In JS i just do if statements and types to create a more concrete sense of error handling. Before not knowing this development was very complicated, i agree every engineer should be keen on error handeling.
@Warflay
@Warflay Жыл бұрын
You need function overloading especially when working with generics, e.g. in C++ the recursive definition of varardic template functions. Example: void write() {} template void write(T const &val, Args && ...args) { std::cout
@sven_527
@sven_527 Жыл бұрын
I think you have to differentiate to errors in your code to errors from user errors, like a fetch failing. If my code doesn't work, I want it to throw. If a fetch returns a 400 because the user forgot to input their age, I want Go style errors.
@Luxalpa
@Luxalpa 10 ай бұрын
Exactly that, that's why I love Rusts error handling.
@ryoriotwow
@ryoriotwow Жыл бұрын
We take use of point 8 a lot actually. Some of our endpoints can have both "use and toss"-data, and something we want to keep in a state-container. Omit comes handy. Sure, the data-structure is the real culprit, but old and reliable monoliths and all. Point 11 is also fair enough. Function overloading is very useful. It allows you to break up huge conditionals into smaller segments. That way you can jump right in on step Z instead of step A if you for some reason already know all the conditionals in a given context, without having to extract some of the logic of already written code. But Typescript doesn't really have this either. Last I checked Typescript demands the same number of parameters, which sort of defeats the entire purpose all together.
@huge_letters
@huge_letters Жыл бұрын
17:50 - I don't think that's really TS unions fault but more fault on the part of how TS treats mutations. I think TS type system is very "math-y" with how sets relate to each other and that's the artifact of that - Array is indeed a subset of Array, there's nothing inherently wrong with TS "thinking" that.
@huge_letters
@huge_letters Жыл бұрын
@llIlllIIlIIlllIlllIl fair point, yeah. Cause then the operations available on set members also are a part of the set. So a mutable Array set also includes an operation .push(string). And then you have that .push(string) is not a subset of .push(string|number) but vice versa so neither Array set is a subset of each other.
@minikame2272
@minikame2272 11 ай бұрын
I'm just saying this to be contrarian low key but if having the *option* for granular handling is what makes Go's approach so awesome: function jsonParse (input) { try { return [JSON.parse(input), null] } catch (e) { return [null, e] } } const [output, err] = jsonParse('{"abc": 4') console.log(output, err)
@911Archie
@911Archie 6 ай бұрын
Actually in go this is how you say you implement an interface: var _ Interface = (*MyStruct)(nil) and then it's checked at compile time
@burdenedbyhope
@burdenedbyhope 11 ай бұрын
the Result | undefined return type is actually pretty nice, you must check for undefined before accessing the Result. But try-catch feels very frustrating, just like old day Java, and even worse, no checked exception, all runtime exception. Maybe typescript can improve on this in the future.
@linkfang9300
@linkfang9300 Жыл бұрын
11:34, I think the 2nd point was trying to argue that if you don't have the if statement to check "err != nil", then you have no idea what goes wrong? I am not familiar with Go, but that's what I get from the article. In the other hand, in JS/TS, if you don't have try catch, your code will stop there and show you the error. You don't need try catch to know where goes wrong when you develop things. And also for try catch, you can put all logic related to tmpls inside try block so you don't need to use let to defined it outside the scope, right? The error in catch is some kind of dynamic, depends on where it goes wrong. So, err is not a static general object but will tell you where and what goes wrong. And if the function that returns the value is your own JS/TS function, then you can make sure it will return an object like, {value: "some value", err: ""}, so when anything wrong happens in the process so you even don't need the try catch to log the error message, you can just const tmpls = func(), and then check if tmpls.value = undefined, and log errorr (tmpls.err), pretty much similar to the way you like in go. So you could actually do it differently using JS/TS. I know you don't like JS and TS, but sometimes, you are a little bit too biased on them. I do enjoy when you argue some facts, but not when it's bias.
@chris-pee
@chris-pee Жыл бұрын
Prime, I think your idea for a Zod competitor already exists. I recall 2 libraries that do what you want, one of which is "Typia", IIRC
@majorhumbert676
@majorhumbert676 Жыл бұрын
Exactly! I wanted to try out Typia myself. It's supposedly very fast. Though, I am not sure it's mature enough to use in a serious project.
@houssamabouiba9848
@houssamabouiba9848 Жыл бұрын
on the point number 5 the notion of saying explicitly struct a implements interface b a seems good i think the golang way batter because in compile time you have to know who implements who and especially when it goes like 5 6 8 deep it can make compile time a lot slower.
@synthatik
@synthatik 10 ай бұрын
nil pointers are only an issue in untested Go, if you're encountering nil maps or nil pointers after deploy - you didn't test the code properly
@whoopsimsorry2546
@whoopsimsorry2546 Жыл бұрын
First thing I did when I was writing go was reinvent Result from rust into it. I see it as more like do it the way you like rather than something premade for you, they would have to implement 100 versions to satisfy everyone instead of just letting you pick out and implement a specific one to your liking. I wrap everything into my Result, takes 10 more characters and I've never crashed. That's the great thing about Errors as values, they can easily morph into anything else without much overhead.
@ferahl
@ferahl Жыл бұрын
Yes but TS is more like Option|Result since the returned value can be the thing, or an error/undefined etc. And TS will error if you try to operate on that returned value without first narrowing the type down to the thing (i.e. check if it's an error or undefined etc). So it's actually safer and forces proper error checking.
@bryanleebmy
@bryanleebmy 11 ай бұрын
TS has error throwing, which just sucks. There's also no `Option | Result` built into TS, and if you pick any one of the "Rust-like" error handling libraries on npm, you're locked into that one library and you have to write wrappers for every other library you use because they're all incompatible. And every single one of those libraries introduces a runtime overhead for every Result / Option they return, since you have to create a new object for each return. Returning `Error` is about the closest thing you can get that's natively supported, but again there's no standard error handling pattern in TS, so different dependencies will use different patterns. Go is infinitely better on that regard, and improvements can be made to the language server to check mutually exclusive access to either `res` or `err`.
@joaodiasconde
@joaodiasconde Жыл бұрын
Errors by values is definitively the best. Rust does it better leveraging sum types to force engineers to handle the error to unwrap the value. I think what is also missing in Go is a sort of propagating the error up the callstack feature, like Rust's question mark operator. That allows the example of one mechanism to catch all and handle the same way. Also, yeah dead locking yourself could be argued as being a skill issue, but so could every C++ footgun and we still dunk on C++ for it... as an industry we need to push for languages with fewer footguns.
@dongueW
@dongueW Жыл бұрын
Valid points!
@matheusjahnke8643
@matheusjahnke8643 10 ай бұрын
If not every, an overwhelming majority(like, 90% or more) of language disadvantages could be compensated with skill... so technically they are all skill issues.
@u007james
@u007james Жыл бұрын
yeah thats good practice for handling each line, but sometimes people just try and catch the entire block once and log the error and line later,
@AlecSorensen
@AlecSorensen 9 ай бұрын
There is function overloading in TS where you can define a function that can different definitions for types in your params. In regular JS, you don't need it, since there are no types.
@yapet
@yapet Жыл бұрын
EDIT: I’ve written this comment before watching the vid completely. Prime does address the sum types in TS, rendering half of this comment honestly stupid. I see the point, but in the end, I do not agree with Prime’s point about unsoundness of ts unions. The is A LOT of ways to break soundness of TS type system, and the presented one is not the worst contender. I never ran into such case, probably because I avoid mutating stuff willy-nilly. Tho I’m not religious about it like at the church of holy haskell. I’m so tired of prime’s dogs**t take on typescript enums. I’m sure he gets this point a lot, but I’ll still reiterate. First of all, the keyword "enum" enums are bs. We can all agree, that those aren’t the best. They do get one thing going for them, if you want to name your ints (which may aid perf, but more on that later). Secondly, the way to do sum types (rust enums, ocaml/haskell variants, discriminated unions, etc.) is to declare a union. Union which you can descriminate cases in some way. The go-to way, is to have objects with "type" property of different literal values, aka: type A = { type: "foo", value: number } | { type: "bar", bazinga: string }. Unions are WAY more powerful feature than plain enums with associated values. But the power is in the ability for tsc to see through discrimintions. Aka, if with the previous type you write: if (a.type === "foo"), typescript will deduce the correct variant in the body. I'm sure we all know this trick. I'm sure Prime knows about it as well. I'm sure Prime used this as well. Then WHY are we still doggin' on TS type system? No-one cares about "enum" keyworded enums. It has sum types. And it is not just a gag. I see time and time again Prime presenting "lack of proper enums" (and by proper he means rust) as a serious downside of TS. TS has problems. JS has a lot. "Lack of rust enums" is not one of them. And about those "enum" perf improvements. Keyworded "enums", do have one thing going for them. They allow you to name integers in the type system. This does provide a form of documentation. If we are to use string literals (as everybody does nowadays) as a union tag, they are self-describing (type Tag = "case-foo" | "case-bar"), not ints unfourtunatelly (type Tag = 1 | 2). SMI’s can give you a bit of that sweet sweet performance oompf, if you use them instead of literal strings. SMIs pack better in arrays. You can do bit twiddling to pack multiple variants into a single SMI. Equality checking ints is a lot faster then strcmp-ing string. Although I speculate that using ints vs strings as a union tag isn't that impactful of a perf jump. Since all of the tag values are likely to be specified in code (not generated dynamically, recieved from the user, fetched from the network, etc.), they are interned strings (judging by the V8's string.h). If JIT is to learn the shape of those tag strings (it should be able to learn that strings in tag properties are always interned), doing the comparison then just equates to a single 64-bit word equality check (comparing if pointers are the same), just like eqality-checking SMIs. And since these are const strings, there shouldn't be any additional GC pressure. I might have missed the joke here, but I don't think it is one. I think that screaming "typescript enums are bad. just look how much they are better in rust" is misinformed and/or just ignorant. Yes, "enum" keyword kinda sucks. Yes, rust enums are a good way to model sum types. No, typescript HAS equivalent capabilities. Typescript allows for far better flexibility when it comes to declaring and using sum types. Thing that is genuinely missing when comparing to rust enums is the pattern matching + a presence of few exhastiveness checking bugs in tsc.
@justsomerandomguyman
@justsomerandomguyman Жыл бұрын
He doesn't really understand the differences between enums, unions, and sum types. It's just a fact. I'm guessing he doesn't have any experience with functional programming, and that's probably why he can only relate to Rust's enums and doesn't really see the bigger picture.
@IdkMaybeShawn
@IdkMaybeShawn 2 ай бұрын
Seems like Try/Catch is better when you have like a several-line block of related code that you don't want to break up but multiple statements in it can throw errors or multiple types of errors that can be thrown with different handling needed for each. You can keep your block of code together making it easier to read then handle all the errors on the outside.
@SigmaChirality
@SigmaChirality 7 ай бұрын
Speaking as an infra engineer, the go packaging system is so much easier to deal with. Deploying node apps at scale is much worse.
@PhatPazzo
@PhatPazzo Жыл бұрын
Come on… try/catch is the worst, but golang error handling is still not “beautiful”. Please correct me if I’m wrong, but if you ignored the error on line 49 (12:24), go doesn’t catch that without a linter, right? And about readability, there are five statements there totaling 18 lines, that kind of error handling completely throws code overview out the window. In a world where we have algebraic data types such as Result and Maybe/Option, the solution in golang is at best acceptable, but absolutely not beautiful…
@TheCalcaholic
@TheCalcaholic Жыл бұрын
Like everything in go, it's not beautiful, it's not the most readable, but it's robust and functional. I much prefer the style of rust over go and I'm kinda undecided whether I like Java's or go's error handling better (at least, both are explicit). But I think we can all agree, that error handling in JS/TS is a pain in the ass. In go, while you can ignore an error, you know that you are doing it (because you need to use a placeholder for the error result explicitly)
@iamrafiqulislam
@iamrafiqulislam Жыл бұрын
TypeScript needs lots of Boilerplate codes without getting any runtime safety which is more crucial.
@thepotatokitty
@thepotatokitty Жыл бұрын
Composition, just create a new struct with those 3 fields and then embed that in the structs which need the common fields.
@flyingmadpakke
@flyingmadpakke Жыл бұрын
But programmers are lazy, we don't want to use two dots to access a nested object property :)
@thepotatokitty
@thepotatokitty Жыл бұрын
Skill issue. You can embed a struct and it will inherit all the properties and you won't have to use the dots.
@flyingmadpakke
@flyingmadpakke Жыл бұрын
Didn't know that is a specific GO thing. I thought you were referring to TS Omit.
@CTimmerman
@CTimmerman 10 ай бұрын
The benefit of try catch is that you don't have to repeat the catch block after every statement.
@MrToup
@MrToup 10 ай бұрын
I really like when you take a really small snippet to explain your point. Would love to see more.
@unowenwasholo
@unowenwasholo Жыл бұрын
ITT: Redditor works backwards from their opinion of enjoying writing TS more than Go. Bro, just say you like TS. It's okay to be a bad developer. I am, too-I write everything in TS. Just embrace it. If it means that you get the job done and push out that application, more power to you.
@robfielding8566
@robfielding8566 10 ай бұрын
what you really want is to explicitly handle all errors that are the result of a bad input, and a 4xx in all such cases. a try/catch or a panic/recover are only to handle something that got missed, that is presumed to be a coding bug as 5xx. the try/catch or panic/recover is a fault barrier. each thread should have a fault barrier at the top if it doesn't continue with a new session; or in the top-most loop as the fault barrier. fault barriers log things that got missed. reaching the fault barrier IS a bug. you can't always recover for real though. "out of filehandles", and your process can't safely proceed with anything.
@robfielding8566
@robfielding8566 10 ай бұрын
the main thing that IS wrong with Go error handling: returning 'error' isn't specific enough. You should return the most specific type you can that has the error interface. ie: ex FileNotFound ... ex.FileName. If you are in the middle of doing a task, then that task's error should get returned. If it was caused by an error inside of that task, then that error should be used to construct that task's error. That way, you get context about what you were DOING when it errored out. It is pretty important that the task know what HTTP error code to suggest. You should return 4XX errors on bad input, and 5XX on errors deemed to be bugs to be fixed if your own code. This is why it's a bug to hit the top-most fault-barriers. It means that you missed something that was bad input, or something that could have gone wrong internally. You need to update your code so that all errors can tell you definitively whether fault lies outside the process, or inside the process.
@oakley6889
@oakley6889 Жыл бұрын
People taking about elixir are actually dead on, kinda insane how much it taught me about alot of these areas
@defnlife1683
@defnlife1683 Жыл бұрын
Help me Prime. I started learning Go, went into Rob Pyke’s history and then ended up in Plan 9 docs and writing drivers. Halp!
@nexovec
@nexovec 5 ай бұрын
OP: "Why can't you be like typescript?" Go: "I'm sorry, dad"
@arnerademacker
@arnerademacker Жыл бұрын
This was basically programming slander in all directions for like an hour and I love it
@kubre
@kubre Жыл бұрын
32 best reasons to develop depression
@YTCrazytieguy
@YTCrazytieguy 3 ай бұрын
36:10 Correction: There is function overloading in typescript. But it's sort of weird - you actually just write one implementation that needs to handle all of the possible cases.
@ameer6168
@ameer6168 Жыл бұрын
we have to write 2x more code to make typescript type safe
@mattymerr701
@mattymerr701 Жыл бұрын
Constructor overloading != function overloading. And function overloading can be generics via syntax sugar.
@GaryFerrao
@GaryFerrao 11 ай бұрын
Is this a moustache competition? 😂
@chaorrottai
@chaorrottai 10 ай бұрын
off topic: something i don't undertand about c++, why not just have the compiler manage inserting delete(var) in the code at relevat code locations. Like if a pointer is declared but not returned in a function, then insert a delete(pointer) and if it is returned, then the delete function could be inserted before the pointer reasignment or the end of the scope containing the pointer. It would litterally be one compiler pass and it should be fairly easy to program. Just follow the pointer to it's scope ends, including function returns.
@Fan_of_Ado
@Fan_of_Ado Жыл бұрын
I've had to write some TypeScript this week despite being someone who usually only does Go. TypeScript was pleasant BUT WTF is the difference between cjs, node, esm2014,esm2020 and on and on. The tooling also sucks. `tsc` for some reason doesn't handle imports correctly and I had to use esbuild to bundle stuff then use tsc just for the d.ts type declarations. I could probably spend a month learning how to use it "properly" but why must it be so painful? I tried bun. It was great except for the fact that the cryptography implementation is incomplete and thus I can't use `bun build`. It's meant to be a simple npm library. It shouldn't take this much effort.
@jhonyhndoea
@jhonyhndoea Жыл бұрын
true. the ecosystem sucks. you can give Deno a shot, my favorite so far.
@oserodal2702
@oserodal2702 Жыл бұрын
Welcome to the Javascript ecosystem.
@Fan_of_Ado
@Fan_of_Ado Жыл бұрын
The bun developers are VERY helpful. They solved my issues with their crypto implementation in an hour
@Dipj01
@Dipj01 Жыл бұрын
Almost everything has to be convoluted in javascript. Almost everything.
@buc991
@buc991 Жыл бұрын
It’s not much effort just ppl trying to use stuff without learning anything about it first. Oh JavaScript have versions oh noo so hard 😮😂
@trapexit
@trapexit Жыл бұрын
@14:00 An uncaught exception is an abort()/assert(). It's pretty trivial to do that around the code if that is in fact the behavior you want.
@Titousensei
@Titousensei Жыл бұрын
About point 7 dynamically looking at struct field names, isn't that what the reflect package is for?
@LuNemec
@LuNemec 11 ай бұрын
On point 7] although I understand that in TS it is "native" and easy to iterate over object attributes, I think the complaint that in Go you need to use reflect is invalid. That is what reflect is for. Runtime introspection. Usage of reflect is the correct answer, but it would be nicer if these would be first class citizen. Although, when you think about it, after over 10 years of working with Go, I had this problem maybe once. But it depeds what software you work on.
@00jknight
@00jknight 10 ай бұрын
In go, you can recover from panics and return a 500, or treat it basically like try/catch. It's kinda wild but it's useful to use at the root of your request handler in a http server for instance.
@kowalkem
@kowalkem Жыл бұрын
Guy must've gotten oat milk instead of soy.
@b3owu1f
@b3owu1f Жыл бұрын
I was waiting on 5. interfaces for the good part about Go interfaces.. something I hope Zig adds. The implicit feature of it makes it so that developers can implement an interface without knowing the interface name. That's a very powerful capability. The flip side of that though is that you could "accidentally" implement an interface without knowing you are. But the flip side of the flap is.. you could now without even knowing/trying, provide an implementation of an interface that could arguably be used in place of another interface implementation. That is one thing I really love.. is I simply define a type (Struct usually), add method(s) that implement some interface, and now I can pass that instance and I am good. Without even importing/depending upon that interface. If I am writing a library without knowing about said interface from another library (lib), and a person is using library lib and also using my library.. they can pass my implementation in to lib's need for that interface.. and all the while I never intended/knew about lib's interface. That's pretty damn powerful.
@nevokrien95
@nevokrien95 Жыл бұрын
For api design inherentance is a great tool. U don't want more than like 2 layers deep. The nice part with Inherentance is that it let's u define a functi9n for the api. In a waybits an api api
@ShadoFXPerino
@ShadoFXPerino Жыл бұрын
25:30 * is a dangerously leaky abstraction. Option and ? are less leaky.
@christian15213
@christian15213 8 ай бұрын
there is definitely overloading in JS/TS. this helps with variations of the function
@codeChuck
@codeChuck 7 ай бұрын
Use eslint rule "no-swadow". Will save you from mutation of a variable declared in the upper scope.
@darvoid
@darvoid 11 ай бұрын
JSON thingy hint: use yaml string tags `yaml:",inline"` and you never miss a object key :'D and you can use yaml tags for json xD (I kinda find this silly xD but works)
@joyride9998
@joyride9998 7 ай бұрын
13:00 that's not really true... you can have similar construct as try catch also in go : func HandlePanic() { r := recover() if r != nil { fmt.Println("RECOVER", r) } } func divide(divisor int, divider int) { defer HandlePanic() if divisor < divider { panic("start is greater than end") } else { fmt.Println(divisor / divider) } }
@christian15213
@christian15213 8 ай бұрын
Agree, there are pros and cons for both languages. You can do functional programming in TS and vice versa in GO.
@mihailmojsoski4202
@mihailmojsoski4202 7 ай бұрын
28:22 you got it right the first time (with for ... in), but went to the pain in the ass route
@user-kw9cu
@user-kw9cu Жыл бұрын
I like simplicity of Go. You dont need to compile bizzlion types in your head like when yo do TS.
@unicodefox
@unicodefox 11 ай бұрын
I think my main problem with the error handling that Go uses, as opposed to try catch statements is, (as someone who hasn't wrote code in a language that uses that), try catches fail closed. for example, you have this code: (written in js/express because thats what I know 🤷) router.post("/user/:id/update", (req,res) => { let validated = validateUserUpdate(req.body) // returns the new data if correct, throws if not. db.updateUser(userId, validated) }) If you forget to catch that error in a environment like TS,C#,Python, etc etc, that DB update will never happen, and will be caught by say, the http framework, or in the worst case, crash the app, but the integrity of the data is always maintained. In a environment like Go, where you're free to just run past the error, there's a chance that you're going to end up wiping out that user's data.
@Nenad_bZmaj
@Nenad_bZmaj 8 ай бұрын
I guess you just have to make a habit to always call db.updateUser (or equivalent in Go) within if err == nil block, or always after the if err != nil block.
@asdqwe4427
@asdqwe4427 2 ай бұрын
Melk looks like TJ half way through a prime transformation
@neociber24
@neociber24 Жыл бұрын
TS is just JS, just fancier. The real question, what is the best type system? TS, Go, Rust, Haskell, Kotlin, ...?
@nenadvicentic
@nenadvicentic 9 ай бұрын
You guys completely missed the point about difference in exceptions in Go and TypeScript. Errors in Go do not stop program execution, which is completely crazy. That is THE difference. In any normal/sane language errors stop the execution. In TypeScript, as an example of such language, you put try/catch when you have "expected exception" and want to continue execution, which is fairly rare case (>5%?). While in Go, in order to stop execution, which is 95+% situations, you have to handle it manually. And people who are writing try/catch blocks all over the place... they are doing it wrong way.
@ThePrimeTimeagen
@ThePrimeTimeagen 9 ай бұрын
Simply disagree Errors are values
@nenadvicentic
@nenadvicentic 9 ай бұрын
@@ThePrimeTimeagen And when your function returns int 0, because of an error, you code should simply continue running and threat your 0 as result from calculation?
@Nenad_bZmaj
@Nenad_bZmaj 8 ай бұрын
@@nenadvicentic Errors are not some random thing, they have causes which you, as the code author, must be able to anticipate and handle in advance. Errors in calculation are not acceptable. You'll discover bugs by testing, bugs are not errors. Aborting is not graceful. Warning the client side and leaving them options to change parameters or exit, is.
@nenadvicentic
@nenadvicentic 8 ай бұрын
​@@Nenad_bZmaj Half of your reply is stating exactly what I am saying and other half is contradicting it. Errors can be expected (once you can anticipate) and unexpected (e.g. random hardware or network failure). Do you think your code should "continue on unexpected error" by default? I think it should throw by default. And BUBBLE. And if you want to provide user with options after error, you do try/catch on top, user interaction level. Not on every intermediate level, just to re-throw it up. That is anti-pattern and that is what Primeagen constantly throws in as an argument against try/catch. Regarding calculation, parts of data you calculate on, or pre-calculated partial, come from different data sources or a different server. What if IO fails while reading the subset of the data? You catch that with unit-tests? You "continue by default" defaulting, let's say `int` to default 0? This is an argument to say that in 90%+ of use-cases we want code/runtime to throw on unexpected error, not to continue. Therefore, language/runtime defaults should cover 90% use-case, not 10% use-case.
@Nenad_bZmaj
@Nenad_bZmaj 8 ай бұрын
@@nenadvicentic To be honest, I have zero experience in any language other than Go, but I very much like the way I can handle errors in Go, because I feel I am in full control and there is no magic or black box that I have to rely upon. In your example, one should always anticipate reading failure. Each os or io function returns errors as values and they should be called that way. Your function that calls reading a file should not abort the whole application, but back propagate the error to the caller. It is up to the overall design at which level the caller decides what to do with that error, say, request data to be sent again before proceeding with calculations. You know what data structure you expect and the nature of the data, so you can also check the data integrity (in case reading was successful) and your function that does this check should return error as value. But even in the case you mentioned, unsuccessful read will not generate zeros in place of missing data - there will be no bytes at that place (you'll also get the returned number of bytes read). So, if you decide to not handle that error, in the next step, when accessing that missing spot, you'll get panic anyway, so the program does abort. I just don't like that, so I'd handle panic as well at some higher caller level to be able to finish gracefully. To be more precise: you have a slice of int32 and it holds N elements, so you expect to read 4*N bytes. But the read was unsuccessful and only 12 bytes were read. What you were saying is that only first 3 ints were populated but the rest remain zeros and the program continues. But that is not true. You have to have a function that converts bytes to int32 and that function ranges through the slice of int32. When it comes to index 3 it wants to access the byte slice at offset: 3*4 , i.e. the 13th byte. But there is no 13th byte in that slice, so program panics with "out of range" if you chose to ignore the reading error.
@nyahhbinghi
@nyahhbinghi 8 ай бұрын
Go is bad *BUT* receiver methods are great because (1) avoid need for `this` and (2) methods don't need to be bound to receiver, they are pre-bound
@nyahhbinghi
@nyahhbinghi 7 ай бұрын
yes
WTF Winamp
30:26
ThePrimeTime
Рет қаралды 80 М.
Git Is Awful | Prime Reacts
23:10
ThePrimeTime
Рет қаралды 204 М.
Когда отец одевает ребёнка @JaySharon
00:16
История одного вокалиста
Рет қаралды 3,9 МЛН
An Unknown Ending💪
00:49
ISSEI / いっせい
Рет қаралды 58 МЛН
From Small To Giant Pop Corn #katebrush #funny #shorts
00:17
Kate Brush
Рет қаралды 72 МЛН
Does PHP Suck? | Prime React
29:56
ThePrimeTime
Рет қаралды 153 М.
Leaving $450,000 a year Job | Prime Reacts
43:42
ThePrimeTime
Рет қаралды 373 М.
Let's Free JavaScript
25:07
mSyke Codes
Рет қаралды 48
Is TypeScript (NodeJS) Faster than Go?? |  A server comparison
9:54
ThePrimeagen
Рет қаралды 222 М.
Is 2024 The Year Of Zig ?
48:20
ThePrimeTime
Рет қаралды 166 М.
Rust vs Go : Hands On Comparison
50:40
ThePrimeTime
Рет қаралды 227 М.
Why Isn't Functional Programming the Norm? - Richard Feldman
46:09
I'm Coming Around To Go...
21:33
Theo - t3․gg
Рет қаралды 116 М.
I Quit Amazon after 2 Months | Reaction
29:29
NeetCodeIO
Рет қаралды 133 М.