text:
• Corpus ID: 235377032

# Energy-Based Models for Code Generation under Compilability Constraints

@article{Korbak2021EnergyBasedMF,
title={Energy-Based Models for Code Generation under Compilability Constraints},
author={Tomasz Korbak and Hady ElSahar and Marc Dymetman and Germ{\'a}n Kruszewski},
journal={ArXiv},
year={2021},
volume={abs/2106.04985}
}
• Published 9 June 2021
• Computer Science
• ArXiv
Neural language models can be successfully trained on source code, leading to applications such as code completion. However, their versatile autoregressive self-supervision objective overlooks important global sequence-level features that are present in the data such as syntactic correctness or compilability. In this work, we pose the problem of learning to generate compilable code as constraint satisfaction. We define an Energy-Based Model (EBM) representing a pre-trained generative model with…
6 Citations

## Figures and Tables from this paper

### Compilable Neural Code Generation with Compiler Feedback

• Computer Science
FINDINGS
• 2022
To improve compilability of the generated programs, this paper proposes COMPCODER, a three-stage pipeline utilizing compiler feedback for compilable code generation, including language model fine-tuning,Compilability reinforcement, and compilabilities discrimination.

### Controlling Conditional Language Models without Catastrophic Forgetting

• Computer Science
• 2021
DPG is extended to conditional tasks by proposing Conditional DPG (CDPG), and results show thatne-tuning using CDPG robustly moves these pretrained models closer towards meeting control objectives and — in contrast with baseline approaches — does not result in catastrophic forgetting.

### Controlling Conditional Language Models with Distributional Policy Gradients

• Computer Science
ArXiv
• 2021
The results show that fine-tuning using CDPG robustly moves these pretrained models closer towards meeting control objectives and — in contrast with baseline approaches — does not result in catastrophic forgetting.

### RL with KL penalties is better viewed as Bayesian inference

• Computer Science
ArXiv
• 2022
This paper analyzes challenges associated with treating a language model as an RL policy and shows how avoiding those challenges requires moving beyond the RL paradigm, and shows that KL-regularised RL is equivalent to variational inference: approximating a Bayesian posterior which informs how to update a prior LM to conform with evidence provided by the reward function.

### AXIMIZATION AND D ISTRIBUTION INE -T UNING L

• Computer Science
• 2021
The intimate connections between the two paradigms are explored, and it is shown that methods such as KL-control developed in the RM paradigm can be construed as belonging to DM, and that while DM differs from RM, it can suffer from similar training difficulties, such as high gradient variance.

### On Reinforcement Learning and Distribution Matching for Fine-Tuning Language Models with no Catastrophic Forgetting

• Computer Science
ArXiv
• 2022
The theoretical connections between the two paradigms, and it is shown that methods such as KL-control developed for RM can also be construed as belonging to DM, are explored, and that while DM differs from RM, it can suffer from similar training difﬁculties, such as high gradient variance.

## References

SHOWING 1-10 OF 42 REFERENCES

### Neural Code Completion

• Computer Science
• 2017
This paperores the use of neural network techniques to automatically learn code completion from a large corpus of dynamically typed JavaScript code, and shows different neural networks that leverage not only token level information but also structural information, and evaluates their performance on different prediction tasks.

### CodeXGLUE: A Machine Learning Benchmark Dataset for Code Understanding and Generation

• Computer Science
NeurIPS Datasets and Benchmarks
• 2021
This paper introduces CodeXGLUE, a benchmark dataset to foster machine learning research for program understanding and generation that includes a collection of 10 tasks across 14 datasets and a platform for model evaluation and comparison.

### Structured Generative Models of Natural Source Code

• Computer Science
ICML
• 2014
A family of generative models for NSC that have three key properties: first, they incorporate both sequential and hierarchical structure, second, they learn a distributed representation of source code elements, and third, they integrate closely with a compiler.

### An Empirical Study on the Usage of BERT Models for Code Completion

• Computer Science
2021 IEEE/ACM 18th International Conference on Mining Software Repositories (MSR)
• 2021
A large-scale empirical study aimed at exploring the capabilities of state-of-the-art deep learning (DL) models in supporting code completion at different granularity levels, including single tokens, one or multiple entire statements, up to entire code blocks.

### Code Completion using Neural Attention and Byte Pair Encoding

• Computer Science
ArXiv
• 2020
This paper uses an encoding that is in-between character and word encoding called Byte Pair Encoding (BPE) and uses this on the source code files treating them as natural text without first going through the abstract syntax tree (AST).

### PHOG: Probabilistic Model for Code

• Computer Science
ICML
• 2016
PHOG generalizes probabilistic context free grammars (PCFGs) by allowing conditioning of a production rule beyond the parent non-terminal, thus capturing rich contexts relevant to programs.

### HuggingFace's Transformers: State-of-the-art Natural Language Processing

• Computer Science
ArXiv
• 2019
The \textit{Transformers} library is an open-source library that consists of carefully engineered state-of-the art Transformer architectures under a unified API and a curated collection of pretrained models made by and available for the community.

### A Survey of Machine Learning for Big Code and Naturalness

• Computer Science
ACM Comput. Surv.
• 2018
This article presents a taxonomy based on the underlying design principles of each model and uses it to navigate the literature and discuss cross-cutting and application-specific challenges and opportunities.

### An Actor-Critic Algorithm for Sequence Prediction

• Computer Science
ICLR
• 2017
An approach to training neural networks to generate sequences using actor-critic methods from reinforcement learning (RL) that condition the critic network on the ground-truth output, and shows that this method leads to improved performance on both a synthetic task, and for German-English machine translation.

### A statistical semantic language model for source code

• Computer Science
ESEC/FSE 2013
• 2013
SLAMC is introduced, a novel statistical semantic language model for source code that incorporates semantic information into code tokens and models the regularities/patterns of such semantic annotations, called sememes, rather than their lexemes.


text:
# Dirac Delta and Exponential integral

I am able to derive the following equation by substituting the definition of a Fourier transform into it's inverse.

$$2\pi\delta(x-x') = \int_{-\infty}^{\infty} e^{ik(x-x')} dk$$

How do you prove that the Dirac Delta is equal to an integral of the exponential function? How do you prove the above equation is true?

• Two answer this question, you need to specify the theoretical framework because this is not standard calculus. – Yves Daoust Aug 24 '17 at 19:07
• @YvesDaoust The framework is the Fourier analysis where it is natural to apply the inversion theorem to the constant function $=1$, which leads directly to the distribution theory. – reuns Aug 24 '17 at 19:11
• @reuns: I need the OP's statement. – Yves Daoust Aug 24 '17 at 19:13
• You can't except someone who doesn't know how to prove the FIT for distributions to explain how to make this rigorous.. – reuns Aug 24 '17 at 19:14
• For an elementary treatment see Lighthill's book on Fourier Analysis and Generalised Functions amazon.com/… – Spencer Aug 24 '17 at 19:21

Let $$h_a(x)= \int_{-a}^a e^{i k x} dk = \frac{2 \sin(a x)}{x}= a \, H'(ax), \\ H(x) = \int_{-\infty}^x \frac{2 \sin(y)}{y}dy, \qquad H(-\infty) = 0, H(+\infty) = C$$ where for some reason $C = 2\pi$

If $\phi,\phi'$ are $L^1$ then $$\lim_{a \to \infty}\int_{-\infty}^\infty h_a(x) \phi(x) dx = -\lim_{a \to \infty}\int_{-\infty}^\infty H(ax) \phi'(x) dx\\ = -\int_{-\infty}^\infty H(+\infty x) \phi'(x) dx = -\int_0^\infty C \phi'(x) dx= 2\pi \phi(0)$$ ie. in the sense of distributions $$\int_{-\infty}^\infty e^{ik x}dk \overset{def}=\lim_{a \to\infty} h_a = 2\pi \delta$$

Note how this proves the Fourier inversion theorem.

• From the Dirichlet integrals it can be proven that the following is true. $$\int_{-\infty}^{\infty} \frac{2\sin(x)}x dx = 2\pi$$ Can you clarify what you mean by $\phi$ and $\phi'$ in the Lebesgue space of $L^1$? Is $\phi'$ the complex conjugate, implicit derivative or fourier transform of $\phi$? – Jeremy Aug 29 '17 at 2:22
• @Jeremy I used integration by parts. And as my answer proves the Fourier inversion theorem, you can obtain $C = 2\pi$ from it. – reuns Aug 29 '17 at 11:10
• The formula for integration by parts is $$(1) \space\space\space\space \int _{-\infty}^{\infty} udv \, = uv - \int_{-\infty}^{\infty} vdu\, dx$$ How did you assign the variables u and v? Suppose $u= H(ax)$ and $v = \phi(x)$ $$\int_{-\infty}^{\infty} h_a(x) \phi(x) dx = - \int_{-\infty}^{\infty} H(ax) dx + (H(ax) \, \phi(x))$$ In your equation you are missing the uv part of eq. 1. The limits have been removed for readability. – Jeremy Sep 1 '17 at 0:01
• @Jeremy The assumption $\phi,\phi' \in L^1$ implies $uv|_{-\infty}^\infty = 0$. This is the same core idea as test functions allowing to differentiate distributions – reuns Sep 1 '17 at 0:07
• What rule of distributions and the assumption of $\phi, \phi' \in L^1$implies $uv|_{-\infty}^\infty = 0$? – Jeremy Sep 1 '17 at 0:30

We can give a meaning to $\int_{-\infty}^{\infty} e^{ikx} \, dk$ by introducing a damping factor $e^{-\frac12\epsilon k^2}$ inside the integral and at the end let $\epsilon \to 0$: $$\int_{-\infty}^{\infty} e^{-\frac12\epsilon k^2} e^{ikx} \, dk = \int_{-\infty}^{\infty} e^{-\frac12\epsilon (k-ix/\epsilon)^2} e^{-\frac12 x^2/\epsilon} \, dk \\ = e^{-\frac12 x^2/\epsilon} \int_{-\infty}^{\infty} e^{-\frac12\epsilon (k-ix/\epsilon)^2} \, dk = \sqrt{\frac{2\pi}{\epsilon}} \, e^{-\frac12 x^2/\epsilon} \to 2\pi \, \delta(x)$$

• As your post states, assume the following two equations are equal. $$\lim_{\epsilon \to 0} \int_{-\infty}^{\infty} e^{-\frac12\epsilon k^2} e^{ikx} \, dk$$ $$\lim_{\epsilon \to 0} \int_{-\infty}^{\infty} e^{-\frac12\epsilon (k^2-ix/\epsilon)^2} e^{-\frac12 x^2/\epsilon} \, dk$$ If both exponentials are continuous well-formed functions then the equations within the integrals must be equal. By the product rule of exponentials $$-\frac12\epsilon k^2 + ikx = -\frac12 \epsilon(k^2 - \frac{ix}\epsilon)^2 -\frac12 \frac{x^2}\epsilon$$ – Jeremy Aug 29 '17 at 3:39
• Can you please explain the first equality? How did you move from eq. 1 to eq. 2? – Jeremy Aug 29 '17 at 3:54
• Completion of the square: $$\frac12 \epsilon k^2 + ikx = \frac12 \epsilon \left( k^2 + 2\frac{ix}{\epsilon}k \right) = \frac12 \epsilon \left( k + \frac{ix}{\epsilon} \right)^2 - \frac12 \epsilon \left( \frac{ix}{\epsilon} \right)^2$$ Now, $$\frac12 \epsilon \left( \frac{ix}{\epsilon} \right)^2 = - \frac12 \epsilon \frac{x^2}{\epsilon^2} = -\frac{x^2}{2\epsilon}$$ – md2perpe Aug 29 '17 at 5:10
• @md2perpe You need some complex analysis to justify the completion of the square. And it is not clear how you justify (in an elementary way) $\int_{-\infty}^\infty e^{ikx}dk = \lim_{\epsilon \to 0} \int_{-\infty}^{\infty} e^{-\frac12\epsilon k^2} e^{ikx} \, dk$ – reuns Aug 29 '17 at 11:12
• Of course you are correct, @reuns. The completion of the square itself is easily justified by basic complex algebra. That the integral can be translated in the imaginary direction is easily verified by a contour integral; the integrals over $[R, R+ix/\epsilon]$ and $[-R+ix/\epsilon, -R]$ tend to $0$ very fast as $R \to \infty$. – md2perpe Aug 29 '17 at 20:52

format: plain


text:
# SC-IAT-example

#### 2020-07-27

library(implicitMeasures)

This vignette illustrates how to use implicitMeasures package for computing SC-IAT D-score. The illustration is based on the data set provided with the package (i.e., raw_data).

### First thing first: Import and explore data

Labels containing specification sc_ in variable blockcode identify SC-IAT blocks.

data("raw_data")
# explore the dataframe
str(raw_data)
#> 'data.frame':    84726 obs. of  6 variables:
#>  $Participant: int 4 4 4 4 4 4 4 4 4 4 ... #>$ latency    : int  2592 628 808 783 2059 1114 608 663 771 676 ...
#>  $correct : int 1 1 1 1 1 1 1 1 1 1 ... #>$ trialcode  : Factor w/ 32 levels "age","alert",..: 31 5 3 20 3 20 5 3 20 3 ...
#>  $blockcode : Factor w/ 13 levels "demo","practice.iat.Milkbad",..: 4 4 4 4 4 4 4 4 4 4 ... #>$ response   : Factor w/ 46 levels "","0","1","19",..: 43 43 43 43 43 43 43 43 43 43 ...

# explore the levels of the blockcode variable to identify the SC-IAT blocks
levels(raw_data$blockcode) #> [1] "demo" "practice.iat.Milkbad" #> [3] "practice.iat.Milkgood" "practice.sc_dark.Darkbad" #> [5] "practice.sc_dark.Darkgood" "practice.sc_milk.Milkbad" #> [7] "practice.sc_milk.Milkgood" "test.iat.Milkbad" #> [9] "test.iat.Milkgood" "test.sc_dark.Darkbad" #> [11] "test.sc_dark.Darkgood" "test.sc_milk.Milkbad" #> [13] "test.sc_milk.Milkgood" raw_data contains data from two different SC-IATs, one for the implicit assessment of the positive/negative evaluation of Milk chocolate (sc_milk), and one for the implicit assessment of the positive/negative evaluation of Dark chocolate (sc_dark). Once the SC-IATs blocks have been identified, it is possible to prepare and clean the data for computing the D-score. Function clean_sciat allows for cleaning the data set of either just one SC-IAT or to clean the data sets of two SC-IATs concurrently. The labels identifying the test blocks must be specified as a character vector via argument block_sciat_1 and argument block_sciat_2 (only if there is a second SC-IAT). The labels identifying the demographic information (if any) must be passed to argument trial_demo, after specifying the column of the data set containing the labels of the demographic information (argument demo_id). DON’T USE THE trial_eliminate ARGUMENT TO ELIMINATE TRIALS EXCEEDING THE RESPONSE TIME WINDOW (rtw). The labels for identifying the responses beyond the rtw (and that hence have to be eliminated) must be included in the variable identified by trial_id, but they have to be specified via argument non_response in function compute_sciat() to actually be deleted. data("raw_data") sciat_data <- clean_sciat(raw_data, sbj_id = "Participant", block_id = "blockcode", latency_id = "latency", accuracy_id = "correct", block_sciat_1 = c("test.sc_dark.Darkbad", "test.sc_dark.Darkgood"), block_sciat_2 = c("test.sc_milk.Milkbad", "test.sc_milk.Milkgood"), trial_id = "trialcode", trial_eliminate = c("reminder", "reminder1"), demo_id = "blockcode", trial_demo = "demo") Since two SC-IATs and demographic data were specified, clean_sciat() results in a list of 3 elements: str(sciat_data) # structure of the resulting List #> List of 3 #>$ sciat1:Classes 'sciat_clean' and 'data.frame':    23328 obs. of  5 variables:
#>   ..$participant: int [1:23328] 4 4 4 4 4 4 4 4 4 4 ... #> ..$ block      : chr [1:23328] "test.sc_dark.Darkbad" "test.sc_dark.Darkbad" "test.sc_dark.Darkbad" "test.sc_dark.Darkbad" ...
#>   ..$trial : Factor w/ 32 levels "age","alert",..: 5 3 5 3 20 3 5 20 5 5 ... #> ..$ correct    : int [1:23328] 1 1 1 1 1 1 1 1 1 1 ...
#>   ..$latency : int [1:23328] 461 1495 639 573 671 643 714 1190 625 517 ... #>$ sciat2:Classes 'sciat_clean' and 'data.frame':    23328 obs. of  5 variables:
#>   ..$participant: int [1:23328] 4 4 4 4 4 4 4 4 4 4 ... #> ..$ block      : chr [1:23328] "test.sc_milk.Milkbad" "test.sc_milk.Milkbad" "test.sc_milk.Milkbad" "test.sc_milk.Milkbad" ...
#>   ..$trial : Factor w/ 32 levels "age","alert",..: 3 23 3 3 3 23 23 23 20 20 ... #> ..$ correct    : int [1:23328] 1 1 1 1 1 1 1 1 1 1 ...
#>   ..$latency : int [1:23328] 653 990 594 550 818 591 570 620 661 623 ... #>$ demo  :'data.frame':  3726 obs. of  6 variables:
#>   ..$participant: int [1:3726] 4 4 4 4 4 4 4 4 4 4 ... #> ..$ latency    : int [1:3726] 53047 53047 53047 53047 21554 21554 11266 11266 11266 11266 ...
#>   ..$correct : int [1:3726] 1 1 1 1 1 1 1 1 1 1 ... #> ..$ trialcode  : Factor w/ 32 levels "age","alert",..: 19 1 21 8 22 4 10 11 12 13 ...
#>   ..$blockcode : Factor w/ 13 levels "demo","practice.iat.Milkbad",..: 1 1 1 1 1 1 1 1 1 1 ... #> ..$ response   : Factor w/ 46 levels "","0","1","19",..: 33 15 41 34 16 20 1 1 1 1 ...

The first two elements (sciat1 and sciat2) are two data.frame with class sciat_clean. They contain the data of the SC-IATs specified in the block_sciat1 and block_sciat2 arguments of the clean_sciat() function, respectively. The third element (demo) is a data.frame that contains the demographic information as specified in the trial_demo argument of function clean_sciat().

Each element of the resulting list can be stored in a separate object.

sciat1 <- sciat_data[[1]] # extract first SC-IAT data
sciat2 <- sciat_data[[2]] # extract second SC-IAT data
demo_data <- sciat_data[[3]] # extract demographic information

#>    participant                block     trial correct latency
#> 23           4 test.sc_dark.Darkbad  darkleft       1     461
#> 25           4 test.sc_dark.Darkbad  darkleft       1     639
#> 27           4 test.sc_dark.Darkbad goodright       1     671
#>       participant latency correct trialcode blockcode response
#> 81001           4   53047       1    gender      demo     male
#> 81002           4   53047       1       age      demo       29
#> 81003           4   53047       1       job      demo     stud
#> 81004           4   53047       1       edu      demo       MD
#> 81005           4   21554       1 milk_eval      demo        3
#> 81006           4   21554       1 dark_eval      demo        4

### Compute the SC-IAT D-score

Once the SC-IAT(s) data have been prepared and cleaned through function clean_sciat(), it is possible to compute the D-score by using function compute_sciat().

This function takes three mandatory arguments and one optional argument. The three mandatory arguments are the data set with class sciat_clean, and the labels identifying the two critical associative conditions (arguments mappingA and mappingB). If the SC-IAT administration included a rtw, the label identifying the trials exceeding the threshold must be specified via the (optional) argument non_response.

# Compute the D-score for the first SC-IAT
d_sciat1 <- compute_sciat(sciat1,
mappingB = "test.sc_dark.Darkgood",

# dataframe containing the SC-IAT D-score of the of the first SC-IAT
str(d_sciat1)
#> Classes 'dsciat' and 'data.frame':   162 obs. of  15 variables:
#>  $participant : chr "100" "101" "102" "103" ... #>$ n_trial          : int  144 144 144 144 144 144 144 144 144 144 ...
#>  $no_response : int 0 0 0 0 0 0 0 0 0 0 ... #>$ nslow10000       : num  0 0 0 0 0 0 0 0 0 0 ...
#>  $nfast400 : num 0.03 0.05 0.01 0.01 0 0 0.01 0.11 0.02 0.05 ... #>$ nfast350         : num  0.01 0.01 0 0 0 0 0 0.01 0 0 ...
#>  $out_accuracy : chr "keep" "keep" "keep" "keep" ... #>$ accuracy.mappingA: num  0.986 0.986 0.958 0.986 1 ...
#>  $accuracy.mappingB: num 0.944 0.986 0.931 0.986 0.931 ... #>$ RT_mean.mappingA : num  626 785 627 586 885 ...
#>  $RT_mean.mappingB : num 730 913 704 633 1056 ... #>$ cond_ord         : chr  "MappingB_First" "MappingB_First" "MappingB_First" "MappingB_First" ...
#>  $legendMappingA : chr "test.sc_dark.Darkbad" "test.sc_dark.Darkbad" "test.sc_dark.Darkbad" "test.sc_dark.Darkbad" ... #>$ legendMappingB   : chr  "test.sc_dark.Darkgood" "test.sc_dark.Darkgood" "test.sc_dark.Darkgood" "test.sc_dark.Darkgood" ...
#>  \$ d_sciat          : num  -0.413 -0.242 -0.393 -0.288 -0.314 ...

# Compute D-score for the second SC-IAT
d_sciat2 <- compute_sciat(sciat2,
mappingB = "test.sc_milk.Milkgood",

# dataframe containing the SC-IAT D-score of the of the second SC-IAT
#>   participant n_trial no_response nslow10000 nfast400 nfast350 out_accuracy
#> 1         100     144           0          0     0.02     0.01         keep
#> 2         101     144           0          0     0.02     0.00         keep
#> 3         102     144           0          0     0.02     0.00         keep
#> 4         103     144           0          0     0.00     0.00         keep
#> 5         104     144           0          0     0.00     0.00         keep
#> 6         105     144           0          0     0.03     0.01         keep
#>   accuracy.mappingA accuracy.mappingB RT_mean.mappingA RT_mean.mappingB
#> 1         0.9436620         0.9722222         695.2269         648.8692
#> 2         0.9861111         1.0000000         917.3706         699.7917
#> 3         0.9583333         0.9166667         757.4988         784.3854
#> 4         0.9861111         0.9722222         640.5077         607.7566
#> 5         1.0000000         0.9861111         849.7500         928.0496
#> 6         1.0000000         1.0000000         540.3099         614.8611
#>         cond_ord       legendMappingA        legendMappingB     d_sciat
#> 1 MappingB_First test.sc_milk.Milkbad test.sc_milk.Milkgood  0.16120777
#> 2 MappingB_First test.sc_milk.Milkbad test.sc_milk.Milkgood  0.58453600
#> 3 MappingB_First test.sc_milk.Milkbad test.sc_milk.Milkgood -0.08226841
#> 4 MappingB_First test.sc_milk.Milkbad test.sc_milk.Milkgood  0.24119095
#> 5 MappingB_First test.sc_milk.Milkbad test.sc_milk.Milkgood -0.26484892
#> 6 MappingB_First test.sc_milk.Milkbad test.sc_milk.Milkgood -0.50147795

Function compute_sciat() results in a data.frame with class dsciat containing a number of rows equal to the number of participants, their D-score, and a bunch of useful information on their performance (see the documentation for the compute_sciat() function for further information on the resulting data frame). Functions descript_d(), d_point(), and d_density() require the object resulting from function compute_sciat() to work.

### Descriptive statistics

The descriptive statistics of the D-score and of the response times in the two critical conditions can be easily obtained with function descript_d():

descript_d(d_sciat1) # Data frame containing SC-IAT D-scores
#>               Mean     SD    Min     Max
#> D-Sciat      -0.04   0.32  -0.91    0.78
#> RT.MappingA 700.53 125.94 459.56 1299.09
#> RT.MappingB 710.23 125.28 462.28 1218.77

By specifying argument latex = TRUE, function descript_d() prints the results in LaTeX code

descript_d(d_sciat2, # Data frame containing IAT D-scores
latex = TRUE) # obtain the code for latex tables
#> % latex table generated in R 4.0.2 by xtable 1.8-4 package
#> % Mon Jul 27 16:06:38 2020
#> \begin{table}[ht]
#> \centering
#> \begin{tabular}{rrrrr}
#>   \hline
#>  & Mean & SD & Min & Max \\
#>   \hline
#> D-Sciat & 0.16 & 0.34 & -0.95 & 1.20 \\
#>   RT.MappingA & 729.20 & 146.02 & 448.56 & 1686.09 \\
#>   RT.MappingB & 681.52 & 109.97 & 485.15 & 1166.36 \\
#>    \hline
#> \end{tabular}
#> \end{table}

### Plotting the results

implicitMeasures comes with several functions for obtaining nice and clear representations of the results at both individual respondent and sample levels. Additionally, it includes functions for plotting SC-IAT D-scores resulting from two different SC-IATs.

#### Individual respondent level

d_point() plots the SC-IAT D-score for each respondent.

 d_point(d_sciat1) # Data frame containing SC-IAT D-scores

Clearly, in case of large sample size the label identifying each respondent is not easy to read, and it can be eliminated by setting x_values = FALSE. Respondents can be arranged by increasing or decreasing D-scores by setting argument order_sbj equal to either "D-increasing" or "D-decreasing". Descriptive statistics (i.e., $$M_{\text{D-score}}\pm 2sd$$) can be added by setting include_stats = TRUE. Finally, the color of the points can be changed by using argument col_point.

d_point(d_sciat1, # dataframe containing SC-IAT D-scores
order_sbj = "D-increasing", # change respondents' order
x_values = FALSE,  # remove respondents' labels
include_stats = TRUE, # include descriptive statistics
col_point = "aquamarine3") # change points color

#### Sample level

Function d_density() plots the distribution of the SC-IAT D-scores. It provides different options for choosing the most appropriate representation.

d_density(d_sciat1) # Data frame containing SC-IAT D-scores

The number of bins can be changed with argument n_bin. Argument graph can be used for changing the graphical representation of the data. It is possible to choose an histogram representation (graph = "histogram", default), a representation of the density distribution (graph = "density"), or a violin plot (graph = "violin"). Argument col_fill can be used to change the color of the points representing each respondent’s score in the violin plot. Finally, also descriptive statistics (i.e., $$M_{\text{D-score}} \pm 2sd$$) can be added to the graph by setting argument include_stats = TRUE.

d_density(d_sciat1, # dataframe containing IAT Dscores
graph = "density", # change graphical representation
include_stats = TRUE) # include descriptive statistics

#### Multiple SC-IATs

Function multi_dsciat() plots the distributions of the D-scores obtained from two different SC-IATs. This function takes only two mandatory arguments, which are the data frames containing the results of each SC-IAT obtained by using function compute_sciat(). The type of graphical representation can be changed by using argument "graph", which is set to "density" by default. Default representation also contains the lines indicating the mean of each distribution. These lines can be taken out of the graph by setting dens_mean = FALSE.

multi_dsciat(d_sciat1, # dataframe containing the results of the first SC-IAT
d_sciat2) # dataframe containing the results of the second SC-IAT

Argument graph can be set equal to "violin" (violin plots of the SC-IATs D-scores) or "point" (point representation of both SC-IATs D-scores). The labels identifying each SC-IAT can be set with arguments label_sc1 and label_sc2 (defaults are "SC-IAT 1" and "SC-IAT 2"). The values labels of the x-axis can be removed by setting x-values = FALSE (suggested in case of big sample size). Argument gcolors can be used to change the colors of each SC-IAT (default is "dark"). Other colors options are "greens", "blues", and "pink".

multi_dsciat(d_sciat1, # dataframe containing the results of the first SC-IAT
d_sciat2, # dataframe containing the results of the second SC-IAT
graph = "point", # change graph type
x_values = FALSE, # take out x values
gcolors = "greens", # change color
label_sc1 = "Dark SC-IAT",  # change label first SC-IAT
label_sc2 = "Milk SC-IAT") # change label second SC-IAT


text:
# Open loop transfer function of a closed loop control system is defined as:

Free Practice With Testbook Mock Tests

## Options:

1. Actuating signal / feedback signal

2. Output / feedback signal

3. Output / actuating signal

4. Feedback signal / actuating signal

### Correct Answer: Option 3 (Solution Below)

This question was previously asked in

PGCIL Diploma Trainee EE Official Paper (Held on 17 Dec 2020)

## Solution:

Closed-loop control system:

These are the systems in which the control action depends on the output. These systems have a tendency to oscillate.

Ex: Temperature controllers, speed control of the motor, systems having sensors, Human eye, etc.

The closed-loop control system can be described by a block diagram as shown in the figure below.

Where, R(s) is Reference Input,

Actuating Signal E(s) = R(s) - C(s)

G(s) is unity feedback open loop gain.

H(s) is Feedback gain.

C(s) is the Output and it is given as a feedback signal to input through the feedback gain function H(s)

From the above figure, we can find out closed-loop transfer function.

CLTF = C(s) / R(s)

From this open-loop transfer function is calculated as,

$$OPLT = \dfrac{CLTF}{1-CLTF}=\dfrac{\frac {C(s)}{R(s)}}{1-\frac {C(s)}{R(s)}}$$

$$OLTF=\dfrac{C(s)}{R(s)-C(s)}=\dfrac{C(s)}{E(s)}$$

OLTF = Output / actuating signal


text:
MathSciNet bibliographic data MR283135 (44 #368) 22.57 Gross, Kenneth I. Restriction to a parabolic subgroup and irreducibility of degenerate principal series ${\rm Sp}(2,\,$${\rm Sp}(2,\,$C$)$$)$. Bull. Amer. Math. Soc. 76 1970 1281–1285. Article

For users without a MathSciNet license , Relay Station allows linking from MR numbers in online mathematical literature directly to electronic journals and original articles. Subscribers receive the added value of full MathSciNet reviews.

Username/Password Subscribers access MathSciNet here

AMS Home Page

 American Mathematical Society 201 Charles Street Providence, RI 02904-6248 USA
© Copyright 2014, American Mathematical Society
Privacy Statement


text:
# Similarity among Binomial, Poisson and Normal Distributions

Binomial Distribution $$\textrm{Binomial}(m, p)$$ is similar to Normal and Poisson distributions.

Especially $$n$$ is large, it can be approximated as a normal distribution, according to the central limit theorem.

Let’s see the similarity with graphics.

Continue reading Similarity among Binomial, Poisson and Normal Distributions

# (日本語) 電力自由化とそのメリット 安い電力会社を見つけよう！

Sorry, this entry is only available in Japanese.

# Money Luck Stone: Tiger’s Eye

Sorry, this entry is only available in Japanese.

# Vitamin C Supplement Comparison

Sorry, this entry is only available in Japanese.

# (日本語) アルゴリズムの評価

Sorry, this entry is only available in Japanese.


text:
# Move type effectiveness chart

5pages on
this wiki

 Body Type Normal Fire Water Ground Wind Grass Poison Dark Magical Mechanic Attack Type Normal *1 *1 *1 *1 *1 *1 *1 *1 *0.5 *1 Fire *1 *0.5 *1 *2 *1 *2 *0.5 *0.5 *2 *1 Water *1 *2 *0.5 *0.5 *1 *0.5 *2 *0.5 *2 *2 Ground *1 *1 *2 *0.5 *1 *1 *1 *0.5 *2 *1 Wind *1 *1 *1 *1 *0.5 *0.5 *2 *0.5 *2 *1 Poison *1 *1 *0.5 *2 *1 *2 *0.5 *0.5 *2 *1 Electricity *1 *0.5 *2 *1 *1 *1 *1 *0.5 *2 *2 Dark *1 *0.5 *1 *1 *2 *1 *1 *0.5 *2 *1 Light *1 *1 *1 *1 *1 *1 *1 *3 *2 *1

This is just a handy guide to quikly check which moves are the best to use against which body type.


text:
# What is the surface area of the solid created by revolving f(x)=e^(x^2+x-1)/(x+1) over x in [0,1] around the x-axis?

Jan 16, 2017

$\approx 1.45099$

#### Explanation:

The Volume of Revolution about $O x$ is given by:

$V = {\int}_{x = a}^{x = b} \setminus \pi {y}^{2} \setminus \mathrm{dx}$

So for for this problem:

$V = {\int}_{0}^{1} \setminus \pi {\left({e}^{{x}^{2} + x - 1} / \left(x + 1\right)\right)}^{2} \setminus \mathrm{dx}$

There is no elementary anti-derivative. The solution can be found numerically as $\approx 1.45099$


text:
Can you help me here?

1. Aug 24, 2007

deah

Establish the ff. properties of δ(y).

(a) δ(y) = δ(-y)
(b) δ(y) = δ'(y)
(c) yδ(y)= 0
(d) δ(ay)= 1/a δ(y)
(e) δ(y²-a²) = [1/(2a)] [δ(y-a)+δ(y+a)]
(g) δ(y) δ(y-a) = f(a) δ(y-a)
(h) yδ'(y) = -δ(y)

thanks..

2. Aug 24, 2007

cristo

Staff Emeritus
You need to show some work for this sort of question and should, in future, post in the homework and coursework questions forum.

What are you denoting by delta? Do you have a definition to work from?

3. Aug 24, 2007

nicktacik

I may be wrong, but according to a) and b) the only possibility is $$\delta (y) = 0$$. (Which is consistent with c-h).

4. Aug 24, 2007

George Jones

Staff Emeritus
No, $\delta$ is the Dirac delta "function" (distribution, actually), and this thread is in the wrong forum. It should be in either Advanced Physics or Calculus & Beyond, depending on the course for which deah received this as an assigned question.

deah, how would you start a demsonstration of any of these properties?

5. Aug 24, 2007

nicktacik

I was not aware that $$\delta (y) = \delta '(y)$$

6. Aug 24, 2007

George Jones

Staff Emeritus
There must be a typo in (b); note also the typo in (g).

7. Aug 24, 2007

ChaoticOrder

First you have to choose a sequence of functions to work with whose limit is the dirac delta. For instance the sequence

y(x,n) = n^2 x + n for -1/n < x < 0
-n^2 x + n for 0 < x < 1/n
0 otherwise

Then delta(x) = lim(y(x,n),n->infinity)

Use this sequence to prove the properties.


text:
## Font not loadable - fontools problem

tex

### Next

• 1. Latex/Anchoring a Table to the top of page
Hello, I was wondering if anyone knew how to anchor a table to the top of a page? Latex seems to let it float around the page when there is a lot of space available. I could include some example code below... cheers - Kingsley \begin{table} \renewcommand{\arraystretch}{1.3} \caption{6-State Partition Adaptation at $P_{e} = 10^{-1}$ } \label{table_example} \centering \begin{tabular}{c|c} \hline SNR range (dB) & Assigned parameters (m,R) \\ \hline \hline 0.0 - 3.2 & QPSK, 2/5 \\ \hline 3.4 - 6.6 & 8PSK, 1/3 \\ \hline 6.8 - 29 & 16QAM, 1/3 \\ \hline 29.2 - 50 & 64QAM, 1/3 \\ \hline \end{tabular}
• 2. putting wide matrix into one column in a two-column setting
I have a 14x14 matrix which is too wide to be put into one column in a two-column typesetting. I wonder how to get around this problem without having to breaking the matrix into two 14x7 matrices. Thanks.
• 3. tables and section
"Sergio Rojas" < XXXX@XXXXX.COM > wrote in message news: XXXX@XXXXX.COM ... > Could somebody, please, point out how to keep in the same page > a section and two tables (that fix in one page)? Using the > format given below, latex put the section name in one page and > the tables in a differnt page.: > > {\samepage{ > \subsubsection{name} > \input{Tables/tab1.tex} > \input{Tables/tab2.tex} > }} > > tab1.tex looks like: > > \begin{table} > \begin{center} > \begin{tabular}{|c|c|c|c|c|} > \hline > \rowcolor{niceyellow} > Nodes & L2 Norm & R L2 & Max Norm & R Max Norm > \\ > \hline > 11 & 0.00724585 & --- & 0.00539460 & --- > \hline > \end{tabular} > }} > \caption{Summary of convergence results for problem \mynumtype{myexctr}} > \end{center} > \end{table} The table environment floats. If you really want the tabulars just where you put them, just use the tabular environment with a fixed caption from the ccaption (double c) package. You can find other suggestions in the FAQ. Peter W.
• 4. Incompatibility of "color" package?
I would check if all the braces are balanced. Matthew Low On Mon, 25 Aug 2003, Chia C Chong wrote: > Hi! > > I am trying to use "color" package to highlight some of the words. > This package seems to work perfectly until recently when I am using the > \begin{figure}...\end{figure} command in which I am no longer able to > compile my document anymore. Anyone come across the same problem before? The > following is the warning message I saw if I used the color package and the > \begin{figure} command... > > Cheers, > CCC > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > File: Chapter2/fig1.eps Graphic file (type eps) > <Chapter2/fig1.eps> > ! Too many }'s. > \color@endbox ->\color@endgroup \egroup > > l.79 \end{figure} > > ? > > > > >
• 5. How not to indent...
I use "\noindent" as told to but the section get's a small indentation anyway. I suspect it might have to do with the fact that i put an image in there (between the sections, that is). And that's the other issue - for some reason the image get's put after the first row of the other section not between the first and the second as supposed to. I try to make the computer understand that by "[h]" but blah... -- Kindly Konrad --------------------------------------------------- Sleep - thing used by ineffective people as a substitute for coffee Ambition - a poor excuse for not having enough sence to be lazy ---------------------------------------------------

