Softpanorama

Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
May the source be with you, but remember the KISS principle ;-)

Language Usage and Design Tips

News Scripting languages Recommended Books Recommended Links Classic Papers Software Engineering Programming as a Profession Programming style
Assembler C Cpp Java Pascal PL/1 Prolog Debugging
Compilers Lexical structure  Control Structures Data Structures Lexical analysis Recursive Descent Parsing Algorithms and Data Structures Coroutines
Brooks law Perl-based Bug Tracking Code Reviews and Inspections Code Metrics Structured programming Design patterns Extreme Programming CMM (Capability Maturity Model)
software Fashion Plagiarism Detection Tools Tips Quotes History Humor Etc

Avoiding blunders of mixing "==" and "=" in C-style languages

You can often reverse the sequence and put constant first like in

if ( 1==i)...
as
if ( 1=i)...
does not make any sense, such a blunder will be detected on syntax level.

Dealing with unbalanced "{" and "}" problem in C-style languages

One of the nasty problems with C, C++, Java, Perl and other C-style languages is that missing brackets are pretty difficult to find. One effective solution that was first implemented in PL/1 and calculation of nesting (in compiler listing) and ability of multiple closure of blocks in the end statement (PL/1 did not use brackets {}, they were introduced in C).

In C one can use pseudo comments that signify nesting level zero and check those points with special program or by writing an editor macro.

Many editors have the ability to point to the closing bracket for any given opening bracket and vise versa. This is also useful but less efficient way to solve the problem.  

Problem of unclosed literal

Specifying max length of literals is an effecting way of catching missing quote. This was implemented in PL/1 compilers. You can also have an option to limit literal to a single line.

In general multi-line literals should have different lexical markers (like "here" construct in shell).

Some language like Perl provide opportunity to use concantenation operator foe splitting liteals that is processes in compile time. This is an effective way to avoid the problem when programming if you can specify one line literal limit.

Editors can use coloring to detect unclosed literal problem. 


Commenting out blocks  of code

This is best done not with comments but with a preprocessor in the languages that has one (PL/1, C, etc)

The "dangling else" problem

Having both an if-else and an if statement leads to some possibilities of confusion when one of the clause of a selection statement is itself a selection statement. For example, the C code

if (level >= good)
   if (level == excellent)
      cout << "excellent" << endl;
else
   cout << "bad" << endl;

is intended to process a three-state situation in which something can be bad, good or (as a special case of good) excellent; it is supposed to print an appropriate description for the excellent and bad cases, and print nothing for the good case. The indentation of the code reflects these expectations. Unfortunately, the code does not do this. Instead, it prints excellent for the excellent case, bad for the good case, and nothing for the bad case.

The problem is deciding which if matches the else in this expression. The basic rule is

an else matches the nearest previous unmatched if

There are two ways to avoid the dangling else problem:

In fact, you can avoid the dangling else problem completely by always using brackets around the clauses of an if or if-else statement, even if they only enclose a single statement.
So a good strategy for notation of if-else statements is always use { brace brackets } around the clauses of an if-else or if statement
Always use { brace brackets } around the clauses of an if-else or if statement
(This strategy also helps if you need to cut-and-paste more code into one of the clauses: if a clause consists of only one statement, without enclosing brace brackets, and you add another statement to it, then you also need to add the brace brackets. Having the brace brackets there already makes the job easier.)

Exceptions

Early computer hardware handled errors it detected in one of 4 ways:

  1. By setting a program-testable flag after any instruction which produced an arithmetic error (divide by zero, overflow); the flag would be reset after the next instruction.

  2. Same as (1), but the flag would only be reset when tested by a special conditional branch instruction;

  3. By generating an "interrupt" (called here a "trap").

  4. By generating an "error value" number, and continuing computation.

To detect an error in case (1), the program would have to include a branch to test the flag after every operation, and doing so would increase the code's complexity substantially. Case (2) allows a block of instructions to be executed, and tested jointly for acceptable execution. Case (3) allows the flexibility of both, together with the option of writing a common "error handling" routine, which could even determine where in the program the error occurred, and "recover" from it (e.g., by setting the result of an arithmetic underflow to zero, and resuming the computation after the error-producing instruction). Case (4) was introduced for floating-point computation, and is helpful in allowing data-parallel computation to proceed without introducing separate computation paths for each datum. "Exceptions" in high-level languages represent the "interrupt" option in those languages, with some limitations.

An exception is an object (data-containing record) produced when an error is detected by hardware, or "thrown" explicitly by the program. The record can contain all the information that would be needed to "resume" execution after the exception-producing operation. When an exception is thrown, control passes immediately to an exception handling routine selected by rules of the language. Usually, each block or subroutine has the option of establishing an exception-handler for itself; the exception handler invoked is selected by: A. The type of exception, and B. The handler associated with the most-recently invoked block. That is, blocks are terminated until one is reached which contains an exception-handler for the particular "exception" that was thrown. In some languages, the exception-handler has the option of ending with "resume <expression>", which returns to the point after the exception was thrown, and (if in the middle of an expression) uses <expression> as the operation's result. E.g. Java:

