Computer Science Teacher
Computer Science Teacher - Thoughts and Information from Alfred Thompson

May, 2009

  • Computer Science Teacher - Thoughts and Information from Alfred Thompson

    Prime Numbers, Code Challenges, and Programming Languages

    • 4 Comments

    Clint Rutkas and I have some friendly back and forth about a couple of things. One is the worth of Visual Basic as a programming language and the other is over who is the better coder. Don’t tell Clint but I have a secret suspicion that he may be the better coder (because he is in his prime and I am past mine) but I will never give up on Visual Basic. In any case we have been talking about a small coding challenge to complicate the discussion. After all facts seldom solve anything but they do add to the discussion. Someone suggested that we both write a program to find the next prime number after 2.2 billion. Sounded like fun to us so we went at it. Now let the discussion begin.

    My solution was written in Visual Basic – of course. Clint’s in C# – not a bad choice at all. Clint went for complication and sophistication (there is an option to use threading in his) while I went for simple, basic and old school. My code looks like this:

     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim i As Long
            Dim timePerParse As Stopwatch
            Dim ticksThisTime As Long = 0
    
            timePerParse = Stopwatch.StartNew()
            For i = Val(txtStart.Text) To Val(txtEnd.Text) ‘ Could use Step 2 here
                If IsPrime(i) Then
                    Exit For
                End If
            Next
    
            timePerParse.Stop()
            ticksThisTime = timePerParse.ElapsedTicks
            Dim ts As TimeSpan = timePerParse.Elapsed
            lblPrime.Text = i.ToString("###,###,###,###")
            lblTime.Text = ts.TotalMilliseconds
    
    
        End Sub
        Function IsPrime(ByVal n As Long) As Boolean
            If (n Mod 2 = 0) Then Return False
            If (n < 2) Then Return False
            If (n < 4) Then Return True
    
    
            Dim iMax As Long = Math.Sqrt(n) + 1
            Dim i As Integer
            For i = 3 To iMax Step 2
                If (n Mod i = 0) Then Return False
            Next
            Return True
        End Function

    The primary optimization is the line that uses the square root of n plus 1 to set the bounds of the loop that brut forces through finding if the number is divisible by something. I use the StopWatch object (I blogged about that some time ago) for the timing. I also display the results outside the timed area because I/O takes too much time and isn’t really part of the problem anyway. I played with using Step 2 to pass half as many numbers through the IsPrime function but that didn’t seem to make a whole lot of difference in the time. I was surprised by that and want to look into that some more. It may be that the first compare in the IsPrime function may be faster than I expected or perhaps the compiler is doing some behind the scenes optimization. I’d have to look at the generated IL (Intermediate Language) code to really know for sure.

    So what do you think? Is Clint’s code better? How do you define “better” when comparing code like this?

  • Computer Science Teacher - Thoughts and Information from Alfred Thompson

    No Subject Is Boring With The Right Teacher

    • 5 Comments

    In between trips to stores and working on the yard and cooking on the grill and yes even remembering those people who have fought and died for this country I spent a lot of free cycles thinking about teaching this week end. NSF wants to have 10,000 teachers teaching real computer science courses in the next few years. Great goal. But when I hear students talk about computer science they use words like “hard” and “boring.” These are not the sort of things that attract students. So I ask myself “is computer science hard and or boring?” And the obvious answer is not to me its not. But as my son regular reminds me I tend to look at things differently. So I think about the role of the teacher in all of this.

    Some years ago one of my former students paid me a huge compliment. He said that what he enjoyed was not so much learning computer science but learning computer science from me. It made my day as you might imagine. But at the same time it concerned me. I’ve seen students get excited about a subject because of a good teacher and I’ve seen students get turned off from a subject because of a poor teacher. So what then for computer science?

    Can we train enough teachers to teach computer science? Probably but it’s not an easy thing. And even then is giving them the base knowledge (say more than a chapter ahead of students) enough for success? Anecdotal evidence suggests otherwise. OK there are some crazy good teachers who can teach anything, get students involved, make learning fun and all but walk on water. I don’t think I’m one of them. How many do you know? And can we get them to teach computer science? More common are stories of people drafted to teach computer science to fill up their contract or fill a need that no one else can or will fill and who share their lack of enthusiasm with their students.

    So what than can we do? There was a recent article by Mortimer Zuckerman in US New & World Reports and a Bill Gates’ TED talk where they talk about quality teachers and point out that individual teachers make a huge difference. They go on to say that we should take advantage of those teachers.

    Now a lot of  teachers don’t like either of these position statements. The Gates talk has taken a lot of flack from teachers and people in education for example. Gates and Zuckerman dare to point out that all teachers are not of the same high caliber. That is something approaching  blasphemy in the education world. Well, when it comes from people who are not teachers that is. Teachers in the privacy of the teacher’s lounge will complain bitterly about other teachers who are doing a poor job. I’ve heard it myself time and again.

    So even if you don’t want to admit it there are teachers who could use some  help. And some students who could benefit from a teacher with a bit more knowledge and a bit more enthusiasm for the subject. But how to make that happen?

    Both Gates and Zuckerman suggest that there is a role that technology can play here. Video conferencing is one way. There are a lot of guest visits going on via Skype and that might be helpful. Perhaps we could get more outstanding lectures and demos on video so that they can be shown to more students. Perhaps we can get some online support groups (wikis perhaps or maybe online chat rooms) to get students assistance in ways that work for them. There are creative teachers in all disciplines doing great things with web 2.0 tools and we can learn from them.

    And maybe we would be better off if it were easier for second career professionals to move into teaching. Some changes to certification requirements perhaps. Or perhaps some financial aid for people making the transition – income while taking certification courses perhaps. There have been industry plans from such companies as IBM and DEC in years past. Perhaps some of today’s high tech firms could invest in education in that way again.

    And we need to address the “hard” part of computer science. Is it really hard to learn or are we just teaching it poorly? We have far too little investment in computer science education research. A faculty member in a computer science department can’t get tenure (or so I am told) by doing research in CS education. Education departments seem either uninterested or unable to do the research in their departments. Some universities with both education and CS departments need to invest in our future by taking this on jointly. Perhaps NSF has funds for this? If not they should. And universities will have to reward this work with tenure too!

    Above all I think that any subject is interesting if taught by the right teacher and any subject is learnable with the right individualized attention to learning styles. We can do it. We just need the will to make is so.

    -------------------------------------------------------------------

    Note that enthusiasm and fun in teaching seems to be a recurring thought for me. A couple of previous posts for example.

    And on the topic of “hard” see Is science too hard or are other courses too easy?

    Note: It bares repeating that these are my personal opinions and not official or policy or representation of any other individual, company or organization. Also I wrote this at 1AM for what ever that may mean. :-)

  • Computer Science Teacher - Thoughts and Information from Alfred Thompson

    Exceptions, Data Validation and Political Correctness

    • 1 Comments

    When I first heard the term “exception handling” as a replacement for “error handling” I was not impressed. At first glance it seemed like political correctness gone wild and brought into computer science. I’d been calling it error handling for a long long time and it worked for me. Why change the term now? In fact this article in the Microsoft knowledgebase refers to “structured error handling.”

    I’ve given this a bunch of thought lately. It really started as I was doing a set of workshops on Visual Basic .NET a month or so ago. One of the key changes between VB .NET and older versions of Visual Basic is that error handling (the OnError statement) has been replaced (for the most part) by exception handling. I see exception handling as a super set of error handling.  Error handling implies that someone or some thing made an error – did something wrong. Exception handling implies that as well but it more broadly implies that something happened that was unexpected.

    As I see it an error is the user’s fault and an exception (something unexpected) is the programmer’s fault. The programmer should expect things to go wrong and should prepare for that certainty. Now one can never make anything idiot proof because God keeps making better idiots but one has to try.

    Recently  Patrick Godwin (@ximplosionx)  started a conversation on Twitter about exception handling with the question “Why are we taught to handle exceptions rather than prevent them? I would think the best way to handle it is to stop it.” The answer really is that what we want to program to do is to handle a situation caused by something going wrong in a way that is at worst helpful to the user and at best transparent to the user.

    What this means is that we have to do a number of things to protect the user from themselves and protect the program from doing “bad things.” Perhaps the worst bad thing is to do the wrong thing without telling anyone what is going on. So let’s look at a couple of simple examples.

    The first is simple range checking. If we are expecting a number between 1 and 100 a program should check that data. The program should go no further if the number it gets from a user, a data file, or other source until the number is corrected. I see that as data validation. Is it also exception handling? Yes though to be honest we don’t have to “throw an exception” using something like a Try/Catch structure. We can use a simple loop for example. Generally back in the old OnError days that is what programmers did and it is still a good way to do things. Of course we also try to help prevent this sort of thing by asking the user specifically what we need for input. And if they give the program the wrong data or put another way exceptional or otherwise unexpected data we want the program to explain what went wrong.

    Some of exception handling is dependent on where you want to handle things. Take for example the case of a divide by zero error. One can catch it when it happens:

            Try
                sum = a \ b
            Catch ex As DivideByZeroException
                MessageBox.Show(ex.Message)
                Return
            End Try

    or one can stop it before it happens by validating the data earlier. For example:

            b = System.Convert.ToInt32(Me.txtNumber1.Text)
            If b < 0 Then
                MessageBox.Show("Value must be greater than zero, please try again...")
                Me.txtNumber1.SelectAll()
                Me.txtNumber1.Focus()
                Return
            End If

    Which is better? I’m not sure there is a clear answer. On one hand validating the data earlier is a good thing especially if the data is likely to be used for something else that would not generate an error but which would generate other bad data. On the other hand there are more things that could go wrong with that data conversion so perhaps something like this would also be a good idea:

            Try  '** validate second input…
                b = System.Convert.ToInt32(Me.txtNumber2.Text)
            Catch ex As Exception
                MessageBox.Show(ex.Message)
                Me.txtNumber2.SelectAll()
                Me.txtNumber2.Focus()
                Return
            End Try

    And then do we check for out of range or do we wait until the divide operation? Or maybe something like:

            Try  '** validate second input…
                b = System.Convert.ToInt32(Me.txtNumber2.Text)
            Catch ex As Exception
                MessageBox.Show(ex.Message)
                Me.txtNumber2.SelectAll()
                Me.txtNumber2.Focus()
                Return
            Finally
                If b < 0 Then
                    MessageBox.Show("Value must be greater than zero, please try again...")
                    Me.txtNumber1.SelectAll()
                    Me.txtNumber1.Focus()
                End If
            End Try

    This data validation gets complicated pretty quickly doesn’t it?  And you know what? There is still a chance that the value of b will get modified in bad ways before we get to the division operation. We may want to keep that Try/Catch anyway.

    Where it gets complicated for real is where the user can’t really do anything about what went wrong. Those are cases where we as programmers really want to avoid. Whether we use exception handling or error handling or structured error handling is not as important as preventing unrecoverable errors from happening. What do we do if that does happen? Well then we need to report as much information as possible in a form that they user can get to the developer. End users are generally not the best reporters of fatal errors. The program is going to have to do that. It may be an error log file (in which case the user needs to know where that file is and what to do with it) or it might be a detailed error message. Again what will the user do with that message?

    These days Microsoft Windows has some built in reporting tools for fatal errors. It might be the OS, a driver or even an application program. This process sends information to Microsoft where it is analyzed and when possible passed on to the right development group for fixing. This has been a powerful and very successful tool for reducing the number of errors and making Windows and Windows applications more stable and robust. And that is a good thing.  It’s the kind of thinking that we need people to learn early on in their careers though. A first programming course is not too soon to start.

Page 1 of 6 (17 items) 12345»