### Font not loadable - fontools problem

I'm trying to install Myriad Pro Opentype fonts with the help of
fontools scripts:

Everything seems to be ok until I launch Yap previewer and see that no
fonts are load, the error message says:

-----------------

Making PK font:
720 600 magstep(1.0) ljfour
Trying to make PK font "LY1--MyriadPro-Regular--base" (at 720 DPI)...
makepk: "LY1--MyriadPro-Regular--base.pk" could not be created.

-----------------

What is missing? I've put all pfb, fd, vf, enc, tfm, map and sty files
and issued mktexlsr before updmap.

Thanks,

Bernhard Enders.

### Re: Font not loadable - fontools problem

Problem found: the MyriadPro.map file was missing from texmf tree. Now
it works. Sorry for the inconvenience.

Bernhard Enders.

Hello,

I started to use CJK in LaTeX recently, and I spend a lot of time
trying to fix the following problem:

! Font C70/song/m/n/9/65=cyberb65 at 9.0pt not loadable:

relax
l.74 ^^e6^^97^^a0
\par
?

I searched Internet to find a fix. I'm not the only one who got such
error, but the only recommendation was to correctly install CJK fonts.
Unfortunately, it wasn't my case. My CJK fonts were installed and
worked.

Finally, I've traced the source of the problem and fixed it. I share
the solution in hope that someone somewhen found it useful.

