How to return a list and a flag in java



  • I just reviewed (anonymized):

    old code:

    List<Integer> myFunc(params) {
     [SNIP]
      return resultList;
    }
    

    new code:

    Map<String, Object> myFunc(params) {
    
      Map<String, Object> themap = new HashMap<String, Object >();
      boolean flagResult = true;
    [SNIP]
      themap.put( "flagresult", flagResult);
      themap.put( "resultlist", resultList");
      return themap;
    }

  • I survived the hour long Uno hand

    Map<String,Object> is overkill. Try using org.apache.commons.lang3.tuple.Pair :trolleybus:


    Filed under: HashMap<String,ArrayList<Pair<Integer, Integer>>>



  • Why change the signature? Just append a 1 or 0 to the end of the list :trolleybus:



  • I don't suppose Java has "out" params.

    @Yamikuronue said:

    Map is overkill. Try using org.apache.commons.lang3.tuple.Pair

    Compiler won't optimize that for you?


  • kills Dumbledore

    Assign to a global static? Obviously not thread safe of course...

    Or create a new class with two public members, the flag s and the return value



  • @blakeyrat said:

    Compiler won't optimize that for you?

    The pair isn't even in Java's standard libraries (or whatever they call it) AFAIK... And even then, reducing a map to a pair would require a lot of shit to prove (such as "you'll only access this map by those strings, and only as literals").



  • @Maciejasjmj said:

    The pair isn't even in Java's standard libraries

    Java doesn't have a tuple in its standard libraries? Seriously!?

    @Maciejasjmj said:

    And even then, reducing a map to a pair would require a lot of shit to prove (such as "you'll only access this map by those strings, and only as literals").

    Well that part's true, but still. It's the kind of thing that should be the compiler's problem, not yours.

    The other option is to just create a quick-and-dirty "FunctionNameReturn" struct that contains the two things you want to return.



  • @blakeyrat said:

    Java doesn't have a tuple in its standard libraries? Seriously!?

    Ya, seriously?! C++ had a pair in their standard lib ever since the first iteration of the C++ standard...how does Java still get this wrong?

    Filed under: you know it's bad when C++ gets it right and you don't


  • area_deu

    @blakeyrat said:

    struct

    Guess what Java doesn't have ...



  • @aliceif said:

    Guess what Java doesn't have ...

    No tuples, no structs, no "out" params, no proper namespaces, no decent GUI libraries, no bug-free runtimes...

    What does Java have?



  • @blakeyrat said:

    Java doesn't have a tuple in its standard libraries? Seriously!?

    .NET didn't for quite a while either. It's fun when you deal with 3.0 code and wonder why the hell new Tuple<int, int>() doesn't work...

    But yeah, at least .NET figured it out eventually.

    @blakeyrat said:

    Well that part's true, but still. It's the kind of thing that should be the compiler's problem, not yours.

    What, picking proper data structures? Eh, I don't know - that would involve a) fairly complex code analysis, and b) knowledge of the standard libraries baked into the compiler.

    @blakeyrat said:

    The other option is to just create a quick-and-dirty "FunctionNameReturn" struct that contains the two things you want to return.

    Yeah, that makes much more sense. Or just make a generic Pair yourself, it's like 5 lines.



  • Not-entirely-off-topic: better tuples is in the "to do" list for C# 7:



  • @blakeyrat said:

    Not-entirely-off-topic: better tuples is in the "to do" list for C# 7:

    C# as a language seems to have been missing only the kitchen sink for at least a few years.

    Ability to actually name tuple arguments instead of going Item1, Item2, etc. would be pretty damn useful though.



  • I'm looking forward to non-nullable reference types.

    I can change a few variable declarations and probably catch 20 bugs in this damned codebase with that alone.



  • Why use a hashmap when the keys are fixed? What's that going to give you that a simple struct wouldn't achieve with more clarity and less overhead?



  • @aliceif said:

    Guess what Java doesn't have ...

    IMHO one of the stupidest things about Java. Seriously.



  • @blakeyrat said:

    What does Java have?

    Classes. Horrible GUI libraries. Buggy runtimes.

    Quickly runs away



  • @Masaaki_Hosoi said:

    one of the stupidest things about Java. Seriously.

    What is a class with no methods if it isn't a struct? A rose by any other name and so forth.



  • HAHAHHAHAHHAAHHHHAHHAHHAHHHA

    Not descriptive enough.



  • @flabdablet said:

    What is a class with no methods if it isn't a struct?

    A miserable little pile of secrets.

    if the members are private



  • @flabdablet said:

    Why use a hashmap when the keys are fixed? What's that going to give you that a simple <a href="http://www.javapractices.com/topic/TopicAction.do?Id=256">struct</a> wouldn't achieve with more clarity and less overhead?

    I think it's the I-have-to-avoid-declarations-at-all-costs brainworms. Only slightly less invasive than the everything-is-a-phone variant.



  • func myFunc() ([]int, bool) {
        // [SNIP]
        return resultList, didTheFunctionCompleteSuccessfullyAlsoIsMyVariableNameTooLong
    }
    


  • @flabdablet said:

    What is a class with no methods if it isn't a struct?

    Allocated on the heap is what it is.



  • @Masaaki_Hosoi said:

    Allocated on the heap is what it is.

    Maybe. The difference has more to do with what happens when you pass one. Yes, in .NET, structs are allocated on the heap by default, but they may not stay there.



  • Oh, and a hashmap isn't?



  • @Masaaki_Hosoi said:

    Allocated on the heap is what it is.

    So just like pretty much everything else. That's not a very good description.



  • @boomzilla said:

    So just like pretty much everything else. That's not a very good description.

    Well, no. Generally, atomic types and structs are allocated on the stack, and popped off of the stack when they exit scope. In environments like .NET, this means you don't have to worry about garbage collection when it comes to value types (and in, say, C++, it means you don't have to manually clean them up - usually). Classes, however, are allocated on the heap. In C++, this means it's your job to manually clean them up or use a memory manager. In .NET, this means garbage collection. Not a big deal for business software, although for high-performance software GC can bite you in the ass pretty hard.

    EDIT: Also the heap is far more prone to memory fragmentation than the stack.



  • @blakeyrat said:

    I don't suppose Java has "out" params.

    One of the few mistakes Gosling et al didn't import from C..

    Out and ref params are a fucking abomination.



  • @Bort said:

    Out and ref params are a fucking abomination.

    Care to explain why? I find them to be amazingly useful.



  • @Masaaki_Hosoi said:

    Well, no. Generally, atomic types and structs are allocated on the stack

    Wake up. We're discussing Java.



  • In Haskell, you would do this like:

    data Flagged a b = Flagged a b
    
    data Flag = Some | EnumerationType | OrMaybeA Text 
    
    flag :: Flag -> b -> Flagged Flag b
    flag = Flagged
    

    and then, to flag a list with Some flag, you would do

    flag Some list


  • They're useful like gotos are useful. They can be used.

    They basically require you to utilize poor code design. Use prevents expression-oriented code that is usually more suitable.

    • Declare a variable.
    • Don't assign anything to it.
    • Call some other method and allow it to share memory space with the current method and will perform a side-effecting operation on variables in the current scope.
    • You may barf now.

    What would be better would be a more concise way of describing record type (they are working on this).

    record NeedsBetterName(List<String> Results, bool Flag);
    

    SORRU SOME ERROR HAS OCRRUEDDS

    Edit - see Captian's post above mine, something similar can be done in your precious C-dull.


  • Discourse touched me in a no-no place

    Depends on what the flag's for. I assumed it was for success/failure and was about to recommend Either when I saw your post.

    EDIT: or Maybe if you don't care why it didn't work.



  • Yeah, my Flagged is just a tagging monad (though I didn't derive that instance). Either is an error monad.



  • @boomzilla said:

    Wake up. We're discussing Java.

    And I was talking about structs, which also aren't in Java.

    On a side note, Java allocates everything on the heap? Really? That sounds absolutely horrible.



  • @Masaaki_Hosoi said:

    And I was talking about structs, which also aren't in Java.

    So did you miss the point deliberately or accidentally?

    @Masaaki_Hosoi said:

    On a side note, Java allocates everything on the heap?

    AIUI the JVM can allocate stuff on the stack based on escape analysis. Primitives are on the stack, as are local references.



  • @boomzilla said:

    So did you miss the point deliberately or accidentally?

    @Masaaki_Hosoi said:

    On a side note, Java allocates everything on the heap?

    AIUI the JVM can allocate stuff on the stack based on escape analysis. Primitives are on the stack, as are local references.

    1.) What was the point? Maybe I did miss it. I was talking about how stupid it is that Java does not have structs.
    2.) Ah, OK. Still a little weird, but not that bad. Does that mean classes in local scope get allocated on the stack rather than the heap? If so that's not horrible I suppose, but there's still quite a few situations where I'd prefer a struct which is always allocated on the stack (rather than a class that may or may not be depending on context and scope)



  • @Masaaki_Hosoi said:

    but there's still quite a few situations where I'd prefer a struct which is always allocated on the stack (rather than a class that may or may not be depending on context and scope)

    What language gives you that?



  • C#/.NET always allocates structs on the stack (not sure what it does with static structs), however that's an implementation detail and could change.



  • @mott555 said:

    C#/.NET always allocates structs on the stack (not sure what it does with static structs), however that's an implementation detail and could change.

    Although, to be fair, it most likely won't.

    There are situations where structs are allocated on the heap - but generally, that's in situations where they're part of something else which is also allocated on the heap, such as a class field or array element. Additionally, if you box/unbox them (say, to/from the 'object' type), that also does a heap allocation. But, in most cases, structs are allocated on the stack.


  • SockDev

    It's also true to say that reference types aren't always allocated on the heap; if the compiler determines that the scope is limited enough, it can elect to put them on the stack instead, saving the GC overhead.


    A lot of people think that the C# spec says to allocate structs on the stack and classes on the heap. But it doesn't; allocation strategy is left entirely down to the implementation.



  • @RaceProUK said:

    A lot of people think that the C# spec says to allocate structs on the stack and classes on the heap. But it doesn't; allocation strategy is left entirely down to the implementation.

    True. Really, the implementation of structs being allocated on the stack is essentially by convention. But, since said convention is followed by the two main .NET runtimes (actual .NET, and Mono aka "kinda sorta .NET"), it's fairly safe to rely on that feature (for now, at least).

    EDIT: Goddamnit, Discourse, and your "Unknown errors".



  • @Masaaki_Hosoi said:

    it's fairly safe to rely on that likelihood (for now, at least).

    FTFY.

    And is it? When is the distinction important? I have a feeling that the times it's most important are also the times when you have to deal with the edge cases where one or the other is in the other spot.



  • Well, it may be good in preventing UniformlySlowCode, e.g. allocating 1M objects/sec for temporaries.


  • SockDev

    @riking said:

    allocating 1M objects/sec for temporaries

    If I'm managing a project, and someone commits code that does that, then they'll meet the business end of this:

    Edit:

    :no_mouth:



  • @RaceProUK said:

    If I'm managing a project, and someone commits code that does that, then they'll meet the business end of this:
    <img src="/uploads/default/20162/ba305c8fefbccc66.png" width="666" height="500">

    Since I frequently work with game code, I'll give you an example of a pattern I encounter on a daily basis.

    [code]
    void Update()
    {
    Vector3 inputMoveDirection = new Vector3( InputManager.ActiveDevice.LeftStick, 0f, InputManager.ActiveDevice.RightStick );
    inputMoveDirection = transform.TransformDirection( inputMoveDirection );

    ApplyInputAcceleration( inputMoveDirection );
    

    }
    [/code]

    Executed at least 60 times per second - if VSync isn't disabled (in which case it could easily be executed 100 times per second or more). Not nearly as bad as 1M per second, but still very frequent (and if inputMoveDirection were allocated on the heap, the same code could trigger frequent garbage collections).



  • Yep, and hitting 16K allocations per game loop is not out of the question...



  • Your game input is based on the screen refresh rate? :wtf:



  • That's not that rare, and works fine as long as you scale any modifications by the amount of time elapsed since the last update.



  • @Magus said:

    Your game input is based on the screen refresh rate? :wtf:

    Yep, in pretty much every game the update rate of the game is directly tied to the refresh rate. It's been this way for a long time, actually - newer games use a delta time multiplier to make everything run at the correct speed regardless of framerate, but older games (or games running on limited systems) didn't and so a lower framerate could slow down the whole game (there was a GBA shoot-em-up I used to play that did this - when there were a lot of bullets onscreen the whole game would slow down)

    EDIT: Actually, now that I think about it, didn't one of the Ninja Gaiden games do that on purpose? So that when there was a lot of action going on, the stress on the CPU would slow down the refresh rate and give you a little more reaction time?
    Could be totally imagining that, but I swear I read that somewhere.


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.