Functions vs Classes: When to Use Which and Why?

แชร์
ฝัง
  • เผยแพร่เมื่อ 21 ก.ย. 2024

ความคิดเห็น • 221

  • @ArjanCodes
    @ArjanCodes  11 หลายเดือนก่อน +4

    👷 Join the FREE Code Diagnosis Workshop to help you review code more effectively using my 3-Factor Diagnosis Framework: www.arjancodes.com/diagnosis

  • @jordanmungo917
    @jordanmungo917 ปีที่แล้ว +83

    Arjan just wanted to let you know that in the past year your channel played a huge role in helping me get significantly better at programming during my final year of college, and now working as a software developer. You're doing great work!

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว +5

      Thank you for sharing this!

    • @mooza.shorts
      @mooza.shorts ปีที่แล้ว

      Brother so happy to read this. The same thing happened to me as well four years ago and I'm so glad to see that the same thing happens to other people. Coding is the most empowering thing we can do

  • @mariacardona8644
    @mariacardona8644 ปีที่แล้ว +43

    This has been my question for YEARS! Thanks for making it simple, love your videos.

  • @poneis88
    @poneis88 ปีที่แล้ว +7

    Last year I made a web scrapper that checked prices of products and used Object Oriented approach "just to keep the code organized". I did not have the need to spawn multiple instances of the scrapper and I was not storing anything in my scrapper instance, so I felt that I was using the wrong tool for the job, because there was no need to use any of the properties of an object, I was just calling its methods. Now it is much clearer to me why to pick one versus the another and I am very thankful that you made this video.

  • @manomancan
    @manomancan ปีที่แล้ว +134

    Arjan is a one-man university.

    • @Generic_text871
      @Generic_text871 ปีที่แล้ว +3

      Someone didn't go to university

    • @RickWeberEcon
      @RickWeberEcon ปีที่แล้ว +1

      Not enough committees to be accredited though.

    • @dansplain2393
      @dansplain2393 ปีที่แล้ว +1

      I would say also for a dev he’s extremely proficient at marketing.

    • @kyrgyzsanjar
      @kyrgyzsanjar 10 หลายเดือนก่อน

      Word!

    • @fabio.1
      @fabio.1 9 หลายเดือนก่อน

      LMAO

  • @dokick2746
    @dokick2746 ปีที่แล้ว +46

    My rule is: If it makes sense to encapsulate something in your own class (so interacting becomes easier and more intuitive), use classes, otherwise stick to functions.

    • @lukekurlandski7653
      @lukekurlandski7653 ปีที่แล้ว +10

      I also have turned to this philosophy. Often times I would find myself writing 3-4 closely connected functions that require much of the same data and are unlikely to be used elsewhere throughout the program. While a function is theoretically a more robust construct to perform this task, the code becomes way more readable if I wrap it in a class and use the __call__ method to initiate the process.

    • @whossname4399
      @whossname4399 2 หลายเดือนก่อน

      ​@lukekurlandski7653 you can just encapsulate it in a module, though? The only reason to use a class is to encapsulate data. Otherwise functional, procedural or declarative are all better approaches.
      Honestly I would never call python code functional though, it's a language best used with the procedural style.

  • @alphenit
    @alphenit ปีที่แล้ว +3

    @2:35 I love it when Arjan always says: "I have a very simple sample application here"
    Me: Eyes squinting: I have no clue what this does

  • @Curatiokyte
    @Curatiokyte ปีที่แล้ว +4

    I have watched hour long lectures/presentations and read more articles than i care to count, on the pros and cons of OOP and using classes, and this is the first time I've seen someone sum it up so well. Honestly I could never figure out why anyone would ever use classes because they just seem to add a lot of complexity compared to the functionality they provide, so they always looked inferior to just using functions. This makes it so much easier to figure out where to use classes.

  • @ledempire9066
    @ledempire9066 ปีที่แล้ว +2

    I just can not believe how every line of code in your videos is useful and worth to even dive deeper in the logic you create! Best of the best!

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว

      Thank you so much!

  • @rossursino8175
    @rossursino8175 ปีที่แล้ว +9

    I also find classes to be useful ways to hold data and define data structures (in this case, dataclasses), which can be passed in as arguments to functions and instances of classes. Thanks for another fantastic video Arjan.

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว

      Totally agree & you’re welcome, Ross!

    • @maleldil1
      @maleldil1 ปีที่แล้ว +2

      I wouldn't count dataclasses as classes. Dataclasses are necessary in Python because there's no obvious way to define pure data: your choices in the standard library are dataclasses, named tuples and dicts, and dataclasses have the best ergonomics. They're much closer to pure structs.

  • @veni_vidi_victorian
    @veni_vidi_victorian ปีที่แล้ว +5

    I also find myself mixing the approaches quite often. In a web backend with routers, for example, I want both states (classes) and pure actions. Pure actions would be a crud module with action-focused SQL statements (or ORM code), while states would be a schema module with classes that hold the state of the request and response.
    Additionally, the ease of testing argument can not be said enough. The amount of mocking and pre-test setups you have to do varies significantly by the amount of state in your code.
    All in all, really great video, I agree with all points made.

  • @andriistefanenko6270
    @andriistefanenko6270 9 หลายเดือนก่อน +3

    It is one the most simple and useful explanations of the difference between function/class usage cases
    Lots of thanks!

  • @divine-favouranigbogu413
    @divine-favouranigbogu413 ปีที่แล้ว +1

    I recently discovered your channel and I can honestly say; the more I watch you and type out the codes you wrote... The better programmer I have become. THANK YOU!!

  • @js46644
    @js46644 ปีที่แล้ว +2

    Hopefully this video is relevant for more than a few more years. Eventually the correct decision will be whatever GPT-5 decides.

    • @joraphpictures
      @joraphpictures 10 วันที่ผ่านมา

      You are already there.

  • @marksegall9766
    @marksegall9766 ปีที่แล้ว +7

    Classes are used to model nouns (objects): employees, products, customers, etc.
    This matches well with relational databases which are also designed around nouns. A product table with a unique ID for each product and a customer table with a unique ID for each customer.The state of the nouns are critical in the database. It is natural to use OOP to represent the entities stored in the database.

    • @gemorp8506
      @gemorp8506 ปีที่แล้ว

      Is there any Subject in programming ?

    • @aocastro
      @aocastro 9 หลายเดือนก่อน +1

      I agree, it sounds to me that objects are like tables in a database, actual structured data being manipulated on the fly, in the computer's working memory instead of non-volatile storage

  • @calum.macleod
    @calum.macleod ปีที่แล้ว +4

    Well described. I spent months coming to this conclusion, I wish I had your video when I started. One big reason I like to use functions with separate data structures, is that it can help to keep Inter Process Communication simple. I use a shared memory approach for performance and I think the OOP model (which tends to include exposing data) would be awkward in an IPC Python system.

  • @Z33Garage
    @Z33Garage 4 หลายเดือนก่อน +1

    I taught myself python for tool creation for Maya and recently I was asked why I don't use classes as much as functions ( I barely use em). I didn't know how to answer but now having watched this has helped me wrap by brain around why, since my maya tools are mainly action oriented. Thanks for a great video!

    • @ArjanCodes
      @ArjanCodes  3 หลายเดือนก่อน +1

      I'm happy to hear the video helped out!

  • @MisterKorihor
    @MisterKorihor ปีที่แล้ว +17

    The duration of state is also an important factor. The rule can be formulated as follows: if you have state that needs to be retained for longer than one procedure call (and that state can be meaningfully encapsulated), then use a class. If the state is only needed for one procedure call, use a procedure .

    • @Flackon
      @Flackon ปีที่แล้ว

      agreed, with the bank account example one could easily handle the state in a file or database, and have all the operations be functional

    • @kicknotes
      @kicknotes ปีที่แล้ว

      This is a pretty sound generalization.

    • @DevinDTV
      @DevinDTV ปีที่แล้ว

      very helpful

    • @jamesgrant3343
      @jamesgrant3343 10 หลายเดือนก่อน

      The bank account example is ambiguous - irl want to use a transactional model with some backend data store. Unless you are the bank, the data isn’t mutated at your end, you send requests which are applied and the results are returned, ie; you don’t hold the object at your end.

  • @YaroslavOliinyk2023
    @YaroslavOliinyk2023 ปีที่แล้ว +3

    I love your humor. You are literally a meme guy.
    Thank you so much for your hard work and contribution to the Python community

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว +1

      You're welcome - glad you find it helpful! Now... I have to go back to creating memes ;).

  • @morgankerle5566
    @morgankerle5566 ปีที่แล้ว +4

    Awesome content! As a self-taught programmer who first learnt functional programming, I often struggled to see the benefit of OOP. This is a super helpful framework for thinking about the differences between the two.

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว

      Thank you, Morgan!

  • @ilangated
    @ilangated ปีที่แล้ว +2

    I feel you can sometimes use classes to making functional programming cleaner. I was developing an automated report for work. The program would calculate some data, then either send a daily report or an invoice at the end of the month. Completely stateless, so a functional approach made sense. Different clients received their own version of the daily or monthly emails so we would need to write the same types of functions for each client. At the end of the day, it was simpler to create an interface which bundled all of these email-sending actions together. For each client, we used a different implementation of this interface. Technically it was an abstract class rather than an interface since Python doesn't have interfaces.

    • @HelmutIsaacPadillaChavarria
      @HelmutIsaacPadillaChavarria ปีที่แล้ว

      hi, python has protocol that can be used as interfaces, Arjan has a video about abstract classes vs protocols

  • @simonarcher1510
    @simonarcher1510 ปีที่แล้ว +1

    As a Go developer I face the same challenge. Generally I start with functions, and find that I "step up" to data classes as needed. But truthfully, using both functions and data classes together is the answer. Personally I find data classes easier to test since they can implement interfaces, which allow for the easy creation of mock/fake implementations. Functions, on the other hand, can be harder to test, especially when they're coupled to other parts of the system.
    Also, in Go, a type introduces a new namespace/scope for its methods, which is valuable when the package you're working in is already heavily populated with functions. With no overloading of methods or functions, managing the namespace is critical.

  • @Gaspar.Albertengo
    @Gaspar.Albertengo ปีที่แล้ว

    Thanks. 12y ago I started programming Python and a big piece of administrative software for my business... Back then I really tried to use classes, because "that's how it's supposed to be". But found it was simpler if there was mostly plain functions. I did it that way, and it's still working everyday today. Now thanks to you I know I'm actually doing it right 👍🎉🎉🎉

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว

      Awesome! Thank so for sharing this!

  • @bearson4075
    @bearson4075 ปีที่แล้ว +1

    Thanks for this, it makes a lot of sense. I wish I had seen this in my earlier days learning to code. I definitely have written code as classes when they should have been functions and written code as functions when they should have been classes.

  • @jorgerios5330
    @jorgerios5330 ปีที่แล้ว

    I don't even need to see the rest of the video but the intro, because you are so clear as allways. I will see it out pure fun and entertainment. Thanks 👍🙏

  • @Georgggg
    @Georgggg หลายเดือนก่อน +1

    Can't go wrong with functions, its that easy.

  • @cerealport2726
    @cerealport2726 ปีที่แล้ว +9

    As a self-taught coding person (though far from expert), I have often asked myself this question. Thanks for a great perspective on it.

  • @kwabenakesseh1282
    @kwabenakesseh1282 ปีที่แล้ว +1

    I can't to be good like you Arjan. Thanks for the effort. Keep up the good work!

  • @outofahat9363
    @outofahat9363 ปีที่แล้ว

    This channel is a gold mine. I'm a DBA and I use Python for simple automations, but I like to know the language more in depth and this channel seems perfect for it. Thanks for explaining the more high level concepts very clearly and with examples that I wouldnt easily find and I didnt get to study at uni not in this detail at least (I mainly did iteration algs in C and statistics with R no OOP)

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว

      Glad you enjoy it!

  • @RonaldPostelmans
    @RonaldPostelmans ปีที่แล้ว

    Hi Arjan, thanks, for this video, i realize i don't have to use classes for everything if i want to programm, following "best practise", i think functions are easier to use and classes are more complicated. so if not needed i will stay with the functions.

  • @dj196301
    @dj196301 9 หลายเดือนก่อน

    What an outstanding video. It even make sense when you're questioning if it makes sense.

    • @ArjanCodes
      @ArjanCodes  9 หลายเดือนก่อน

      I'm glad you enjoyed the video!

  • @KonstantinPrydnikov1
    @KonstantinPrydnikov1 ปีที่แล้ว

    Amazing cosmically music, good light. I almost fly away to the andromeda. Thanks

  • @moneypennysloverboy
    @moneypennysloverboy ปีที่แล้ว

    from now on I will think about classes and functions in terms of bank accounts and file i/o. Thanks dude

  • @bjh4970
    @bjh4970 ปีที่แล้ว

    I love this framework! One more: if your program is process-focused, that’s when you use an imperative style

  • @JFloridaTech
    @JFloridaTech ปีที่แล้ว

    Finding out about classes is almost the same “omg” revelation moment as when you first find out about Python 😅 dope vid

  • @doop9134
    @doop9134 7 หลายเดือนก่อน

    Thank you, ArjanCodes!

    • @ArjanCodes
      @ArjanCodes  7 หลายเดือนก่อน

      Glad you enjoyed the content!

  • @7scientist
    @7scientist 5 หลายเดือนก่อน

    Very helpful, thanks

    • @ArjanCodes
      @ArjanCodes  4 หลายเดือนก่อน

      Glad it was helpful!

  • @redkvicka
    @redkvicka ปีที่แล้ว

    The intro is perfect :D love your content and your humble attitude.

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว

      Thank you so much! :)

  • @vaishnavisonawane8559
    @vaishnavisonawane8559 ปีที่แล้ว

    Arjan, you inspired me to dive deeper into python and made me want to get better at it! Good stuff. Kudos!!!!

  • @DouglasHirsh
    @DouglasHirsh ปีที่แล้ว

    The Babylon 5 reference is Awesome! Really takes me back.

  • @joeblack8843
    @joeblack8843 4 หลายเดือนก่อน +1

    I learned more by just hearing than by just watching the video. For me there is too much information in short term by watching it.

  • @joxa6119
    @joxa6119 ปีที่แล้ว

    Listening to you is like listening to the best senior developer that never existed in my company.

  • @amitaniket5472
    @amitaniket5472 ปีที่แล้ว +1

    Are you spying on me. Seriously you come up with topics which I recently search😊❤

    • @GOTHICforLIFE1
      @GOTHICforLIFE1 ปีที่แล้ว

      Same for me - Been moving onwards to functional programming recently and found myself struggling with certain aspects feeling more complicated than if i used classes. So this hybrid solution is what works the best for my imo.

  • @Dubs3
    @Dubs3 ปีที่แล้ว

    Perfectly explained, I loved this

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว +1

      Thank you, Kyle!

  • @Lekkerman
    @Lekkerman ปีที่แล้ว

    Thx for this video. I am doing something like the first example you provided.
    I did a function oriented programme but decided to move to a object oriented one to look more professional. I feel what you said : it’s highly complex (but maybe I architectured it wrongly) and not as easy to read as functional based. I think I am going to roll back part of the code 🤔

  • @johncrunk8038
    @johncrunk8038 ปีที่แล้ว

    One more notch in the programming Swiss Army Knife. Thanks.

  • @djl3009
    @djl3009 ปีที่แล้ว +1

    functools.partial, which you have already covered in a few videos, is a great example of using functions to cover that "grey area" where you want to leverage some lightweight state but don't want the belt-and-braces approach of classes.

  • @PaulBrema
    @PaulBrema 4 หลายเดือนก่อน

    thank you

  • @djbroake9810
    @djbroake9810 ปีที่แล้ว

    Thank you for making this video.

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว

      Glad you liked it!

  • @ScottVanDress
    @ScottVanDress ปีที่แล้ว +1

    Valuable insights as always!

  • @TheWrighteousOne
    @TheWrighteousOne 9 หลายเดือนก่อน

    Coding sensei, thank you for explaining the difference between class and functions. To confirm, if I wanted a code that monitored the stability of proteins over time, that would be state-focused, vs if I wanted to model the kinetics of protein binding, would that be more action-focused. please let me know if I am understanding.

  • @jatodd3746
    @jatodd3746 11 หลายเดือนก่อน

    Liked for the B5 reboot reference!!!

  • @moinulislam7935
    @moinulislam7935 ปีที่แล้ว

    Thanks for sharing. It really helps

  • @JohnCoughlan_JAC
    @JohnCoughlan_JAC 8 หลายเดือนก่อน

    Great advice, thanks for sharing!

    • @ArjanCodes
      @ArjanCodes  8 หลายเดือนก่อน

      Glad you enjoyed it, John!

  • @Forseti2
    @Forseti2 ปีที่แล้ว

    I prefer this kind of content, over videos of his studio or equipment.

  • @joansparky4439
    @joansparky4439 6 หลายเดือนก่อน

    thanks for the overview.

    • @ArjanCodes
      @ArjanCodes  6 หลายเดือนก่อน

      Glad you enjoyed the video!

  • @armanzeynali1955
    @armanzeynali1955 หลายเดือนก่อน +1

    I want to write a date convertion program but I don't know to use classes or functions, and I didn't get my answer from this video, you want to convert a date so it's action based so it should be with functions? And it would be state based if you wanted to store those dates? I'll appreciate who answers this.

  • @Michael201078
    @Michael201078 ปีที่แล้ว

    Perfect explanation.

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว

      Thank you, Michael, glad you liked it!

  • @mugudev
    @mugudev ปีที่แล้ว

    Exact tutorial i was looking ❤. Thanks

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว +1

      Enjoy the video!

  • @rahulkmail
    @rahulkmail 9 หลายเดือนก่อน

    Very nice explanation....

  • @arthurdent8086
    @arthurdent8086 ปีที่แล้ว

    Well done, thx!!

  • @AhmedBesbes
    @AhmedBesbes ปีที่แล้ว

    Hey ChatGPT, can you summarize the following video and focus on the code examples it used?
    """
    Sure, in the video, the speaker provides two examples to illustrate when to use functions versus classes.
    In the first example, the speaker demonstrates a simple program that analyzes data from a CSV file. The program has a few functions that take input arguments, do something with the data, and then return a result. These functions are then called in a specific order to carry out the analysis. In this case, the program is action-focused, and functions are the most suitable choice for organizing the code.
    In the second example, the speaker demonstrates a program that simulates a simple game of blackjack. In this case, the program needs to maintain state information such as the player's hand, the dealer's hand, and the deck of cards. The program also needs to have methods that modify this state such as dealing cards and checking for a win. In this case, the program is state-focused, and classes are a better choice for organizing the code.
    Overall, the examples demonstrate that functions are best suited for action-focused programs, while classes are better for state-focused programs. However, it's important to note that there is no hard and fast rule, and the choice between functions and classes ultimately depends on the specific requirements of the program.
    """

  • @hbbexxter4666
    @hbbexxter4666 ปีที่แล้ว +2

    Hello Arjan,
    I like to ask a question on type hints in Python.
    For example, @ 2:54, consider line 49:
    "column_name" is of type "str", "file" of type "DictReader" and "field_sep
    appears to be of particular type "str | None = None". The function returns an object of type "Counter[str]", i.e. "Counter" is being fed a list of strings.
    Question 1: How come "DictReader" is a file type at all and what is "str | None = None" supposed to mean?

    Question 2: Can you please elaborate, or make a detailed video on advanced type hints.
    Using type hints is probably a big issues for lots of learners .I know you already have one out, but there seems to be much more on the topic. It would probably also fit nicely to a guide on how to use "pylint" effectively.
    Many thanks for your help.

    • @jurgenrusch4041
      @jurgenrusch4041 ปีที่แล้ว +3

      Hi "hb bexxter", regarding your question 1, which actually holds 2 'sub'-questions, here is my 2 cents.
      The DictReader class is defined in the csv module from the Python Standard Library. I would not call it a 'file type'. It is a type hint stating that the argument named "file" has that type. As the documentation of DictReader explains it is a class that implements iteration and at each iteration a dict is returned. And that is exactly what you see in the implementation of the function where it reads "for line in file:". And then, on the next line, you can see confirmed that the loop variable "line" is indeed used as a dictionary since it is indexed by a column name.
      Regarding your 2nd 'sub'-question: in "str | None = None" the part before the '=' is the type-hint which states that argument field_sep is either a str(ing) or None. A slightly older form of this type-hint would be "Optional[str]".
      And finally, the part "= None" (so after the type hint) states that the default value of argument field_sep is None. I.e., if the function cumulative_count would be called with only one argument (being the actual value for argument file) then the value None would be used for argument field_sep.
      I hope this helps you further.

    • @hbbexxter4666
      @hbbexxter4666 ปีที่แล้ว +1

      @@jurgenrusch4041 many thanks Jurgen, for your great explanation and being such a proactive member of the community.

  • @damienong1462
    @damienong1462 ปีที่แล้ว

    Thank you for the content!
    Just subscribed because i really need this knowledge in video. Hopefully I can gain more after subscribing !

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว +1

      Glad to hear you like the content, and welcome on board! ;)

  • @RemySchrader
    @RemySchrader 4 หลายเดือนก่อน

    The stakes couldn’t be higher. B5 is a great show

  • @MultiJpva
    @MultiJpva ปีที่แล้ว

    God bless!, thank you for you knowleadge

    • @ArjanCodes
      @ArjanCodes  ปีที่แล้ว

      You’re welcome - glad you find it helpful!

  • @TN-cx4qi
    @TN-cx4qi 11 หลายเดือนก่อน

    I like to group tasks, if they are complex, and data into classes.

  • @paxdriver
    @paxdriver ปีที่แล้ว

    I'm learning Python just to get Babylon 5 reboot. I don't know how that'll happen, but I have faith in arjan lol

  • @Louviewtube
    @Louviewtube 10 หลายเดือนก่อน

    Thank you.

  • @JasonTaylor-y4g
    @JasonTaylor-y4g ปีที่แล้ว

    For me I prefer the more data oriented approach where data is first class citizen, for more back end application. I personally believe this approach give clear definitions between the layers and void a lot of mocking and stubbing if it more data centric. Though I do like using my own types h i.e data class etc. For python libs I go more OO seems reasonable to when creating a lib.

  • @kosmonautofficial296
    @kosmonautofficial296 ปีที่แล้ว

    Great video thank you

  • @kicknotes
    @kicknotes ปีที่แล้ว +1

    30 seconds in, and I'm questioning my life as a developer. Think I'll buy a farm. Good luck with your black holes!

  • @adrianzuur5589
    @adrianzuur5589 ปีที่แล้ว

    Thanks, Arjan. A question: Say I take a class, make all its instance methods return "self", and then just take them out of the class and convert them into functions. After this, the class is left with only attributes that represent state, and no behavior. What are some good arguments against doing this? I can think of one, which is it can make it harder to quickly read which functions "go together with" which data, loosely speaking. But I'm curious to know if people have other reasons.

  • @nathansun1654
    @nathansun1654 ปีที่แล้ว +1

    Have been looking for an answer for this question for long time and just wanted to ask you one hour ago…. Also another question: how can we organize and/or import multiple functions and classes better in py file(s)?

    • @Dyanosis
      @Dyanosis ปีที่แล้ว

      Comments. Use them.
      If your editor/language allows region comments, use those.

  • @Djellowman
    @Djellowman ปีที่แล้ว

    Goeie video Arjan!

  • @ekaterinakorolkoviene5824
    @ekaterinakorolkoviene5824 ปีที่แล้ว

    Arjan is extra witty today. 😜

  • @spaceidiot200
    @spaceidiot200 ปีที่แล้ว

    yay, another B5 fan

  • @oscarengland6122
    @oscarengland6122 ปีที่แล้ว

    State-focused programming is ill advised, especially for bigger more complex code. My suggestion: avoid mutable state like the plague. Classes are still very useful though, even if their attributes don't get mutated: classes model data, encapsulate properties (read-only) and encapsulate functionality bound to this data (like closures). I think of classes as (1) immutable structs that can have calculated fields or (2) parameterized modules. Functions can tempt you to call global objects or global configuration, which are then difficult to factor out when you need to switch those objects. Classes can tempt you to mutate the object state, which after a few hundred lines looks a lot like mutating globals. So basically, avoid side effects.

    • @Jedimaster36091
      @Jedimaster36091 11 หลายเดือนก่อน

      Software is all about side effects. There is not much benefit for a software which does not mutate state. At the end of a workflow, you still need to persist the mutated state in a database, file, etc.

  • @shadeofsound23
    @shadeofsound23 11 หลายเดือนก่อน

    "And then we'll never get that reboot of Babylon 5."
    I suddenly have a new reason to never fuck up ever again.

  • @mghalix
    @mghalix 10 หลายเดือนก่อน

    Great video! comming from pure object-oriented languages to Python I've always struggled to know when to choose just functions over classes, I still have a question though.
    What about classes that act as a container for multiple related actions? for example, having a class responsible for file utilities, getting a file's absolute path, basename, extension, .... you name it. Would it be better to have file utils as a file containing those functions or have them inside a FileUtils class and mark those methods @staticmethod?

  • @joelmanning249
    @joelmanning249 10 หลายเดือนก่อน

    You know I really like this explanation. Too often I find videos where OOP is decried as demonic and you can get away with using functions for most OOP uses.

  • @dovids.greenberger435
    @dovids.greenberger435 ปีที่แล้ว +3

    Classes are great for Polymorphism which helps write code that follow solid principles like open closed and others.

  • @prozaclink
    @prozaclink หลายเดือนก่อน +1

    But what do you mean by 'state'?

  • @maleldil1
    @maleldil1 ปีที่แล้ว +3

    The decision is usually intuitive: pure functions become the obvious choice if you minimise state. In the cases where you _need_ state (and if you're careful about your design, you'll realise that there aren't many), introduce classes, but be very careful about how you present this state to the outside world.
    My code is primarily dataclasses (or TypedDicts if I can't help it) and functions that operate on them, with a few classes here and there when state is unavoidable.

    • @kayakMike1000
      @kayakMike1000 ปีที่แล้ว +1

      Why wouldn't something require state? I work in firmware, motor control, and everything I am used to is managing state, encoders, tachometer, dynos, prechargers, igbts.... it's all very stateful.

    • @Jedimaster36091
      @Jedimaster36091 11 หลายเดือนก่อน

      It depends on what you consider as state. I'd argue that any data you pass as arguments to functions or return from functions represents state. A number passed as argument to a function represents some state somewhere in your system.

  • @ruslanoid
    @ruslanoid ปีที่แล้ว +1

    +1 for Babylon5 reboot

  • @vitalyromas6752
    @vitalyromas6752 ปีที่แล้ว

    The intro is quite triggering. I couldn't continue with lesson at once, rewinding the example with Haskell around 6-7 times and trying to calm down. Realizing that the intro idea was nice and witty, explaining just the idea of code over complication consequences with irony. The video footage just hit me showing the ukrainian defence weapons surrounded with words "start WW3", reminding the ruzz prop.
    ("Neptun" system which allowed to sink the ruzzian "Moskva" destroyer, preventing ruzzian occupation of Odessa, saving big part of Ukraine from ruzzian bombers which have previously used "Moskva" "umbrella".)
    No blames, just sharing my impressions.
    I got to watch the lesson "Functions vs Classes" - it is just great. The critical info missing in many courses and tutorials. Thank you for sharing the lesson, I really appreciate it.

  • @aocastro
    @aocastro 9 หลายเดือนก่อน

    it sounds to me objects are more suitable when we have to store and manipulate data during the program/system execution, i am right @arjancodes ?

  • @pointer333
    @pointer333 10 หลายเดือนก่อน

    perfection

    • @ArjanCodes
      @ArjanCodes  10 หลายเดือนก่อน

      Thank you!

  • @ErikS-
    @ErikS- ปีที่แล้ว

    Arjan has a new logo...
    But what about the cushion that his wife made (with the old logo)?!
    And maybe Arjan can explain the idea behind the new logo? I.e. what does it stand for?
    Maybe it is a bit inspired by the "NPO" logo of the dutch public TV😉 The NPO also has two squares on top (in green for NPO3).

  • @neilmurphy7064
    @neilmurphy7064 ปีที่แล้ว

    Great intro!

  • @digiryde
    @digiryde ปีที่แล้ว

    ++Functional languages (when you can and it makes sense)

  • @kevon217
    @kevon217 ปีที่แล้ว

    what’s your lighting budget? love the hues in your videos.

    • @Dyanosis
      @Dyanosis ปีที่แล้ว

      He made a whole video about his set-up, you should probably start there.

  • @spaderkungskuk
    @spaderkungskuk ปีที่แล้ว

    Classes makes it easy to collect belonging functions. What’s good strategy there when using functions to not end up with everything together?

  • @sylvainprive1754
    @sylvainprive1754 ปีที่แล้ว

    can you make a video about OpenSource code ? how to contribut, and maybe launch a new wave ? i'm sure you community can do big things. who knows, maybe the full safe driving is in our hands ... ;)

  • @edgeeffect
    @edgeeffect 10 หลายเดือนก่อน

    Babalon 5!!!! :)

  • @Florian1509_
    @Florian1509_ 7 หลายเดือนก่อน

    so often i was asked if i do object oriented or what style i code in and i never knew what i did.... apparently i write funtion oriented code. my code just does things

  • @alexander_sinclair
    @alexander_sinclair 5 หลายเดือนก่อน

    What about mixing functional with oop?

  • @harrycrab8725
    @harrycrab8725 ปีที่แล้ว

    I have a question about basic programming structures.
    I have a series of functions that access different databases. I’m not using APIs or json requests, but direct connections, think of them as simple spreadsheets. Function 1 hits database 1 and for those records that meet the criteria, I return values from columns A, C, D, and G. What is the pythonic or professional way to return? I’ve got multiple rows that meet the criteria. I’ve tried tuples of lists, dictionaries of tuples, e.g.
    return [row1 : (A, C, D, G)] … and returned a dict of subdicts [row1 : [A:value], [C:value]…]
    They all work but retrieving values by index or keys:subdict key seems convoluted.
    Thanks!

  • @kristoffertjemsland8087
    @kristoffertjemsland8087 ปีที่แล้ว

    What I don't get, is how classes are supposed to "store" these states/data/transactions. I assume you'de have to pass every transaction to a database, for example MS SQL?

  • @lv99redchocobo37
    @lv99redchocobo37 4 หลายเดือนก่อน

    I'm really confused. How come your code has those arrows ( -> ) in it? How come python doesn't error with those? I've never seen those arrows before in the videos I've watched.