I use background texts which are produced in \EveryShipout. The text
should be displayed in Helvetica font, so the shipout code contains:

... \fontfamily{phv}\selectfont ...

Now let's trace TeX execution. It processes CJK text, and the current
encoding is some "CXX". A page is full, so shipout procedure is
activated. "Selectfont" tries to load "phv" for "CXX" encoding (font
shape "CXX/phv/m/n"). It's undefined, so fallback is "CXX/song/m/n",
which somehow is translated to "cyberbXX" (my CJK font), and for some

The fix is simple. The shipout code should also define the font
encoding:

... \fontfamily{phv}\fontencoding{T1}\selectfont ...

All this seems obvious now, but it wasn't easy to realize. TeX error
message is very misleading: error context is the source code, not the
shipout code.

Thanks for being so responsive, Derek! I am mailing you the file in
question.

The Debian freetype package I use claims to be 2.0.9-1 (I have also
installed freetype1-tools version 1.4pre20011029-1, but I doubt this
matters). xpdf is 1.00-3.1.

Meanwhile, I have run a couple of tests using different options for
the PostScript output from Word. The (I suppose quite popular) way I
use to convert Word to PostScript is to "print" it to a PostScript
printer but redirect this to a file. I have discovered there are a few
switches in the printer settings (I am translating these since my
stuff is in German; the wording might not be exactly what is said in
English) that do influence the result in a more or less pronounced
way:

