Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Reuse your code! Don't do something if somebody else has done it before! Use Library!

Discussion in 'General Discussion' started by guitarxe, Apr 11, 2014.

  1. guitarxe

    guitarxe

    Joined:
    Dec 1, 2013
    Posts:
    131
    Constantly I hear this advice. Reuse your own code that works. Use somebody else's code that works. Use libraries. Don't try to re-invent the wheel when you can use someone else's work.

    But then what do I learn? If I just keep pasting code from tutorials, or if I only rely on APIs (Unity and third party ones), then how will I be able to solve problems I encounter that do not have a solution already done by somebody else?

    I'm just curious why I see this advice so much, when to me this seems like such a bad idea.
    Yeah, sure, if you're employed and you have a deadline, and there's a freely available solution for your problem in the form of a library or whatever, then it makes perfect sense to go ahead and use somebody else's work.
    But if you're struggling to become an indie dev I don't think that's a smart idea - you should figure out how to do these things yourself. Or do you think that's wrong?
     
  2. GMM

    GMM

    Joined:
    Sep 24, 2012
    Posts:
    301
    Usually i try to rely as little as i can on code that others have written, as i am unsure of how well they integrate/perform with the rest of my project. I reuse a lot of my own code, but usually i iterate on the same scripts since they might not work out of the box with the new project, so this leads to rewriting the script to make it more efficient and self contained.
     
  3. sphericPrawn

    sphericPrawn

    Joined:
    Oct 12, 2013
    Posts:
    244
    If you're learning how to code, I wouldn't recommend following the advice to not to "do something if somebody else has done it before." I'm still in the learning process and I only look up examples of how to do something if I'm absolutely stumped (as in, days of trying to figure it out) and even then I just use the resources I find as a guide rather than a copy-paste solution.
    Why do I do this? Because, at the moment, I'm making games to thoroughly learn the process and not just push a game out as efficiently as possible.
     
  4. MarkrosoftGames

    MarkrosoftGames

    Joined:
    Jan 5, 2012
    Posts:
    442
    well then why should you use a game engine when you could write your own? why use a programming language when you could do the assembly yourself? why use a pre made computer parts when you could just solder your own circuit boards?

    there are pros and cons to both sides. you have to evaluate what works best for you, and just how dirty you want to get your hands.
     
    RCFrings likes this.
  5. Aiursrage2k

    Aiursrage2k

    Joined:
    Nov 1, 2009
    Posts:
    4,835
    You want to be able to write your code so that you can reuse it for your many games so try to make it generalized where it can be reused. You dont want to rewrite the same thing 100x times. One way to do that is to use events and delegates so you dont have to have them depending on various classes.
     
  6. dogzerx2

    dogzerx2

    Joined:
    Dec 27, 2009
    Posts:
    3,957
    Depends, Unity is polished to perfection. It has years of professional work behind it, years you really can't afford.

    But using small middleware is a great time saver. As long as it works, why re-invent it?
    But it does have downsides, you're limited to what it has to offer, and you don't learn much... so you don't have as much control over what you're doing. And if it's not very well written or something, well ... it can give you much more trouble than what it solves.

    Regarding making your own code reusable. I personally like to be a bit flexible. The goal is to be productive. If you make everything extremely generic and reusable for everything... you're writing an engine! Do you have time to write an engine? Or do you want to write a game?
    Sometimes you have to compromise a bit, do something you know will work... and if you need to add something later, you're still saving more time than doing something extremely generic for every situation.
     
    Last edited: Apr 11, 2014
  7. Kinos141

    Kinos141

    Joined:
    Jun 22, 2011
    Posts:
    969
    There is always something to learn from someone's code. Look it over, see how it works, and try to fix their bugs. Tweak it to your liking.
     
  8. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    If you try to make all your code universally generic, you end up with the Inner Platform Effect. If you just need a script to do one particular thing, there's nothing wrong with just doing that. That said, sometimes you can make a script more reusable without adding much dev-time or complexity, so you might as well do so.

    Regarding middleware - if you're learning, or writing something for fun, go ahead and do it yourself. If you're trying to get a project done, middleware is often a good move. Not always - sometimes nothing available fits your needs, or you need to have exact control over how a particular system works. But often.
     
  9. lmbarns

    lmbarns

    Joined:
    Jul 14, 2011
    Posts:
    1,628
    Assuming there's a manual and API for middleware, I think it would be silly to write it yourself other than for a learning exercise. Networking middleware for example, raknet, photon, etc. Same with augmented reality libraries like metaio and vuforia or OpenCV....teams of engineers have put countless hours into crafting these products.

    Why not leverage other's hard work? How much has the web experience improved thanks to libraries such as jquery?

    Learning to leverage other APIs means you're adaptable and efficient. And figuring out how to implement them does help you learn, you just work with more complicated abstracted methods, but usually you get to see how things should be done.


    If we're talking about asset store code, then yeah it can be made by anyone and unless it's well documented it probably isn't going to benefit you as a beginner.
     
  10. Photon-Blasting-Service

    Photon-Blasting-Service

    Joined:
    Apr 27, 2009
    Posts:
    423
    For myself, I want to make games and not re-invent the wheel.

    If I can spend $50 and have something as amazing as Playmaker, I will spend $50 happily. NGUI, $95? Yes, please. I want to stand on the shouder's of giants and see farther.

    If you enjoy re-typing code that has been typed 1,000s of times before, that's fine. You don't need to justify it. But you could write new, cutting edge tools that build on existing work instead of re-re-re-re-re-re-re-re-solving problems.
     
  11. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,613
    If you're struggling to become an indie dev then that is being employed and having a deadline. Just because you're not working for someone else doesn't mean there isn't a point at which you're going to run out of money, run out of motivation, or just run out of days to live.

    And if you do want to learn how to build everything yourself, where exactly are you going to draw the line? Are you going to build your own rendering APIs, instead of using existing ones? Are you going to build your own drivers? Your own hardware?

    It's always better to understand how things work, but you can't learn everything at once; you have to pick what you're going to learn and when. And I'd say it's much easier to learn how something works after spending some time using it - familiarizing yourself with all its features, seeing its API, feeling its limitations, and so on - so that when you go on to then dig inside it and figure out how to build it yourself, you have a better understanding of the context in which it exists.
     
  12. Gigiwoo

    Gigiwoo

    Joined:
    Mar 16, 2011
    Posts:
    2,981
    My breadboard was a total disaster and my assembly was even worse! Thank God punch cards were before my time and horray for modern languages!!! I prefer to learn what I need to accomplish my next task, so I can use my remaining time to CREATE!

    Gigi
     
  13. Enoch

    Enoch

    Joined:
    Mar 19, 2013
    Posts:
    198
    Of course you reuse what you can. Never do more work than you have to. Software Developers aren't lazy as a matter of flawed personalities, they are lazy as a matter of efficiency. You can also learn a lot (certainly not everything) by just looking at other code and running it through a debugger (assuming you have code access). An alternative to rewriting it to learn is to write tests around it. It's a great way to get closer to understanding it without having to fully rewrite it yourself.

    Be wary however of those projects that are overly complicated and over engineered for no good reason. Make sure the library actually solves your problem sufficiently. If the library is excessively complicated and would require a good deal of refactor to support you task, then in some cases you will do better by just re-writing it from scratch rather than spending weeks or months trying to learn it sufficiently to make your modifications. There is also something to be said for being the world's foremost expert in that piece of code (and if you wrote it thats you... usually).
     
  14. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    If you use some assets for the stuff that's already been solved, there's still absolutely tons of stuff left to do that you can't buy assets for. Also, you can use the time and/or money saved by not reinventing the wheel for the Nth time to make your game better. So I don't think the "but I won't learn anything unless I do everything myself" argument holds any water.

    --Eric
     
  15. Mwsc

    Mwsc

    Joined:
    Aug 26, 2012
    Posts:
    189
    The answer is not black and white, there are many shades of gray, and it is up to you to figure out where to draw the line.

    I started out writing VGA games in C++ and assembly for DOS. I had to write my own code for loading and drawing sprites, as well as physics, keypresses, and so forth. However, I used a compiler that someone else wrote, and I relied on DOS and BIOS to handle the lowest level things.
    This seemed like the best compromise at the time. I learned a lot, but I did not learn how to write a compiler or an operating system or a driver.

    I have written code to load meshes, render them in OpenGL, let the user fly around, have some interaction, and so forth.
    These things are part of what makes up a game engine, so I have some small hint of what goes on inside something like Unity.
    I have not written a 3D renderer from scratch that takes triangles+textures+lights as inputs, and does every single calculation to produce
    the final pixels as output. However, I have read extensively on these things, and understand the concepts and algorithms. This helps me know
    what kinds of things OpenGL might be doing under the hood.

    However, modern GPUs operate wildly differently than a textbook software rasterization algorithm, although the end result is the same.
    Do I care to learn hardware design? Nope. Would it be possible for me to do so? Not really, considering those internals are trade secrets.

    For someone just getting into game programming today, you could only learn Unity and C#. You might never learn pointers, or what OpenGL is,
    or how rasterization can be implemented. You might have no need to know how to change resolutions using assembly code, or how to parse a mesh from a file and put it into a data structure. Maybe you will end up wanting to learn these things, maybe you will never care.

    Just get started and learn what you need as you go.
    Or read books on the subject, written by someone who has already figured out what he thinks you might need to know.
     
  16. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    I use as much off the shelf as I possibly can and so does every AAA developer out there. If you are a geek or a deep nerd who wants to understand everything then knock yourself out. If you are someone who wants to get a game done, just use as much middleware as possible. Believe me, you'll be learning *long* before your game is complete, no matter how much middleware you use.

    I only dig deeper or reinvent the wheel if something isn't working as good as it should.
     
  17. tiggus

    tiggus

    Joined:
    Sep 2, 2010
    Posts:
    1,240
    I look at code assets as free training, some of it is good and some is bad. There are a fair number of bad ones but even those you can at least see what the authors approach was to your problem and it is Unity specific.

    I've just spent the last week diving into x86 assembler for a exploit writing class and the thought of looking at some C# or C++ next week sounds positively joyful.
     
  18. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,039
    That advice applies to people who have are already coders. Generally you don't use a library because you can't do it yourself, you use it because someone else has already put a large chunk of time in to it which you wont have to put in yourself.

    If you are at the stage when you are still concerned about learning to code then you shouldn't be struggling to be an indie dev you should be learning how to code. This doesn't mean your learning can't be in the context of creating games but it does mean your approach will be different.

    (EDIT: this applies to someone who wants to primarily be a coder, there are obviously viable paths to developing indie games which don't involve coding or where coding is a minor part, if you are taking one of these paths then who cares about learning to code!)
     
    Last edited: Apr 12, 2014
  19. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    The way I look at game dev (being the programmer) is that my job is to take all the great plugins (NGUI, HOTween, Curvey, Edy's Vehicle Physics, GameAnalytics, Everyplay, etc), and glue them all together to make one spectacular piece of software. Just gluing them together is an enormous job in it of itself, let alone writing each one from scratch!
     
  20. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    If you're trying to make a half decent game, there will be more than enough opportunity to "learn" no matter how much middleware you use. I'd guess there are very few people around here who actually say to themselves "My game is just getting done too quickly and easily; I wish I had a lot more coding left to do."
     
  21. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    Speaking as a matter of practice, ideally you should design your code with reuse in mind, and I'm not just talking within your current project; what I'm talking about is portability.

    Formally, code portability is when you can take a system's code for one platform and successfully use it on another hardware platform, but Unity manages this for us automatically. However, as far as we game programmers are concerned, portability is when you can take code from one project, and start using it in another. In other words, a different project is a different platform for your code.

    You can achieve this by controlling your code's dependencies, so that it's not linked to project specific infrastructure. Additionally, I don't know if you've heard of the SOLID principles, but the 'O' refers to something called the 'Open-Closed Principle.' Good, maintainable, scalable, and portable code is simultaneously open to changes, but closed to modification without necessarily needing changes to the source code. This dosen't mean you don't fix bugs in it; this just means that a particular set of code is resilient enough to handle whatever is thrown at it. In other words, 'Open-Closed'ness of code is a good measure of how resuable it is.

    A final thought - we tend to focus on games as sets of art, or vehicles for storytelling, which they are and can be, respectively. However, what a video game always is, is a software package. Treat it as such.
     
  22. yoonitee

    yoonitee

    Joined:
    Jun 27, 2013
    Posts:
    2,364
    I tend not to use many 3rd party code unless it is a very popular library that has been thoroughly tested.

    Also, you can add lots of bells and whistles and sfx to your game by downloading libraries etc. but if you're making a mobile game this can be a hinderance rather than a positive. Also, it can sometimes take longer to read the documentation for the library than writing your own code! I'd rather just make something simple that I know has no bugs and works! There are exceptions. For example if making a poker game, it would be quicker to find a free poker engine to use, than study game theory for five years.

    On the other hand, if I wrote some code for a menu, or translation system in one game, of course I'm going to reuse that in another game! It would be stupid not to. I don't really design it for reuse because its easy just to delete all the bits from the code I don't need and make any modifications. Also, I don't think Unity's really designed to have two projects reference the same code (maybe I'm wrong).

    But yeah, once you've done one game Copy Paste will be a major factor in finishing your next game!
     
  23. techmage

    techmage

    Joined:
    Oct 31, 2009
    Posts:
    2,133
    if your learning to code, I think you should do it all from scratch to understand it

    if you already know how to code, and have a pretty intuitive understanding of it, and can probably just infer how a programming library works by seeing what it is, reading through all the implementation is really just a chore that wastes time
     
  24. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    I don't understand this, why should I write code with reusability in mind? All I'm trying to do is finish my game and ship, why must I be burdened by making all of my scripts reusable for many use cases? I just need to use them in 1 use case (and that is the current project).

    Now after shipping if you have the energy and motivation to go back, refactor, rename, and package part of my source code into some kind of framework then absolutely go for it. But trying to create some framework, out of all your scripts (at all times), during development seems extremely strenuous.
     
    Last edited: Apr 14, 2014
  25. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    First, you're taking my statement way out of context. I'll flesh out exactly what I mean further down, but it's usually not feasible to make your entire game just one gigantic framework, and I never said that. I said that, ideally, you should strive for reuse. I think you are misunderstanding what I was trying to say.

    With that out of the way, for now, let's talk practicalities, since you're rightly concerned with them - the reason you consider reusability first, is so that you don't have to write the same thing repeatedly, because as a programmer, your time and effort are valuable.

    Sure, you could write a method like this:

    Code (csharp):
    1. public void Foo()
    2. {
    3.     for(int i = 0; i < someMaxValue; i++)
    4.     {
    5.         // Operations...
    6.     }
    7.  
    8.     for(int i = 0; i < someMaxValue; i++)
    9.     {
    10.         // Operations...
    11.     }
    12.  
    13.     for(int i = 0; i < someMaxValue; i++)
    14.     {
    15.         // Operations...
    16.     }
    17. }
    ...But do you? I certainly hope not! Here's a better way:

    Code (csharp):
    1. public void Foo()
    2. {
    3.     ProcessBars(Bars);
    4.     ProcessBars(Bazes);
    5.     ProcessBars(FooBars);
    6. }
    7.  
    8. public void ProcessBars(IFooBarBaz thingy)
    9. {
    10.     for(int i = 0; i < someMaxValue; i++)
    11.     {
    12.         // Operations...
    13.     }
    14. }
    The second, more reusable code, has the benefits that:

    A) you have to do less typing, allowing you to work on other stuff. In other words: do what you have to, then do something else that you have to do.

    B) If you uncover a bug, you have fewer places to keep track of. In the first example, you have three loops that are the same loop to keep track of, and thus three places where you'll need to place debug code; in the second example, you only have one suspect place, which you can quickly either rule out or determine what is wrong.

    C) On the subject of the code taking less effort to type, you have less code in the first place, which is better for understanding and debugging*

    D) You don't repeat yourself, which also helps with understanding the codebase. The human mind is a pattern-recognition engine, and when we see something enough, we start handling that sequence on auto-pilot. This is why it's more possible to make mistakes with a repetitive codebase, than with a DRY one.

    *: Yes, this point wraps around into a A and B, but that's a higher-level meta-point I'm trying to make here - code is a trade in that it's both art and science. The technical aspects, the aesthetic, and the philosophy of how the code is constructed are all interrelated. Clean code, among other things, does not repeat itself - it dosen't need to, it's expressive enough on its own to be perceived clearly the first time. This sort of thing is the reason why two or more programmers can solve the same problem, even using the same algorithm, but have sources that look totally different.

    Actually, if done right, it's usually not; a pretty fair chunk of a project's code base is what I like to call 'project-specific' code - it's just code intended to work on the project you're implementing. The parts that are reusable, and portable, tend to surface naturally, in my experience.

    The rule of thumb that I like to take: if you have to contrive a case in which to generalize some set of code, then that's code that you should not generalize (in my concrete experience, it will either not generalize because it's highly case-specific, or the 'generalized' version will be anything but intuitive to use.)

    Conversely, if you're using something all over the place, pretty commonly, that's a great indicator that you really should take a second look at refactoring it - as stated above, you'll simplify your codebase, making it easier to read and debug.

    Reading between the lines of your argument, I think that you were interpreting my statement as, 'you should generalize everything to the highest extent possible on a single project.' I am not saying that, and did not; I am saying you should strive for reuse, because it will help your current and future projects. (Going back and actually reading my post may help.)

    It's not possible to reuse everything. You have to exercise common sense when writing code, and three times as much when refactoring.

    Additionally, I like to think, when I'm writing code, that every line I write is an investment towards my future works. But that's a high-level philosophy of mine, which guides my entire process. Quick-and-dirty code has its uses too - like, as I'm reading from your arguments, 'gettin' stuff done.'
     
    Last edited: Apr 14, 2014
  26. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    Oh I agree that once you solve a problem, don't solve it again. If you made a good button in your last project and now need a button in your current project, then instead of creating a new one just go get the old one. If that's what you're saying then I concur.

    About the code sample you posted, the one I would choose would be based on whichever one felt clearer (more obvious) to me. But actually there are so many weighs to judge whether code is good or not: Does it perform better? Is it easier to read? Is it less lines of code? Is it ugly but extremely fast?
     
  27. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    That is exactly what I'm saying. I'm glad I was able to explain myself a bit more clearly the second time around. For me at least, words are like pointers - it's easy to use them incorrectly.

    For judging the quality of code, I actually recently had a similar situation with the team I work with. In an older app we support, I kept seeing this pattern:

    Code (csharp):
    1. if(condition)
    2. {
    3.     if(otherCondition)
    4.     {
    5.         // Operations...
    6.     }
    7. }
    ...my first reaction was to refactor like this:

    Code (csharp):
    1. if(condition  otherCondition)
    2. {
    3.     // Operations...
    4. }
    ...But my teammates stepped in and we talked about it. The reason they had written it the first way was for debugging - they could simply create set a debug statement, or breakpoint on the inner if statement to see if the first one had even been triggered in the first place, and if so, what it's value was. Given some of the logic in the app, this makes sense, so I'm not quite so trigger-happy with ReSharper now when I see the if-if pattern. I still prefer if-and, because it's a little shorter (darn curly braces!) but, I guess it still reads just as quickly, compiles to roughly the same IL code, and should be equally as fast as each other. So, no harm done.
     
  28. minionnz

    minionnz

    Joined:
    Jan 29, 2013
    Posts:
    391
    The code I would choose would be the one that was easily maintained and debugged without sacrificing performance (secondary concern though, optimization can be done later).
    I can't think of ANY situation where I would choose the first version over the second - Sure, I could probably follow the code easier when reading through it (though not by much), but more code == more room for bugs.

    As for reusing code, there's a balance between quick/easy code and reusability. Nobody can really tell you what the right balance is for your specific project, but the more experience you gain, the easier that balance will be to find - and once you find that balance, your job becomes a lot easier: less bugs, quicker implementation of new features and bug fixes, more confidence in your code.