How do YOU code?

Just starting out? Need help? Post your questions and find answers here.
spongehammer
User
User
Posts: 84
Joined: Sat Jul 19, 2003 6:45 pm
Location: UK

Post by spongehammer »

Hello fweil

thank you for your response, and indeed to all those who have taken the time to reply.

I make every effort to look at the code posted here and to understand how other people do what they do and why.
I have been using computers since about 1978 when i built my first one, a Nascom 1 kit. I have spent time 'fiddling' with code ever since. My first steps in basic programming was entering code from a PC magazine into a Commodore Pet, then having to wait 'till the following month for them to print the corrections to get the program working!

Its only recently, in fact since i started using PB that i felt like i really want to make an effort. I see some excellent programs written with this language and feel inspired to do the same.
The real power with this software is not it the names of variables or in structures or anything else. It is here in this forum, when people give their time to help and explain (over & over in some cases :D ) to those of us who cant remember what they did 10 mins ago let alone how to code in ASM :D .

Thanks

Chris
I looked up 'paranoid' in the dictionary this morning.
It said, 'what do you want to know that for?'
Doobrey
Enthusiast
Enthusiast
Posts: 218
Joined: Sat Apr 26, 2003 4:47 am
Location: Dullsville..population: me
Contact:

Re: How do YOU code?

Post by Doobrey »

I`ve never done flowcharts, but I always scribble down some notes , mostly pseudo code. I also think a lot rather than rushing straight in, just to get things straight in my mind.

At the end of the day, just do whatever you feel you need to inorder to have a better understanding of what you want your code to do, and what problems you could come up against.

One thing I always do , is to always look to see how I could crash the code. Always check input data for errors, not just at the 'user end' of your code, but also check the parameters passed to any procedure you use.

eg, if you have a procedure that takes a pointer to a structure as its input, make sure the pointer isn`t zero before trying to access the structures fields.
User avatar
blueznl
PureBasic Expert
PureBasic Expert
Posts: 6166
Joined: Sat May 17, 2003 11:31 am
Contact:

Post by blueznl »

here's two samples, one just hacked away, the second one after putting in a little more thought...

first the hacked one...

Code: Select all

Procedure.s x_strex1(v.l,format.s)
  Protected s.s, l.l, a.l, b.l, d.l, p.l, v.l
  Debug format
  ;
  l = Len(format)                          ; total length of the format string
  a = FindString(format,".",1)             ; find a dot
  If a = 0                                 ; is there a dot?
    a = Len(format)                        ; digits in front of the dot
    d = 0                                  ; no dot
  Else
    b = l-a                                ; digits behind the dot
    a = a-1                                ; digits in front of the dot
    d = 1                                  ; there's a dot
  EndIf
  ;
  If Left(format,1)="+" 
    p = 2                                  ; always show the sign
    a = a-1                                ; one space less in front of the dot
  ElseIf Left(format,1)="-"
    p = 1                                  ; only show negative sign
    a = a-1                                ; one space less in front of the dot
  Else
    p = 0                                  ; floating sign
  EndIf
  ;                 
  If v < 0                                 ; make sure we ain't got a sign here
    s = Str(0-v)
  Else
    s = Str(v)
  EndIf
  If d = 0                                 ; no dot
    If v > 0 And Len(s) > l                ; doesn't fit...
      s = LSet("",l,"*")                   ; -> stars
    ElseIf v < 0 And Len(s) > l-1          ; doesn't fit...
      s = LSet("",l,"*")                   ; -> stars
    EndIf
  ElseIf Len(s)-b > a                      ; there's a dot but does it fit?
    s = LSet("",a,"*")+"."+LSet("",b,"*")  ; nope -> stars
  Else                                     ; goodie! it fits
    s = Left(s,Len(s)-b)+"."+RSet(Right(s,b),b,"0")  ; make sure there are zeroes directly behind the dot if needed
  EndIf
  ;
  s = RSet(s,1+l-FindString(format,"#",1),"0")  ; add any leading zeroes
  ;
  If p <> 0 And v < 0
    s = "-"+RSet(s,l-1," ")                ; insert parity sign and leading spaces
  ElseIf p = 2
    s = "+"+RSet(s,l-1," ")
  ElseIf v <0
    s = RSet("-"+s,l," ")
  Else
    s = RSet(s,l," ")
  EndIf
  ;                         
  ProcedureReturn s                        ; done, pfew