Any method that throws an exception must declare that fact;

A method that uses an exception-throwing method must either declare that IT throws the same exception, or provide a handler for it;

Handlers (the form is "catch <Exception name> {}") cannot "resume", and cannot find out where the exception they handle came from.

Handlers are very useful for quickly terminating a deep nest of procedures, say in a compiler that detects a syntax error, and wants to abandon part of the parsing, and start skipping input until it locates, say, a ";". However, the current designs have some problems -- handlers may not have access to variables within the block that invoked them. Logically, they provide "sneak" exits from loops and other constructs, which may cause loop behavior to be hard to understand.

Coroutines

Coroutines are subroutines, with neither the caller nor the callee being "dominant". Instead, they allow "democratic" program-controlled interleaving of instructions generated by both. Suppose A calls B. Then B wants to allow A to perform some more computation. B can "resume A", which then runs until it "resumes B". Then A can execute until it needs data from B, which might produce part of that data, and resume A, to examine or compute with the part produced so far. Coroutines have been exploited in the past in compilers, where the "parser" asks the "lexer" to run until the lexer has to stop (say at end of line). The lexer then resumes the parser to process that line's data, and is itself resumed to continue reading input characters. The text also shows an example of a tree-comparison problem solved logically by coroutines. Their advantage is that the cooperative behavior allows the "high-level" program to terminate the computation early, before the companion routine "completes" its assigned task. I have also used them to simulate parallel computation, when I want to build my own control over the task scheduling process.

As an interesting exercise, the text shows how coroutines can be simulated in C, using C's "setjmp()" and "longjmp()" library procedures. These procedures are intended for use in setting exception-handler routines. However, they have the property that they create concrete realizations of a "stopped" task -- an instruction counter, along with a variable reference context is stored when a setjmp occurs, and is resumed when a longjmp to the saved item is performed. The longjmp(Buf, Return) causes the setjmp(Buf) to return (again), this time returning value Return, instead of the 0 setjmp(Buf) returns when it is called.

Iterators

Iterators are a special flavor of coroutines. They produce a sequence of values, rather than just one. Each time an iterator executes a yield <value> statement, the iterator returns <value>. When it is called again, the iterator picks up its computation after the yield, so it can compute the next value to return. In CLU, when the iterator finishes, the controlling for loop in which it is being called also terminates.

Java also provides the functionality of iterators. A Collection object in Java can produce an iterator object IT, with methods next(), hasNext(), and remove(). Repeatedly calling next() until hasNext() returns false steps through the elements of the collection. This seems to provide the essential features of an iterator. It also appears that no special internal mechanism is needed to implement Java Iterators -- each iterator maintains its own "state" in it private variables, and its methods can at any time test and modify that state.

Continuations

A "continuation" is a parameter (descriptor or pointer) which represents "the remainder of the computation to be performed". The language Io uses continuations, together with a goto which passes parameters, as the sole control structure. Some syntactic fudging let you think of such goto's as ordinary procedures:

declare writeTwice: -> N; Continuation;

Write N; Write N; Continuation

writeTwice 7;

Write 6;

terminate.

writeTwice is declared to accept N, and Continuation as parameters. The "call" on writeTwice performs a goto to its declaration, which, which after writing N twice, "calls" the Continuation. In fact, the actual parameter corresponding to Continuation is
"Write 6; terminate."

Continuations of a sort are present in LISP...

C Continuations

The "setjmp(Buf)" operation acts as a form of "continuation" in C. On call, it takes a snapshot of the current environment, and places it into data structure Buf. A subsequent "longjmp(Buf, ReturnValue)" causes the original "setjmp(Buf)" to return again. The first return from setjmp() returns 0, while subsequent returns via "longjmp()" return the ReturnValue instead. A mechanism like this allows the "concretization" of a "program in operation", allowing this conceptual object to be stored, copied, and "executed" under full program control. This forms the basis for the implementation of other control structures, like co-routines, in C.

General comments on control structures

    1. Exceptions have simplicity of expression, address a common problem, and are easy to understand and to implement. They first were inplemend in PL/I and then copied in Ada, C++, Java, Python and other languages.

    2. Coroutines add  important functionality (they define a form of parallelism). They are easy to think about as separate passes and you can separate coroutines into independent passws and debug it separatly. Compared to functions., and they require that each object has its own stack.

    3. Continuations are powerful and elegant, but very confusing to use.



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2018 by Dr. Nikolai Bezroukov. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) in the author free time and without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

 

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: September, 12, 2017