- you can choose between "download TrueType fonts to the printer as
softfonts" and "replace TrueType by printer fonts"

"outline" (or "shape"?), and "TrueType"

- a third option the name of which I have forgotten offers you the
choice between "optimise speed", "optimise portability",
"encapsulated postscript", and "archive (the) format".

I have run tests combining almost all these options (I have NOT tried,
however: 1) "replace TT by printer fonts", because this was not what I
was concerned about (I assume that would produce more portable
documents if you are using Helvetica and Times and the like), 2)
speed", which does not make sense when printing to a file), amounting
to a total of 9 combinations for the PostScript output from Word.

That postscript output was then, still under Windows, converted to PDF
1.3 by FreePDF, which really uses AFPL Ghostscript 8.14. Because I had
become curious, I also ran this step under Linux, using the ps2pdf13
script which invokes GNU Ghostscript 6.53.

I have tried viewing both the PS files and the PDF files. The former
with gsview under Windows, and gv under Linux, both of which use the
respective Ghostscript versions. I tried viewing the resultant PDF
under Windows. Under Linux, I tried xpdf and gv.

Of course the results fill a table with 9 rows and 12 columns, which
I'll mail to anyone who's interested, but I'll extract here what
pertains to the question I have posted here:

- the problem with the boxes instead of glyphs arises only if the TT
supposedly meaning the same).