EndProcedure
and the one thought over...

Code: Select all

Procedure.s x_strex(var.l,format.s)
  Protected s.s, fl.l, sl.l, *f.BYTE, *s.BYTE, *l, p.l, sb.l
  ;
  ; *** format integer to string
  ;
  ; in:  var.l    - int varar
  ;      f.s    - format
  ; out: .s    - string
  ;
  ; convarert int varar to string using a pattern
  ;
  ; pattern elements:
  ;
  ; '#' - number or leading zero
  ; ' ' - space, number or (when there's no '+' or '-' used in the format) sign
  ; '+' - positivare or negativare indicator
  ; '.' - decimal sign
  ;
  ; examples:
  ;
  ; x_strex( 1234,     "###") =     "***"
  ; x_strex( 1234,   "##.##") =   "12.34"
  ; x_strex(-1234,   "##.##") =   "*****"
  ; x_strex(    1,  ".#####") =  ".00001"
  ; x_strex(   -1, "+   .##") = "-   .01"
  ;
  fl = Len(format)
  s = Str(var)
  sl = Len(s)
  ;
  *f.BYTE = @format+fl                               ; using two pointers and two counters
  *s.BYTE = @s+sl
  ;
  If PeekB(@format) = '+'                            ; remember is there is a sign in a fixed place
    p = 2
  ElseIf PeekB(@format) = '-'
    p = 1
  EndIf
  ;
  While fl > 0
    *f-1
    fl-1
    If *f\b = '.'                               ; skip a dot if we pass one
    Else
      sl-1
      If sl >= 0
        *s-1
        sb = *s\b                               ; sb contains the digit, AND is used as a flag
      EndIf
      Select *f\b
        Case '-'                                ; ah, a sign in a fixed place
          If sb = '-'
            sb = -1                             ; if sb = -1 we'vare managed to store the sign
          Else
            *f\b = ' '
          EndIf
        Case '+'                                ; same thing for the +
          If sb = '-'
            *f\b = sb
            sb = -1
          EndIf
        Case '#'                                ; if we havare data that is not a sign we're gonna fill it in
          If sb = '-' Or sl < 0
            *f\b = '0'                          ; otherwise it's going to be a zero
          Else
            *f\b = *s\b
          EndIf
        Case ' '                                ; if there is no fixed spot for a sign we'll store the minus
          If sb = '-'                           ; immediately on the first space we encounter
            If p = 0
              *f\b = '-'
              sb = -1
            EndIf
          ElseIf sb <> -1 And sl >= 0           ; otherwise we'll just gonna fil it in
            *f\b = *s\b
          EndIf
      EndSelect
    EndIf
  Wend
  ;
  If sb = '-' Or sl > 0                         ; if the sign wasn't stored or there was some data left
    format = LSet("",Len(format),"*")           ; we'll put in some stars to indicate ovarerflow
  EndIf
  ;
  ProcedureReturn format
EndProcedure
the hacked one is shorter :-)
( PB6.00 LTS Win11 x64 Asrock AB350 Pro4 Ryzen 5 3600 32GB GTX1060 6GB)
( The path to enlightenment and the PureBasic Survival Guide right here... )
PB
PureBasic Expert
PureBasic Expert
Posts: 7581
Joined: Fri Apr 25, 2003 5:24 pm

Re: How do YOU code?

Post by PB »

> Do not use a simple var like i as for next loop

Why not? In short loops, a "disposable" short variable name is fine. For
example, I often have short loops that use a short variable name, like:

Code: Select all

For k=0 To 255
  GetAsyncKeyState_(k) ; Clear all key buffers.
Next k
What's wrong with using a short variable here? Nothing. It's considered
to be "disposable" because it's not used to hold anything permanent, so
why give it a long name? All that does is make your typing take longer:

Code: Select all

For LongNameForNoReason=0 To 255
  GetAsyncKeyState_(LongNameForNoReason) ; Clear all key buffers.
Next LongNameForNoReason
> always look to see how I could crash the code

