Visual Basic/JArithmetic

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Introduction[edit | edit source]

JArithmetic is a prototype application intended to be a sort of poor man's MathCad.

When you start to write a program you need a set of requirements. Sometimes the goal is very precise and can be exhaustively described but it often happens that while the goal is clear it is neither desirable nor practical to describe in detail what the program is to do. JArithmetic is an example of the second type.

The basic requirements are these:

  • An editor for a document type that can include formulas and show both the formula and the result,
  • The editor must support text formatting (typeface, type size, type style.

Obviously such a set of requirements doesn't constrain the developer very much. In this case an additional consideration is this:

  • we aren't sure of the costs and benefits of different capabilities.
  • we aren't sure what we mean by formula,
  • we aren't sure what we mean by text formatting,
  • we aren't sure what we mean by result.

This means that we must develop the program a little before we can decide what additional requirements should be added. Still we ought not to just wander aimlessly in the programming landscape. Therefore we define a set of desired features, a wishlist:

  • It should be possible to include graphics in the document,
  • Results should be displayable as charts.

Another valuable list of characteristics is a negative one. That is a list of things that are not required. This doesn't mean that they are forbidden, just that time is not to be spent on developing them at the expense of required or wishlist features:

  • We will not demand the ability to format mathematical formulas in textbook style. That is, we are after some of the capabilities of Mathcad but are not trying to make camera ready copy.

With the basic requirements, the wishlist and the non-requirements in mind we can begin to sketch the outline of an implementation. However, before we go any further we should remind ourselves of the chief virtues of a programmer.

First the ones that get the process of programming moving, the passionate virtues:

laziness
never write code when you can 'steal' it, never write anything twice,
impatience
demand results now,
hubris
have pride in your power.

and then those that keep it going:

diligence
don't be satisfied with sloppy work,
patience
don't be deterred when things get slow and hard,
humility
take help gladly from whomever and where ever it comes.

The headwords are from Larry Wall but the definitions are mine.

So let's see how far our basic requirements and the passionate virtues can get us.

Outline Implementation[edit | edit source]

Nothing says we have to take the requirements in the order in which they are presented so lets combine the second one:

  • The editor must support text formatting (typeface, type size, type style

with the first two virtues: laziness and impatience to get a basic editor. Once we have that we can start to think about the other principal requirement:

  • An editor for a document type that can include formulas and show both the formula and the result.

The essence of this requirement is that the program must somehow read the document, work out the results of executing the formulas and then put the answers back into the document.

Basic Editor[edit | edit source]

Built into Windows is a component called the rich text editor. Visual Basic Classic can use this component. This component implements a fancy text box that supports all the typefaces that Windows can use along with type sizes and type styles such as italic, bold, etc. This looks like it should fulfil the requirement and the first virtue. Now let's be impatient.

All you have to do is create a new project and add a reference to the Rich Text control. On NT, Windows 2000 and XP this is usually found in:

 x:\WINNT\system32\RICHTX32.OCX

and you can add the reference by clicking Components on the Project menu. File:VBClassicRichTextReference.png

Now add a Rich Text box to the form. Don't worry about naming and resizing just now. Rich text example form.

Now run the project. Even with no code you have an editor in which you can type that understands tabs and newlines.

Now add the following code to the form:

 Private Sub RichTextBox1_KeyPress(KeyAscii As Integer)
   Select Case KeyAscii
     Case Asc("B") - 64
       RichTextBox1.SelBold = Not RichTextBox1.SelBold
     Case Asc("U") - 64
       RichTextBox1.SelUnderline = Not RichTextBox1.SelUnderline  
     Case Asc("I") - 64
       RichTextBox1.SelItalic = Not RichTextBox1.SelItalic
   End Select
 End Sub

Don't worry about the lack of proper naming, constants and so on; this is just throwaway code to play with for the next five minutes.

Run the program, type some text, highlight some text (use the mouse or shift and arrow keys). Now press control-B, control-I or control-U. See the text style change.

This little experiment proves that we can get an editor that satisfies at least one of out principal requirements with almost no code.

Exercises[edit | edit source]

  • Read the documentation for the rich text control,
  • Extend the program to include font selection and indented paragraphs,
  • Think of another extension and implement it,
  • If you haven't already tried setting the text to italic with control-I try it now. Explain why it doesn't work.
  • Provide an alternative way of setting the bold, italic and underline attributes.

Processing the Document[edit | edit source]

Now we must see if we can find a way to satisfy our other requirement:

  • An editor for a document type that can include formulas and show both the formula and the result.

This is very vague and leaves to the readers imagination the definitions of a number of key words:

formulas
what is a formula? Does it look like the quadratic equations you see in a school text book?
result
Is a result a number? Could it be a set of numbers? What about a chart? What about text?

Now we could answer all these questions by doing an in depth study of the real meaning of the words and interview our end users about what they want but there is another way: turn around and face the other way, ask what have we already got that could do the job.

Look into your own experience and surroundings for ideas. You are or want to be a programmer so ask yourself 'what do our requirements remind me of?'. Look at our document type, it is made of formulas and results; formulas are just a kind of instruction, they say things like add a to b and multiply the answer by c and results are just whatever comes out of that process. Sounds remarkably like a computer program.

So if our document is to be a computer program we need to decide what language it will be written in. In principle we can use anything from textbook mathematical expressions with all the fancy symbols to Fortran, Lisp, Basic, Pascal, Prolog, etc., etc,. ad nauseam.

We apply Larry Wall's virtues:

hubris
tells us that we can implement what we like,
laziness
says that would be hard work,
impatience
says I can't wait that long!

So are there any languages that are already available to us in a form that our little program can use? The answer is a resounding yes. We can use one of the scripting languages: Ruby, Python, VBScript, JavaScript, etc.

Which one should we choose? We can dismiss some straightaway because they require too much work on our part or make the final program too big:

Ruby or Python
great languages, clean and powerful but need a significant amount of stuff to be installed before they will run,
VBScript or JavaScript
you probably already have these in the guise of the Microsoft Script Control.

So to get it flying quickly and be able to deliver it to a user who doesn't have Python or Ruby we'll choose the scripting control. We'll delay the choice of VBScript or JavaScript until later.

Processing the document is, in principle, simply a case of sending the text to the Scripting Control and reading back the answers.

Lets add the Scripting Control to the little experimental application. There is no need for a visible control so just add the reference:

Add Script control reference

Now add a command button to the form:

Form with command button

Now add this code to the form:

 Private Sub Command1_Click()
 
   Dim oSC As ScriptControl
   Set oSC = New ScriptControl
   oSC.Language = "JScript"
   oSC.Eval RichTextBox1.Text
 
   With RichTextBox1
     .SelStart = Len(.Text)
     .SelText = vbCrLf & oSC.Eval("a")
   End With
 
 End Sub

Run the project and type:

 a=1

in the rich text box. Make sure you delete anything else that might be there.

Now the moment of truth: click the command button. If all is well the number one should appear on the line following the a=1 statement.

Pretty boring though. Try something a little more exciting, clear the text and add this instead:

 b=2
 c=3
 a=b*c

Click the button again. Should say 6. Click again and another 6 should appear.

Now it's time to explain what has been happening. The script control is actually an interpreter or the front end for an interpreter. In fact it can interpret both VBScript and JScript. VBScript is a sort of Visual Basic where all data is Variant and JScript is Microsoft's implementation of JavaScript.

The tiny scrap of code in the command button event handler just creates the script control, tells it which language to use, then asks it to evaluate the code in the rich text box. After that it asks to evaluate the simplest statement:

 a

This returns the value of the variable a as the value of the Eval method. Then a little bit of magic with the rich text box adds that value to the end of the text.

This tiny application satisfies in essence all our requirements. Do some exercises before moving on the next section where we will criticize our poor little application and make some improvements.

Exercises[edit | edit source]

  • Examine the command button event and write a sentence or two of explanation and clarification for each line. Don't repeat what the code says, concentrate on explaining what it does and why.
  • Try the bold, italic and underline formatting commands. Do they affect the results?
  • Add more statements, more variables, make the statement that sets the a variable more complex.
  • If you know JavaScript you can add a function, use the function to set the value of a. If you don't know JavaScript then it's time to learn.
Previous: Case Studies Contents Next: JArithmetic Round Two