why not use DO WHILE in Fortran [closed] - while-loop

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 months ago.
Improve this question
I'm studying Fortran from the book of Stephen Chapman "Fortran for Scientists and Engineers" (2018).
In page 134, the author wrote this:
Good Programming Practice:
Do not use DO WHILE loops in new programs. Use the more general while loop instead.
This sentence is puzzling me a lot. Is DO-WHILE an unwanted practice? I often find DO-WHILE neater to work with. Is there any disadvantage of using DO-WHILE in terms of speed?
DO-WHILE
INTEGER :: i = -1
DO WHILE (i < 0)
PRINT *, 'Enter a non-negative number:'
READ(*,*) i
END DO
General while loop:
INTEGER :: i = -1
DO
PRINT *, 'Enter a non-negative number:'
READ(*,*) i
IF (i >= 0) EXIT
END DO

Is there any disadvantage of using DO-WHILE in terms of speed?
No. There is no general reason why do while would be slower than do. A decent optimising compiler should always be able to convert a do while loop into the equivalent do loop (although not always vice-versa). Of course, if you are interested in performance in a specific case then you should try both and profile the code rather than relying on generalities.
Is DO-WHILE an unwanted practice?
No. If a do while loop is the clearest way of expressing your code, use a do while loop.
The argument "X is more general than Y, so always use X instead of Y" is clearly a fallacious over-generalisation. A GOTO is more general than a do loop, but you certainly shouldn't be replacing your do loops with GOTOs.

I can read from this book, just before the citation you give :
This construct is a special case of the more general while loop, in which the exit test must always occur at the top of the loop. There is no reason to ever use it, since the general while loop does the same job with more flexibility.
These are mostly facts, except "There is no reason to ever use it", which is just the personal opinion of the author. And anyway "there is no reason to use it" is not the same as "there are reasons to never use it" (as far as I know there are no such reasons).
That said, as a matter of style, in the particular example you give, the do while construct is not the best choice IMO, as it forces you to (artificially) initialize i before the loop. The initialization is not needed with the general do loop.
EDIT : as mentioned in the comments the initialization is actually still needed. But this is because of the READ(*,*) that does not garantee i to be assigned. Such a read should be protected against possible input errors, but this a different topic...

Related

How to name boolean variable that indicates whether to do something? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
As far I as my experience tells me, boolean variables usually named in format - is/has+noun/adj/verb, e.g isValid, isButton, hasClickedLink
But say there is the case where we have some flag which straightly tells whether to do something, like for example, clean to indicate that cleanup function should be automatically called in the end.
How to name such a booleans? Same clean - is ambiguous, looks like a method name more, but naming it toClean is, I don't know, too weird. Or should I name it like callCleanup?
Thanks in advance!
In this case i usually append the word wanted, which makes cleanWanted. In general, for boolean variables I also prefer to always let the last word be an adjective. This makes it very clear that it represents a truth value. The is/has prefix is often superfluous, as in hasClickedLink which is more concisely communicated with linkClicked.
methods are usually one word adjectives with a capitol at the start
maybe create a method that sets the flag
for example
void Clean(){
clean = True;
}