A very good idea! You always have to assume the user will crash your
app somehow, so test EVERYTHING. :)
Edwin Knoppert
Addict
Addict
Posts: 1073
Joined: Fri Apr 25, 2003 11:13 pm
Location: Netherlands
Contact:

Post by Edwin Knoppert »

You are doing the same as i do.
For short for next situations it's fine.
But when i extend the loop i get hanged up by leaving it in.

When is the moment to change to proper name, that's always the point...

It was just a learning remark to watch out for these situations.
User avatar
geoff
Enthusiast
Enthusiast
Posts: 128
Joined: Sun Apr 27, 2003 12:01 am
Location: Cornwall UK
Contact:

Post by geoff »

For some applications a state based approach is convenient.

You draw a diagram with a blob representing each state the system can be in, then you draw lines between the blobs representing the actions that cause movement between the states.

Coding the application is simple. You write a block of code for each state which checks for the actions that take the system to other states.

For example, consider the software in an ATM machine.

State 1 might be "waiting for card entry"
State 2 might be "waiting for next PIN code digit"
State 3 might be "PIN submitted, waiting for verification"
State 4 might be "PIN verified, waiting for user command"
State 5 might be "PIN invalid, waiting for re-entry"

A complex system may have hundreds of states, but doing it this way the software is simple to understand and maintain. In conventional code the "implied" state of the system can be the combination of several variables, current position in the code and the content of the stack.
spongehammer
User
User
Posts: 84
Joined: Sat Jul 19, 2003 6:45 pm
Location: UK

Post by spongehammer »

Hi geoff,

i originally asked the question in an attempt to gain an insight as to how to approach a project. There have been lots of answers all very useful too :D . I understand your approach, and its very logical but my main problem is how to start a project which seems (at this time) to have an ever growing feature list. :? What i want to do is to ensure that as the project grows, and features (unthought of now) spring to life, that i have the means to incorperate them without tripping over some sort of self imposed limit set at the start.
It seems to me that the most logical approach is to make everything as modular as possible. The other thing i need to do is to draw a line under the features list! :lol:

Chris
I looked up 'paranoid' in the dictionary this morning.
It said, 'what do you want to know that for?'
Dr_Pixel
User
User
Posts: 36
Joined: Fri Oct 24, 2003 1:36 pm

Post by Dr_Pixel »

Here's my method, which has served me well - It's admittedly very slow, but it keeps me from spending endless hours tracking down bugs.

First, I never make notes on paper, because when I do, I lose them ;)

Any notes to myself are in comments at the very top of the source.

Anyway, when I first start, I simpley make the code to open my window, and an event-loop that checks for the window close gadget.

I then test this - yes, even just this "nothing" code, because I test everylittle thing, from start to finish, as I go.

Next, I make a sort of "outline" of the program, just a series of comments in the order I want things to happen (or, really, the order in which they MUST happen)

Then, I start the actual coding - as each part is done (to the point of working), I'll add it to the main loop - for example, once the response to a gadget is ready, then I add that gadget to the event loop, and test to see if it works. If it does, I then look at it's code again, to see if I can make any speed improvements, or whatever...

So, anyway, I code in such a way that the program is workable, and runnable, right from the start, even if it does nothing more than open and close the window at first.

And, I also correct any problems as soon as I find them, rather than put them off until later. I've found this avoids many headaches later.
And by problems, I don't mean just bugs - If I'm not satisfied with how something works, I work at it until I am before going on to something else. Maybe it's just me, but if I say "well, that's ok for now, I'll get back to it later" I never do ;)
Dr Pixel
ppjm99
User
User
Posts: 23
Joined: Mon Jun 02, 2003 7:39 pm
Location: Canada

A comment on variable naming

Post by ppjm99 »

I like to use the CamelHump style variable names because I type them out in correct case when I first declare them like ThisIsMyStringVar$ but then when I refer to them later in code I type them in all lower case and let my editor correct the case to match the declared version. The benefit of this is that if the editor doesn't change thisismystring$ to ThisIsMyString$ then I instantly know I have either mispelled the variable or not declared it at all.

Of course you need to use an editor that does this, also I like to use descriptive names because most of the time code completion in the editor will type the var for you and your code is more self documenting.

