Jump to content


Photo

Programmer shizzies


97 replies to this topic

#91 Dennis

Dennis

    Shizz JediMaster

  • Members
  • PipPipPipPipPipPipPipPip
  • 3,199 posts
  • Location:Winnipeg

Posted 24 May 2012 - 05:30 PM

I get to program in crummy coldfusion where we have nifty boolean operators like EQ, NEQ, GT, LT, GTE, LTE and you can use "yes" and "no" in place of TRUE or FALSE.

I found some old code that used the following logic and I cringed:
<cfif form.not_admin NEQ 0>

My brain melted on my desk while I tried to figure out what the intent was there.


Hah, is that triple-reverse boolean logic?

But yeah, my similar "boolean woe" story: Ruby doesn't even have Booleans. Stuff can be Truthy or Falsy, but there is no object of type "Boolean". I got lulled into a trap the other day by a Gem we are using at work for a Rails app we're developing (Gems are like external libraries or packages, for the non Ruby/Rails savvy folks out there). Anyways, I was speccing out a controller and was trying to assert that a value should have been of type boolean and equal false, as this Gem provided a "Boolean Type." My test for "should equal false" passed, but the object type caused an exception, claiming "Unintialized Constant Boolean." After some inspection, the object's type was FalseClass. Of course, this was not a problem that couldn't be fixed by coffee, refactoring and the act of cursing controller tests. But yeah, if you load up a Ruby or Rails console and use the .class function on anything, it returns the class of the object (I think it's like getClass() in java). So, when I did a few tests ("hi".class will return "String", 1.class will return "Integer", etc), I found out that true's class is TrueClass and false's class is FalseClass. Not sure if that helps anyone, but it helped me!
captain tortilla internet carpet bombing mission:
official website
myspace
8bitcollective
last.fm
facebook

other:
dissolution[official site][myspace]
PMPR[official site][myspace]

#92 Daemon9623

Daemon9623

    Sleeveless

  • Members
  • PipPipPipPipPipPipPipPipPipPipPip
  • 13,115 posts
  • Location:Middle Earth

Posted 24 May 2012 - 08:42 PM

I just want to thank you dudes for all of your help in here. It's the reason I passed my class. :)
Available for download now!
Posted Image Posted Image

#93 Dennis

Dennis

    Shizz JediMaster

  • Members
  • PipPipPipPipPipPipPipPip
  • 3,199 posts
  • Location:Winnipeg

Posted 24 May 2012 - 10:48 PM

Had a chance to look at this, I'll add my own comments.
import java.util.Scanner;

public class NumberEvaluation
{
    public static void main(String[]args)
    {
        // I personally dislike doing a "variable declaration" block at the top like this, it increases
        // the "variable lifespan" too much and it makes it hard to keep track of what you're declaring,
        // and most importantly, why.
        double sum = 0;
        int count = 0;
        double avg = 0;
        double min = 0;
        double max = 0;
        boolean end = false;
        
        Scanner in = new Scanner (System.in);
        
        // it has usually been my experience that you should avoid unnecessary false checks if possible,
        // this could probably be set up as loop = true and you could just go while(loop), then when you
        // reach the condition to stop looping within your loop set it to false.  but, if you insist on a negative check, 
        // while(!end) is, in my opinion a cleaner way of writing it.
        while(end == false)   		//EDIT: fixed the =
        {
            System.out.println("Please enter a number, type 'end' to exit: ");
              
            //EDIT: as an example, input "5.5" is a string that also represents a valid double
            //      hasNextDouble tests to see if it is a valid double or not
            if(in.hasNextDouble())  
            {
                sum+=sum;    // It doesn't appear that this value will ever be anything but 0
                count++;
                    
                if(in.nextDouble()>=max)
                {
                    max=in.nextDouble();
                }
                else if(in.nextDouble()<=min)
                {
                    min = in.nextDouble();
                }
            }
            else if(in.hasNext()) //EDIT: if it's not a double, is it anything at all?
            {
                if(in.toString().equalsIgnoreCase("end"))  //EDIT: yes it's something.. is it the string end?
                    end=true;
            }
            else
            {
                //EDIT: error handling code in case the input is neither a double nor hasNext() == true
            }

        }

        avg = sum / count;  //Since count is initialized to 0, and in the while loop is added to itself over and over, this will always evaluate to 0/anything, which will always evaluate to 0
        System.out.println("Number of items entered: " + count);
        System.out.println("The total of all items entered is: " + sum); // will probably always display 0, see above
        System.out.println("The average of all items entered is: " + avg); // will probably always display 0, see above 
        System.out.println("The smallest number entered was: " + min);
        System.out.println("The largest number entered was: " + max);
    }
}


edit: missed Wild_Cat's comments, but yeah, he's right :)
captain tortilla internet carpet bombing mission:
official website
myspace
8bitcollective
last.fm
facebook

other:
dissolution[official site][myspace]
PMPR[official site][myspace]

#94 Wild_Cat

Wild_Cat

    Pimpin

  • Members
  • PipPipPipPipPip
  • 581 posts
  • Location:Montreal, QC

Posted 25 May 2012 - 07:21 AM

Another thing I just noticed:

if(in.nextDouble()>=max)
{
    max=in.nextDouble();
}
else if(in.nextDouble()<=min)
{
    min = in.nextDouble();
}

