Habits That Help: Developing Good Programming Style Casey Cantrell, Clarion Consulting, Los Angeles, CA

Total Page:16

File Type:pdf, Size:1020Kb

Habits That Help: Developing Good Programming Style Casey Cantrell, Clarion Consulting, Los Angeles, CA Habits that Help: Developing Good Programming Style Casey Cantrell, Clarion Consulting, Los Angeles, CA ABSTRACT The first goal of most new programmers is to write programs that run. Often, more time is spent checking and debugging programs than is spent writing them. As programmers mature, they typically find it easier to test, debug and document their programs. This occurs in large part because they have developed a consistent programming style and acquired habits that expedite error detection and documentation. Putting into practice a few simple procedures will yield significant benefits: greater accuracy, fewer hours invested and less aggravation. This paper will discuss practical programming ‘habits’ that will make the programmer’s work easier. INTRODUCTION One evening many years ago, while talking shop with some work mates, the conversation turned to the question of "What makes a good program?" Without thinking much about it, I stated imperiously that a good program was one that could complete a task with the fewest lines of code. My colleague, and senior partner, considered this for a while before offering his definition. “A good program," he said, " is one that can complete a task with the fewest lines of code that someone else can understand.” In the intervening years, I've come to realize how right he was and would delete only the words “someone else” from his definition. While it is certainly important to write code than others can work with, the programmer who does so also profits from the effort. Well-written programs are easier to maintain, modify and debug. Programs that are well organized, conforming to a consistent style facilitate documentation. Carefully planned programs provide for efficient use of the most important resource of all: the programmer’s time. Time invested in writing good programs will pay off handsomely for everyone in the long run. Although each programmer will develop his/her own style, there are habits common to all good programmers. First, they write with clarity and consistency, opting for simplicity whenever possible. Second, they test their programs and meticulously checks results. Third, the good programmer writes flexibility into his programs. Since his programs are "data-driven", they require little or no modification when the data change. Finally, the good programmer documents extensively. In short, good programmers write with an eye towards simplicity and flexibility. Their programs work, require little maintenance and are organized to expedite documentation. GOOD HABIT #1: WRITE CLEAR CODE Writing clear code involves not only writing programs that are easy to understand, but writing programs that are easy to read. Get in the habit of using adequate spacing, blank lines and indentation. SAS® is free format, meaning you may start your program on any column of any line, continue your program over several lines, and include as many blank columns and blank lines as you want. Like a good designer, use white space to your advantage. Do not try to squeeze your programs into as few lines as possible, nor put multiple statements on a single line. Remember that other programmers may read your programs on their computers, so format your code to fit comfortably on the screen. The programs below differ only in layout, but Program 1b is far easier to read.. DATA BOTHGEND; MERGE MEN (RENAME=(POP = MENPOP)) WOMEN; BY RACE AGE; PCT_MEN = (MENPOP/(MENPOP+ POP))* 100; Run; Program 1a DATA BOTHGEND; MERGE MEN (RENAME=(POP = MENPOP)) Easier WOMEN; to read BY RACE AGE; PCT_MEN = (MENPOP/(MENPOP+ POP))* 100; run; Program 1b 1 These two programs are also identical. Program 2b uses spacing and indention to improve legibility. Data bothgend; set male (in=menfile) female (in=womfile); if menfile then sex='M'; else if womfile then sex=’F'; run; Program 2a Data bothgend; Easier Set men (in=menfile) to read women (in=womfile); if menfile then sex = 'M'; else if womfile then sex = 'F'; run; Program 2b Get in the habit of beginning each program with a program header. The header should include your name, dates the program was written and modified, the program file name and location, and a description of what the program does. You may also include input and output files and any pertinent notes. An example follows. /*******************************************************************************/ /* MDsample.sas CC 2/21/10 */ /* c:/CMC3/Baseline/SAS Programs */ /* */ /* Reads: c:/CMC/Baseline/Data/PatientWave1 */ /* Writes: c:/CMC/Baseline/Analyis/PilotSample */ /* Create a sample of patients who completed the survey representing */ /* 7.5% of each MD’s patients. */ /* */ /* Modified 3/5/10 to increase sample to 10%. */ /* Note: Dr. Smith retired 12/31/09. Dr. Jones has taken over the practice */ /*******************************************************************************/ Get in the habit of using comments throughout your programs. Explain what you are doing and why. Describe problems, anomalies and complicated logic. If there is anything unusual about your program or data, make note of that. What may seem perfectly clear to you at 3am tonight may not be as clear six months from now. Comments are also a valuable way to organize and clarify your own thinking. /* Bookend style comment */ * This is also a comment ; SAS pays no attention to semicolons used within bookend style comments, so you may block out entire sections of code you do not want SAS to execute. This is especially helpful when testing or debugging a program. Use the label option on the data step to identify and describe files. If the file is a subset of another file, make note of that on the label. Later, this information may prove invaluable when you are searching for a particular file or trying to figure out how one file differs from several others just like it. Program 3 utilizes the label statement, as shown in Figure 1. data analysis1 (label=Subset of COMPLETED. Deletes records for MDs who did not complete baseline interview.); set newstat.allwave2; run; Program 3 2 Figure 1 Separate steps and conceptually distinct tasks for clarity. SAS will end and execute a step when it encounters the key words DATA or PROC, which designate the start of a new step. Nonetheless, get in the habit of including the "run;" statement to delineate steps in your programs. This will make it easier to follow your program logic and help you resist the temptation to mix DATA and PROC steps inappropriately. Program 3b illustrates the use of the “run;” statement, which is not used in Program 3a. DATA ages; dog_age=5; humanyrs=dog_age * 7; PROC PRINT data=ages; TITLE “Dog’s age in human years”; Program 3a DATA ages; dog_age=5; humanyrs=dog_age * 7; run; Include RUN; PROC PRINT data=ages; statement TITLE “Dog age in human years”; run; Program 3b Simplify complex expressions. Break tasks into steps. Use multiple statements if necessary to clarify your logic. Programs 4a and 4b do exactly the same thing: read a text variable (patient) and write out a new variable (name) in a different format, as illustrated in Figure 2. Which program is easier to read? Which would be easier to modify? Figure 2 data mailing; set patnames; name=substr(patient,index(patient,',')+2,length (patient)-index(patient,',')-1) || ' || substr(patient,1,index(patient,',')-1); run; Program 4a 3 data mailing; Easier set patnames; to read comma = index(patient,','); & follow longn = length (patient); lname = substr(patient,1,comma-1); fname = substr(patient,comma+2,longn - comma-1); pat_name =trim(fname) || ' ' || lname; run; Program 4b Avoid compound expressions when possible, and be particularly stingy in your use of NOTs and nested ANDs/ORs. Use DO LOOPS instead to clarify your logic and remember that compound expressions are less efficient, since SAS will evaluate each condition even when the first one is false. Evaluations stated in the affirmative are also easier to follow. Consider the following programs. Each in the pair performs the same task. Which is easier to follow? if sex=‘M’ AND race NE ‘B’OR race NE ‘W’’…; Program 5a if sex = ‘M’ then do; if race ne ‘B’ and race ne ‘W’ … end; DO loop Program 5b if elisa=1 &wb24 >1 & wb24 <4 & (wb120=1 or wb160=1) then westblot='1'; Program 6a if elisa = 1 then do; if 1 < wb24 < 4 then do; DO loop if wb120=1 or wb160=1 then westblot='1'; end; end; Program 6b GOOD HABIT #2: DEVELOP A CONSISTENT STYLE Get in the habit of organizing your programs using a consistent scheme. Define arrays, create labels and declare length attributes at the same place in your programs and group similar statements together. This makes it easier to see what you've done and easier to modify. Programs 7a and 7b again perform the same tasks. Data forlogit; set analyfile; LENGTH assignment length preteen $1. if 0 < age < 12 then preteen ='1'; else preteen = '0'; LABEL label preteen = 'Age < 12 years'; FORMAT assignment format preteen $teenf.; LENGTH assignment length senior $1.; if 65 < age < 99 then senior ='1'; else senior = '0'; LABEL label senior = 'Age > 65"; format senior $seniorf.; FORMAT assignment Program 7a 4 Data forlogit; set analyfile; LENGTH assignments length preteen senior $1.; if 0 < age < 12 then preteen ='1'; else preteen = '0'; if 65 < age < 99 then senior ='1'; else senior = '0'; LABEL assignments label preteen = 'Age < 12 years senior = 'Age > 65"; format preteen $teenform. Senior $seniorform.; FORMAT Program 7b assignments Keep SAS default actions in mind. Remember that new variables built from existing ones will inherit the attribute type of the original variable. Use explicit length statements when necessary and define them before using the variable in your code. Figure 3 illustrates the output generated from the Program 8a. Use of the LENGTH statement in Program 8b corrects the truncation as shown in figure 4.
Recommended publications
  • Inf 212 Analysis of Prog. Langs Elements of Imperative Programming Style
    INF 212 ANALYSIS OF PROG. LANGS ELEMENTS OF IMPERATIVE PROGRAMMING STYLE Instructors: Kaj Dreef Copyright © Instructors. Objectives Level up on things that you may already know… ! Machine model of imperative programs ! Structured vs. unstructured control flow ! Assignment ! Variables and names ! Lexical scope and blocks ! Expressions and statements …so to understand existing languages better Imperative Programming 3 Oldest and most popular paradigm ! Fortran, Algol, C, Java … Mirrors computer architecture ! In a von Neumann machine, memory holds instructions and data Control-flow statements ! Conditional and unconditional (GO TO) branches, loops Key operation: assignment ! Side effect: updating state (i.e., memory) of the machine Simplified Machine Model 4 Registers Code Data Stack Program counter Environment Heap pointer Memory Management 5 Registers, Code segment, Program counter ! Ignore registers (for our purposes) and details of instruction set Data segment ! Stack contains data related to block entry/exit ! Heap contains data of varying lifetime ! Environment pointer points to current stack position ■ Block entry: add new activation record to stack ■ Block exit: remove most recent activation record Control Flow 6 Control flow in imperative languages is most often designed to be sequential ! Instructions executed in order they are written ! Some also support concurrent execution (Java) But… Goto in C # include <stdio.h> int main(){ float num,average,sum; int i,n; printf("Maximum no. of inputs: "); scanf("%d",&n); for(i=1;i<=n;++i){
    [Show full text]
  • Jalopy User's Guide V. 1.9.4
    Jalopy - User’s Guide v. 1.9.4 Jalopy - User’s Guide v. 1.9.4 Copyright © 2003-2010 TRIEMAX Software Contents Acknowledgments . vii Introduction . ix PART I Core . 1 CHAPTER 1 Installation . 3 1.1 System requirements . 3 1.2 Prerequisites . 3 1.3 Wizard Installation . 4 1.3.1 Welcome . 4 1.3.2 License Agreement . 5 1.3.3 Installation Features . 5 1.3.4 Online Help System (optional) . 8 1.3.5 Settings Import (optional) . 9 1.3.6 Configure plug-in Defaults . 10 1.3.7 Confirmation . 11 1.3.8 Installation . 12 1.3.9 Finish . 13 1.4 Silent Installation . 14 1.5 Manual Installation . 16 CHAPTER 2 Configuration . 17 2.1 Overview . 17 2.1.1 Preferences GUI . 18 2.1.2 Settings files . 29 2.2 Global . 29 2.2.1 General . 29 2.2.2 Misc . 32 2.2.3 Auto . 35 2.3 File Types . 36 2.3.1 File types . 36 2.3.2 File extensions . 37 2.4 Environment . 38 2.4.1 Custom variables . 38 2.4.2 System variables . 40 2.4.3 Local variables . 41 2.4.4 Usage . 42 2.4.5 Date/Time . 44 2.5 Exclusions . 44 2.5.1 Exclusion patterns . 45 2.6 Messages . 46 2.6.1 Categories . 47 2.6.2 Logging . 48 2.6.3 Misc . 49 2.7 Repository . 49 2.7.1 Searching the repository . 50 2.7.2 Displaying info about the repository . 50 2.7.3 Adding libraries to the repository . 50 2.7.4 Removing the repository .
    [Show full text]
  • C Style and Coding Standards
    -- -- -1- C Style and Coding Standards Glenn Skinner Suryakanta Shah Bill Shannon AT&T Information System Sun Microsystems ABSTRACT This document describes a set of coding standards and recommendations for programs written in the C language at AT&T and Sun Microsystems. The purpose of having these standards is to facilitate sharing of each other’s code, as well as to enable construction of tools (e.g., editors, formatters). Through the use of these tools, programmers will be helped in the development of their programs. This document is based on a similar document written by L.W. Cannon, R.A. Elliott, L.W. Kirchhoff, J.H. Miller, J.M. Milner, R.W. Mitze, E.P. Schan, N.O. Whittington at Bell Labs. -- -- -2- C Style and Coding Standards Glenn Skinner Suryakanta Shah Bill Shannon AT&T Information System Sun Microsystems 1. Introduction The scope of this document is the coding style used at AT&T and Sun in writing C programs. A common coding style makes it easier for several people to cooperate in the development of the same program. Using uniform coding style to develop systems will improve readability and facilitate maintenance. In addition, it will enable the construction of tools that incorporate knowledge of these standards to help programmers in the development of programs. For certain style issues, such as the number of spaces used for indentation and the format of variable declarations, no clear consensus exists. In these cases, we have documented the various styles that are most frequently used. We strongly recommend, however, that within a particular project, and certainly within a package or module, only one style be employed.
    [Show full text]
  • A Description of One Programmer's Programming Style Revisited
    A Description of One Programmer’s Programming Style Revisited Adam N. Rosenberg 1990 August 1 2001 October 1 ABSTRACT We present the outlook of a programmer at AT&T Bell Labs who has written much code during his eight years there and thirteen years in other places. This document describes the author’s own programming style and what he considers important in generating reli- able, readable, and maintainable code. Since this document is the opinions and prejudices of an individual, it is written in the first person in a conversational tone, and with subjects covered in no particular order. It is intended to be a repository of good questions rather than a source of answers. The author feels that many programmers suffer from gross inattention to detail in writing code. He suggests that clarity and consistency will be rewarded sooner than most people think. A veteran of many languages and operating systems, the author today finds himself using the MS-DOS and UNIXr operating systems and the FORTRAN and C languages. The examples here are all either FORTRAN or C. A decade later the author feels that programming productivity in our “post modern” world has decreased sharply from 1990 to 2000. Many of the reasons for this decline were discussed in the original version of this paper. Our pleasure in prescient prognostication is mitigated by frustration with the “dumbing down” of computing in general. Based on this unhappy downturn of programming education and style, we have added materal (in italics) emphasizing areas of recent concern. The original text and examples (still in regular type) have been left virtually intact.
    [Show full text]
  • Comparative Studies of 10 Programming Languages Within 10 Diverse Criteria Revision 1.0
    Comparative Studies of 10 Programming Languages within 10 Diverse Criteria Revision 1.0 Rana Naim∗ Mohammad Fahim Nizam† Concordia University Montreal, Concordia University Montreal, Quebec, Canada Quebec, Canada [email protected] [email protected] Sheetal Hanamasagar‡ Jalal Noureddine§ Concordia University Montreal, Concordia University Montreal, Quebec, Canada Quebec, Canada [email protected] [email protected] Marinela Miladinova¶ Concordia University Montreal, Quebec, Canada [email protected] Abstract This is a survey on the programming languages: C++, JavaScript, AspectJ, C#, Haskell, Java, PHP, Scala, Scheme, and BPEL. Our survey work involves a comparative study of these ten programming languages with respect to the following criteria: secure programming practices, web application development, web service composition, OOP-based abstractions, reflection, aspect orientation, functional programming, declarative programming, batch scripting, and UI prototyping. We study these languages in the context of the above mentioned criteria and the level of support they provide for each one of them. Keywords: programming languages, programming paradigms, language features, language design and implementation 1 Introduction Choosing the best language that would satisfy all requirements for the given problem domain can be a difficult task. Some languages are better suited for specific applications than others. In order to select the proper one for the specific problem domain, one has to know what features it provides to support the requirements. Different languages support different paradigms, provide different abstractions, and have different levels of expressive power. Some are better suited to express algorithms and others are targeting the non-technical users. The question is then what is the best tool for a particular problem.
    [Show full text]
  • DSS: C/C++ Programming Style Guidelines
    C/C++ Programming Style Guidelines C/C++ Programming Style Guidelines Table of Contents Introduction File Contents File Format Choosing Meaningful Names Comments Syntax and Language Issues Conclusion Appendix A. Review Checklist References De gustibus non est disputandum. Introduction This document contains the guidelines for writing C/C++ code for Dynamic Software Solutions. The point of a style guide is to greater uniformity in the appearance of source code. The benefit is enhanced readability and hence maintainability for the code. Wherever possible, we adopt stylistic conventions that have been proved to contribute positively to readability and/or maintainability. Before code can be considered for peer review the author must check that it adheres to these guidelines. This may be considered a prerequisite for the review process. A checklist is provided at the end of this document to aid in validating the source code's style. Where code fails to adhere to the conventions prescribed here may be considered a defect during the review process. If you have not already, please study Code Complete by Steve McConnell. This book provides a detailed discussion on all things related to building software systems. It also includes references to statistical studies on many of the stylistic elements that affect program maintainability. Another valuable source of solid programming practice tips is The Practice of Programming by Brian W. Kernighan and Rob Pike. Scott Meyers' books, Effective C++ and More Effective C++ should be considered required reading for any C++ programmer. And what person would be considered complete without having read The Elements of Style by Strunk and White? References The C++ Programming Language, Bjarne Stroustrup, 0-201-88954-4, Addison-Wesley, 1997.
    [Show full text]
  • Javascript Code Quality Analysis
    JavaScript Code Quality Analysis Master’s Thesis Joost-Wim Boekesteijn JavaScript Code Quality Analysis THESIS submitted in partial fulfillment of the requirements for the degree of MASTER OF SCIENCE in COMPUTER SCIENCE by Joost-Wim Boekesteijn born in Hoogeveen, the Netherlands Software Engineering Research Group m-industries Department of Software Technology M-Industries BV Faculty EEMCS, Delft University of Technology Rotterdamseweg 183c Delft, the Netherlands Delft, the Netherlands www.ewi.tudelft.nl www.m-industries.com c 2012 Joost-Wim Boekesteijn. JavaScript Code Quality Analysis Author: Joost-Wim Boekesteijn Student id: 1174355 Email: [email protected] Abstract Static analysis techniques provide a means to detect software errors early in the development process, without actually having to run the software that is being analyzed. These techniques are common for statically typed languages and have found their way into IDEs such as Eclipse and Visual Studio. However, applying the same techniques to dynamically typed languages is much less common. Tool support is less mature and the amount of published research is relatively small. For this project, we design and build a static analyis tool for JavaScript code. We start by giving background information on relevant parts of the JavaScript language, followed by a survey of existing tools and research. In the design of our analysis tool, we achieved a clear separation of responsibilities between the different modules for parsing, analysis, rule definition and reporting. The level of detail in the default reporter makes our tool an ideal candidate for integration in a JavaScript IDE. On the other hand, our tool is also suited for batch analysis of large code collections.
    [Show full text]
  • How Developers Engage with Static Analysis Tools in Different Contexts
    Noname manuscript No. (will be inserted by the editor) How Developers Engage with Static Analysis Tools in Different Contexts Carmine Vassallo · Sebastiano Panichella · Fabio Palomba · Sebastian Proksch · Harald C. Gall · Andy Zaidman This is an author-generated version. The final publication will be available at Springer. Abstract Automatic static analysis tools (ASATs) are instruments that sup- port code quality assessment by automatically detecting defects and design issues. Despite their popularity, they are characterized by (i) a high false positive rate and (ii) the low comprehensibility of the generated warnings. However, no prior studies have investigated the usage of ASATs in different development contexts (e.g., code reviews, regular development), nor how open source projects integrate ASATs into their workflows. These perspectives are paramount to improve the prioritization of the identified warnings. To shed light on the actual ASATs usage practices, in this paper we first survey 56 developers (66% from industry and 34% from open source projects) and inter- view 11 industrial experts leveraging ASATs in their workflow with the aim of understanding how they use ASATs in different contexts. Furthermore, to in- vestigate how ASATs are being used in the workflows of open source projects, we manually inspect the contribution guidelines of 176 open-source systems and extract the ASATs' configuration and build files from their corresponding GitHub repositories. Our study highlights that (i) 71% of developers do pay attention to different warning categories depending on the development con- text; (ii) 63% of our respondents rely on specific factors (e.g., team policies and composition) when prioritizing warnings to fix during their programming; and (iii) 66% of the projects define how to use specific ASATs, but only 37% enforce their usage for new contributions.
    [Show full text]
  • Software Engineer [email protected] - 720-565-1569
    Gabriel Perry – Software Engineer [email protected] - 720-565-1569 SUMMARY Software Engineer living in Boulder, Colorado with 17+ years of experience in software development in multiple environments with a focus on web technologies. Strong analytic and problem-solving skills, self- motivated, detail-oriented, creative, open-minded, and friendly. Writing maintainable, readable, and well- documented code is a passion. PROFESSIONAL EXPERIENCE VCA Animal Hospitals, Westminster, CO, (9/2018 – Present) Software Engineer - Camp Bow Wow Software development using Angular/Typescript for Camp Bow Wow, a leading doggy daycare and boarding franchise with 150+ locations across the United States. Technologies Used: Typescript, Angular 6/7/8/9, NgRx, RxJS, Jasmine, Karma, Angular Flex Layout, Angular Material, CSS/Sass. Dev Platform: MacBook Pro, Linux. Tools: PhpStorm, WebStorm, Chrome, Git, Bitbucket, Sourcetree, Insomnia, MySQL Workbench, and Jira. New feature and maintenance development in a highly collaborative, fast paced, agile environment. Significant system refactorizations and improvements: Payments, Invoices, Reports, internal libraries/utilities. Massive endpoint/API integrations/updates in support of significant database and endpoint/API upgrades. Removing NgRx layer and replacing it with direct backend API calls. Advocated for the overall improvement of code quality, development processes and (written) communication for the Frontend team. o Designed a Typescript and Angular programming style-guide which was adopted by the Frontend development team. o Advocated for and helped the team adopt regular code-reviews using Bitbucket. o Encouraged the team to write more unit tests, especially for the tricky parts of the code. o Worked with management to help refine their Agile/Scrum development life-cycle. o Encouraged dev team to be more disciplined regarding code and process documentation as well as design specs/artifacts.
    [Show full text]
  • Elements of Programming Style
    THE ELEMENTS OF PROGRAMMING STYLE SECOND EDITION Kernighan and Plauger THE ELEMENTS OF PROGRAMMING STYLE Second Edition Brian W. Kernighan Bell laboratories Murray Hill, New Jersey P. J. Plauger Yourdon, Inc. New York, New York McGRAW-HILL BOOK COMPANY New York St. Lou1; San Franc1;co Auckland Bogota Du;seldorf London Madnd Mexico Montreal New Delhi Panama Pan' Sao Paulo Singapore Sydney Tokyo Toronto Library of Congress Cataloging in Publication Data Kernighan, Brian W. The elements of programming style. Bibliography: p. Includes index. I. Electronic digital computers-Programming. I. Plauger, P.J., date joint author. II. Title. QA 76.6.K47 1978 001.6'42 78-3498 ISBN 0-07-034207-5 The Elements of Programming Style Copyright © 1978, 1974 by Bell Telephone Laboratories, Incorporated. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopy­ ing, recording, or otherwise, without the prior written permission of Bell Laboratories. Printed in the United States of America. 12 13 14 15 DODO 8 9 This book was set in Times Roman and Courier 12 by the authors, using a Graphic Sys­ tems phototypesetter driven by a PDP-11/70 running under the UNIX operating system. UNIX is a Trademark of Bell Laboratories. We are deeply indebted to the following authors and publishers for their kind permission to reproduce excerpts from the following copyrighted material: R V Andree, J P Andree, and D D Andree, Computer Programmmg Techniques, A nalys1s, and Mathematics. Copyright © 1973 by R V Andree By permission of Prentice-Hall, Inc F Bates and M L Douglas, Programmmg Language/One with Structured Programming (Thtrd Edmon) Copyright © 1975 by Prentice-Hall, Inc Reprinted by permission C R Bauer and A P Peluso, Basic Fortran IV with Waifor & Wa(/iv.
    [Show full text]
  • Self-Study Guide 2: Programming in Fortran 95
    University of Cambridge Department of Physics Computational Physics Self-study guide 2 Programming in Fortran 95 Dr. Rachael Padman Michaelmas 2007 Contents 1. THE BASICS 3 1.1 A very simple program 3 1.2 Running the program 4 1.3 Variables and expressions 5 1.4 Other variable types: integer, complex and character 8 1.5 Intrinsic functions 11 1.6 Logical controls 13 1.7 Advanced use of if and logical comparisons 15 1.8 Repeating ourselves with loops: do 16 1.9 The stop statement 17 1.10 Arrays 17 1.11 Array arithmetic 19 2 GOOD PROGRAMMING STYLE 21 2.1 Readability 21 2.2 Self-checking code 22 2.3 Write clear code that relates to the physics 22 3. INPUT TO AND OUTPUT FROM A F95 PROGRAM 24 3.1 F95 statements for I/O 24 4 GRAPHICS AND VISUALISATION 27 4.1 Plotting a data file 27 4.2 Getting help 28 4.3 Further examples 28 4.4 Printing graphs into PostScript files 29 SUGGESTED EXERCISE 1 30 5. PROGRAM ORGANISATION: FUNCTIONS AND SUBROUTINES 31 5.1 Functions 31 5.2 Formal definition 33 5.3 Subroutines 34 5.4 Local and global variables 34 5.5 Passing arrays to subroutines and functions 35 5.5.1 Size and shape of array known 35 5.5.2 Arrays of unknown shape and size 35 5.6 The intent and save attributes 36 6. USING MODULES 38 6.1 Modules 38 6.2 public and private attributes 41 7 NUMERICAL PRECISION AND MORE ABOUT VARIABLES 42 7.1 Entering numerical values 42 7.2 Numerical Accuracy 42 1 8 USE OF NUMERICAL LIBRARIES: NAG 44 8.1 A simple NAG example 44 8.2 A non-trivial NAG example: matrix determinant 44 9 SOME MORE TOPICS 47 9.1 The case statement and more about if 47 9.2 Other forms of do loops 48 SUGGESTED EXERCISE 2 49 Acknowledgements: This handout was originally prepared by Dr.
    [Show full text]
  • Comparing LISP and Object-Oriented Programming Languages
    Wang 1 Pengfei Wang Professor Christopher A. Healy Computer Science 475 11 April 2016 Compare LISP with Object-Oriented Programming Languages Introduction LISP, which stands for List Processor, is a family of functional programming languages, invented by John McCarthy in MIT based on Lambda Calculus in 1958. It is the second-oldest high-level programming language and it was originally designed for Artificial Intelligence, but it is a good general-purpose language as well. This paper is going to discuss the differences between LISP and Object-Oriented Languages, focusing mainly on LISP. This paper is going to firstly introduce functional programming language and LISP. Then, advantages and disadvantages of LISP comparing to object-oriented languages will be discussed, and finally a specific case study will be done. Functional Programming Languages and List Processor Typically, programming languages are divided into two general types, imperative languages and declarative languages. The computer program written in imperative languages consists of statements, instructions, which indicate how (and in what order) a computation should be done. Imperative languages include all of the object-oriented languages. On the other hand, declarative languages define functions, formulas or relationships. Declarative languages do not specify how the functions are performed step-by-step in program. Functional Wang 2 programming language is one type of the declarative languages. ;; Example: Written in Common LISP (format t “Result: ~A.~%” (* 2 (+ 2 3))) ; functions /* Example: Written in C*/ int a = 2 + 3; /*statement*/ int b = a * 2; /*statement*/ printf("Result: %d.\n", b); /*statement*/ Function languages employ a computational model based on the recursive definition of functions.
    [Show full text]