• C-Octothorpe (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    airdrik:
    C-Octothorpe:
    In any case, extension methods are different because it's not like you're subtyping Int32, right? And that's what bothers me because you're giving different meaning to something that is a single unit of something. It also breaks polymorphism (which obviously doesn't work for value types anyway) because if MyEnumType.First has a .ToFoo(), but MyEnumType.Second has a .ToBar(), then you're doing something wrong IMO (imagine the code necessary to handle that). Of course all of this is useless if my understanding of java enums is completely off base...
    But that's not how they work. MyEnumType (being the class of the enum) would have a set of properties and methods which are shared by its values (MyEnumType.First and MyEnumType.Second). The definition would look something like this:
    public enum MyEnumType
    {
        First('Foo'),
        Second('Bar');
        public String value;
        public MyEnumType(String value)
        {
            this.value = value;
        }
    }
    

    The enum type also comes with a few other handy features like a name method which returns the enum's name as a string (we actually store enum names in the database rather than worrying about having and syncing a separate enum names table), being iterable (iterate over the values of the enum).

    Of course the bottom line in deciding if it's worth having all of this extra functionality is the question: what do I want/need to do with this enum? Is there some functionality that would be worth putting on the enum itself?

    One example I can think of is with statuses where some statuses are errors (application died, database error, application error, data error), some are success (success with new data, success but no data). You could mark in the enum which values are errors and which are success. Then you don't have to have a separate function which remembers which ones are which because it is right there on the enum value.

    Thanks for explaining that more clearly, but I have got to ask, what is the difference between an enum and a class other than the type modifier (class vs enum)?

    This: http://www.artima.com/weblogs/viewpost.jsp?thread=128338

    God damnit akismet! This isn't spam you robotic whore!

  • (cs) in reply to C-Octothorpe
    C-Octothorpe:
    They're just syntactic sugar, and aren't really supported by intellisense (try to type .ToIntPtr if you don't have the right using statement where the extension is defined)
    I thought extension methods were only available when the right using statement appears. That's not an intellisense issue.

    And I could care less whether or not extension methods are "pure". Just imagine how terse my code is when I have extension methods like this:

    static bool ForEach(this SqlConnection connection, string sqlExpression, bool isStoredProcedure, ForEachDataRowDelegate method, <snip exception logging optional parameter>)

    Which lets you run a lambda statement against every DataRow in a SELECT statement. Very nice, one-line O-R mapping is the result (if you are creating objects in the lambda).

    I also have these:

    public static string CE64Serialized<T>(this T unserializedObject, byte[] encryptionKey, byte[] initializationVector)

    public static T CE64Deserialized<T>(this string serializedObject, byte[] encryptionKey, byte[] initializationVector)

    for de/serializing, de/compressing, de/encrypting, and then base64 de/encoding any serializable object. In one line of code.

    Extension methods are the shit.

  • C-Octothorpe (unregistered) in reply to hoodaticus
    hoodaticus:
    C-Octothorpe:
    They're just syntactic sugar, and aren't really supported by intellisense (try to type .ToIntPtr if you don't have the right using statement where the extension is defined)
    I thought extension methods were only available when the right using statement appears. That's not an intellisense issue.

    And I could care less whether or not extension methods are "pure". Just imagine how terse my code is when I have extension methods like this:

    static bool ForEach(this SqlConnection connection, string sqlExpression, bool isStoredProcedure, ForEachDataRowDelegate method, <snip exception logging optional parameter>)

    Which lets you run a lambda statement against every DataRow in a SELECT statement. Very nice, one-line O-R mapping is the result (if you are creating objects in the lambda).

    I also have these:

    public static string CE64Serialized<T>(this T unserializedObject, byte[] encryptionKey, byte[] initializationVector)

    public static T CE64Deserialized<T>(this string serializedObject, byte[] encryptionKey, byte[] initializationVector)

    for de/serializing, de/compressing, de/encrypting, and then base64 de/encoding any serializable object. In one line of code.

    Extension methods are the shit.

    You're right, I have several sprinkled through my code base as well.

    I try to avoid it if I can by putting common logic in my base classes. For example I have a two protected overloaded methods called Exec, one takes a Func<T1, TResult> and the other just an Action (no return) and wraps them in a try/catch with the catch closing the DB connection and throwing the ex. I could have easily put this in a common extension, but to be honest it isn't used outside of any class that inherits from it.

    OTOH, I have an extension method for a custom enum type which is decorated with custom attributes to support localization: ToDescription(this MyType type){ // get the desc }. I did this because it's used everywhere in the app and because I can't stick it in the enum itself...

    I do like them, I guess I'm just a little resistant to throw them at everything... And probably because I'm moderately retarded. :)

  • (cs) in reply to Master and Commander of the Troll Amry
    Master and Commander of the Troll Amry:
    YHBT. YHL. HAND.

    Good job, boog.

    See, people, this is what happens when you don't post an "inb4".

    Sometimes the old ways really are best.

  • Coffee Hound (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    C-Octothorpe:
    airdrik:
    But that's not how they work. MyEnumType (being the class of the enum) would have a set of properties and methods which are shared by its values (MyEnumType.First and MyEnumType.Second). The definition would look something like this:
    public enum MyEnumType
    {
        First('Foo'),
        Second('Bar');
        public String value;
        public MyEnumType(String value)
        {
            this.value = value;
        }
    }
    

    .......

    Thanks for explaining that more clearly, but I have got to ask, what is the difference between an enum and a class other than the type modifier (class vs enum)?

    This: http://www.artima.com/weblogs/viewpost.jsp?thread=128338

    God damnit akismet! This isn't spam you robotic whore!

    Actually the real power comes from the fact that enums in Java are treated specially by the compiler. They are guaranteed to be singletons, they are final, their order is set, and best of all, using things like EnumSet<T>, you have the speed and memory usage of an Bit Field. Use Enums liberally in Java

  • C-Octothorpe (unregistered) in reply to Coffee Hound
    Coffee Hound:
    Actually the real power comes from the fact that enums in Java are treated specially by the compiler. They are guaranteed to be singletons, they are final, their order is set, and best of all, using things like EnumSet<T>, you have the speed and memory usage of an Bit Field. Use Enums liberally in Java

    Thank you for the first real answer. I wasn't trying to troll, I was just curious as to why one would use the enum type in java.

  • jhominal (unregistered) in reply to C-Octothorpe

    I can think of a few differences between java's enums and regular classes:

    • The set of enum values is bound by the JVM - creating an additional instance of an enum type at runtime is not possible AFAIK - making using an enum the recommended way of implementing a singleton (cf. Effective Java) (other approaches are vulnerable to serialization or reflection methods)
    • You can use the Enum values in a
      switch
      statement.
    • Using an Enum allows you to also use EnumSet or EnumMap, which will be backed by an integer type.
  • Anon (unregistered) in reply to English Dick
    English Dick:
    philly guy:
    Someone who can't be bothered to login from work:
    dadasd:
    justsomedude:
    TRWTF is the capital O.

    It's upper case, not capital. As is the 'H', for equally baffling reasons.

    ..."upper case" and "capital" mean exactly the same thing in everyday English.

    Yes, just yesterday I mailed my tax return to Harrisburg, the upper case of Pennsylvania.

    I tried to open a business there but couldn't get enough venture upper case raised.

    All right, this is just being bloody minded. Yes there are homonyms for capital. They are still different words and it is clear from the context which version of capital the poster is using (i.e. the one that means exactly the same thing as "upper case" - e.g. A,B,C,D...).

  • Anon (unregistered)

    TRWTF is that he uses the majuscule for H and O and the minuscule all the other letters. Am I right?

  • SG_01 (unregistered) in reply to boog
    boog:
    Clearly he should have used an enum of strings instead of chars. See how it improves readability:
    '******* Status Constants ********
    Private Const MsgErrorStatus = "e"c as Byte
    Private Const MsgInformationStatus = "i"c as Byte
    Private Const ProdMsgStatus = "p"c as Byte
    Private Const UpLoadStatus = "u"c as Byte
    Private Const RemovedStatus = "x"c as Byte
    ...
    

    '******* Status Enums ********* Public Enum MessageStatus MsgError = MsgErrorStatus MsgInformation = MsgInformationStatus ProdMsg = ProdMsgStatus UpLoad = UpLoadStatus Removed = RemovedStatus End Enum ...

    See? Much better. And unlike the char solution, he won't need to change his code whenever ASCII changes.

    FTFY

  • SG_01 (unregistered)

    waits for someone to fix his example of the code, wondering if they'll spot the nasty little change

  • I Push Pixels (unregistered) in reply to anonymouser
    anonymouser:
    Gunslinger:
    I'm sure there's some reasonable explanation for why 'H' and 'O' are capitalized...
    The man was a model train enthusiast?

    Clever.

    +4 plus an extra 2 for rail fan geekery.

  • FASs (unregistered) in reply to Nagesh
    Nagesh:
    Nastesh:
    That is the most horrific thing I've seen all day and I sit next to Nagesh at HackSoft Hyderabad. I've seen things, awful things (like his comments on the TDWTF).

    If yuo truly in Hyderabad, tell me quick, where is best place to get Biryani. ALso tell me what is colour of Auto in Hyderabad?

    Don't eat this Biryani crap. All bicycles are brown.

  • joog (unregistered) in reply to Power Troll
    Power Troll:
    boog:
    brazzy:
    neminem:
    C-Octothorpe:
    brazzy:
    A Java enum isn't just syntactic sugar for an int with a compiler-checked range of values. It's a fully-fledged class with fields and methods (the latter of which can even be overriden for individual instances).

    ewww, really? I wouldn't call that "powerful"... I think code smell is more like it.

    Right. "Powerful". As in, "holy frell, that is one powerful odor."
    Sour grapes much? If you can't understand the usefulness through the description, no language in the world is going to make you a good programmer.
    Bullshit. Not seeing the usefulness only amounts to not having any use for it himself, nothing more. Are you really suggesting he's not a good programmer because he doesn't know how to make use of features he doesn't need?

    Um, hello? Pray tell at what point does this absurd argument end?

    Oh, I don't know how to use abstract classes, but that's OK. No need for them. I'm still an otherworldly java dev.

    Except that isn't really what he said, is it?

  • Devil's Advocate (unregistered) in reply to brazzy
    brazzy:
    C-Octothorpe:
    So tell me, what other fields and methods would you add to Int32? Maybe int.ToXml()?, or int.TheRealREALValueShhDontTellAnyone?
    I'll read that as "enums are a simple concept, how could adding functionality to them possibly be anything except ridiculous overengineering?".

    And to that I answer that while Int32 is used as-is (not sure if .Net lets you extend it, but I imagine there would be little demand because integers are a rather complete concept), enums inherently require you to define your own, and they often represent distinct domain concepts with meanings far beyond "there are only these specific instances of this thing".

    So why should they in an OO language not be implemented as objects that can hold additional data and even functionality?

    So you want to use enums instead of classes/object? By allowing additional data and functionality you seem to be getting rid of the concept of enums in favour of classes.
    Ironically, isn't this sort of over-engineering to make something availbale that is already available through other means exactly what todays WTF is about?

    I'm guessing it depends on what you wnat an enum to be and what you want it to do

  • Jenny (unregistered) in reply to brazzy
    brazzy:
    boog:
    Bullshit. Not seeing the usefulness only amounts to not having any use for it himself, nothing more. Are you really suggesting he's not a good programmer because he doesn't know how to make use of features he doesn't need?
    Hmmm... Yes, I think that's exactly what I'm saying. Because nobody really *needs* anything other than a couple of switches to enter machine code one bit at a time. Good programmers can recognize a useful new feature even though they have done without it so far.

    Which side were you arguing again?

  • brad (unregistered) in reply to boog
    boog:
    brazzy:
    boog:
    Bullshit. Not seeing the usefulness only amounts to not having any use for it himself, nothing more. Are you really suggesting he's not a good programmer because he doesn't know how to make use of features he doesn't need?
    Hmmm... Yes, I think that's exactly what I'm saying. Because nobody really *needs* anything other than a couple of switches to enter machine code one bit at a time. Good programmers can recognize a useful new feature even though they have done without it so far.
    Point: missed.

    By need, I don't mean the literal sense you've suggested. And what's useful/powerful to one person might be overly-complex/burdensome-to-maintain to another. That doesn't make either person a bad programmer.

    I'm with boog on this one.

    If we all wanted exactly the same functionality, we'd all agree that teh same language was best. We always see the old c(c++,c#) vs Java on here, with spatterings of python, haskell, lisp etc... (I won;t mention VB - I think every realises that is the absolute root of all evil).

    And I think your clutching at straws claiming that people who dislike (or don't see the point of) features you like must be imbecile programmers...

  • Squire (unregistered) in reply to English Dick
    English Dick:
    philly guy:
    Someone who can't be bothered to login from work:
    dadasd:
    justsomedude:
    TRWTF is the capital O.

    It's upper case, not capital. As is the 'H', for equally baffling reasons.

    ..."upper case" and "capital" mean exactly the same thing in everyday English.

    Yes, just yesterday I mailed my tax return to Harrisburg, the upper case of Pennsylvania.

    I tried to open a business there but couldn't get enough venture upper case raised.

    Upper Case! Oh such wit!

  • Driddle (unregistered) in reply to Power Troll
    Power Troll:
    C-Octothorpe:

    Wow, reading comprehension fail!

    The fact that I don't use every nook and cranny of my development platform doesn't make me a bad programmer. In fact, it makes me an efficient programmer. I'm going to use the correct tools for the correct situations.

    Does the problem call for an instance of an object? No? Ok then, I can create a static class with static methods. I can even add some caching and thread safety to make it hella fast...

    Do I need object inheritance? Yes? Abstract, and away we go!

    Do I need loose coupling? Yes? Here we are, interfaces...

    Your argument is nonsensical and completely off the mark, but you keep supplying and proving your own arguments... It makes you more right, right?

    Um, yes. Except, as you explicitly stated, you have a clear understanding of when to use language-appropriate tools. That was not the context of the original statement, which you conveniently ignored.

    If we go to the context of the original post, the hypothetical developer in question is not convinced of the utility of a particular language tool. Perhaps he is justifiably skeptical of the benefits or uses that the tool brings, when weighed alongside any negatives, or perhaps not.

    boog then replied that one who does not see as tool as useful means that one has no use for the tool himself (or perhaps he meant something different, I'm not sure). He then asked, "Are you really suggesting he's not a good programmer because he doesn't know how to make use of features he doesn't need?"

    My stance is that yes, one can be an absolutely terrible programmer by not understanding how to make use of (==not understanding how to use? Apparently not) features that he "doesn't need". Nobody really needs to use objects, interfaces, abstract classes, polymorphism, threads, or methods besides main() to be a java developer. Indeed, a poor developer could very likely convince himself that these things aren't needed at all, and as a result, not understand how to make use of them.

    boog:
    WhenTF did I ask a rhetorical question about programming skill? Do you only speak in Strawman?

    I said the guys ripping on all the whizbang-bells-and-whistles that come with Java's Enum are entitled to their opinions, and that not having any business or design need for Java's Enum themselves does not make them bad programmers. What about this has to do with programming skill?

    Anyway, it's now obvious to me that I read way too much into boog's statement. My bad.

    Yah - I think you take word 'need' to a bit of extreme. If we ignore things we don't need, we'd still paper processing in most industries - and I don;t think that was even remotely boog's point...

  • Double Bass (unregistered) in reply to Jim Fell
    Jim Fell:
    Although this would be difficult to implement using Windows, an enumeration of strings could conceptually be done in an embedded environment using a vector table.

    First, you'd need to define a location in memory for the vector table. Let's call it VTBL_ADDR.

    Next, define your enumeration:

    typedef enum STRING_ENUMS
    {
      STR0 = VTBL_ADDR,
      STR1 = VTBL_ADDR + 1,
      STR2 = VTBL_ADDR + 2,
      MAX_ENUMS
    };

    Setup the vector table at the predefined address. Different compilers may use pragma or linker settings. The vector table would look something like this:

    volatile const unsigned char * vStrTable[MAX_ENUMS] = {0};

    The strings need to be declared separately because we need to know where each is located in memory for this to work.

    volatile const unsigned char * VSTR0 = "String 0\0";
    volatile const unsigned char * VSTR1 = "String 1\0";
    volatile const unsigned char * VSTR2 = "String 2\0";

    Finally, the application's init code needs to wire the vector table to the strings:

    *((unsigned char **)VTBL_ADDR) = &VSTR0;
    *((unsigned char **)(VTBL_ADDR + 1)) = &VSTR1;
    *((unsigned char **)(VTBL_ADDR + 2)) = &VSTR2;
    

    Viola! You now have a string enumeration. Essentially, an enumeration of pointers boils down to an enumeration of integers. I did something similar to this for a project about a year ago, so I know it can be done. However, this code I wrote off the top of my head and is untested; it may (probably) needs some tweaking.

    Here comes the orchestra!

  • WTF (unregistered) in reply to Anachronda
    Anachronda:
    Steve The Cynic:
    Otherwise you would be able to go to your upper case city to see the new upper case ship being launched (well, you could if your capital city has shipyards capable of building capital ships).
    Only if "capitol" and "capital" were *also* the same thing.

    What you talkin' about? Capital would be used in both of the cases Steve mentions. Capitol (as far as I know) is a yankee word for where parliament sits (or congress, or something), thus Capitol City is the (fictional?) city where the Capitol is (there is apparently a Capitol City in kentucky, but Im guessing this is something else again).

    Capital Ships are some sort of warships Capital Cities are the 'heads' of a state or country...

    capitol is definitely very different to capital (as you point out) but there hasn;t been anuy confusion in mr The Cynics post...

  • These guys are tools (unregistered) in reply to Matt Westwood
    Matt Westwood:
    boog:
    Power Troll:
    boog:
    Bullshit. Not seeing the usefulness only amounts to not having any use for it himself, nothing more. Are you really suggesting he's not a good programmer because he doesn't know how to make use of features he doesn't need?

    Um, hello? Pray tell at what point does this absurd argument end?

    Well, considering I was talking about one context and not generally speaking, it ends as soon as you try to apply it elsewhere. Oh look, here you go:

    Power Troll:
    Oh, I don't know how to use abstract classes, but that's OK. No need for them. I'm still an otherworldly java dev.
    WhoTF said anything about "not knowing how to use" anything? I was talking about not knowing how to put something to use that you don't need. Exactly which comment were you reading?

    A very good point. Only people who have real programming jobs getting computers to do something interesting and/or important get to discover the delightful convenience and elegance of a fully-fledged enum implementation. If, as you say, your job doesn't put that level of intellectual demands upon you, you can happily get away without bothering to get to grips with enums at all.

    Right.... So Java introduced these (fully fledged, apparently) enums in the last 7 or so years, but people who don;t understand what these things are or how powerful and fun they are couldn't possibly know the first thing about programming.

    Hum. Wonder how much software has been written without such functionality (often, I dare say, by people who still wouldn;t understand the need for it). I'll give you a clue: A lot of software was written more than 7 years ago, and relatively loads of software is written using technologies other than Java.

    No wonder there's so much crap software around. Let's all vote for Java and insist that people use as much of these fully fledged [strikeout]unicorns[/strikeout] Geiger-good enums as possible. This will guarantee that only the best people create only the best sodtware!

  • Jin (unregistered) in reply to justsomedude
    justsomedude:
    English Dick:
    philly guy:
    Someone who can't be bothered to login from work:
    dadasd:
    justsomedude:
    TRWTF is the capital O.

    It's upper case, not capital. As is the 'H', for equally baffling reasons.

    ..."upper case" and "capital" mean exactly the same thing in everyday English.

    Yes, just yesterday I mailed my tax return to Harrisburg, the upper case of Pennsylvania.

    I tried to open a business there but couldn't get enough venture upper case raised.

    I think the last two posters don't understand the difference between capital and capitol.

    CAPTCHA: eros - as in, those posters commited an eros.

    Really? I think you don't.

  • Tom Dickson-Hunt (unregistered)

    Now he just needs to start writing in C, where it's not a problem to do that.

  • (cs) in reply to Double Bass
    Double Bass:
    Jim Fell:
    Although this would be difficult to implement using Windows, an enumeration of strings could conceptually be done in an embedded environment using a vector table.

    First, you'd need to define a location in memory for the vector table. Let's call it VTBL_ADDR.

    Next, define your enumeration:

    typedef enum STRING_ENUMS
    {
      STR0 = VTBL_ADDR,
      STR1 = VTBL_ADDR + 1,
      STR2 = VTBL_ADDR + 2,
      MAX_ENUMS
    };

    Setup the vector table at the predefined address. Different compilers may use pragma or linker settings. The vector table would look something like this:

    volatile const unsigned char * vStrTable[MAX_ENUMS] = {0};

    The strings need to be declared separately because we need to know where each is located in memory for this to work.

    volatile const unsigned char * VSTR0 = "String 0\0";
    volatile const unsigned char * VSTR1 = "String 1\0";
    volatile const unsigned char * VSTR2 = "String 2\0";

    Finally, the application's init code needs to wire the vector table to the strings:

    *((unsigned char **)VTBL_ADDR) = &VSTR0;
    *((unsigned char **)(VTBL_ADDR + 1)) = &VSTR1;
    *((unsigned char **)(VTBL_ADDR + 2)) = &VSTR2;
    

    Viola! You now have a string enumeration. Essentially, an enumeration of pointers boils down to an enumeration of integers. I did something similar to this for a project about a year ago, so I know it can be done. However, this code I wrote off the top of my head and is untested; it may (probably) needs some tweaking.

    Here comes the orchestra!

    Makes sense. He is talking about enumerating different strings after all.

  • (cs)

    All this talk of using enums in OOD is giving me agita.

  • Anal Retentive Bastard (unregistered) in reply to Abso
    Abso:
    User of Dictionaries:
    Sorry 'dude, but capitol is used solely to refer to "the building in which an American legislative assembly meets".
    FTFY.

    FTFY. You forgot the 'n'.

  • (cs) in reply to These guys are tools
    These guys are tools:
    Matt Westwood:
    boog:
    Power Troll:
    boog:
    Bullshit. Not seeing the usefulness only amounts to not having any use for it himself, nothing more. Are you really suggesting he's not a good programmer because he doesn't know how to make use of features he doesn't need?

    Um, hello? Pray tell at what point does this absurd argument end?

    Well, considering I was talking about one context and not generally speaking, it ends as soon as you try to apply it elsewhere. Oh look, here you go:

    Power Troll:
    Oh, I don't know how to use abstract classes, but that's OK. No need for them. I'm still an otherworldly java dev.
    WhoTF said anything about "not knowing how to use" anything? I was talking about not knowing how to put something to use that you don't need. Exactly which comment were you reading?

    A very good point. Only people who have real programming jobs getting computers to do something interesting and/or important get to discover the delightful convenience and elegance of a fully-fledged enum implementation. If, as you say, your job doesn't put that level of intellectual demands upon you, you can happily get away without bothering to get to grips with enums at all.

    Right.... So Java introduced these (fully fledged, apparently) enums in the last 7 or so years, but people who don;t understand what these things are or how powerful and fun they are couldn't possibly know the first thing about programming.

    Hum. Wonder how much software has been written without such functionality (often, I dare say, by people who still wouldn;t understand the need for it). I'll give you a clue: A lot of software was written more than 7 years ago, and relatively loads of software is written using technologies other than Java.

    No wonder there's so much crap software around. Let's all vote for Java and insist that people use as much of these fully fledged [strikeout]unicorns[/strikeout] Geiger-good enums as possible. This will guarantee that only the best people create only the best sodtware!

    I myself wrote plenty of s/w before about 7 years ago, and (as that was what the co. I worked for was paying me for) I wrote a lot of that in java. When enums came along I was delighted because it allowed me to achieve the effects I wanted in a lot more streamlined and maintainable manner.

    I understand that as it was written in java it is by your definition substandard, but that's what I was paid to do. But it's facile to opine that because a program was written in a particular language it stands to reason it is rubbish. It's the sort of statement that causes one to come very close to blows. Even outside of the obvious trollery of a forum like this, this attitude is widespread in industry. It's one of the reasons I quit my last job: one of the DBAs refused to take on his responsibility on a project task because one of the sections that I wrote was done in PL/SQL. He told me it was rubbish code without even bothering to read it. It took six months and managerial intervention for him finally to even read the bloody thing. And when he did he had to sheepishly agree that it wasn't a bad implementation of what was indeed a fiendishly complicated requirement.

    So, apologies for coming down on the side of "enums in java are good" but they certainly have their advantages. You don't choose to use them? Good for you. Now FOAD.

  • PaladinAlpha (unregistered)

    Enums should be compile-time shortcuts treated as primitive types in closed sets typed by the enum name. Functionality for enums should come from the same place that functionality comes from for all primitive types.

    Since Java uses hey-I'm-really-a-class primitive methods, the implementation of enum (a class with a bit less typing in the start) is passable.

    Similarly, since C doesn't associate machine types with machine instructions, its implementation is also sound.

    Personally, since I prefer coding in C, I prefer C enums, although if I could add one thing to the standard it'd be compile-time strict enum typechecking (automatically disqualifying the ugly to-int mappings).

  • Billy Goat Gruff #1 (unregistered) in reply to boog
    boog:
    Power Troll:
    boog, at what point does "not putting something to use that you don't need" become laughably absurd to you in Java? Abstract classes? Static methods? Methods period?
    IBT
    Power Troll:
    Your premise, that someone who fails to understand how to "put something to use" that s/he does not understand is not necessarily a bad programmer, is completely nonsensical.
    IL
    Power Troll:
    By that logic blah blah bull-shit blah... Do you see why what you're saying is ridiculous?
    HAND

    FTFY

    Has anyone else noticed how astute / apt / ironic the Captcha Test has become. On this occasion, "damnum"; being the cod-Latin explecitve that boog would undoubtably have chosen when he realised he'd been had, lost...

  • (cs) in reply to C-Octothorpe
    airdrik:
    But that's not how they work. MyEnumType (being the class of the enum) would have a set of properties and methods which are shared by its values (MyEnumType.First and MyEnumType.Second).
    To expand upon that: All instances of MyEnumType will share the same fields and methods, but individual instances can have different values for the fields *and* (a truely unique and interesting feature) have different implementations of the methods.
    C-Octothorpe:
    Thanks for explaining that more clearly, but I have got to ask, what is the difference between an enum and a class other than the type modifier (class vs enum)?
    At the bytecode level, there is no difference at all. But at the language level, the difference is that enums have a predefined, fixed set of instances (which is after all the definitive property of enums) with the same simple syntax and use cases as your traditional thin-int-wrapper enums, plus optional features based on the fact that they're really fully-fledged classes.

    Basically, Java enums are just syntactic sugar for the pre-Java-5 "typesafe enum pattern", with all the tricky parts (especially serialization) automatically implemented correctly and hidden from view.

  • syockit (unregistered) in reply to drusi
    drusi:
    Nagesh:
    Those constant are for making code more readable. In VBScript there is no type. So everything needs to have some silly hunger notation. Type based language > Non Type based language.

    Developer could have used this small hack in place of defining constants.

    'UNtested code. I don't do this for living.
    'I write work of art classes in java.
    Dim a
    a = "a"
    Wscript.Echo Asc(a)
    
    I thought hunger notation was when you named all your variables after foods.
    //Restaurant menu with price. prefix c: rice, r: bread, m: mutton
    cBiryani = 15.00
    cKashmiriPulao = 20.00
    rNaan = 10.00
    rChapati = 8.00
    mMasala = 14.00
    mKeema = 12.00
    Curry = null // Curry of what?
    
  • (cs) in reply to Devil's Advocate
    Devil's Advocate:
    So you want to use enums instead of classes/object? By allowing additional data and functionality you seem to be getting rid of the concept of enums in favour of classes. Ironically, isn't this sort of over-engineering to make something availbale that is already available through other means exactly what todays WTF is about?

    I'm guessing it depends on what you wnat an enum to be and what you want it to do

    Where does "wanting" enter into it? My point is that the core definitive property of enums is that there is only a predefined, fixed, named set of instances. C enums implement that that (except you can break the property by casting ints, but you can break everything in C like that because at runtime it's all just bits and that's the point of C). Java enums implement that too. And both of them give you some side benefits related to the easy mapping between enums and ints: can be used in switch statements, very compact serialzation, very efficient map and set implementations.

    On top of that, Java enums give you a lot more very useful features. But how does that mean "getting rid of the concept of enums"? The core property is still there. How is that "over-engineering" when the basic syntax is just as dead simple as in C and only gets a little more complicated if you actually use the additional features?

    I stand firm in my conviction that the kneejerk rejection of the concept I was originally responding to can only be born out of ignorance and an unwillingness to even consider that implementing a concept differently from what you're used to can be any good.

  • (cs) in reply to brad
    brad:
    If we all wanted exactly the same functionality, we'd all agree that teh same language was best.
    Ah yes, the good old "let's agree to disagree because it's all down to taste" gambit...
    brad:
    We always see the old c(c++,c#) vs Java on here, with spatterings of python, haskell, lisp etc... (I won;t mention VB - I think every realises that is the absolute root of all evil).
    So it's *not* all just differences in taste then? What would you think about the merits of a programmer who claimed that VB was a better language than all the others?
    brad:
    And I think your clutching at straws claiming that people who dislike (or don't see the point of) features you like must be imbecile programmers...
    If some things are so clearly bad that everyone with enough understanding can recognize them to be bad, why can't some things be so clearly good that rejecting them out of hand is a strong indication of being ignorant?
  • QJ (unregistered) in reply to brazzy
    brazzy:
    Devil's Advocate:
    So you want to use enums instead of classes/object? By allowing additional data and functionality you seem to be getting rid of the concept of enums in favour of classes. Ironically, isn't this sort of over-engineering to make something availbale that is already available through other means exactly what todays WTF is about?

    I'm guessing it depends on what you wnat an enum to be and what you want it to do

    Where does "wanting" enter into it? My point is that the core definitive property of enums is that there is only a predefined, fixed, named set of instances. C enums implement that that (except you can break the property by casting ints, but you can break everything in C like that because at runtime it's all just bits and that's the point of C). Java enums implement that too. And both of them give you some side benefits related to the easy mapping between enums and ints: can be used in switch statements, very compact serialzation, very efficient map and set implementations.

    On top of that, Java enums give you a lot more very useful features. But how does that mean "getting rid of the concept of enums"? The core property is still there. How is that "over-engineering" when the basic syntax is just as dead simple as in C and only gets a little more complicated if you actually use the additional features?

    I stand firm in my conviction that the kneejerk rejection of the concept I was originally responding to can only be born out of ignorance and an unwillingness to even consider that implementing a concept differently from what you're used to can be any good.

    I agree with every word, pal. My experience of java enums is fully positive.

    They're easy to misuse by those who don't understand the concept and haven't bothered to learn the useful features (e.g. I've seen static helper classes written to convert the enum value to a descriptive string, e.g. "if (myEnum == MyEnum.BROKEN) return "Broken" else if ..." and full-on iteration through the instances instead of using valueOf etc.) but such things are amenable to maintenance improvements.

    I believe a lot of the trouble here is that there is a perception of what an enum "ought to be" and anything which enhances the programmer experience of such enums is viewed as "a bad thing".

  • oppeto (unregistered) in reply to Paul Karlsson
    Paul Karlsson:
    I would not have defined constants here.

    Yep, defining variables instead of constants would have made things much more interesting.

    Also note G is missing.

  • oldWing (unregistered) in reply to Bit Head
    Bit Head:
    If you are sitting at a US English keyboard right now, look down at the key just above the left Shift key. It probably is labeled "Caps Lock". Whaddaya suppose the "Caps" in that phrase stands for?

    I thought it stood for "Shift", as in "Shift Lock" which was provided on typewriters. It's always been a mystery to me why it changes the behavior of all of the character keys, not just the letters. Perhaps there really are capital digits and punctuation marks.

    Must be an Elbonian spelling.

  • (cs) in reply to brazzy
    brazzy:
    brad:
    If we all wanted exactly the same functionality, we'd all agree that teh same language was best.
    Ah yes, the good old "let's agree to disagree because it's all down to taste" gambit...
    Is he wrong? Different languages are better fitted to different business needs and architectures. Since these things vary, so do languages.
    brazzy:
    If some things are so clearly bad that everyone with enough understanding can recognize them to be bad, why can't some things be so clearly good that rejecting them out of hand is a strong indication of being ignorant?
    They can, but is that even what happened here? As I see it, most who've complained about Java enums have complained about their flexibility, and not just rejected them out of hand. That doesn't make them ignorant or bad programmers, in fact quite the opposite since they're considering the maintenance aftermath of their decisions.

    A better response from you would have questioned the accuracy of their concerns (Ex: do Java enums lead to the problems they fear?), rather than dismiss their concerns entirely and call them bad programmers.

  • CT (unregistered) in reply to boog
    boog:
    brazzy:
    neminem:
    C-Octothorpe:
    brazzy:
    A Java enum isn't just syntactic sugar for an int with a compiler-checked range of values. It's a fully-fledged class with fields and methods (the latter of which can even be overriden for individual instances).

    ewww, really? I wouldn't call that "powerful"... I think code smell is more like it.

    Right. "Powerful". As in, "holy frell, that is one powerful odor."
    Sour grapes much? If you can't understand the usefulness through the description, no language in the world is going to make you a good programmer.
    Bullshit. Not seeing the usefulness only amounts to not having any use for it himself, nothing more. Are you really suggesting he's not a good programmer because he doesn't know how to make use of features he doesn't need?

    If he's not, I will. How can anyone decide they don't need features if they don't know how to use them ? Not knowing how to use a fundamental language feature makes you a bad programmer, because when the time comes for you to use it, you won't realize it, and instead use buggy hacks that will land your code on TDWTF with a sarcastic comment about how you should have read a Java Programming For Dummies handbook.

  • philly guy (unregistered) in reply to justsomedude
    justsomedude:
    English Dick:
    philly guy:
    Someone who can't be bothered to login from work:
    dadasd:
    justsomedude:
    TRWTF is the capital O.

    It's upper case, not capital. As is the 'H', for equally baffling reasons.

    ..."upper case" and "capital" mean exactly the same thing in everyday English.

    Yes, just yesterday I mailed my tax return to Harrisburg, the upper case of Pennsylvania.

    I tried to open a business there but couldn't get enough venture upper case raised.

    I think the last two posters don't understand the difference between capital and capitol.

    CAPTCHA: eros - as in, those posters commited an eros.

    I suppose I could make a fort out of sofa cushions and luggage. If I were to put one suitcase on top of the other to form a roof, then it would be true in both senses that it would be the upper case (by which I mean capital) and the capital (by which I mean upper case) of FT.WTF. Any way you look at it, sofa cushion forts are good places to commit eros.

    CAPTCHA: populus. Man, I loved that game.

  • (cs) in reply to boog
    boog:
    They can, but is that even what happened here? As I see it, most who've complained about Java enums have complained about their flexibility, and not just rejected them out of hand. That doesn't make them ignorant or bad programmers, in fact quite the opposite since they're considering the maintenance aftermath of their decisions.

    Do these really sound like well-considered worries about maintenance to you?

    neminem:
    C-Octothorpe:
    ewww, really? I wouldn't call that "powerful"... I think code smell is more like it.
    Right. "Powerful". As in, "holy frell, that is one powerful odor."
  • (cs) in reply to C-Octothorpe
    C-Octothorpe:
    hoodaticus:
    C-Octothorpe:
    They're just syntactic sugar, and aren't really supported by intellisense (try to type .ToIntPtr if you don't have the right using statement where the extension is defined)
    I thought extension methods were only available when the right using statement appears. That's not an intellisense issue.

    And I could care less whether or not extension methods are "pure". Just imagine how terse my code is when I have extension methods like this:

    static bool ForEach(this SqlConnection connection, string sqlExpression, bool isStoredProcedure, ForEachDataRowDelegate method, <snip exception logging optional parameter>)

    Which lets you run a lambda statement against every DataRow in a SELECT statement. Very nice, one-line O-R mapping is the result (if you are creating objects in the lambda).

    I also have these:

    public static string CE64Serialized<T>(this T unserializedObject, byte[] encryptionKey, byte[] initializationVector)

    public static T CE64Deserialized<T>(this string serializedObject, byte[] encryptionKey, byte[] initializationVector)

    for de/serializing, de/compressing, de/encrypting, and then base64 de/encoding any serializable object. In one line of code.

    Extension methods are the shit.

    You're right, I have several sprinkled through my code base as well.

    I try to avoid it if I can by putting common logic in my base classes. For example I have a two protected overloaded methods called Exec, one takes a Func<T1, TResult> and the other just an Action (no return) and wraps them in a try/catch with the catch closing the DB connection and throwing the ex. I could have easily put this in a common extension, but to be honest it isn't used outside of any class that inherits from it.

    OTOH, I have an extension method for a custom enum type which is decorated with custom attributes to support localization: ToDescription(this MyType type){ // get the desc }. I did this because it's used everywhere in the app and because I can't stick it in the enum itself...

    I do like them, I guess I'm just a little resistant to throw them at everything... And probably because I'm moderately retarded. :)

    As usual, we think exactly alike. I have never written an extension method for any class I own or can inherit from.
  • fool (unregistered)

    It's actually not so weird to do this in C. (Well, it's a little weird in this post though not a full WTF.)

    Often stuff like device protocols involve ASCII character codes, so you can do this

    typedef enum { Foo = 'f', Bar = 'b', Baz = 'z', Bat = 't' } ControlCode;

    int sendControlCommand(ControlCode code, int value);

    The whole point of an enum is to use a nice descriptive symbolic name ("Foo") for an abritrary value ('f'). I.e. as an improvement in clarity. No reason those values can't be chars (in C at least). The whole a, b, c thing in this post is either neccesary in VB or the programmer was uninformed about using character constants in the language (I don't know I don't know VB).

  • (cs) in reply to brazzy
    brazzy:
    Do these really sound like well-considered worries about maintenance to you?
    neminem:
    C-Octothorpe:
    ewww, really? I wouldn't call that "powerful"... I think code smell is more like it.
    Right. "Powerful". As in, "holy frell, that is one powerful odor."
    Code smell is a driver for refactoring, and a primary goal of refactoring is to improve maintainability. In other words, code smell implies a lack of maintainability.

    So yes, their comments (though sardonic) seem to indicate a concern over maintainability to me.

  • (cs) in reply to Gunslinger
    Gunslinger:
    I'm sure there's some reasonable explanation for why 'H' and 'O' are upper case-ized...

    FTFY

  • Dave (unregistered)

    Actually, you can do something like

    Enum SomeEnumName SomeValue = Asc('a'c) SomeOtherValue = Asc('b'c) End Enum

    This has the advantage that the enum value is easily converted to a char if that's what you need to write out to a file and you can tell what character it is without memorizing ASCII codes. The compiler realizes that Asc('a'c) is really constant.

  • Design Pattern (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    Thanks for explaining that more clearly, but I have got to ask, what is the difference between an enum and a class other than the type modifier (class vs enum)?
    Well the question deserves an answer, and there is none so far!

    The differences are:

    1. You can't subclass an enum.
    2. All possible instances (values) of an enum must be defined at the point of the definition of the enum. So when you work with an enum, you know all it's possible instances.
    3. You can compare enum variables for equality with "==", while for class instances tghis will not test for equality, but for identiy (variable points to same object on the heap) and the "equals(Object)" must be used to compare for equality.
    4. enums come with a builtin feature for serialization. For classes, this must be implemented manually.
    5. As already written, you can iterate over all instances of an enum.
  • Omglolbah (unregistered) in reply to drusi

    This code is still present in the ticket validation system at the science center where I used to work... I left after being told I would not be allowed time to document anything I did and that I "would be around to fix things anyway" :p (just one of the reasons :p)

    Please excuse the horrible coding practice, it was meant as a quick test but stayed.... (it is a simple logging of values to database, just statistics so I didnt care if I lost the occasional value...)

    private Boolean sqlwrite(string muffinmix)
    SqlConnectionStringBuilder flour = new SqlConnectionStringBuilder();
      *snip*
      try
      {
          SqlConnection muffin = new SqlConnection(flour.ConnectionString);
          muffin.Open();
          SqlCommand mixer = new SqlCommand(muffinmix, muffin);
    
          if (muffin.State == ConnectionState.Open)
          {
              int blargh = mixer.ExecuteNonQuery();
              muffin.Close();
              return true;
          }
          else
          {
              KillMeNow.Text += string.Format("No database connection!{0}", Environment.NewLine);
              return false;
          }
    
      }
    
  • Hexadecima (unregistered)

    There is a difference between capital and upper case letters, but all of you are about four hundred years too young to know or care: a capital letter is a large embellishment that begins a scribal paragraph or sentence (but smaller than what we'd call drop caps), and an upper case letter is one modeled after the old Roman cursive as it applies to typography. Printers (that is, human beings who operate printing presses) would have two boxes ("cases") of metal letters to draw from, and the majuscule letters (which is the actual term) were in the upper one.

    Also, "capitol" is a noun. "Capital city" is correct. The only city that is "capitol city" is a city called Capitol. Like Metro City or something.

    Out-pedanted, ohh yeaaaaah. B-|

  • Hexadecima (unregistered)

    Shit, I forgot what I was originally going to post about.

    The random letters are in capitals because VB automatically corrects the capitalization of a declared variable throughout the project whenever it's re-declared, including in a function definition. If the variable isn't declared (and Option Explicit isn't enabled) then every use of the variable changes its case.

    This means that the moron responsible is not only picking terrible variable names, but also re-declaring them for e.g. For counters.

    My god, Alex, why can't we do inline code tags?

Leave a comment on “A Char'd Enum”

Log In or post as a guest

Replying to comment #:

« Return to Article