in.nextDouble() always reads something from in -- meaning that on each of these lines that gets executed, it returns something different. In the worst-case scenario these lines will end up reading three numbers, discarding the first two and storing the third in min (with no guarantee that it is, in fact, smaller than min's previous value).

#95 arise_shine

arise_shine

    Shizz JediMaster

  • Members
  • PipPipPipPipPipPipPipPip
  • 3,986 posts
  • Location:Scansin

Posted 25 May 2012 - 10:35 AM

Another thing I noticed .. admittedly, i'm kind of a style Nazi, but I don't like not putting a space between keywords like "if" and "while" and the condition. It's fine for a function, but "if" isn't a function (or while, switch, for, etc.).

And I never thought about not putting declarations up front, but what Dennis says makes a lot of sense. You're not supposed to write very long functions, but sometimes I think it's hard to avoid, and it's kind of a pain sometimes to have to pig-up several times to see what the heck that var actually is.

Landscape.png
My personal blog.

My MTG blog.
"The sun has left the sky, now you can close your eyes, leave all the world behind until tomorrow." (Latimer/Bardens)


#96 Wild_Cat

Wild_Cat

    Pimpin

  • Members
  • PipPipPipPipPip
  • 581 posts
  • Location:Montreal, QC

Posted 25 May 2012 - 11:41 AM

Agreed. Style consistency is often seen as overrated, but in my experience it makes your code much more pleasant to read and helps avoid a lot of silly mistakes (this is one of the reasons I love Python -- indentation is used instead of {} blocks, so your code's presentation/visual layout *is* its structure).

If you're using an IDE like Eclipse, NetBeans or IntelliJ, you should make use of its code auto-reformatting capabilities. You hit one keyboard shortcut and boom, your current source code is reformatted, reindented and re-laid out to match the style preferences you configured.

#97 Dennis

Dennis

    Shizz JediMaster

  • Members
  • PipPipPipPipPipPipPipPip
  • 3,199 posts
  • Location:Winnipeg

Posted 27 May 2012 - 02:26 PM

because I apparently like to procrastinate, I thought it would be a fun exercise to re-factor that number program thingy:


import java.util.Scanner;

public class NumberEvaluation
{
	public static void main( String[] args ) 
	{
		System.out.println( "Please enter a number, type 'end' to exit: " );

		int count = 1;
		double sum = 0, min = 0, max = 0;
		Scanner in = new Scanner (System.in);
	
		while( !in.toString( ).equalsIgnoreCase( "end" ) )
		{
			if( double current = in.hasNextDouble( ) )
			{
				sum += current;

				if( current > max )
				{
					max = current;
				}

				if( current < min )
				{
					min = current;
				}
			}
		
			count++;
		}

		double avg = sum / count;

		System.out.println( "Number of items entered: " + count );
		System.out.println( "The total of all items entered is: " + sum );
		System.out.println( "The average of all items entered is: " + avg );
		System.out.println( "The smallest number entered was: " + min );
		System.out.println( "The largest number entered was: " + max );
	}
}

Disclaimer: I haven't done any Java programming in about 2 years, and I didn't try compiling this, so my double declaration in the evaluation section of that if loop may not be valid syntax, but that can be replaced with something like:

double current = in.hasNextDouble( )
if( current != null ) // or !current.isNull() if Java has isNull(), I can't remember

But yeah, on the topic of code style, in the "real world" I have found that a lot of this is dependent on (1) what your employer tells you to do (at my work, for the most part we follow this, even though it's optional), (2) suggestions from your coworkers (you may find everyone on your team prefers braces on the same line as the block, like if() { instead of { on the next line), and (3) lastly, but probably most importantly (where allowed), what you prefer to look at (two spaces in lieu of a tab, or vice-versa?, single print statement with new lines identified in the string vs. multiple printlines? etc?)

I like reading what the big places do with their code style though, it's often a neat glimpse into different code philosophies, and you might even learn some neat stuff
captain tortilla internet carpet bombing mission:
official website
myspace
8bitcollective
last.fm
facebook

other:
dissolution[official site][myspace]
PMPR[official site][myspace]

#98 Classic-wolf

Classic-wolf

    Shizz JediMaster

  • Members
  • PipPipPipPipPipPipPipPip
  • 3,771 posts
  • Location:Burning Dayton OH, since 1990

Posted 14 June 2012 - 04:42 PM

HYPER-CROSSOVER-THREAD ATTACK!!

Programmers! I have a job for you!



I FINALLY took the time to find something nice to display my collection! :D

3 zappers? I'd love to pretend zapper fight!

I have another orange one, too! Somebody should make a 4-zappers-players homebrew game! :D

4-player hack of Something!!

EDIT: Please!

O.N.H.C. Put it on t-shirts, wear it, live it, love it.
Only Noobz Hit Civillians
"Oh Lovely, they're all musical puns! Must be Base! Gavel-gavel-gavel!"

 

"Trig: 'These damn Raccoons are everywhere!'

Serker: 'I got one in my Bee-hole!'

Yellow: 'From now on, please refer to your fueling port as a mouth... or anything else.'"
That one topic with the songs and stuff
Not my site, 'cuz I don't have one, but awesome nonetheless. Fightersgeneration.com
The album art was too big, so:

Colons!

Me Right Now:

Spoiler




Reply to this topic



  


0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users