Wide Method Call VB.NET [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I've just written this:
ldb.Update(emp.Code,emp.number, "text", String.Empty, "EMP", emp.scheme, emp.status, emp.tod, emp.timestamp, emp.Code, emp.oldfrmd)
Its far to wide! How can I shorten this method call? The problem is this isn't my method, so I can't edit it.
It depends on what your concern is:
Too many parameters? Can't really change that without changing the method, although you could introduce a proxying method containing fewer parameters, where each parameter may map to several of the original ones. It looks like you might want to make this a method on whatever the type of emp is, but it's hard to know without more information.
Just too wide on the screen? Use line continuations:
ldb.Update(emp.Code, emp.number, "text", String.Empty, "EMP", _
emp.scheme, emp.status, emp.tod, emp.timestamp, _
emp.Code, emp.oldfrmd)
(IIRC the "_" isn't actually needed in VB10.)
Too many characters? Introduce some local variables, potentially, shortening the eventual call to something like:
ldb.Update(code, number, "text", "", "EMP", scheme, status, _
tod, timestamp, code, oldfrmd)
(Although your overall code will be bigger, of course.)
Since you can't change the method signature, you must really be passing all those fields of emp into it. I would tend to write my own function (pardon my terribly rusty VB; I'm sure there's something wrong with this):
updateLdb(Employee e)
which simply called ldb's function and did nothing more. Using a single letter for a variable name is generally a bad idea, but in this case it saves your line 16 characters, and in a one-line function, "e" isn't particularly less informative than "emp". As Jon says if you move this function into the Employee class, you can get rid of another 16 characters - and it does appear to really belong there.
I would not use "e" as a variable or parameter name in any function that is longer than one or two lines, but in that small a scope, I think you can get away with it without significantly sacrificing readability.

Using colons to put two statements on the same line in Visual Basic [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Is it considered bad practice to use colons to put two statements on the same line in Visual Basic?
There is nothing inherently wrong with using the colon to combine statements. It really depends on the context but as long as it doesn't reduce readability, there is nothing wrong with it.
As a general rule I avoid using the colon for this purpose. I find it's more readable to have one statement per line. However this is not a colon specific issue. I avoid doing the same with a semi-colon in C# or C++. It's just a personal preference.
It's a good practice in moderation, because sometimes readability is enhanced by concatenating two lines:
when the lines are short and intimately
related
when the lines are short and trivial
Option Compare Database: Option Explicit ''My favorite!
rsDataSet.Close: Set rsDataSet= Nothing
Don't do it if:
it hurts readability.
it complicates debugging. Control structures such as If...Then need to stay clean. You'll be glad you kept it simple when it's time to set a break point.
it compromises future editing. Often you want to keep sections portable. Moving or re-structuring a block of code is easily hindered by attempts to minimize your code.
In general, I'd advise against it, as it makes for busier code.
However, for simple tasks, there is nothing wrong with it. For instance:
for i = 1 to 10: ProcessFoo(i): next
I think a line like this is short enough not to cause confusion.
I'll take the other side. I don't like dense lines of code. It is easier to skim code when lines are not combined.
Combining statements also makes it easier to create long functions that still fit on a single screen.
It isn't a major sin, I just don't like it.
I also don't like one line If statements.
To me you shouldn't say "never do thus", you should just say "If you do this, a possible problem is such and such." Then just weigh the pros and cons for yourself. The pro is brevity/few lines of code. Sometimes this can aid readability. For instance some people use it to do vb.Net declarations:
Dim x As Long: x = 1
Or wait loops:
Do Until IE.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
But obviously you can really make it rough on someone too:
Public Sub DoYouKnowWhatThisDoes()
MsgBox Example
End Sub
Private Function Example()
Const s$ = "078243185105164060193114247147243200250160004134202029132090174000215255134164128142"
Const w% = 3: Const l% = 42: Dim i%, r$: For i = 1 To l Step w: r = r & ChrW$(Mid$(s, i, w) Xor Mid$(s, i + l, w)): Next: Example = r
End Function
Another practical reason that you might not want to use this approach is breakpoints. Breakpoints can only be set by the line. So if you have several things executing on the same line you can't isolate the second thing. It will stop on the first statement. (This is also one of the reasons some people don't like single line ifs.) It just complicates debugging a little.
I usually don't use colons in production code for this reason. However I do use them to improve the brevity of "copy/paste" code that I post in forums and elsewhere. YMMV:)
I realize this is a very old question, but it was the first result on my Google search, so I hope I can be forgiven for chiming in here.
There is one situation (exactly what led me here in fact) in which this approach is not only useful, it's the only way to accomplish the desired result: the Immediate window. Any code you want to execute in the Immediate window must all be on one line. So in order to use any form of Do, Case, For, While, or With in the Immediate window, you will need to use colons.
It is considered bad practice in most of the sites at which I have worked. And by most of the VB developers with whom I have worked. And in my head. If I see it, I will admit that I would almost certainly change it. I say "almost" because I admit there's a possibility that I could find a piece of code that looked better that way. I don't expect to see it in my lifetime, though.
I also really don't like one-line **If**s either.
Both are most likely hangovers from the days of VGA (640x480) monitors; that's no excuse these days.
I've only ever used it when I'm clsoing a recordset and setting the variable to nothing. I figure one line instead of two gives me more lines of code on the screen and doesn't detract from readability.
I've seen it used in simple select cases such as the following but that would be as far as I would go.
Select Case success
Case ERROR_FILE_NO_ASSOCIATION: msg = "no association"
Case ERROR_FILE_NOT_FOUND: msg = "file not found"
Case ERROR_PATH_NOT_FOUND: msg = "path not found"
Case ERROR_BAD_FORMAT: msg = "bad format"
from http://vbnet.mvps.org/index.html?code/system/findexecutable.htm
And even then I would've lined up the "msg =" portion.
I've never seen this mentioned in an official capacity at any of the companies which I've worked. But I do think that using colons excessively can start to make your code less readable and more of a pain to maintain.
I do tend to use these myself at times, for example when checking for cancel in one of my recent projects:
If _bCancel Then Status = CancelProcess() : Return Status
Putting this in kept my code readable than the alternative IF block.
But it can be taken too far, I've recently inherited a project which is replete with examples of taking colon usage too far :
Select Case GetStringValue(Index).Trim.ToLower
Case "yes", "y" : GetBooleanValue = True
Case "no", "n" : GetBooleanValue = False
Case Else : GetBooleanValue = Nothing
End Select
Personally I find the above to be a bit much.
I like this one
Using pro As New Process() : With pro
...
End With
End Using
I've seen it used in class declarations when using inheritance or implementing an interface:
Public Class DerivedClass : Inherits BaseClass
...
End Class
But like the others, I also discourage its use.
Chris
The answer to the question is No. Anything beyond No is purely subjective and wasteful irrespective of the answer outside of a simple No. Below is my waste of typing.
Are you some sort of slave? Do as you wish. You are the center of your universe not some stranger from StackOverflow. If you work for a company the question is mute because coding style would already be defined and completely out of your control. As for one's self, who in this universe is going to ever in all eternity look at let along care about your code.
I would choose A over B. As evident this shows the purpose of a colon without the use of a colon. It's to save space. Below saves space and makes code far more readable. Keeps It Simple Stupid. Same for ternary ? : usage. When the code is inherently complex then a colon, single line if then else, or ternary no longer should be considered.
'================================================================
'A
If somevalue1 = 0 Then AddLogTry("True") Else AddLogFalse("False")
If somevalue2 = 0 Then AddLogTry("True") Else AddLogFalse("False")
If somevalue3 = 0 Then AddLogTry("True") Else AddLogFalse("False")
'================================================================
'================================================================
'B
If somevlaue1 = 0 Then
AddLogTrue("True")
Else
AddLogFalse("False")
EndIf
If somevlaue2 = 0 Then
AddLogTrue("True")
Else
AddLogFalse("False")
EndIf
If somevlaue3 = 0 Then
AddLogTrue("True")
Else
AddLogFalse("False")
EndIf
'================================================================

What is readable code? What are the best practices to follow while naming variables?

Do you think x, y, z are good variable names? How will you explain a new programmer to write readable code?
Readable code means some combination of comments and variable and function naming that allows me to read the code once and understand it. If I have to read it more than once, or spend my time working through complicated loops or functions, there's room for improvement.
Good summary descriptions at the top of files and classes are useful to give the reader context and background information.
Clear names are important. Verbose names make it much easier to write readable code with far fewer comments.
Writing readable code is a skill that takes some time to learn. I personally like overly verbose names because they create self documenting code.
As already stated x, y, and z are good variables for 3D coordinates but probably bad for anything else...
If someone does not believe that names are important, just use a code obfuscator on some code then ask them to debug it :-).
(BTW that's the only situation where a code obfuscator can be useful IMHO)
There seems to be slightly different conventions per progamming language; however, the consensus these days is to...
use pascal case
make the name meaningful
end with a noun
Here is a decent recap of what Microsoft publishes as standard naming conventions for .NET
The inventor of python has published a style guide which includes naming conventions.
There was a time when Microsoft VC++ developers (myself included) actually rallied around what was known as Hungarian Notation
Certainly there are multiple schools of thought on this, but I would only use these for counters, and advise far more descriptive names for any other variables.
x, y and z can be perfectly good variable names. For example you might be writing code that refers to them in reference to a 3D cartesian coordinate system. These names are often used for the three axes in such a system and as such they would be well suited.
I would give them some maintenance work on some code with variables called x, y, z and let them realise for themselves that readability is vital...
95% of code viewing is not by the author, but by the customer that everyone forgets about - the next programmer. You owe it to her to make her life easy.
Good variable names describe exactly what they are without being overly complex. I always use descriptive names, even in loops (for instance, index instead of i). It helps keep track of what's going on, especially when I'm working on rewriting a particularly complex piece of code.
Well give them a chunk of bad code and ask them to debug it.
Take the following code (simple example)
<?php $a = fopen('/path/to/file.ext', 'w');$b = "NEW LINE\n";fwrite($a, $b);fclose($a);?>
The bug is: File only ever contains 1 line when it should be a log
Problem: 'w' in fopen should be 'a'
This obviously is a super easy example, if you want to give them a bigger more complicated example give them the WMD source and ask them to give you readable code in 2 hours, it will get your point across.
As long as x, y and z are (3D) Cartesian co-ordinates, then they're great names.
In a similar vein, i, j and k would be OK for loop variables.
In all cases, the variable names should relate to the data
x,y and z are acceptable variable names if they represent 3d coordinates, or if they're used for iterating over 2 or 3 dimensional arrays.
This code is fine as far as I'm concerned:
for(int x = 0; x < xsize ; x++)
{
for(int y = 0; y < ysize ; y++)
{
for(int z = 0; z < zsize ; z++)
{
DoSomething(data[x][y][z]);
...
This one is a short answer, but it works very well for me:
If it would need a code comment to describe it, then rethink the variable name.
So if it's obvious, why "x" was choosen, then they are good names. E.g. "i" as variable name in a loop is (often) pretty obvious.
An ideal variable name is both short (to make the code more compact) and descriptive (to help understanding the code).
Opinions differ on which of the two is more important. Personally, I'd say it depends on the scope of the variable. A variable used only inside a 3 line loop can get away with being single letter. A class field in a 500 line class better be pretty damn descriptive. The Spartan Programming philosophy says that as far as possible, all units of code should be small enough that variable names can be very short.
Readable code and good naming conventions are not the same thing!
A good name for a variable is one that allows you to understand (or reasonably guess) the purpose and type of the variable WITHOUT seeing the context in which it is used. Thus, "x" "y" and "z" say coordinates because that is a reasonable guess. Conversely, a bad name is one that leads you to a wrong likely guess. For example, if "x" "y" and "z" represent people.
A good name for a function is one that conveys everything you would need to know about it without having to consult its documentation. That is not always possible.
Readable code is first of all code whose structured could be understood even if you obfuscated all variable and function names. If you do that and can't figure out the control structure easily, you're screwed.
Once you have readable code and good naming, then maybe you'll have truly readable code.

What's bad about the VB With/End With keyword?

In this question, a user commented to never use the With block in VB. Why?
"Never" is a strong word.
I think it fine as long as you don't abuse it (like nesting)
IMHO - this is better:
With MyCommand.Parameters
.Count = 1
.Item(0).ParameterName = "#baz"
.Item(0).Value = fuz
End With
Than:
MyCommand.Parameters.Count = 1
MyCommand.Parameters.Item(0).ParameterName = "#baz"
MyCommand.Parameters.Item(0).Value = fuz
There is nothing wrong about the With keyword. It's true that it may reduce readibility when nested but the solution is simply don't use nested With.
There may be namespace problems in Delphi, which doesn't enforce a leading dot but that issue simply doesn't exist in VB.NET so the people that are posting rants about Delphi are losing their time in this question.
I think the real reason many people don't like the With keyword is that is not included in C* languages and many programmers automatically think that every feature not included in his/her favourite language is bad.
It's just not helpful compared to other options.
If you really miss it you can create a one or two character alias for your object instead. The alias only takes one line to setup, rather than two for the With block (With + End With lines).
The alias also gives you a quick mouse-over reference for the type of the variable. It provides a hook for the IDE to help you jump back to the top of the block if you want (though if the block is that large you have other problems). It can be passed as an argument to functions. And you can use it to reference an index property.
So we have an alternative that gives more function with less code.
Also see this question:
Why is the with() construct not included in C#, when it is really cool in VB.NET?
The with keyword is only sideswiped in a passing reference here in an hilarious article by the wonderful Verity Stob, but it's worth it for the vitriol: See the paragraph that starts
While we are on identifier confusion. The with keyword...
Worth reading the entire article!
The With keyword also provides another benefit - the object(s) in the With statement only need to be "qualified" once, which can improve performance. Check out the information on MSDN here:
http://msdn.microsoft.com/en-us/library/wc500chb(VS.80).aspx
So by all means, use it.