B.T.W. My first machine was also a Commodore Pet and I remember typeing in those endless DATA statements from COMPUTE Magazine's programs then saving to cassette tape. We have come a long way.
User avatar
blueznl
PureBasic Expert
PureBasic Expert
Posts: 6166
Joined: Sat May 17, 2003 11:31 am
Contact:

Post by blueznl »

ah, geoff, state-logic... that's nice you bring it up, as it is a very good but often overlooked concept...
( PB6.00 LTS Win11 x64 Asrock AB350 Pro4 Ryzen 5 3600 32GB GTX1060 6GB)
( The path to enlightenment and the PureBasic Survival Guide right here... )
User avatar
NoahPhense
Addict
Addict
Posts: 1999
Joined: Thu Oct 16, 2003 8:30 pm
Location: North Florida

Re: A comment on variable naming

Post by NoahPhense »

ppjm99 wrote:I like to use the CamelHump style variable names because I type them out in correct case when I first declare them like ThisIsMyStringVar$ but then when I refer to them later in code I type them in all lower case and let my editor correct the case to match the declared version. The benefit of this is that if the editor doesn't change thisismystring$ to ThisIsMyString$ then I instantly know I have either mispelled the variable or not declared it at all.
Ah, the good ole CamelToe syntax..

- np
Randy Walker
Addict
Addict
Posts: 989
Joined: Sun Jul 25, 2004 4:21 pm
Location: USoA

Post by Randy Walker »

One thing I have learned that has made life MUCH easier and I would strongly recommend (because I haven't found a better way to deal with the problem... hint, hint!! )

This problem exists in both the original and the jaBEe editors. When you create a new project and run it, the editor automatically overwrites your existing source code file. This is very very bad because you may forget to restore the backup that is thoughtfully created in the background before making your alternative modification. You can define the number of backup files in the editor, but forget once and you can very very easily lose track of which backup to restore. To test the backup you think "may" be the right one, you have to compile and run it, which in turn creates a new backup. Very VERY confusing imho. (Really wish the editor could compile and run from a backup instead of the main source code file... hint hint!! :wink: )

Simple Solution:
Not only will this protect your main source code file from the envasive overwrite, it also make it very convenient to refer back to the original code that you are modifying. These are the steps I use and rules I apply while using the jaPBe (ver 2.4.9.25):

1. Load main source code file, ie. "MyProject.pb"
(You will see your file name on the tab at the top of the document.)

2. Highlight the entire document and copy to the clipboard.

3. Click on the new document "icon" seen just below "File" in the menu bar.

4. Paste your clipboard copy to the empty "New" document that just opened.

5. Modify code in the new document and test until satisfied with changes.
(Here is where it is very handy to click on the tab and refer back to the original code.)


DO NOT PROCEED UNTIL... you are happy with your changes and all is good.

6. Click the tab to bring your original source code page to the top, and close it!

7. Click back to your modified code, Press F12 and save back into the original file name.

8. Return to step 2 above to begin your next modification.

Two Important Rules To Follow:
1. DO NOT give the "New" project a name or save it, accept as noted above!!
2. Modify your code ONLY in the "New" project. Every successfull modification results in the original file being replaced, else you ALWAYS have the untainted original sitting there on the disk to fall back on, as it was before you started. A third benefit is ALL the complimentary auto-backups that are created will be good working code. It may be short one modification, but the procedure above only allows "good working" copies to overwrite your original code file.

This procedure works well for me and "maybe" its the way I was supposed to be doing it from the beginning but, those instructions weren't made apparent to me anywhere. The editor could very easily be made to operate in a similar manner if it would only write to a backup file and compile from there instead of using the main source file. This would allow "the user" to determine when it is appropriate to save and overwrite his own work.

One last thing. I wouldn't want to leave you with the wrong impression. Although I have little experience with the original Purebasic editor, the jaPBe product is very powerful, very efficient, very well layed out and very easy to use. PureBasic is a marvel unto itself. The jaPBe is an extreme compliment to that power and makes it all really easy to harness. Of couse, as you pointed out, the people here are generous so coding is made even easier.
- - - - - - - - - - - - - - - -
Randy
I *never* claimed to be a programmer.
Post Reply