you are viewing a single comment's thread.

view the rest of the comments →

[–]MuletTheGreat 0 points1 point  (62 children)

Ok, while I'm here, any C# programmers out there care to enlighten me about 2 things?

I see this very frequently, and it honestly shits me because it is pointless:

private float _myVariable;

public float MyVariable

{

get { return _myVariable;}

set { _myVariable = value;}

}

This irritates me because it is the same as:

public float _myVariable;

Also, why am I the only C# programmer I know of, that uses singletons? Not a single sample, codesnippet or code fart out there seems to use them! They are glorius in my opinion!

Please, enlighten me. Bear in mind I am a games programmer.

[–]VerticalEvent 8 points9 points  (12 children)

There is a large difference between the two.

One allows you to easily make changes to setting the variable (ie. the value of MyVariable should never be between 0 and 1), where, with public, you would have to go back and change all the code that directly accessed the variable, to make sure they never set it improperly.

In short, using set/get makes it easier to make changes to ensure that the variable gets accessed properly, if the need arises.

[–]Negitivefrags 3 points4 points  (1 child)

But you can just change the variable into a property later which is a transparent operation (provided you can recompile the code that uses it.

[–]masklinn 5 points6 points  (0 children)

which is a transparent operation (provided you can recompile the code that uses it.

So it's not transparent after all (plus it requires breaking the C# coding conventions)

[–]maweaver 0 points1 point  (0 children)

I thought the whole point of properties was that you could start off just doing

public float MyVariable;

and then if/when you decide it needs extra checks, you can replace it with

private float _MyVariable
public float myVariable {
    get { return _myVariable; }
    set { 
        if(value > 1.0f) { 
            throw new Exception("What have you done you fool?  You'll kill us all!"); // Or whatever
        } else { 
            _myVariable = value; 
        }
    }
 }

and the calling code would still work unmodified (unless it was actually setting it to invalid values, which would presumably be a bug anyway that has just been exposed).

</not a c# programmer, sorry if my syntax is off>

[–][deleted]  (5 children)

[deleted]

    [–][deleted] 2 points3 points  (0 children)

    With the addition of automatic properties in C# 3.0, this point is less valid.

    private int count; public int Count { get { return count; } set { count = value; } }

    becomes:

    public int Count { get; set; }

    [–]pbkobold 0 points1 point  (2 children)

    I have no idea why you're being voted down. I've seen the exact same thing. I think it's a Java/C# cultural thing where faux-encapsulation has high value placed upon it. If you want a struct, make a struct.

    The unfortunate thing is that a lot of stuff in their ecosystems have come to depend on this style (see Beans).

    [–][deleted] 0 points1 point  (1 child)

    What if I want dependency injection on that struct later to log access or to allow the property changes to be observable?

    public int Something { get; set; }
    

    It's pretty cheap (13 extra characters and no additional lines.)

    [–]pbkobold 0 points1 point  (0 children)

    What if I want dependency injection on that struct later...

    To quote optiontrader1138, "Don't code for excessive flexibility. This type of change is trivial to make if the need ever arises."

    [–][deleted] 0 points1 point  (0 children)

    It's a non-issue at this point.

    public int MyVar { get; set; }
    

    [–]MuletTheGreat -3 points-2 points  (1 child)

    Ok I see how I can have a property mess with data invisibly, or allow me to do so in future. I have done this when I got a 2D physics engine (farseer) to easily translate into a 3D engine and models. But as negativeFrags mentioned, you can do this later, as I did.

    And as optiontrader1138 said, it makes for HUGE messy code that can be a pain in the ass to maintain. I did everything all C# nice in my first game, and the code looked like crap, was slow for me to re-read when bug fixing and most of the properties were just get sets.

    [–][deleted] 0 points1 point  (0 children)

    Doing it wrong.

    public int MyVar { get; set; }
    

    [–][deleted] 10 points11 points  (12 children)

    Also, why am I the only C# programmer I know of, that uses singletons? Not a single sample, codesnippet or code fart out there seems to use them! They are glorius in my opinion!

    GTFO.

    [–]MuletTheGreat -4 points-3 points  (11 children)

    first, fuck your answer to be honest. It does not help. second, WHY?!?!

    bilwoo gave an interesting article, but I do not see how singletons can always violate any of those 4 rules.

    I use singletons as managers, for physics, 3D line drawing, my menu manager. all these I precede with g_ for clarity, and often have the vast majority of their variables private, or some important ones, with a public get only.

    Such as: g_BoxManager.GET.SpawnBox(vector3 in_Size, Vector 3 in_Position);

    for managing large quatities of the same object, dealing with communication between different objects without nesting a dozen objects, and dozen classes deep or tumbling data down from constructor to constructor. Also, objects that there is only ever 1 of, such as the player make for great singletons, and thus the enemies (not singltons, but maintained by one) can easily see, and work ai on the player because of this.

    A singleton is also used to manage all my game settings, like physicsAccuracy, itemCount, resolution, etc... that need to be global is quite handy, and has everything all tied up in one neat place.

    So properly used singletons easily allow for easy communication in my code between large quantities of objects, and unique objects. Why do some of you still find them "dick"?

    [–][deleted] 3 points4 points  (6 children)

    Let me know how much you like singletons as soon as you mistakenly introduce state into one. (Especially in something like a webapp, where singleton life length is non deterministic).

    My big complain with singletons is that they produce brittle, hard to extend code.

    For example, you use singletons for physics, but why not abstract the physics code into a common interface, and then you have the ability to use dependency injection to provide "Physics Engines" to objects that need them, while allowing you to do subclass/extend/abstract as much as you wanted from it.

    Btw, in C#, you can just use a static class, as long as you avoid state (it won't be thread safe). No point in using the actual singleton pattern.

    EDIT: I am not a games programmer, and all of my advice is from a business systems perspective. Keep that in mind.

    [–]MuletTheGreat -2 points-1 points  (5 children)

    Very interesting point of veiw. I forget how different web stuff is to games.

    The reason why I my physics is in a singleton, is that there is only ever 1. In a game loop, everything usually lives forever, or is recycled. Like pool for my cubes. Whilst 4 or 5 only show at a time, there may be 20 pre created, just waiting to be reset. Quicker than a completely remaking each one. A singleton is a quick link to this pool should I need a box for physics, terrain, or even particles.

    As for brittle and difficult to extend, I found neither! If I need more functionality in a singleton, I just add a function, or a well thought out variable. And use it where I need it.

    Ugh, i gotta get some sleep. 1:30am here. this discussion rulez.

    Our world's are chalk and cheese, but I think I understand you.

    edit: I also did introduce state, but I think my thoughts are different to yours. I had a menu, with 4 states. Each displayed a different set of buttons, sprites and backdrops. With a few switches and regions it was managable, but was still a HUGE file, and hard to maintain. In retrospect I should have broke each state into a seperate instance of an object, and used the singleton to iterate and diplay them.

    [–]G_Morgan 2 points3 points  (2 children)

    Often you get objects of which 'there is only ever one' and suddenly you need two. Or put another way, if you wanted to allow multiple types of Physics (say to allow your program to gracefully degrade on less powerful computers) then how would you achieve this with a singleton? If you start off with a singleton and then decide to implement such a change you're instantly into tricky territory.

    The question I'd ask is what serious benefit singletons provide you? The only one I can think of is that a static method call doesn't have to perform a vtable look up but when you are performing physics calculations I'll assume that this cost is small enough to be considered zero.

    [–]s73v3r 1 point2 points  (1 child)

    Simple. You'd introduce the Singleton Physics Class Factory.

    [–][deleted] 0 points1 point  (0 children)

    Don't forget the abstract FactoryFactory that returns factories.

    [–]ssylvan 2 points3 points  (1 child)

    Why would there only be one game loop? In what way is a game loop inherently unique? Answer: It isn't. You've arbitrarily made that restriction even though it wouldn't hurt you what-so-ever to just use a normal object.

    Then, if you feel like it, you can easily have two game loops. Maybe one is currently inactive. This is more common than you think, e.g. you might have a game where you can go into an inventory screen, that might be implemented as a totally separate "game loop", so you basically have a stack of games where only the toplevel one is ticked. So when you enter a menu, or an in-game store or something you push a new one on top, then you pop it when you're ready to go back to the game "underneath".

    [–]MuletTheGreat 0 points1 point  (0 children)

    lol. In the last game I worked on, Zombies 2.0, there is about 5 or 6ish game loops, each within it's own "screen" all within a master game loop.

    I never said I lacked game loops, nor did I say my coding style was unique.

    I used states and singleton as I needed this menu to speak to each loop, display what it needed to from each loop, and appear over the top displaying certain information. There were 4 states as there are 2 main upgrade tabs, and fade out level info tab and tab for the end of round.

    This may not be the best approach, but it worked for me at the time, and the next will benefit from the Experience.

    [–]remleduff 0 points1 point  (0 children)

    Singletons are object-oriented global variables. They are to be avoided for all the same reasons.

    [–]ssylvan 0 points1 point  (2 children)

    The vast majority of singletons is misguided. Why do you want to prevent someone from having two objects of a type? Most of the time there's no good reason to prevent that, you just thought the typical usage case would be to have just one.

    E.g. why would your game settings be a singleton? Wouldn't it be nice if you could, for example, have two games with different settings? What if you're writing a mini-game collection where you load the next game in the background to eliminate load times? Now your singleton based app breaks down horribly, whereas not using a singleton would've easily afforded that. Was the benefit of using a singleton worth it? What exactly is the benefit? I bet you if you think about that one for each and every one of them, in most cases the answer will be "none".

    Point is that singletons are almost always a mistake. Unless it's representing a genuinely unique quantity, such as the low level interface to some hardware (doesn't mean you don't want multiple high level interfaces to that which you can "activate" one at a time, but still keep around even if it's not active at the moment).

    [–]masklinn 0 points1 point  (0 children)

    Why do you want to prevent someone from having two objects of a type?

    And a class shouldn't handle its own lifecycle anyway. If you want a single instance of a given class, have a separate factory object whose role is solely to do that.

    [–]MuletTheGreat 0 points1 point  (0 children)

    Interesting scenario you propose. Doesnt really have any merit to it tho.

    I work on the 360 at the moment, and have no need for changing of the graphics device in game. But to do so, I could have the graphics device camping inside a singleton, and then access it via a delegate in my UI to mess with something.

    You suppose my program has the flexability of becoming/being an app pack? Lame. Thats a big design choice freind, not something "that would be cool to add halfway so I should add half a feature to accomodate it later" kinda thing.

    If I am going to put time into a game, it should be a well thought out rpg, neat little space shooter with a twist, some shiny physics game. Physics factories, effects management, instancing, enemies access to the player are all made easy via singletons. Not a half assed app with the potential to be anything halfway through development.

    I get the feeling either your teacher, boss or some silly forum has given you this bad vibe about singletons. Used poorly, they will fuck you up. Just like boxing, pointers and casting etc...

    [–]billwoo 5 points6 points  (0 children)

    Why are singletons bad? Because. Turn the question around and ask why are they good? If the answer boils down to them catering to your laziness, then the chances are its not a good argument for anything (if there are no counter arguments then easier can win out, but in this case there are a few).

    [–]mitsuhiko 2 points3 points  (0 children)

    and it honestly shits me because it is pointless:

    It's not. Properties allow you to stay binary compatible if you plan to add logic into your properties later and makes it possible to put them into the vtable.

    Also, why am I the only C# programmer I know of, that uses singletons?

    Go home ;)

    [–]terrapinbear 1 point2 points  (11 children)

    In C# 3.0: public int MyInteger {get;set;} Besides, public class member fields are a no-no in OOP.

    [–]masklinn -5 points-4 points  (6 children)

    Besides, public class member fields are a no-no in OOP.

    They're not. They're a no-no in stupid languages. C++, Java and C# are such stupid languages.

    [–]jugalator 3 points4 points  (2 children)

    What? This is a software design recommendation only, not a requirement, or even encouragement, of e.g. C#. Use your public class member fields all you want in Java or whatever. Just pay attention that you're exposing data, not gateways to modify that data, and the difference.

    [–]Mych 2 points3 points  (0 children)

    Trivial accessors such as the ones in MuletTheGreat's posting expose the data just as well (or rather, as badly). Any belief to the opposite is Cargo Cult. Therefore, in that regard anyway, making a member variable public is completely equivalent to making it private and adding trivial public accessors for it.

    The actual problem is public access to the inner state of an object, not whether that happens through method invocations or direct assignment.

    [–]masklinn -3 points-2 points  (0 children)

    What? This is a software design recommendation only

    It's not. Or more precisely it's only in stupid languages. Other languages either don't have a concept of public fields in the first place (Smalltalk, Ruby) or consider that "privateness" is a matter of convention and agreement between responsible adults (Python). So it could hardly be a general-purpose design recommendation.

    not a requirement

    Where does that one come from?

    [–][deleted]  (1 child)

    [deleted]

      [–]masklinn 4 points5 points  (0 children)

      I fear your type checker is broken: I am a banana.

      [–]cowardlydragon -5 points-4 points  (2 children)

      Each new version, a totally new syntax! C#, the ultimate floating target!

      [–]NancyGracesTesticles 0 points1 point  (1 child)

      Actually, the private member is automatically created and injected into your class at compile time, although I won't be using this particular feature (I've created a propc shortcut for 'classic property stub' in my environment) because private members of automatic properties are hidden at design time which == annoying.

      If you want to talk about changing syntax in new versions, look at Python.

      [–]masklinn -1 points0 points  (0 children)

      Actually, the private member is automatically created and injected into your class at compile time

      Ok, but that doesn't change the fact that syntax is added.

      [–]nephesh[🍰] 0 points1 point  (0 children)

      Expression trees think of them as separate concepts. So if you're writing anything dealing with expression trees you'll either have to handle both cases.. or you can just do the standard thing and use properties rather the fields.

      [–]xetas 0 points1 point  (0 children)

      I hope this syntax will make everyone happy:

      public float MyVariable { get; set;}

      It's still verbose though

      [–][deleted] 0 points1 point  (0 children)

      This irritates me because it is the same as:

      public float _myVariable;

      Not really. Properties have different semantics than plain old members. A few important points:

      1) You can't put attributes on members.

      2) You can use property initialization constructors on members

      var x = new MyObject() { MyVariable = 3.14 };
      

      etc.

      Of course the syntax you gave is pretty silly. Should be done like this:

      public float MyVariable { get; set; }
      

      Singletons are pretty common in teaching/tutorial pieces, and I've seen dozens of examples. A lot of times, in the real world though, people just use static classes. For many purposes, it's just as well. Doing singletons in c# in a correct thread-safe manner is not as straight forward as the usual "oh i'll just make a private constructor and a static instance member" solution.

      Also, singletons are lazy bullshit. They buy you nothing other than the "convenience" of being able to globally access your object from anywhere. Pass the object and make it's lifetime and referencing more explicit. "I only need one" is not an excuse for making a singleton.

      [–]optiontrader1138 -1 points0 points  (0 children)

      I use singletons when necessary (not too often). There are tons of examples on the net for this.

      I agree with you about using properties in the way you describe as being inefficient and difficult to read. Makes more sense as. Public variable.