Interestingly, both xpdf and gv have this problem if the PDF was
produced under Windows (though the boxes look somewhat different in

Very interestingly, if the PS->PDF conversion step was performed
under Linux instead, xpdf displays PART of the file (roughly the
second part), while gv displays the whole. The Windows viewers have
again no problem, but there is a difference: with Acrobat Reader 5,
the result looks very pixelish, if not to say unpleasant to read.

- when the TT fonts are downloaded to the "printer" as "outline" (or
"shape"?), the results are fine (and very similar) on all viewers I
tried out (and regardless of whether PS-->PDF was done under Win or
Linux). This was apparently the only PDF deserving the attribute
"portable" one could produce with the tools I had.

- the "illegal bfrange" message seems to lead on the wrong path: it is
issued if and only if the PDF was produced by the win combo
(FreePDF/AFPL gs 8.14), but not if it was produced by ps2pdf13 under
Linux (GNU gs 6.53). This is so regardless of other factors, and
does not seem to have an impact on the display of the file.

Although I now know (by trial and error) HOW to produce one kind of
"P"DF, I have no idea why this is the case. If in both cases, TrueType
fonts are embedded (but are they?), there should be no problem with
either. But what is the difference between PostScript with embedded
TrueType "as TrueType", and with TrueType as "outline" (or "shape")?
And in what way do PDF documents normally contain/embed/use
TrueType? Do they normally need the external .ttf files?

The reason for my concern is that I expect from a "portable" document
format to be portable. Hence I assume there must be a standard way of
implementing things, not several possibilities. At least if using
TrueType in PDF _is_ to be considered standard.

--

Florian v. Savigny

If you are going to reply in private, please be patient, as I only
check for mail something like once a week. - Si vous allez rondre
personellement, patientez s.v.p., car je ne lis les courriels
qu'environ une fois par semaine.

Hi!

When installing a new LaTeX font from Postscript type1 I put the following
line in my fontinst driver file:

\substitutesilent{bx}{b}

But I?m still getting the LaTeX font warning:

Font shape T1/pbbx/bx/n' in size <12> not available
Font shape T1/pbbx/b/n' tried instead on input line 11.

So, what is \substitutesilent for? If we have to put
\renewcommand*{\bfdefault}{b} in every font package we create, why use
\substitutesilent?

Another question: Is a verbose fontinst file really necessary to install
semibold weight available in a font set. Can \latinfamily macro do this
task, how? I've got the following warning when using \latinfamily:

LaTeX Font Warning: Font shape T1/pbbx/sb/n' undefined

TIA,

Bernhard.
`


text:
# Ideals of $M_2(Q)$ [duplicate]

Could any one tell me how to show that only ideals of above ring are $(0)$ and the whole ring?

My thought was to show that by taking any proper ideal if we can prove identity element belongs to it then we can generate the whole ring? Thanks for helping

In general, the two-sided ideals of $M_n(R)$ are given by $M_n(I)$ where $I$ is an ideal of $R$.
I assume that $Q$ is $\mathbb Q$, which is a field. In this case, you know all its ideals.


text:
# methods early in Java - before objects

Does it make sense to introduce methods even before objects? What we are attempting to do is to get students out of the "everything in main()" mode as soon as possible.

Suppose one starts out with a simple program to compute the roots of a quadratic equation. One can imagine the main() method (very early in the course) looking something like:

Scanner src = new Scanner(System.in);
System.out.print("Enter coefficient a");
double a = src.nextDouble();
// similar pairs of lines for b and c
double rad = Math.sqrt(b*b - 4*a*c);
System.out.println("1st solution is" + (-b + rad)/(2*a));
// print second root

Now we want to introduce methods to demonstrate decomposition into methods invoked from main()t each of which does some parts of the work. One can imagine method signatures like:

    double getCoefficient(String prompt, Scanner src) {...}
double computeRad(double a, double b, double c) { }
void   printRoot(String label, double a, double b, double rad) {
// called twice, once with rad, once with -rad }

If we want to call these methods from main() the methods must be declared static. Alternatively one can create an instance of the class and invoke the (non-static) methods via the instance. But, we really haven't discussed objects yet (or at least objects the student writes). Our group is split between the static vs non-static approach. The other split involves passing both objects and primitives to methods as this can get into the discussion of pass-by-reference. However, the latter discussion can be brought up later when revisiting methods in future work.

If we go the static route, then later we must point out that many/most methods are non static. If we go the new X() route, one ends up talking about constructors, even if we use a default constructor.

Where and how do you introduce method in your first programming course? Is the proposed structure too advanced? How might you alter it?

Thanks

UPDATE 1:

I mostly agree with Objects early, but I wanted to do methods even before conditionals. I have students use Objects before creating their own classes. Thus the many small methods. Yes, it is encapsulated in a class, but I don't need to deal with constructors yet. My style of programming was dramatically changed when I took MIT's SICP at HP in the 1980's.

To flush out my ideas I created the following: QuadEqn. The assignment consists of several parts. Part A is designed to be completed before conditionals are introduced. Parts B, C, and D come later, perhaps as lab short exercises rather that full blown assignments. I have run this by our undergrad TA's but would like to solicit additional feedback as well.

Again, thanks

UPDATE 2:

Thanks for all the valuable feedback! I have not decided on using a methods first approach, but am simply trying it out to see how it would come together.

• Certainly you can do that. But a deeper question is whether you actually should teach students to program first with static methods. My experience is that it makes it more difficult for them to ever really understand the essence of an OO language like Java and how to use it. See, for example: cseducators.stackexchange.com/a/2883/1293 Sep 19 '19 at 0:06
• I am, of course, a strong advocate of starting with objects and leaving lower level things for later. But you can't do it naively and just follow the language. Here are some ideas about resources for doing it well: cseducators.stackexchange.com/q/4025/1293. The big idea is how do you move effectively from a problem to a solution. Matching the parts implied in the program to the objects that represent them. Few problems in the real world are naturally expressed in terms of ints. More can be naturally represented as objects. Sep 19 '19 at 12:30
• Note that the book Karel J Robot has the students write classes and methods prior to introducing conditionals or iteration. In fact it has almost no use of variables (other than references to objects) and no use of int variables and such. Polymorphism comes before iteration, in fact. Nov 5 '19 at 0:55

## 7 Answers

The two general approaches to teaching OO that I've seen are "objects first" and "objects last". Objects first takes the notion that, since we are teaching OO, we should start with instances, APIs, method calls, and inheritance. (See Greenfoot as an excellent start to an objects-first curriculum if you are interested in exploring this approach.) Eventually, you start to delve further into the nitty-gritty of the language, adding in arrays, loops, mods, etc, etc, etc.

Objects last follows the historical developments more directly, teaching imperative programming without OO first in order to highlight some of the thought process that went into developing OOP in the first place.

If you are taking an objects-last approach to your course (and it sounds like you are), then methods naturally fall before objects, and need to be included. Methods were an important development for both code clarity and code reuse. Though it's true that everything will need to be static at first, you can either leave this in as a temporary magical incantation, or make note of it as something exciting that will come later, and that about two-thirds of the way through the course, you will flip everything on its head, and those static markers will largely go away.

• One major pedagogical problem with objects-late is that students practice the essential parts of OO programming the least. If you start with objects then everything else you do gets to reinforce those early lessons on object structure. Doing it the other way doesn't permit that same level of reinforcement. Learning is by reinforcement and feedback, not by having information logically presented. Nov 6 '19 at 19:41

I second Ben. I and csabinho's views above. While there are semantic differences between methods, procedures, functions and subroutines that are paradigm-dependent, at a high level they can all be considered as ways of organising related code into reusable and more manageable chunks. Pretty much all programming paradigms support this, even scripting languages. So I don't think they should tied to objects and only introduced along with objects.

I understand your concern around static and the fact that methods are inherently tied to objects in Java, but I don't think this is problematic, students have to deal with so much "boilerplate" when learning to program in Java I think they're used to just overlooking things until they need to understand them. The fact that most methods are non-static can be introduced along with objects. There is also the reduced cognitive load advantage of objects being a new concept on its own, without methods also being new (no new pun intended).

Structuring code into reusable chunks with methods/functions/procedures/subroutines is so fundamental to good software design that I think it should be introduced as early as possible. Otherwise student's learn bad design habits that have to be unlearned/untaught later. It also ends up making life easier for students in the long run. Working on huge main methods is every professional engineer's nightmare, we shouldn't expect students to have to cope with it!

This is anecdotal obviously, but I've seen methods introduced late, when students have been dealing with main methods 100s of lines long for months. There were some visible "a-ha" moments when they realised how much easier it was to work with code structured into methods, and many of them reported how much easier they found it. static didn't pose any mayor difficulties.

In my opinion methods/functions should be introduced really early as they prevent the duplication of code. In general, as least according to my experiences, they seem to be introduced quite late, mostly as a final topic in first grade of engineering classes or at the start of the second grade. The use of static shouldn't be problematic and can even be useful, if you build on that and point out the differences when introducing objects and instances.

Additionally I would really point out scopes, as you might use the same names for parameters as you have used as variable names in main. That's a topic that is often forgotten, or at least not talked about enough, but would be really important to be understood by all students.

• IMHO they should be taught even before any consideration of avoiding code duplication, as a way to structure the thought, giving significant names to user defined actions (groups of instructions). Important in the process of writing code step by step. If you chose plain Java for teaching to beginners, the static keyword is already present for the unavoidable main(). Sep 29 '19 at 15:22
• Well, I'm quite sure that you should at least know some control structures to see how useful functions/methods are to avoid code duplication. Before that point you only declared and initialized some variables, so I can't even imagine how to demonstrate the use of functions/methods in a proper way. Sep 30 '19 at 21:17

## Methods and objects

Does it make sense to introduce methods even before objects?

At a base level, your suggestion that methods only make sense in the context of objects relies on the idea that methods are only used with objects, which is not the case. Functional programming very much eschews objects (to a reasonable degree) and very much relies on functions instead, proving the point that functions and objects are not married.

## To static or not to static

If we go the static route, then later we must point out that many/most methods are non static.

Much to the chagrin of my teachers and senior developers, I do not distinguish functions from methods as they are the exact same thing to me. To me, staticness (or not) is irrelevant to define the purpose of a function.

But you might be on the other side here and very much separate methods and functions.

If you think they are separate definitions, then you are in luck. When you later introduce objects, you talk about methods. Before, when you were dealing with statics, you would've only been talking about functions, so there's less of a collision and you don't need to go back on your words after introducing objects.

If you don't think they are separate definitions, then you are in luck. Since staticness then isn't a core part of the definition of "method" and "function", then you don't need to change your students understanding of methods/functions just because you start using non-static methods.
Instead, focus a lesson on static vs non-static to get the point across that they should be used in different scenarios.

Generally speaking, students think statically before they learn to think object(ive)ly, so it makes sense for you to stick to that order.

## A practical example

Where and how do you introduce method in your first programming course?

Functions teach two important skills: abstraction and the avoidance of repetition. They are both very easy to demonstrate, but need to be demonstrated in different ways:

1. Ask your students to perform a particular calculation (e.g. count the letters in a string)
2. Ask your students to perform this calculation ten times (e.g. on a string[10]). They will probably copy/paste code. Let them. Don't correct them.

The third step is different based on what you want to teach them. If you're teaching them to avoid repetition:

1. Ask your students to perform this calculation one million times (e.g. on a string[1000000]). They will immediately sigh at the thought of having to copy/paste this another 999,990 times. (Though this is a personal thought, I believe that any student who mindlessly starts doing it without complaints does not have the right mindset to become a developer)

If you're teaching them about abstraction:

1. Ask your students to change the calculation logic (e.g. only count vowels). If they don't mind making the same change ten times, either get them to increase the repetition before making a change, or simply require them to make change after change, making the calculation increasingly complicated.

In either case, the same will happen: your students will be unhappy about all the stupid brute force copy/pasting. When they've reached the point of discontent, it's time for you to demo something to them:

1. Solve task 1 using a function for the calculation. Agree with them that the function isn't truly necessary here.
2. Solve task 2 when you already have the existing function. Point out how little time it took you.
3. Solve task 3 (whichever you picked) and have them realize that your solution means that they could either execute the logic any arbitrary number of times without needing to change anything (other than the input array size), or only needed to change the function body once instead of changing the copy/pasted logic X times.

## To summarize

Teaching follows a strict pattern of incentivization. Unincentivized students don't care about your lesson, whereas incentivized students take it to heart. I've always been a fan of this quote:

If you want to build a ship, don't drum up people to collect wood and don't assign them tasks and work, but rather teach them to long for the endless immensity of the sea.
--Antoine de Saint-Exupery

If your students balk at the idea of a function and think of it as "pointless extra effort", then they clearly haven't experienced the horrors of programming in a world without functions.

Rather than expect them to take your word for it, make them experience the issues with not using functions. Make them hungry for a better way to do the horrible task they have been assigned.

And when they're hungry enough, show them the better way. Suddenly, they will love and accept functions as opposed to groaning at them.

• You seem to fail to understand some really fundamental things. One minor one (not the worst) is that functions (in all paradigms) are not primarily there so that you don't need to repeat yourself. That is just a by-product. A good Pascal program has a lot of functions that are called exactly once. Nov 5 '19 at 11:40
• @Buffy: Which is why I separately mention the purposes of abstraction and DRY. The example you're highlighting (one-reference-methods) is one of abstraction (most commonly encountered for separation of concerns) Nov 5 '19 at 11:43
• And if you really conflate static and non-static methods you have a really fundamental misunderstanding of how a language like Java actually runs. The chagrin of your teachers may be well justified. Learn to use your tools. Nov 5 '19 at 11:43
• @Buffy: I didn't claim that there's no real-world difference between statics and non-statics during runtime. I said that my core definition of what a function/method is (i.e. a small compartmentalized algorithm) is independent of whether that function happens to be static or not. "should I make this static" and "should I use a function/method" are two questions that are independent of eachother. Both should be evaluated but their answers are not related (one's answer does not suggest the other's answer) Nov 5 '19 at 11:44
• Then, I question whether you understand scope. These sorts of things can't really be glossed over without giving students a burden of misinformation that they will eventually have to fight their way past. Nov 5 '19 at 11:46

IMHO, the response by @Ben I. and the advocacy for OOP first by @Buffy capture the essence of your problem. You have to choose whether to go imperative first or OOP from the outset. Once you make the choice, the other matters resolve naturally. However, there are considerations that affect your choice. Incidentally, you did not tell us if your students are completely new to programming or have had some previous exposure. This is one key consideration in the choice of direction.

Other considerations are: what is the thrust of your curriculum? How much time do you have to cover the curriculum’s content? One semester? Two? How many contact hours do you get in a week? Will the time available afford you the luxury to start imperative and come later to OOP as we do traditionally? Or you have to hit the ground running OOP to cover much before time lapses, as @Buffy would have loved?

If your students are stark new to programming, starting them with objects (from my experience teaching many beginner classes), may be problematic later. Creating objects and classes requires so much background knowledge you end up having to explain too many things in one lesson, generating cognitive overload. If you manage somehow, to get them to learn the higher abstractions, sooner or later, you have to come back down from the gang plank to do lower level things like control structures, arrays etc. Trouble is: it is more difficult for someone who has learnt to drive an automatic car to learn to drive a car with manual gear.

However, if your students have had some programming knowledge or are running another parallel course in the semester under consideration, by all means go OOP outrightly, Now! For, whatever they could not learn with your OOP Java, will be made up by the past exposure or the parallel course.

So for complete beginners, go imperative first. Teach static methods soon after covering the elementaries and control structures + if possible, arrays. I appreciate yours and @Buffy’s concern about the proactive inhibition, earlier knowledge of static methods may cause when you get to classes/objects, and the subsequent difficulty unlearning. However, the benefits of teaching method/functions early in a first programming course overwhelm any “side effect” of it.

It teaches the student disciplined and good structuring of code and also as you noted, it weans them off the “everything-in-main()” bad habit early. One significant benefit of this I learnt by experimenting different order of topics with different beginner streams I have taken is: the students that have written functions/methods in earlier lessons learn to write a class/object faster and easier. They transfer learning of the naming rules and layout of functions/methods etc. to the writing of classes/object. Makes your teacher’s life easier.

Secondly, a beginner that has not written any aggregate entity like function/method or struct (C++) with many statements in the block can get overwhelmed at first. So learning methods first, facilitates writing class/objects and, especially a class with large number of statements and structural complexity.

Besides, static methods are part of class/object. Teaching it before teaching class reduces the cognitive load when you subsequently come to teach class since hopefully, you won’t have to explain that part again. You can focus on other things like why privating/who publicking, Messrs. constructors/destructors et.al.

It also helps the students build more sophisticated programs early. They can play with controls structures and method calls to create more interesting things even before knowing how to use class/objects.

As per the concerns about static methods not being thread safe etc., I understand from Java 8 onward some of these issues have been addressed. For example, we can have static methods in interfaces too.

Finally, a caveat: if you choose to go imperative first, let them at least learn control structures (branching & looping constructs) & scope before teaching them methods as @csabinho had pointed out. Scope may be taught in the course of teaching methods when you explain perishing of variables as you go out of scope, out of the fence, though. So make your choice in light of your situation and that of your students.

PS: I looked up your QuadEqn exercise. It was good. I like the annotation especially. But leave the part where they pass parameters to main () till the end. Else the cognitive payload will kill the smooth learning I expect from your exercise.

I've hesitated to provide an answer for this since it would be, necessarily, very long. But I've spent more than 20 years on this basic question and suppose I need to bite the bullet and try to clear up misconceptions that should have been dispelled generally years ago. My focus has long been on how to teach programming effectively, as well as programming languages in general.

And for starters, you don't teach programming by teaching a lot of syntax. Nor is the difference between languages primarily their syntax. Not if they represent different paradigms, at least.

I apologize in advance for the denseness of this. I hope it is accurate. My writing in general has been described as accurate but too dense. Because of this, it may be hard to grok the implications of some of it without reflection.

When we teach a first course in programming, per se, the course has to answer the fundamental question "What is a program?". Giving a concise definition to a beginner will just lose them, but, by the end of the course, they should have a good understanding of an answer as well as guidance in How To Program. If the course leaves them confused about that you have done a disservice and they will, mentally, need to start over to get an understanding of what is a program and how do we construct one.

Everything we do in that first course should be directed to that end. What is a program? How do we create one?

Sadly, too many people think of a programming language as a bunch of stuff thrown together, features, that can be used in any way you like. While that is literally true, it leads to terrible, unmaintainable, impossible to understand, cruft. We need to do better and our students need to have proper guidance.

In fact, language designers don't think that way at all.

However, there are different conceptions about what a program is, and those different conceptions (paradigms) lead us to different answers to the question "What is a program?" and the question "How do we create one?" Especially, how do we create a beautiful, useful, maintainable, understandable, program?

My university once declined to hire a very smart guy because he admitted that the program he created as the basis of his dissertation was so complex that he couldn't really understand it and was afraid to modify and extend it because it was so fragile. A naive understanding of programs and programming will leave you in exactly that place. It's creator has lost control of the creation. A Frankenstein Program.

There are others, but the three main paradigms are Functional, Procedural, and Object-Oriented. I will try to explain each of these in turn and also explain why one shouldn't try to mix them with beginners (and mix them only very carefully for experts - C++, say). Each of these paradigms has a different answer to the question "What is a program?" They also give guidance about how to construct a program within that paradigm.

Note that for all of these paradigms, the descriptions and the definitions are highly recursive, even when the programs written in them are not.

And note that once you have answered the question What is a Program for any paradigm, you can write any program at all. All the paradigms are Turing Complete hence equivalent in power. If you master any of the paradigms, and have adequate language tools, then you don't need any other paradigm to be able to write programs. Some may be more suitable for some kinds of problems, but all are capable.

## Functional Programming

Since this paradigm is less important to the current question I won't expand it so deeply. But a functional program in something like Scheme, or even Standard ML, is an expression that, when evaluated, gives the answer to a problem. Normally that expression is a function, expressed usually as a list, and the evaluation usually results in another list.

But that brings us to the question of what is a function and an expression. An expression could be simple, like a value (42), or it could be a list, or it could be the result of applying a function to some arguments, which are, themselves, expressions. Note the recursion.

The question of How to Program is, then, you create an expression to represent the solution. If the expression requires function evaluations then those functions are, themselves, written to evaluate expressions that are smaller problems within the larger problem. When the overall function is evaluated it starts a cascade of evaluations of functions solving the smaller problems and then the original function constructs a solution from the solutions of the sub problems.

And no, that description isn't suitable for a novice. They need seasoning and practice so that the definition starts to emerge in a way that they can eventually (end of the course) understand.

But note that this is recursive. An expression is composed from expressions, many of which are the results of function invocations.

There is more that can be said, and I could probably refine this quite a bit, but that is really the essence of functional programming. What is a functional program? It is an expression. How do I create a program? By creating an expression that represents the answer I want, probably by writing functions that are themselves compositions of functions.

But note that this "definition" means nothing to a novice. Gibberish. They learn it by writing simple expressions and simple functions, then progressing to more complex situations in which an expression needs to be composed from the invocations of several functions. If you look at a well-formatted Scheme program (i.e. properly indented) the indentation shows the structure.

## Procedural Programming (aka imperative)

Procedural programming was probably best defined by Edsger Dijkstra for the Algol family of languages, such as Algol, Pascal, and Modula-2. In this paradigm a Program is a procedure that when executed produces a solution to a problem. How do you create a program (procedure)? If the problem is simple enough, you just write down the solution as the body of the procedure.

But mostly, trying to do that results in a mess since the problem is too hard to understand (and solve) in a single pass without decomposition. Therefore, in order to write that procedure (solve that problem) you factor out sub problems that, collectively, have three characteristics:

1. The sub problem is a problem in its own right. The nature of the problem and what would constitute a solution is known.

2. The sub-problem is solvable with a procedure, in theory.

3. There is a known way to recompose the solutions to the sub problems into a solution of the overall problem.

Then, the sub problems need procedures to solve them. To do that, you proceed recursively decomposing those problems as needed into smaller problems with the above three characteristics. The recursion stops when you can actually solve all the smallest problems with (simple) procedures. Then you recompose those procedures into the solution you initially desired.

This is why procedures can be nested in languages like Pascal and why C isn't ideal as a Procedural Programming Language. Additionally, the ability to nest functions implies (in these languages, at least) that variables defined at one level are visible at lower levels (scoping), but not elsewhere. This disciplined approach to information hiding/revealing is very powerful. In particular it is used to reduce coupling and increase cohesion in programs. (I can expand this if needed.)

What is a Procedural Program? It is a tree of procedures where each node in the tree represents the solution of a sub problem, with lower nodes representing the decomposition of a problem and leaves of the tree represent simply written procedures needing no further decomposition.

How do you create a Procedural Program? You construct the tree from the top down, decomposing as needed to extract simpler problems and then re-composing solutions to solve the overall problem.

Again. This explanation means nothing to a novice. They learn it from practice. Start with relatively simple problems/programs that don't require decomposition and progress to more complicated ones to get practice with both the decomposition of problems and the recomposition of solutions.

And none of what I have said has anything to do with if-statements and while-statements and integer variables and such. That isn't the essence. Those are used only for structure at the very lowest level of the program. If you try to define the overall (complex) program using only these you will fail all of the criteria of what makes a program good. In particular, as little as two pages of such code can be unintelligible even to its creator. (I have evidence of this from a very important - mission critical - project at a major US company. And, well, student projects, of course.)

So, to think as a procedural programmer, you think in terms of procedures (some of which are functions) and, if the problem is difficult, imagine all of the simpler problems that, if they could be solved, would represent the solution you desire. Solve the simpler problems with procedures.

### Note 1.

In both procedural and functional paradigms the text of the program is tree-like. Namely nested structures. But the running program is also tree-like. A procedure or function can invoke its "child" nodes generating a run-time tree of execution. Call down the structure. Return up the structure. The tree is traversed (in time) as the program executes. And in both of these paradigms, the program is thought of as a process, not a thing. It answers a "how does it work?" question, not a "what is it?" sort of question. And most of the structure of such a program is a description of an algorithm. The overall program does something. It's parts do some part of that. The structure models the process. This will be different in object-oriented programming.

### Note 2.

Until recently procedural programming in the above model was impossible in Java, since functions couldn't be nested. The introduction of Lambdas in Java 8 has changed that, but for a different purpose. And I'm pretty doubtful anyone has yet used lambdas in this way. And if you do, you come to something closer to a functional program than a procedural one. But if you want to solve a large and complex problem with static methods in Java, the structure is flat, not nested. All of those functions are at the same level in the program. This is actually the programming model of FORTRAN. One function that solves part of the problem of another can't be nested inside that other function.

### Note 3.

In a procedural program, at any time that a procedure is called, the actual text of the program will tell you precisely which code will be executed. But in a functional program this may not be the case. This is because functions are, themselves, values that can, for example, be stored in lists and passed around as arguments to other functions and then invoked. In other words, you may need to actually execute a functional program to determine what it will do next. We shall see this again with object-oriented programs, but in a different way.

## Object-Oriented Programming

While Simula 67 was technically the first OO language, the slightly later Smalltalk better represents what we think of today as an object oriented language. (C++ derives from Simula and is actually a multi-paradigm language, or paradigm-agnostic language, not, specifically an OO language.) The following doesn't describe Javascript, since it came from yet another trend that started with the language Self. Javascript has objects, but no classes.

What is an object oriented program? It is the orchestration of a web of interacting encapsulated values (objects). The web of interactions produces the solution to the problem at hand. The interactions are modeled as services that an object provides to other objects.

How do you write an OO program? You first analyze the internal structure of the problem and determine its "parts" you model these parts as faithfully as necessary for your purposes (objects). You also define the web of interactions, partly externally (function main), but mostly internally as determined by the needs of the objects.

Example: If you want to solve problems about traffic flow (self driving), you model the transportation system to some necessary level of detail. A transportation system has parts: it has roads and bridges, cars, busses, intersections, signals, detours, ... These "parts" are modeled by objects, which are, in turn, described by classes. There is only one "system" but it has several "cars", etc. The cars interact, on occasion, with each other and with other objects,

Example: A student information system has parts: courses, students, instructors, records, rules and exceptions, ... The parts interact: students enroll (a service) in classes, etc.

Example: A calculator has parts: one or more displays, keys, internal stacks, ... The parts interact. Key presses (a service) cause changes in the display (sometimes). ....

What, then, is an object? An object is an encapsulated actor that is comprised of both data and behavior. The behavior models services that the object can provide. The data can only be acted on by requesting a service of it. In a complex program, the "data" within an object is made up of other (lower level) objects, that provide services to the containing object. (Note the recursion here).

What services can an object provide? These services are defined by an interface, that might be stated explicitly or not. Each service is modeled as a protocol for a procedure or function (collectively called methods). In smalltalk derived languages (Java, Python, ...) the protocols are defined in classes, that also specify the data used by objects created from the class.

Objects are created dynamically as the program runs, not statically from the program syntax. A class is a description of a certain type of object, but the objects are distinct. Most classes can be used to create many, independent, objects of the same type, but individually encapsulated. Objects (via their services) can create other objects, both internal to their own structure and externally.

Communication (the web of interactions) in an OO system is via messages. A message requests a specific object to perform a specific service. Some services return data (functional). Some update internal structures of the objects or request further services of other objects without returning data (procedural). While possible to do both, it is discouraged as it makes the program more complex and harder to maintain. It isn't forbidden, but novices should be discouraged until they have more experience. (A saw can be used as a hammer, but the novice is discouraged.)

It is a feature of OO programming that the text of a program cannot predict, precisely, the code to be executed when a message is sent. This is similar to the situation in Functional programming where functions are values. Objects from different classes can be sent the same messages, provided that the classes implement the same interface (In Java you need explicit implementation of a defined interface, but not in Python.) The implication of this is that when a reference variable "points to" some object that is defined by an interface, the code to be executed is only "known" to the object - and the object doesn't exist in the text of the program but only at runtime. And, the implication of that is that you program to interfaces, not to specific class structures. The same is true in subclassing. Objects from the subclass implement (at least) the interface of the superclass, but may do so in different ways. (See the notes on polymorphism, below.)

---- Complete for now, but I'll think some more. -----

## Good and Bad OO Programs

Here are some rules for creating good programs. I'll focus on Java. In Python and Ruby they would be a bit different. The rules in those other languages still hold, but those languages give you a bit less support for them since they are dynamically typed where Java is statically (compile time) typed.

True experts can break these rules, but normally consider them. But in the first course, insist on them and teach students that dangers lie outside the safe zone provided by the rules. "Here there be monsters!"

Don't write big classes: classes should be small with only a few methods. They should be single purpose. Do one thing well on request.

Don't write long methods: methods should be short with very low Cyclomatic Complexity. I start to get itchy when a method is more than three statements or when I need nested statements. The complexity of an application isn't in the individual methods (or classes) but in the interactions between objects. This skill, factoring a complex program into small and simple parts, is one of the most important and hardest to develop. It needs to be practiced.

Write a lot of classes: This is a consequence of the first two rules. A system is made up of a lot of parts, but the parts, themselves are simple.

Use subclassing very sparingly and never deeply. Novices tend to break this rule, thinking that subclassing is the Big Idea of OO programming. It actually isn't. There is much more power in using composition and polymorphism than in subclassing.

Write classes whose internal data is mostly other objects, not language primitives: Complex parts are made from simpler parts. This is the purpose of inner classes. You can hide the structure of an object by hiding the structure of its parts. This is encapsulation and data hiding done well. A car object has an engine object. An engine object has piston objects. A piston has bushing objects. Complex things made up of simpler things. But a car (as a whole) doesn't need to "know" about pistons. Only the engine does. And certainly the transportation system can ignore pistons. This is programming by composition. Composition is really the Big Idea of OO.

Write a lot of interfaces, even if only one class will implement a given interface: The interface documents your intent. Understanding the intent, and programming only to that intent, is what makes complexity manageable.

If you create a subclass, don't also extend its implicit interface: That is, don't add additional public methods. You will be forced at some point to use static polymorphism to resolve things if you do. If you need new "features" then extend the formal interface instead and have the subclass implement that interface. (I've found this to be one of the most important measures of code comprehensibility.) A circle isn't a subclass of (special case of) a point. Use subclassing for specialization, not extension.

Most reference variables should be typed with an interface, not a class: This also helps you avoid the trap of being forced into static polymorphism (and warned, at least) when you fall into it.

Use only public and private for class features. The others are for experts. Protected, in Java, is a land mine. All data elements, other than constants, should be private. Among the methods, only the service-defining ones are public. Protected is intended for large teams building complex software over several packages. Unspecified visibility increases the possibility of linking between elements of a class, complicating maintenance and extension. Just. Say. No.

Use static methods sparingly and only for their intended purpose. A method that tells you the number of cars created by the Car class is static. A method that tells you the color of an individual car is not static and returns information separately by each individual object.

Don't build classes speculatively, thinking that you might want them later. (Reuse is overrated). Classes are there for purpose-build (bespoke) objects, not for general principles. Don't build the Car class in your transportation system model until you know you need it. Don't commit much to its interface until you know how it will be used and what actual services it must provide. A mutator to change the color might be completely superfluous. Build what you need, when you need it.

Achieve polymorphism in a program, not via subclassing as such, but by judiciously replacing one object with another. Both have the same interface, but each performs some process in a different way. See the Strategy and Decorator Design Patterns.

### A note on OO libraries

One would like to use the libraries supplied with a language as models for good programming in the language. Unfortunately it doesn't work out so well. Library code breaks many of the rules I suggest above as you are probably aware. There are two aspects.

First is the the goals of a library writer are very different from those of an application programmer. The former is providing general purpose services for programmers, rather than purpose built solutions for users. The modeling problem, in particular, is simpler.

And second, the library writers are experts who interact with other experts to define the libraries. When they break a rule they do so very carefully and after long thought and testing.

Class nesting and using protected features are often used in libraries. But so are lots of interfaces and extensions of interfaces. But these are expert-only tools.

“Do not meddle in the affairs of wizards, for they are subtle and quick to anger.”

### Polymorphism: static and dynamic

Selection statements in a programming language are a form of polymorphism. They provide different actions, depending on circumstances. But this is static polymorphism. Almost all programmers are familiar with it, even if not by that name.

Dynamic polymorphism, however, is something that happens only at run time. If a variable references an object, then a message to the object names the variable, not the object directly. If the variable refers to different objects of different classes (but the same interface) then different things can occur when the same message statement is re-executed. And the text of the program doesn't normally reveal this. In Java, however, you can subvert the system by forcing static polymorphism using something like the instanceof operator. Through it you can learn the specific class of an object (usually) and you can then know the precise code that will be fired in a message. But this usage represents a failure. You should never need to write code that does this, and if you really need it then your program is broken in other ways. Perhaps you used subclassing naively. This sort of programming is a code smell that indicates something sick or wounded elsewhere. Let your program heal to avoid it. Let dynamic polymorphism be your friend. If you need to fight it, you need to rethink how you are using your tools. Hammer, meet Saw.

And don't confuse polymorphism with subclassing.

## How Abstraction fits this scheme

Abstraction (simple names for complex phenomena) are vital to all three paradigms. But different languages have more or fewer ways to do it. Procedural abstraction (naming a complex process) is about all that is available in Pascal (or C). But class based abstraction (naming of things) can be a very powerful adjunct. So powerful, in fact, that it becomes the main tool. Model the things. Give them good names. And, the rules I've suggested (lots of small classes and methods) means that you create abstractions for many things in an OO program when built as described above. You become a namer of things. Which, itself, is a kind of wizard.

What emerges from programming OO in the way described here, when mastered, is programs that are expressed directly in the language of the model - which is closely related to the language of the problem and in terms of our intent. The opposite is programs expressed mostly in terms of language primitives which, at best, are mere surrogates for our intent.

## Pedagogy

Given my insistence that students learn from repetition (reinforcement) and feedback, if I want to teach them to program in Java, I have to do objects first. Otherwise they get too little practice on the most important things. But I never start with an empty class and an empty main method. Students in a course I'd be willing to teach will start with a substantial amount of scaffolding that lets them focus on the important things, rather than low level syntactic details.

Students can work to extend an existing system. With care, a simulation can be created that allows the students to program in a Turing Complete environment while emphasizing the essence of "What is a program?" and "How do I build it?". The Greenfoot programming system provides a fairly rich set of starting points. The Greenroom site, linked from there, is the specific teacher resource. (I know the developers and have contributed to Greenfoot, but have no connection.)

## Conclusions

If you are using an object-oriented programming language, learn (and teach) how to do it well. Don't use it for things (other paradigms) for which it is ill suited. Teach students in the first course some paradigm, but only one. paradigm, so that they have a meaningful answer to the two questions: What is a program? How do I create one?

So, for a formal answer to the question posed, no, I wouldn't do that. It is actually more like C programming. If I wanted to teach C and its concepts (and have done), I'd use C. C is a better C, anyway.

• If I had a blog. Final version ought to be a Pulitzer. Nov 6 '19 at 8:57
• Question: How you done software development in the workplace? While this is pretty great conceptually, it smacks over overly theoretical "pure OOP" philosophy that one sees in academia but not so much in real engineering work, IME. Nov 6 '19 at 19:22
• @DanielR.Collins, it depends on what you mean. I've never had a boss telling me what or how to write. But I've consulted to companies on their software process, which can be appalling. I mostly produce educational software (large and complex) with something over 20,000 users. And, yes, I eat my own dog food. (Actually, the last time I had such a boss was waaaaay back on a FORTRAN project.) Also. I'm focused on the first course here. I also normally use Agile software practice in conjunction with the things I recommend here. Unit tests, frequent delivery, and all that. Nov 6 '19 at 19:31
• @Buffy Thanks so much for your many detailed comments. This answer takes me back to MIT 6.001 SICP that I took at HP. It literally changed my whole career as I learned a whole new way of looking at programs. Nov 6 '19 at 20:52
• What a tour de force! This is possibly the most substantial (and possibly the most important) answer I have seen on CSEd so far. I regret only that I have but one upvote to give.
– Ben I.
Nov 7 '19 at 0:39

Does it make sense to introduce methods even before objects?

Short answer: Yes. Without arguing that it's necessarily better, it's at least a reasonable approach; it's common enough that major textbooks are published following that strategy. For example, the Gaddis Starting Out with Java books have two variants, for whichever approach you prefer:

In the former, writing methods is introduced in Chapter 5 (before writing classes), and indeed, all of the examples in that chapter necessarily have the static keyword. It works sufficiently well enough that this particular textbook is now on its 7th edition.

I'll point out that Gaddis also has an analogous pair of textbooks for C++. At my institution we do use the "control structures through objects" version (largely with a procedural C-like first semester, and then an object-oriented second semester, using the single textbook for the year-long sequence).

Also I will recall that circa 2002 or so I was at another institution where I proposed this approach for our Java sequence, and other faculty argued that no, that wasn't logically possible when teaching Java. But here we are almost 20 years later and that's exactly what my current department does.

One more thing to consider: Among my friends who are practicing software engineers, one (in his late 20's) a few weeks ago complained bitterly to me that the pure-OOP philosophy with Java taught throughout his undergraduate program was almost entirely a waste, as he uses none of it for his work in web services. But functional thought is something he certainly uses daily, so he argued there should have been more of that in his education.


text:
# How do you factor 4c^2 – 9?

${a}^{2} - {b}^{2} = \left(a - b\right) \left(a + b\right)$
$4 {c}^{2} - 9$
$= {\left(2 c\right)}^{2} - {3}^{2}$
$= \left(2 c - 3\right) \left(2 c + 3\right)$


text:
1:13 AM
@JohnRennie Sir please justify this statement," solid state diffusion in metals is kinetically enabled."
@Buraian Also give a try to this..

4 hours later…
5:34 AM
@user586228 I have no idea what that means.

6 hours later…
11:50 AM
Does one-way speed of light can be infinite in some direction make any sense?
I just found a post a PSE post on this... physics.stackexchange.com/questions/590983/…

It is true that it's hard to design an experiment that unambiguously measures the one way speed of light. There are lots of irritating technical details that get in the way.
But we have to step back and take a common sense view of this. A speed of light that depended on direction would violate a fundamental symmetry of the universe and that's a big deal. Anything of that sort would be immediately obvious.
The fact we have never observed an violation of isotropy suggests that arguments about the one way speed of light are best left to those with too much free time.
6

12:20 PM
@JohnRennie Isn't this much like the interpretation of QM?

Interpretations of QM are also best left to people with too much free time :-)

2 hours later…
1:59 PM
Well that would explain why I have less interest in interpretations of QM as I get busier!

2:43 PM
Is there any sensible interpretation of the huge number of states that you have at each level in string theory? I.e. the $N=1$ state of the closed bosonic string has 576 states, do these all represent the exact same particle or is there something more to it?
Maybe a more specific question would be, does it matter which of these states we use in calculations?

@Charlie I can also write down a QFT that has 1000 fundamental particles, does that bother you, too?
no one says bosonic strings describe the real world, so why does the number of states matter?

Oh is bosonic string theory more of a toy model to introduce the subject?

Yes

Ah, I didn't know that, I guess it doesn't matter in that case, ty

the "real" models are the five 10d superstrings, and these still produce particle spectra for 10d SUGRA theories that you need to compactify to arrive at 4d spectra you can actually compare to the real world

2:48 PM
oh yikes is string theory not actually useful until you've done superstrings?
useful in the experimental sense, not for the purpose of torturing prospective students of the subject

it is debatable whether it is useful experimentally at all :P
but yes, without superstrings you cannot even hope to do something meaningful because you can't produce fermions with just bosonic strings, and the real world obviously contains fermions

3:14 PM
@ACuriousMind related nitpick to active vs passive
when computing variations, it might matter whether you're computing $\delta(v^\mu)$ vs $(\delta v)^\mu$
actually that's not an example :P
but if you're expressing things relative to a frame and not coordinates
the frame might be changing

3:33 PM
What are you actually varying in $(\delta v)^\mu$?
I've never seen varying an abstract vector itself before

@Charlie I think he's saying that if you have a moving frame (e.g. vielbein formalism) it matters in $\delta v^\mu$ where $\mu$ is w.r.t. the frame whether you're varying $v$ or varying the frame
@RyanUnger but I'm not actually sure which of the two versions is which :P

I didn't realise until the other day that the vier in vierbein come from the german for four
Because the word furfbein came up

3:50 PM
you mean fünfbein :P
'furf' isn't a word

oh yeah i mean funf
idk how you get your u to have eyes
2
I remember from school it's called an oomlau

German keyboards have a dedicated key for the umlauts :P

which is another word I'm almost definitely not spelling correctly
ah there you go lol

note also that vielbein isn't a typo for vierbein but 'viel' means many and hence 'vielbein' covers beins of all dimensions

I was hoping that fünfundzwanzigbein would be a thing in string theory and they called it stringbeins

3:53 PM
:(

but I have a feeling I'm going to be let down

I think the days when English scientists borrowed the German words for stuff are long gone
It's often easier for me to talk about physics in English than in German because I don't actually know the German words (if they even exist) for many of the more exotic terms

4:24 PM

4 hours later…
8:02 PM
(lol) yes, in some quarters, interpretations are like the rodney dangerfield of physics, not getting any respect. oh but, huh, people who worked on "so called" interpretations of QM: Bohr, Heisenberg, Einstein, Schroedinger, De Broglie, Bell, Bohm, ... and how about the latest cutting edge experiments that address interpretations? as the old slogan goes this aint your fathers oldsmobile™

8:39 PM
oh, on 2nd thought, have (further) axe to grind here; have recently been researching the area. and more recent inquirers, how about Gisin, Minev, Carmichael? if you ask me interpretations cut to the very heart of the foundations of QM, and points to the future, and incuriosity taken to extremes is unscientific. vzn1.wordpress.com/2021/02/04/…

9:39 PM
In tutoring lately, I have been amazed at how many students cannot write out Newton's second law for an object given the force diagram of that object

10:30 PM
what on earth are a Feynman propagator and a photon propagator?

Two passages that I especially enjoyed in “[28] Collapse. What else? / Gisin” is the one attacking many-worlds for being hyper-deterministic:
“Given the complexity of the (many-) worlds, it had to be encoded in some infinitesimal digits of some quantum state, possibly in the billionths of billionths decimal place. I am always astonished that some people seriously believe in that. Mathematical real numbers are undoubtedly very useful when doing our theory. But are they physically real [15]^8? (^8 recall that the assumption that real numbers are physically real implies that there could be an

@Bohemianrelativist Objects in QFT that are parts of Feynman diagrams

1 hour later…
11:52 PM
@Charlie the more often I read this line the harder it cracks me up and I will now imagine all umlauts with googly eyes


text:
# What is the pressure term appearing in Bernoulli's Equation? [duplicate]

In Bernoulli's equation the pressure plus kinetic and potential energy is constant. But what is this pressure term, physically? Is it the pressure of the fluid on the walls of the container or is it the pressure exerted on the fluid by the surroundings (air/liquid as air is also fluid). Because these two types of pressure are entirely different. In torricelli's law it is the pressure exerted by the atmosphere on the fluid and in venturimeter it is the pressure that the fluid under consideration exerts on the tube. I want some logical answers so that I could easily see what this pressure is physically - the formulas I know.