答:
Different variables behave differently in Ruby, but none of them need explicit declaration.

The most interesting behavior is for local variables: Ruby allows you to leave off the receiver for a message send to self (self is the implicit receiver), so foo() is the same thing as self.foo(), and it also allows you to leave off the argument list if there are no arguments, so foo.bar is the same thing as foo.bar(); putting the two together, we get that foo is the same thing as self.foo(), i.e. a message send without arguments to the implicit receiver self. It could, however, also be a reference to the local variable foo. This ambiguity is resolved the following way: foo is interpreted as a message send, unless an assignment to foo has been parsed (but not necessarily executed) before, then from that point on it is interpreted as a local variable.

This is the closest thing Ruby has to variable declaration:

```<code>foo
# NameError: undefined local variable or method `foo'

defined?(foo)
# => nil

def foo; 23 end

foo
# => 23

defined?(foo)
# => 'method'

methods
# => [:foo, …]

if false then foo = 42 end

foo
# => nil

defined?(foo)
# => 'local-variable'

local_variables
# => [:foo]
</code>```

Note that the NameError is not raised because the local variable is undefined, but because Ruby doesn't know what to make of the expression: is it a local variable or a method call?

Instance variables and global variables behave similarly, they evaluate to nil even if they are not defined:

```<code>@foo
# => nil

defined?(@foo)
# => nil

@foo = 42

@foo
# => 42

defined?(@foo)
# => 'instance-variable'

instance_variables
# => [:@foo]

$foo
# => nil

defined?($foo)
# => nil

$foo = 42

$foo
# => 42

defined?($foo)
# => 'global-variable'

global_variables
# => [:$foo, …]
</code>```

Class hierarchy variables and constants behave differently, they raise NameError if they are not defined:

```<code>@@foo
# NameError

defined?(@@foo)
# => nil

@@foo = 42

@@foo
# => 42

defined?(@@foo)
# => 'class-variable'

self.class.class_variables
# => [:@@foo]

FOO
# NameError

defined?(FOO)
# => nil

FOO = 42

FOO
# => 42

defined?(FOO)
# => 'constant'

self.class.constants
# => [:FOO]
</code>```

Title: Ruby Terminology Question: Implicit Declaration or no declaration at all?

Body:
I have a question, because in most serious sources I read, all say the same No variable is ever declared in Ruby, but still I have doubts, because according to what I was taught in my university implicit declaration is when a variable is created via allocation, where you can specify the type of a variable through conventions established in the language.

This contrasts with explicit declaration, when the data type specified in its declaration, like C... or at least that's what I understood.

So I was taught wrong?, or I misunderstood something?

Body:
Different variables behave differently in Ruby, but none of them need explicit declaration.

The most interesting behavior is for local variables: Ruby allows you to leave off the receiver for a message send to self (self is the implicit receiver), so foo() is the same thing as self.foo(), and it also allows you to leave off the argument list if there are no arguments, so foo.bar is the same thing as foo.bar(); putting the two together, we get that foo is the same thing as self.foo(), i.e. a message send without arguments to the implicit receiver self. It could, however, also be a reference to the local variable foo. This ambiguity is resolved the following way: foo is interpreted as a message send, unless an assignment to foo has been parsed (but not necessarily executed) before, then from that point on it is interpreted as a local variable.

This is the closest thing Ruby has to variable declaration:

foo
# NameError: undefined local variable or method `foo'

defined?(foo)
# => nil

def foo; 23 end

foo
# => 23

defined?(foo)
# => 'method'

methods
# => [:foo, …]

if false then foo = 42 end

foo
# => nil

defined?(foo)
# => 'local-variable'

local_variables
# => [:foo]

Note that the NameError is not raised because the local variable is undefined, but because Ruby doesn't know what to make of the expression: is it a local variable or a method call?

Instance variables and global variables behave similarly, they evaluate to nil even if they are not defined:

@foo
# => nil

defined?(@foo)
# => nil

@foo = 42

@foo
# => 42

defined?(@foo)
# => 'instance-variable'

instance_variables
# => [:@foo]

$foo
# => nil

defined?($foo)
# => nil

$foo = 42

$foo
# => 42

defined?($foo)
# => 'global-variable'

global_variables
# => [:$foo, …]

Class hierarchy variables and constants behave differently, they raise NameError if they are not defined:

@@foo
# NameError

defined?(@@foo)
# => nil

@@foo = 42

@@foo
# => 42

defined?(@@foo)
# => 'class-variable'

self.class.class_variables
# => [:@@foo]

FOO
# NameError

defined?(FOO)
# => nil

FOO = 42

FOO
# => 42

defined?(FOO)
# => 'constant'

self.class.constants
# => [:FOO]


问:
How to report progress on code research progress?
I am given a task which I need to do research on codebase and report my progress.

The dev environment is not set up. I can only read the code and analyze it, e.g. the workflow of user account creation.

There is a lot of uncertainty as my understanding on the code may not reflect the actual execution of the code.

I understand increase the visibility of my progress for everyone is good. But I don't know how to do it.

Thanks.

答:
Given that the question is about reporting progress I would propose adapting one of the agile development methodologies to your case.

More precisely:

Start dividing the bulk of research work in User Stories, each of them for the different parts of the basecode you have to cover. You don't need to know all the parts in advance, just capture the ones that according to your current understanding are the main ones.

For every User Story create the tasks that you think you will need to perform to gain understanding of the source code. For instance, a task could be Understand Class X, another Document how Instances of Class Y are created, or Determine the main responsibilities of Class Z, etc.

Use your preferred ticket system to register your User Stories and their Tasks.

Now you could use, say, TDD to approach the analysis. Take one task and write down the evidence you would consider sufficient to conclude that the task has been accomplished. One way to do this would be to design a form whose fields correspond to pieces of information the task is intended to find out. You could write Unit Tests that check that each of the information fields has been completed. You don't need anything fancy, a very simple parser on the content of a text file named after the task will suffice. Something on the lines of

```<code>    Class name:
    Responsibilities:
    Weaknesses:
    Collaborations:
    Dependencies:
    ...
</code>```

As you progress with this methodology you will discover new User Stories and new Tasks. You will also be able to create more unit tests that the fruits of your research should make them pass. The tests will give you a very clear visualization of progress. The records containing the information in the fields you will test will capture in a structured way the understanding you have developed so far.

One important thing that is not always recognized as valuable is the visualization of progress towards the horizon of knowledge you are trying to reach. So, let me explain this better.

It consists on a single plot that is very easy to draw and provides a lot of insights: Use the X axis to represent the time elapsed since day 1. Use the Y axis to represent the cumulative number of tasks identified so far. Since the Y axis is a cumulative quantity the curve will not decrease. In day 1 and 2 the plot would show the initial number of tasks you could identify. As the time elapses the number of tasks will increase. At certain point in time you will notice that you are still adding tasks, but now at a lower pace. This will give you an idea of convergence, meaning that you will see the horizontal asymptote that you should ideally reach.

The addition of tasks is not a smooth curve because you add tasks one day, and then work on them for say, a week or so. This is represented by the green curve. The black curve is a smooth fit. The top horizontal line (blue) is your current best guess of the asymptote. The distance between the actual curve and the asymptote is a measure of your unknown unknowns, the tasks you haven't identified yet, but eventually will.

Note that this graph doesn't include the (cumulative) number of tasks closed so far. You can add them and get many more insights. My point, however, is that even without this information you will be able to report progress in your understanding. The tasks closed so far will measure your known knowns. The difference between the total number of tasks and the number of closed ones will be a measure of your known unknowns.

And of course, if you want to be really rigorous you should use these graphs to provide probabilistic estimations of the time required to achieve intermediate milestones.

ContentLicense: CC BY-SA 3.0

Body:
Given that the question is about reporting progress I would propose adapting one of the agile development methodologies to your case.

More precisely:

Start dividing the bulk of research work in User Stories, each of them for the different parts of the basecode you have to cover. You don't need to know all the parts in advance, just capture the ones that according to your current understanding are the main ones.

For every User Story create the tasks that you think you will need to perform to gain understanding of the source code. For instance, a task could be Understand Class X, another Document how Instances of Class Y are created, or Determine the main responsibilities of Class Z, etc.

Use your preferred ticket system to register your User Stories and their Tasks.

Now you could use, say, TDD to approach the analysis. Take one task and write down the evidence you would consider sufficient to conclude that the task has been accomplished. One way to do this would be to design a form whose fields correspond to pieces of information the task is intended to find out. You could write Unit Tests that check that each of the information fields has been completed. You don't need anything fancy, a very simple parser on the content of a text file named after the task will suffice. Something on the lines of

    Class name:
    Responsibilities:
    Weaknesses:
    Collaborations:
    Dependencies:
    ...

As you progress with this methodology you will discover new User Stories and new Tasks. You will also be able to create more unit tests that the fruits of your research should make them pass. The tests will give you a very clear visualization of progress. The records containing the information in the fields you will test will capture in a structured way the understanding you have developed so far.

One important thing that is not always recognized as valuable is the visualization of progress towards the horizon of knowledge you are trying to reach. So, let me explain this better.

It consists on a single plot that is very easy to draw and provides a lot of insights: Use the X axis to represent the time elapsed since day 1. Use the Y axis to represent the cumulative number of tasks identified so far. Since the Y axis is a cumulative quantity the curve will not decrease. In day 1 and 2 the plot would show the initial number of tasks you could identify. As the time elapses the number of tasks will increase. At certain point in time you will notice that you are still adding tasks, but now at a lower pace. This will give you an idea of convergence, meaning that you will see the horizontal asymptote that you should ideally reach.

The addition of tasks is not a smooth curve because you add tasks one day, and then work on them for say, a week or so. This is represented by the green curve. The black curve is a smooth fit. The top horizontal line (blue) is your current best guess of the asymptote. The distance between the actual curve and the asymptote is a measure of your unknown unknowns, the tasks you haven't identified yet, but eventually will.

Note that this graph doesn't include the (cumulative) number of tasks closed so far. You can add them and get many more insights. My point, however, is that even without this information you will be able to report progress in your understanding. The tasks closed so far will measure your known knowns. The difference between the total number of tasks and the number of closed ones will be a measure of your known unknowns.

And of course, if you want to be really rigorous you should use these graphs to provide probabilistic estimations of the time required to achieve intermediate milestones.


问:
Repeating groups of arguments with argparse
Let's say that I want to enter info about multiple users from the command line AND that each user has multiple data associated with it.

Is it possible (syntactically permissible) to use argparse to parse something like myprpgrm.py --user john --email john@doe.com --valid Y --user jane --email jane@doe.com --valid N?

As you can see, each user should have 3 parameters associated with it - a name, an email and a valid flag.

Can argparse make sure that if a user parameter is seen, it must be accompanied by an email parameter and a validity parameter?

And can it give me the grouped information when I add multiple users, each with 3 parameters?

[Update] Could this be achieved somehow with Argument Groups?

答:
I wouldn't use command line arguments for this.  Command line arguments are meant for simple, transient configuration.  What you have here is structured data.  You want to put it into a more permanent format, such as JSON:

```<code>[
    {
        'user': 'john',
        'email': 'john@doe.com',
        'valid': true
    },
    {
        'user': 'jane',
        'email': 'jane@doe.com',
        'valid': false
    }
]
</code>```

Python conveniently has a module for parsing JSON:

```<code>import json

with open('path/to/data.json') as file:
    data = json.load(file)
</code>```

Argparse has special facilities for passing files on the command line; you probably won't have to call open() by yourself.

ContentLicense: CC BY-SA 4.0

Body:
I wouldn't use command line arguments for this.  Command line arguments are meant for simple, transient configuration.  What you have here is structured data.  You want to put it into a more permanent format, such as JSON:

[
    {
        'user': 'john',
        'email': 'john@doe.com',
        'valid': true
    },
    {
        'user': 'jane',
        'email': 'jane@doe.com',
        'valid': false
    }
]

Python conveniently has a module for parsing JSON:

import json

with open('path/to/data.json') as file:
    data = json.load(file)

Argparse has special facilities for passing files on the command line; you probably won't have to call open() by yourself.


问:
Understanding the differences: traditional interpreter, JIT compiler, JIT interpreter and AOT compiler
I'm trying to understand the differences between a traditional interpreter, a JIT compiler, a JIT interpreter and an AOT compiler.

An interpreter is just a machine (virtual or physical) that executes instructions in some computer language. In that sense, the JVM is an interpreter and physical CPUs are interpreters.

Ahead-of-Time compilation simply means compiling the code to some language before executing (interpreting) it.

However I'm not sure about the exact definitions of a JIT compiler and a JIT interpreter.

According to a definition I read, JIT compilation is simply compiling the code just before interpreting it.

So basically, JIT compilation is AOT compilation, done right before execution (interpretation)?

And a JIT interpreter, is a program that contains both a JIT compiler and an interpreter, and compiles code (JITs it) just before it interprets it?

Please clarify the differences.

答:
Overview

An interpreter for language X is a program (or a machine, or just some kind of mechanism in general) that executes any program p written in language X such that it performs the effects and evaluates the results as prescribed by the specification of X. CPUs are usually interpreters for their respective instructions sets, although modern high-performance workstation CPUs are actually more complex than that; they may actually have an underlying proprietary private instruction set and either translate (compile) or interpret the externally visible public instruction set.

A compiler from X to Y is a program (or a machine, or just some kind of mechanism in general) that translates any program p from some language X into a semantically equivalent program p′ in some language Y in such a way that the semantics of the program are preserved, i.e. that interpreting p′ with an interpreter for Y will yield the same results and have the same effects as interpreting p with an interpreter for X. (Note that X and Y may be the same language.)

The terms Ahead-of-Time (AOT) and Just-in-Time (JIT) refer to when compilation takes place: the "time" referred to in those terms is "runtime", i.e. a JIT compiler compiles the program as it is running, an AOT compiler compiles the program before it is running. Note that this requires that a JIT compiler from language X to language Y must somehow work together with an interpreter for language Y, otherwise there wouldn't be any way to run the program. (So, for example, a JIT compiler which compiles JavaScript to x86 machine code doesn't make sense without an x86 CPU; it compiles the program while it is running, but without the x86 CPU the program wouldn't be running.)

Note that this distinction doesn't make sense for interpreters: an interpreter runs the program. The idea of an AOT interpreter that runs a program before it runs or a JIT interpreter that runs a program while it is running is nonsensical.

So, we have:

AOT compiler: compiles before running

JIT compiler: compiles while running

interpreter: runs

JIT Compilers

Within the family of JIT compilers, there are still many differences as to when exactly they compile, how often, and at what granularity.

For example, some JIT compilers compile code as soon as it is loaded for the first time. Some JIT compilers wait until the code needs to be executed. Some JIT compilers compile code only once. Some may choose to recompile code later. Some compile whole modules or classes, some whole methods, some only smaller blocks.

Some compilers may gather information while the program is running and recompile code several times as new information becomes available that allows them to better optimize it. Some JIT compilers are even capable of de-optimizing code. Now, you might ask yourself why one would ever want to do that? De-optimizing allows you to perform very aggressive optimizations that might actually be unsafe: if it turns out you were too aggressive you can just back out again, whereas, with a JIT compiler that cannot de-optimize, the program would crash or return a wrong result; in other words, you simply can't allow yourself to perform the aggressive optimizations in the first place.

JIT compilers may either compile some static unit of code in one go (one module, one class, one function, one method, …; these are typically called method-at-a-time JIT, for example) or they may trace the dynamic execution of code to find dynamic traces (typically loops) that they will then compile (these are called tracing JITs).

Combining Interpreters and Compilers

Interpreters and compilers may be combined into a single language execution engine. There are two typical scenarios where this is done.

Combining an AOT compiler from X to Y with an interpreter for Y. Here, typically X is some higher-level language optimized for readability by humans, whereas Y is a compact language (often some kind of bytecode) optimized for interpretability by machines. For example, the CPython Python execution engine has an AOT compiler that compiles Python sourcecode to CPython bytecode and an interpreter that interprets CPython bytecode. Likewise, the (original) YARV Ruby execution engine has an AOT compiler that compiles Ruby sourcecode to YARV bytecode and an interpreter that interprets YARV bytecode. (Note: more recent versions of YARV also have a JIT compiler.) Why would you want to do that? Ruby and Python are both very high-level and somewhat complex languages, so we first compile them into a language that is easier to parse and easier to interpret, and then interpret that language.

The other way to combine an interpreter and a compiler is a mixed-mode execution engine. Here, we "mix" two "modes" of implementing the same language together, i.e. an interpreter for X and a JIT compiler from X to Y. (So, the difference here is that in the above case, we had multiple "stages" with the compiler compiling the program and then feeding the result into the interpreter, here we have the two working side-by-side on the same language.) Code that has been compiled by a compiler tends to run faster than code that is executed by an interpreter, but actually compiling the code first takes time (and particularly, if you want to heavily optimize the code to run really fast, it takes a lot of time). So, to bridge this time where the JIT compiler is busy compiling the code, the interpreter can already start running the code, and once the JIT is finished compiling, we can switch execution over to the compiled code. This means that we get both the best possible performance of the compiled code, but we don't have to wait for the compilation to finish, and our application starts running straight away (although not as fast as could be).

This is actually just the simplest possible application of a mixed-mode execution engine. More interesting possibilities are, for example, to not start compiling right away, but let the interpreter run for a bit, and collect statistics, profiling information, type information, information about the likelihood of which specific conditional branches are taken, which methods are called most often etc. and then feed this dynamic information to the compiler so that it can generate more optimized code. This is also a way to implement the de-optimization I talked about above: if it turns out that you were too aggressive in optimizing, you can throw away (a part of) the code and revert back to interpreting. The HotSpot JVM does this, for example. It contains both an interpreter for JVM bytecode as well as a compiler for JVM bytecode. (In fact, it actually contains two compilers!)

It is also possible and in fact common to combine those two approaches: two phases with the first being an AOT compiler that compiles X to Y and the second phase being a mixed-mode engine that both interprets Y and compiles Y to Z. The Rubinius Ruby execution engine works this way, for example: it has an AOT compiler that compiles Ruby sourcecode to Rubinius bytecode and a mixed-mode engine that first interprets Rubinius bytecode and once it has gathered some information compiles the most often called methods into native machine code. The same applies to current versions of YARV.

Note that the role that the interpreter plays in the case of a mixed-mode execution engine, namely providing fast startup, and also potentially collecting information and providing fallback capability may alternatively also be played by a second JIT compiler.

This is how the second generation of Google's V8 ECMAScript engine worked, for example. This generation of V8 never interprets, it always compiles. The first compiler is a very fast, very slim compiler that starts up very quick. The code it produces isn't very fast, though. This compiler also injects profiling code into the code it generates. The other compiler is slower and uses more memory, but produces much faster code, and it can use the profiling information collected by running the code compiled by the first compiler. (Note: V8 has significantly changed in the meantime. It now also has an interpreter, for example.)


问:
the perils of using eval() for dynamic object creation -- is this a valid argument in a consenting-adults culture?
I've read on stackoverflow explicit warnings against using eval() to create objects.  The reason that seems to be given is that malicious code could be injected and blindly created objects could compromise a system.  Isn't this malicious-intent argument invalidated by the consenting-adult argument, though?

Some sample code:

```<code>class Test(object):
    def __init__(self, vala, valb, valc):
        self._vala = vala
        self._valb = valb
        self._valc = valc

    def __repr__(self):
        return "<Test(vala={0}, valb={1}, valc={2})>".format(self._vala, self._valb, self._valc)

testlist = [dict(cls="Test", vala="this is vala", valb="this is valb", valc="this is valc"), dict(cls="Test", vala="this is vala II", valb="this is valb II", valc="this is valc II")]

mytestobjects = []

for test in testlist:
    newobj = eval(test['cls'])(**{key: value for key, value in test.items() if key != "cls"})
    mytestobjects.append(newobj)

print(mytestobjects)
</code>```

答:
This is done by Python's stdlib, in collections.namedtuple(), though they do use exec() rather than eval().  When I reported a possible code-injection vulnerability (initially to python-security), it was fixed, but not treated as a security issue.  In particular, they kept the exec() despite the existence of a patch which avoided it.

As I understand it, the Python developers are allowing practicality to beat purity in this case.  The patch is rather complex and involves metaclasses and other cleverness, while the exec() is easier to understand.  Moreover, it's uncommon to call collections.namedtuple() with untrusted user input, and even more uncommon to pass the kind of strange object I had to construct to get around the safety checks already in place.

I probably wouldn't use this technique myself unless I had no other viable options, but I'm not quite sure I can reasonably call this implementation wrong.


问:
Programming language heritage of the word 'field'
What programming language introduced the word "field" to describe what we might call a member variable in C++? What modern programming languages carry on this usage as the preferred term?

I've seen this word used in both a C and C++ context but it always feels a bit foreign. I don't have a copy of  the C standard, but the C++ standard  uses the phrase "member variable". (It does use the word "field" in the phrase "bit-field".) Whenever I hear this I can't help but wonder where the speaker got that word from.

答:
Field is used in Eiffel, Java, C#, and VB.NET. In Smalltalk and some of its descendants and languages inspired by it (e.g. Ruby), it is called instance variable, in Self and languages inspired by it (Newspeak, Io, Korz), it is called slot. Simula and Python call it attribute (which means something else in C# and something yet different in Ruby), ECMAScript calls it property (which is of course something else in C#), C++ calls it member variable.

So, the term "field" does not come from one of the OO pioneer languages (Simula or Smalltalk). Eiffel predates Java and C#, so at least of all the languages that I am personally familiar with, Eiffel is the one which is most likely to be the origin of the term.

However, it does seem to be a rather obvious term, in analogy to fields on a form.


问:
How do I avoid cascading refactorings?
I've got a project. In this project I wished to refactor it to add a feature, and I refactored the project to add the feature.

The problem is that when I was done, it turned out that I needed to make a minor interface change to accommodate it. So I made the change. And then the consuming class can't be implemented with its current interface in terms of the new one, so it needs a new interface as well. Now it's three months later, and I've had to fix innumerable virtually unrelated problems, and I'm looking at solving issues that were roadmapped for a year from now or simply listed as won't fix due to difficulty before the thing will compile again.

How can I avoid this kind of cascading refactorings in the future? Is it just a symptom of my previous classes depending too tightly on each other?

Brief edit: In this case, the refactor was the feature, since the refactor increased the extensibility of a particular piece of code and decreased some coupling. This meant that external developers could do more, which was the feature I wanted to deliver. So the original refactor itself should not have been a functional change.

Bigger edit that I promised five days ago:

Before I began this refactor, I had a system where I had an interface, but in the implementation, I simply dynamic_cast through all the possible implementations that I shipped. This obviously meant that you couldn't just inherit from the interface, for one thing, and secondly, that it would be impossible for anybody without implementation access to implement this interface. So I decided that I wanted to fix this issue and open up the interface for public consumption so that anybody could implement it and that implementing the interface was the entire contract required- obviously an improvement.

When I was finding and killing-with-fire all the places that I had done this, I found one place that proved to be a particular problem. It depended upon implementation details of all the various deriving classes and duplicated functionality that was already implemented but better somewhere else. It could have been implemented in terms of the public interface instead and re-used the existing implementation of that functionality. I discovered that it required a particular piece of context to function correctly. Roughly speaking, the calling previous implementation looked kinda like

```<code>for(auto&& a : as) {
     f(a);
}
</code>```

However, to get this context, I needed to change it into something more like

```<code>std::vector<Context> contexts;
for(auto&& a : as)
    contexts.push_back(g(a));
do_thing_now_we_have_contexts();
for(auto&& con : contexts)
    f(con);
</code>```

This means that for all operations that used to be a part of f, some of them need to be made a part of the new function g that operates without a context, and some of them need to be made of a part of the now-deferred f. But not all methods f call need or want this context- some of them need a distinct context that they obtain through separate means. So for everything that f ends up calling (which is, roughly speaking, pretty much everything), I had to determine what, if any, context they needed, where they should get it from, and how to split them from old f into new f and new g.

And that's how I ended up where I am now. The only reason that I kept going is because I needed this refactoring for other reasons anyway.

答:
From (the wonderful) book Working Effectively with Legacy Code by Michael Feathers:

When you break dependencies in legacy code, you often have to suspend your sense of aesthetics a bit. Some dependencies break cleanly; others end up looking less than ideal from a design point of view. They are like the incision points in surgery: there might be a scar left in your code after your work, but everything beneath it can get better.

If later you can cover code around the point where you broke the dependencies, you can heal that scar, too.

Title: How do I avoid cascading refactorings?


问:
Is it always a best practice to write a function for anything that needs to repeat twice?
Myself, I can't wait to write a function when I need to do something more than twice. But when it comes to things that only appear twice, it's a bit more tricky.

For code that needs more than two lines, I'll write a function. But when facing things like:

```<code>print "Hi, Tom"
print "Hi, Mary"
</code>```

I'm hesitant to write:

```<code>def greeting(name):
    print "Hi, " + name

greeting('Tom')
greeting('Mary')
</code>```

The second one seems too much, doesn't it?

But what if we have:

```<code>for name in vip_list:
    print name
for name in guest_list:
    print name
</code>```

And here is the alternative:

```<code>def print_name(name_list):
    for name in name_list:
        print name

print_name(vip_list)
print_name(guest_list)
</code>```

Things become tricky, no? It's hard to decide now.

What's your opinion about this?

答:
No, it's not always a best practice.

All other things being equal, linear, line-by-line code is easier to read than jumping around function calls.  A non-trivial function call always takes parameters, so you have to sort all that out and make mental contextual jumps from function call to function call.  Always favor better code clarity, unless you have a good reason for being obscure (such as obtaining necessary performance improvements).

So why is code refactored into separate methods then?  To improve modularity.  To collect significant functionality behind an individual method and give it a meaningful name.  If you're not accomplishing that, then you don't need those separate methods.


答:
There is no hard and fast rule that must be applied, it will depend on the actual function that would be used. For simple name printing I would not use a function but if it is a maths sum that would be a different story. You then would create a function even if it only gets called twice, this is to ensure that the maths sum is always the same if ever changed. In another example if you are doing any form of validation you would use a function, so in your example if you needed to check the name is longer than 5 characters you would use a function to ensure the same validations are always done.

So I think you answered your own question when you stated "For codes that need more than two lines, I'll got to write a func". In general you would be using a function but you must also use your own logic to determine if there is any kind of value add from using a function.

Title: Is it always a best practice to write a function for anything that needs to repeat twice?

Body:
Myself, I can't wait to write a function when I need to do something more than twice. But when it comes to things that only appear twice, it's a bit more tricky.

For code that needs more than two lines, I'll write a function. But when facing things like:

```<code>print "Hi, Tom"
print "Hi, Mary"
</code>```

I'm hesitant to write:

```<code>def greeting(name):
    print "Hi, " + name

greeting('Tom')
greeting('Mary')
</code>```

The second one seems too much, doesn't it?

But what if we have:

```<code>for name in vip_list:
    print name
for name in guest_list:
    print name
</code>```

And here is the alternative:

```<code>def print_name(name_list):
    for name in name_list:
        print name

print_name(vip_list)
print_name(guest_list)
</code>```

Things become tricky, no? It's hard to decide now.

What's your opinion about this?


答:
Although it's one factor in deciding to split off a function, the number of times something is repeated shouldn't be the only factor.  It often makes sense to create a function for something that's only executed once.  Generally, you want to split a function when:

It simplifies each individual abstraction layer.

You have good, meaningful names for the split-off functions, so you don't usually need to jump around between abstraction layers to understand what's going on.

Your examples don't meet that criteria.  You're going from a one-liner to a one-liner, and the names don't really buy you anything in terms of clarity. That being said, functions that simple are rare outside of tutorials and school assignments.  Most programmers tend to err too far the other way.


答:
It's seldom clear-cut, so you need to weigh options:

Deadline (fix burning server room ASAP)

Code readability (may influence choice either way)

Shared logic's level of abstraction (related to above)

Re-use requirement (i.e. is having exact same logic important, or just convenient right now)

Difficulty of sharing (here is wher python shines, see below)

In C++, I usually go by the rule of three (i.e. the third time I need the same thing, I refactor it into a properly sharable piece), but with experience it's easier to make that choice initially as you know more about the scope, software & domain you're working with.

However, in Python it is fairly light-weight to reuse, rather than repeat, logic. More so than in many other languages (at least historically), IMO.

So, consider just re-using the logic locally, for instance by by creating a list from local arguments:

```<code>def foo():
    for name_list in (vip_list, guest_list): # can be list of tuples, for many args
        for name in name_list:
            print name
</code>```

You can use a tuple of tuples, and split it directly into the for-loop, if you need several arguments:

```<code>def foo2():
    for header, name_list in (('vips': vip_list), ('people': guest_list)):
        print header + ": "
        for name in name_list:
            print name
</code>```

or make a local function (maybe your second example is that), which makes the logic re-use explicit but also clearly shows that print_name() isn't used outside the function:

```<code>def foo():
    def print_name(name_list):
        for name in name_list:
            print name

    print_name(vip_list)
    print_name(guest_list)
</code>```

Functions are preferable especially when you need to abort the logic in the middle (i.e. use return), as break or exceptions might clutter things unnecessarily.

Either is superior to repeating the same logic, IMO, and also less cluttering than declaring a global/class function that is only used by one caller (albeit twice).

Body:
It's seldom clear-cut, so you need to weigh options:

Deadline (fix burning server room ASAP)

Code readability (may influence choice either way)

Shared logic's level of abstraction (related to above)

Re-use requirement (i.e. is having exact same logic important, or just convenient right now)

Difficulty of sharing (here is wher python shines, see below)

In C++, I usually go by the rule of three (i.e. the third time I need the same thing, I refactor it into a properly sharable piece), but with experience it's easier to make that choice initially as you know more about the scope, software & domain you're working with.

However, in Python it is fairly light-weight to reuse, rather than repeat, logic. More so than in many other languages (at least historically), IMO.

So, consider just re-using the logic locally, for instance by by creating a list from local arguments:

def foo():
    for name_list in (vip_list, guest_list): # can be list of tuples, for many args
        for name in name_list:
            print name

You can use a tuple of tuples, and split it directly into the for-loop, if you need several arguments:

def foo2():
    for header, name_list in (('vips': vip_list), ('people': guest_list)):
        print header + ": "
        for name in name_list:
            print name

or make a local function (maybe your second example is that), which makes the logic re-use explicit but also clearly shows that print_name() isn't used outside the function:

def foo():
    def print_name(name_list):
        for name in name_list:
            print name

    print_name(vip_list)
    print_name(guest_list)

Functions are preferable especially when you need to abort the logic in the middle (i.e. use return), as break or exceptions might clutter things unnecessarily.

Either is superior to repeating the same logic, IMO, and also less cluttering than declaring a global/class function that is only used by one caller (albeit twice).


问:
Why empty function are needed
I started learning Python and I am wondering why empty function are needed in a programming language.

e.g. in python:

```<code>def empty_func():
    pass
</code>```

Even in shell scripts empty functions are available.

My Understandings and question:

Why do programming languages need empty functions?  Is it for just playing around with programming language or nothing else that really matters?

If this has a purpose, can anyone describe the use case or give a real example of the usage of empty functions?

Or is there any tradition of programming languages allowing empty functions?

EDIT (Things I got from reading your answers):

For Sketching Algorithms or with Abstract Functions

For Submitting forms with no action needs to be performed

Placeholder for some mandatory operations

答:
In shell languages of the Bourne family, the : command, which does nothing at all, is typically used in two situations:

Placeholder for when something expects a mandatory command, e.g.

```<code>while some_condtion
do :
done
</code>```

since do requires at least one command.

Discarding the arguments, but performing side effects inside the argument list, e.g.

```<code>: ${myvar=foo}
</code>```

I'm sure there are probably other applications that shell experts would know :)

In Python (and other languages) it's used less frequently.  It can act as an argument to a higher-order function when you don't actually want to do anything.  For example, say you have a function that submits a form and allows an function to be called asynchronously after submission is complete:

```<code>def submit(callback=empty_func):
    ...
</code>```

This way, if the callback is not provided, the submission will still go through but no further actions will be performed.  If you had used None as the default value, you'd have to explicitly check whether the callback was None, adding clutter to the code.

Title: Why empty function are needed

Body:
In shell languages of the Bourne family, the : command, which does nothing at all, is typically used in two situations:

Placeholder for when something expects a mandatory command, e.g.

while some_condtion
do :
done

since do requires at least one command.

Discarding the arguments, but performing side effects inside the argument list, e.g.

: ${myvar=foo}

I'm sure there are probably other applications that shell experts would know :)

In Python (and other languages) it's used less frequently.  It can act as an argument to a higher-order function when you don't actually want to do anything.  For example, say you have a function that submits a form and allows an function to be called asynchronously after submission is complete:

def submit(callback=empty_func):
    ...

This way, if the callback is not provided, the submission will still go through but no further actions will be performed.  If you had used None as the default value, you'd have to explicitly check whether the callback was None, adding clutter to the code.


问:
Disadvantages of scoped-based memory management
I really like scope-based memory management (SBMM), or RAII, as it is more commonly (confusingly?) referred to by the C++ community. As far as I know, except for C++ (and C), there's no other mainstream language in use today that makes SBMM/RAII their main memory management mechanism, and instead they prefer to use garbage collection (GC).

I find this rather confusing, since

SBMM makes programs more deterministic (you can tell exactly when an object is destroyed);

in languages that use GC you often have to do manual resource management (see closing files in Java, for example), which partly defeats the purpose of GC and is also error prone;

heap memory can also (very elegantly, imo) be scope-bound (see std::shared_ptr in C++).

Why is not SBMM more widely used? What are its disadvantages?

答:
SBMM makes programs more deterministic (you can tell exactly when an object is destroyed);

For most programmers the OS is non-deterministic, their memory allocator is non-deterministic and most of the programs they write are concurrent and, therefore, inherently non-deterministic. Adding the constraint that a destructor is called exactly at the end of scope rather than slightly before or slightly after is not a significant practical benefit for the vast majority of programmers.

in languages that use GC you often have to do manual resource management (see closing files in Java, for example), which partly defeats the purpose of GC and is also error prone;

See using in C# and use in F#.

heap memory can also (very elegantly, imo) be scope-bound (see std::shared_ptr in C++).

In other words, you could take the heap which is a general purpose solution and change it to only work in a specific case that is seriously limiting. That is true, of course, but useless.

Why is not SBMM more widely used? What are its disadvantages?

SBMM limits what you can do:

SBMM creates the upward funarg problem with first-class lexical closures which is why closures are popular and easy to use in languages like C# but rare and tricky in C++. Note that there is a general trend towards the use of functional constructs in programming.

SBMM requires destructors and they impede tail calls by adding more work to do before a function can return. Tail calls are useful for extensible state machines and are provided by things like .NET.

Some data structures and algorithms are notoriously difficult to implement using SBMM. Basically anywhere that cycles are naturally occurring. Most notably graph algorithms. You effectively end up writing your own GC.

Concurrent programming is harder because control flow and, therefore, object lifetimes are inherently non-deterministic here. Practical solutions in message passing systems tend to be deep copying of messages and the use of excessively long lifetimes.

SBMM keeps objects alive until the end of their scope in the source code which is often longer than necessary and can be far longer than necessary. This increases the amount of floating garbage (unreachable objects waiting to be recycled). In contrast, tracing garbage collection tends to free objects soon after the last reference to them disappears which can be much sooner. See Memory management myths: promptness.

SBMM is so limiting that programmers need an escape route for situations where lifetimes can not be made to nest. In C++, shared_ptr offers an escape route but it can be ~10x slower than tracing garbage collection. So using SBMM instead of GC would put most people wrong footed most of the time. That is not to say, however, that it is useless. SBMM is still of value in the context of systems and embedded programming where resources are limited.

FWIW you might like to check out Forth and Ada, and read up on the work of Nicolas Wirth.


答:
In general I agree with Robert Harvey, but wanted to add a case to split up a functionality into functions. To improve readability. Consider a case:

```<code>def doIt(smth,smthElse)
    for x in getDataFromSomething(smth,smthElse):
        if not check(x,smth):
            continue
        process(x,smthElse)
        store(x)
</code>```

Even though those function calls are not used anywhere else, there is significant gain in readability if all 3 functions are considerably long and have nested loops etc.

Body:
In general I agree with Robert Harvey, but wanted to add a case to split up a functionality into functions. To improve readability. Consider a case:

def doIt(smth,smthElse)
    for x in getDataFromSomething(smth,smthElse):
        if not check(x,smth):
            continue
        process(x,smthElse)
        store(x)

Even though those function calls are not used anywhere else, there is significant gain in readability if all 3 functions are considerably long and have nested loops etc.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
If you can't measure it, you can't
  improve it.

Lord Kelvin

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Why are return values from compare functions in many languages defined loosely?
Many languages define that compare functions should return ANY negative value, zero, or ANY positive value.  Is there some reason that it shouldn't be clearly defined as -1 0 and 1?  Does a wide range in possible return values help more advanced algorithms to work more efficiently?  If so, what algorithms work this way?</p>

答:
For simple use cases it allows for a very trivial implementation:

```<code>public int compare(Child a, Child b) {
    return a.age - b.age;
}
//sort children by age to determine who babysits
</code>```

Meanwhile if more complex logic is required it is still easy to return the magic numbers -1, 0, or 1 once order is determined.

As CodesInChaos says in the comments the subtraction method fails to accommodate any overflow that may occur. General purpose libraries require greater robustness and complexity in their comparisons.

Here are a couple of a battle tested implementations:

Java's Integer.compare():

```<code>public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
</code>```

Mono's Int32.CompareTo():

```<code>public int CompareTo (object value)
{
    if (value == null)
        return 1;

    if (!(value is System.Int32))
        throw new ArgumentException (Locale.GetText ("Value is not a System.Int32"));

    int xv = (int) value;
    if (m_value == xv)
        return 0;
    if (m_value > xv)
        return 1;
    else
        return -1;
}
</code>```

As you can see both of these apply the required logic then return the appropriate magic number.

Body:
For simple use cases it allows for a very trivial implementation:

public int compare(Child a, Child b) {
    return a.age - b.age;
}
//sort children by age to determine who babysits

Meanwhile if more complex logic is required it is still easy to return the magic numbers -1, 0, or 1 once order is determined.

As CodesInChaos says in the comments the subtraction method fails to accommodate any overflow that may occur. General purpose libraries require greater robustness and complexity in their comparisons.

Here are a couple of a battle tested implementations:

Java's Integer.compare():

public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

Mono's Int32.CompareTo():

public int CompareTo (object value)
{
    if (value == null)
        return 1;

    if (!(value is System.Int32))
        throw new ArgumentException (Locale.GetText ("Value is not a System.Int32"));

    int xv = (int) value;
    if (m_value == xv)
        return 0;
    if (m_value > xv)
        return 1;
    else
        return -1;
}

As you can see both of these apply the required logic then return the appropriate magic number.


答:
If you allow comparison function to return any negative value instead of exactly -1, this can make for a simpler implementation. For instance, you can write

```<code>return this.position - that.position;
</code>```

instead of having to write

```<code>if(this.position == that.position) {
    return 0;
}
else if(this.position < that.position) {
    return -1;
} else
    return 1;
}
</code>```

(The alternative is to use an operator, like Perl's <=>, that generates exactly -1, 0, or 1. But it's easier to define a lenient API than to get a new operator into your language, unless you're Larry Wall.)

Title: Why are return values from compare functions in many languages defined loosely?

Body: Many languages define that compare functions should return ANY negative value, zero, or ANY positive value.  Is there some reason that it shouldn't be clearly defined as -1 0 and 1?  Does a wide range in possible return values help more advanced algorithms to work more efficiently?  If so, what algorithms work this way?</p>

Body:
If you allow comparison function to return any negative value instead of exactly -1, this can make for a simpler implementation. For instance, you can write

return this.position - that.position;

instead of having to write

if(this.position == that.position) {
    return 0;
}
else if(this.position < that.position) {
    return -1;
} else
    return 1;
}

(The alternative is to use an operator, like Perl's <=>, that generates exactly -1, 0, or 1. But it's easier to define a lenient API than to get a new operator into your language, unless you're Larry Wall.)


答: It's because when you do a compare you are usually just taking the difference of two values and instead of wasting more time and effort into mapping the result to {-1,0,1}, just leave the result and define the function as so. For example x.comparedTo(y) = 0 means that if x and y are both 5, (5 - 5) = 0 but if x = 100 and y = 150, (100 - 150) = -50 and so x < y.


问:
Parsing input into multiple subclasses
Lets say I have 10 xml message types that come into my program via some type of input (file, port, etc). I have 10 subclasses of a type Message to handle the unique needs of each message type.

When a new message comes in, is there a better way than a switch statement that switches on a substring of the message, or a huge if/elseif tree to decide which subclass of Message I need to instantiate with the incoming message string?

I'd like to pass the string to a factory and have the proper subclass returned, but I am unable to find a way that does not use a switch statement.

edit:
I did not specify a language because I've run into a similar situation in more than one language so I wanted a generic solution.

答:
There are three general approaches to deciding which sub-class to construct when you only have a serialized data stream.

Hard-code the Message sub-classes and their identifying tags in the Factory class and select the right Message using a switch or if/else ladder.

The Factory class keeps a dynamic registry of supported Message sub-classes and performs a linear search over the registry to select the correct Message sub-class. This solution requires that somehow the Message sub-classes get registered with the Factory and the Factory needs to be able to instantiate classes that it doesn't really know about (the Factory only knows about the base Message class). This can be done by registering a factory function or a prototype object for each Message sub-class.

You use reflection to match the XML tag to a Message sub-class. This all but requires that the class names correspond to the XML tag names.

Title: Parsing input into multiple subclasses


问:
How to prove that this while loop calculates n^2
I'm studying for my exam of logic later this week and I have to prove that this while loop:

```<code>i := 0
s := 0
while i < n do
    i := i + 1
    s := s + (2*i -1)
</code>```

calculates n^2. This question is made up of 2 subquestions. We have to prove that 0 ≤ i ≤ n ∧ s = i^2 is a loop invariant for this while loop. I managed to prove that, but the second subquestion is that I have to prove that this loop calculates n^2, but I don't really know how to start. The course is a bit confusing about this part of the question.

答: The loop calculates 1 + 3 + 5 + 7 + ... + (2n-1). The easiest way to visualise that this sums to n^2 is


答:
Using the formula of arithmetic progression we can derive it directly:

number of elements is n, first element is 1 last element is 2*n-1

```<code>n*(1 + 2*n-1)/2 = n*(2*n) /2 = n*n
</code>```

Title: How to prove that this while loop calculates n^2

Body:
I'm studying for my exam of logic later this week and I have to prove that this while loop:

```<code>i := 0
s := 0
while i < n do
    i := i + 1
    s := s + (2*i -1)
</code>```

calculates n^2. This question is made up of 2 subquestions. We have to prove that 0 ≤ i ≤ n ∧ s = i^2 is a loop invariant for this while loop. I managed to prove that, but the second subquestion is that I have to prove that this loop calculates n^2, but I don't really know how to start. The course is a bit confusing about this part of the question.

Body:
Using the formula of arithmetic progression we can derive it directly:

number of elements is n, first element is 1 last element is 2*n-1

n*(1 + 2*n-1)/2 = n*(2*n) /2 = n*n


问:
Backend as a Service (BAAS): temporary or long term solution?
Right now I'm building an app that relies heavily on Parse.com's products. The app uses nearly all of their features:

Data storage

User management

Push messages

Analytics

Crash reporting

There are of course upsides

Very very fast development: less time to market

Service reliability

Free of cost (to a certain extent)

No server setup

and downsides

the risk of BAAS shutting down: that would render the app worthless

what happens to my data

What do you think?

答:
I am hesitant to provide an answer to your question, since it has a side of general micro economy question that is not really on-topic here at Programmers SE.  But, since the site also allows questions of professional interest to programmers (as far as I remember), I think your question falls into the scope.

I would answer that the general problem you are talking about is called Vendor lock-in, and the usual solution is to establish standards in the market.

In a more specific, technical sense, you could establish your own "market standardization" by decoupling your software from the BAAS' services through your own API abstraction library.


答:
Personally I have adopted the rule of three - which I'll justify by calling YAGNI. If I need to do something once I'll write that code, twice I may just copy / paste (yes I just admitted to copy/paste!) because I ain't gonna need it again, but if I need to do the same thing again then I'll refactor and extract that chunk into it's own method, I've demonstrated, to myself, that I will need it again.

I agree with what Karl Bielefeldt and Robert Harvey have said and my interpretation of what they're saying is that the overriding rule is readability. If it makes my code easier to read then consider creating a function, keep in mind things like DRY and SLAP. If I can avoid having changing level of abstraction in my function then I find that easier to manage in my head, so not jumping between functions (if I can't understand what the function does simply by reading it's name) means fewer switches in my mental processes.

Likewise not having to switch context between functions and inline code such as print "Hi, Tom" works for me, in this case I might extract a function PrintNames() iff the rest of my overall function were mostly function calls.


答:
In your particular example making a function may seem overkill; instead I would ask the question: is it possible that this particular greeting will change in the future? How so?

Functions are not simply used to wrap up functionality and ease reuse, but also to ease modification. If requirements change, copy-pasted code will need to be hunted down and changed manually, while with a function the code needs to be modified only once.

Your example would benefit from this not via a function - since the logic is nearly non-existent - but possibly a GREET_OPENING constant. This constant could then be loaded from file so that your program would be easily adaptable to different languages, for example. Note that this is a crude solution, a more complex program would probably need a more refined way to track i18n, but again it depends on requirements vs work to do.

It's all about possible requirements in the end, and planning things in advance to ease your future self's job.


答:
The Command pattern would likely best suit your needs in this case.  Have a MessageHandler base class that has two methods.

The first would be called IsHandlerFor that takes as input the xml and returns true if it is the proper handler for that specific type of message.  Then you'd have a second method called Handle that takes the xml and performs the proper action with it.

You would have a MessageBus class that initially instantiates a list of these handlers.  If you wish to separate concerns further, you could use a factory, pass it to the constructor of MessageBus, or use reflection and a configuration file.

Then when a new message is received, you loop through all your MessageHandlers calling IsHandlerFor.  If it returns true, you call its Handle method.  If you're sure that there will only be one such handler, break out of your loop.  Otherwise, continue for all handlers and without knowing how each handler works, you've managed to handle a message without using a switch and by modularizing your code.

Hope that helps.

Title: Parsing input into multiple subclasses

Body:
Lets say I have 10 xml message types that come into my program via some type of input (file, port, etc). I have 10 subclasses of a type Message to handle the unique needs of each message type.

When a new message comes in, is there a better way than a switch statement that switches on a substring of the message, or a huge if/elseif tree to decide which subclass of Message I need to instantiate with the incoming message string?

I'd like to pass the string to a factory and have the proper subclass returned, but I am unable to find a way that does not use a switch statement.

edit:
I did not specify a language because I've run into a similar situation in more than one language so I wanted a generic solution.


答:
You could also prove this by a method called 'mathematical induction', which works for positive integers.

To put it simply: You assume that you statement about the loop is true for a arbitrary 'n' and so it's also true for 'n+1' and therefore for every integer bigger than your lower border (which normally is 1, but in your case, 0 works as well).

It's a way more mathematical approach and so you may like it or you hate it. But here we go:

If you're not familiar with the sigma operator in mathematics, this is how it works. It's simply a 'for' loop, with 'a' being the starting value and 'b' being the included upper limit. It increases 'a' every 'iteration' by one and sums the values together.

So mathematically, your problem could be written like this:

Now, for mathematical induction to work, we first have to prove that this statement is true for the lowest value of 'n' (this would normally be 1, but 0 works here as well):

Which definitely is true.

And thats true as well.

Great, so let's move on to the 'exciting' part... Proving this statement for any (positive integer) 'n' by replacing 'n' with 'n + 1':

Now, this looks quite complicated, but let's analyse it step by step. The first part is exactly the same as in the second picture, but now every 'n' is replaced by 'n + 1'. The second part (after the '->' and there especially the left side of the equation) may not be obvious at the first glance. But from a programmers point of view it might be a bit easier to understand, because

```<code>for(int i = 0; i <= n; i++)
{
    ...Do sth here.
}
</code>```

is exactly the same as

```<code>for(int i = 0; i <= l; i++)
{
    ...Do sth here (part 1)
}

for(int i = l + 1; i <= n; i++)
{
    ...Do sth here (part 2)
}
</code>```

On the right side of the equation I simply expanded '(n + 1)^2' to 'n^2 + 2n + 1'.
Now the final spurt:

Since for our second 'loop' (=sigma operator) the upper value equals the lower value, we don't need it at all. There's only one iteration with this particular value, so we simply can replace 'k' with 'n + 1', which then gives us '2*(n + 1) - 1'. So we now have still the same sigma left, which we had in the beginning and we wanted to prove being 'n' squared. So to get rid of it, we simply can replace it by 'n^2' in the second part (after the '->'), because if our assumption is true, there is no difference between them. We now have 'n^2' on both sides, so we can simply subtract it to get rid of it as well.

So whats now left we can simply out multiply and eventually get an equation, which is true as well. Therefore we have proven that a loop summing up all odd numbers (starting from 1 up to '2n - 1') equals 'n^2'.

Body:
You could also prove this by a method called 'mathematical induction', which works for positive integers.

To put it simply: You assume that you statement about the loop is true for a arbitrary 'n' and so it's also true for 'n+1' and therefore for every integer bigger than your lower border (which normally is 1, but in your case, 0 works as well).

It's a way more mathematical approach and so you may like it or you hate it. But here we go:

If you're not familiar with the sigma operator in mathematics, this is how it works. It's simply a 'for' loop, with 'a' being the starting value and 'b' being the included upper limit. It increases 'a' every 'iteration' by one and sums the values together.

So mathematically, your problem could be written like this:

Now, for mathematical induction to work, we first have to prove that this statement is true for the lowest value of 'n' (this would normally be 1, but 0 works here as well):

Which definitely is true.

And thats true as well.

Great, so let's move on to the 'exciting' part... Proving this statement for any (positive integer) 'n' by replacing 'n' with 'n + 1':

Now, this looks quite complicated, but let's analyse it step by step. The first part is exactly the same as in the second picture, but now every 'n' is replaced by 'n + 1'. The second part (after the '->' and there especially the left side of the equation) may not be obvious at the first glance. But from a programmers point of view it might be a bit easier to understand, because

for(int i = 0; i <= n; i++)
{
    ...Do sth here.
}

is exactly the same as

for(int i = 0; i <= l; i++)
{
    ...Do sth here (part 1)
}

for(int i = l + 1; i <= n; i++)
{
    ...Do sth here (part 2)
}

On the right side of the equation I simply expanded '(n + 1)^2' to 'n^2 + 2n + 1'.
Now the final spurt:

Since for our second 'loop' (=sigma operator) the upper value equals the lower value, we don't need it at all. There's only one iteration with this particular value, so we simply can replace 'k' with 'n + 1', which then gives us '2*(n + 1) - 1'. So we now have still the same sigma left, which we had in the beginning and we wanted to prove being 'n' squared. So to get rid of it, we simply can replace it by 'n^2' in the second part (after the '->'), because if our assumption is true, there is no difference between them. We now have 'n^2' on both sides, so we can simply subtract it to get rid of it as well.

So whats now left we can simply out multiply and eventually get an equation, which is true as well. Therefore we have proven that a loop summing up all odd numbers (starting from 1 up to '2n - 1') equals 'n^2'.


答:
Rufflewind did a good job covering when you might use an empty function in a completed program.  In my experience, it tends to be used more often in unfinished programs, so you can plan out what you're going to write and have it still compile until you get around to actually implementing it.  In other words, it's usually just a placeholder.

It's necessary in python's case because it uses indentation to mark blocks, unlike C-like languages who use braces {}.  This means if you didn't have pass, the parser couldn't tell if you meant to leave it empty or if you forgot.  Including pass makes the parser much simpler, and gives you a convenient word to search for when you're looking for unimplemented blocks.

Title: Why empty function are needed

Body:
I started learning Python and I am wondering why empty function are needed in a programming language.

e.g. in python:

```<code>def empty_func():
    pass
</code>```

Even in shell scripts empty functions are available.

My Understandings and question:

Why do programming languages need empty functions?  Is it for just playing around with programming language or nothing else that really matters?

If this has a purpose, can anyone describe the use case or give a real example of the usage of empty functions?

Or is there any tradition of programming languages allowing empty functions?

EDIT (Things I got from reading your answers):

For Sketching Algorithms or with Abstract Functions

For Submitting forms with no action needs to be performed

Placeholder for some mandatory operations


答:
All best-practices have a particular reason, which you can refer to in order to answer such a question.
You should always avoid ripples, when one potential future change implies changes to other components as well.

So in your example:
If you assume that you have a standard greeting and you want to ensure it's the same for all people, then write

```<code>def std_greeting(name):
    print "Hi, " + name

for name in ["Tom", "Mary"]:
    std_greeting(name)   # even the function call should be written only once
</code>```

Otherwise, you'd have to pay attention and change the standard greeting at two places, if it happens to change.

If, however, the "Hi" is the same just by accident and changing one of the greetings does not necessarily result in changes for the other, then keep them separate. Therefore, keep them separate if there are logical reasons to believe, that the following change is more likely:

```<code>print "Hi, Tom"
print "Hello, Mary"
</code>```

For your second part, to decide how much to "package" into functions probably depends on two factors:

keep blocks small for readability

keep blocks large enough so that changes occur in only few blocks. Not need to cluster too much as it's hard to track the calling pattern.

Ideally, when a change occurs you will think "I have to change most of the following block" and not "I have to change code somewhere inside a large block".

Body:
All best-practices have a particular reason, which you can refer to in order to answer such a question.
You should always avoid ripples, when one potential future change implies changes to other components as well.

So in your example:
If you assume that you have a standard greeting and you want to ensure it's the same for all people, then write

def std_greeting(name):
    print "Hi, " + name

for name in ["Tom", "Mary"]:
    std_greeting(name)   # even the function call should be written only once

Otherwise, you'd have to pay attention and change the standard greeting at two places, if it happens to change.

If, however, the "Hi" is the same just by accident and changing one of the greetings does not necessarily result in changes for the other, then keep them separate. Therefore, keep them separate if there are logical reasons to believe, that the following change is more likely:

print "Hi, Tom"
print "Hello, Mary"

For your second part, to decide how much to "package" into functions probably depends on two factors:

keep blocks small for readability

keep blocks large enough so that changes occur in only few blocks. Not need to cluster too much as it's hard to track the calling pattern.

Ideally, when a change occurs you will think "I have to change most of the following block" and not "I have to change code somewhere inside a large block".


问:
Publish Modules from a Java Project on Github and integrate into IntelliJ

What is the best practice to work with several Java modules from different GitHub sources using IntelliJ?

This might be an odd qeustion but I do not know what the standard workflow is to achieve what I have in mind.

The current situation

I develop a Java project with IntelliJ and I manage my code with GitHub. The project is currently stored in a private repository on GitHuband it consists of several independent Maven modules. This is a sample structure:

The plan

Now I plan to publish only ModuleB on a public repository on GitHub. I want to share only this module and allow others to use it. What is the best practice so that I can develop Module B further within my project and all changes get published in the public repository? I do not know how to do this in IntelliJ. I am insecure about the workflow here or is there another pattern which I could follow to achieve this?

Idea

I think I could export ModuleB, import it as a separate public repository into GitHub and then send pull requests when I make changes. But how do I do this with IntelliJ? How can I fork the public repository into my existing project, which is itself shared in a privare repository? Can I nest GitHub projects? Is this a good idea after all? Please let me know if my question is clear.

Further clarification

I know that I can import several "modules" in IntelliJ, but this is a different thing, isn't it? An IntelliJ module is the same as an Eclipse project, which is an independent entity. I think I could solve the problem with this approach, but then I would have to commit the overall project seperately. Could this be solved more elegantly with  Git submodules perhaps?

Proposed Solutions

My created a new GitHub repository for ModuleB and uploaded the source code to it. This module is now set as public and independent from the main project.

Use IntelliJ import Module

Instead of trying to integrate the "external" repository directly into my current project, I cloned the ModuleB repository to a different directory. Then I imported the said folder as a new module in IntelliJ.

IntelliJ then asks if there sould be a dependency between the newly added ModuleB. Unfortunately this only adds an entry into the .iml file

```<code><orderEntry type="module" module-name="Submodule" />
</code>```

and not into the pom.xml file. So this information where to obtain the source for the module is only available in IntelliJ. How could this problem be addressed? I only tried it with a toy project so far, but if someone wants to import the whole project into Eclipse for instance, this might cause a problem. How could I reference the other GitHub repository in a useful way?

答:
Solution: Git Subtrees

After fidelling around with submodules, I found that git subtrees allow me to achieve what I wanted. I mainly used this page to learn about subtrees and followed the following procedure in order to integrate a submodule (submodule-repo.git) into the parent repository (parent.git)

```<code># Start at the root of the parent repository. Add a new remote repository to the  parent.
# Add a new remote repository location called Submodule-Subtree
git remote add Submodule-Subtree https://github.com/yourname/submodule-repo.git

# Check that the new remote location is there
git remote -v

# Now add the newly added remote location of the submodule to the parent
# by specifying a folder name where you want the submodule to be stored locally.
git subtree add --prefix=NewSubModule/ Submodule-Subtree master

# Save to the parent master
git push origin master

# make changes in the new module
cd NewSubModule/
touch ThisIsANewFile.txt
git add .

# Commit to the parent
commit -m "we added a new file in the submodule from the parent repository"
git push origin master

# So far the changes the changes are only visible in the parent repository,
# but not in the original location. To share your changes with the original
# submodule-repo.git, you need this command:
git subtree push --prefix=NewSubModule/ Submodule-Subtree master

# You also need to update the submodule-repository manually
# git subtree pull —prefix=NewSubModule/ Submodule-Subtree master
</code>```

As a next step you can import this folder as a module via the File | Import Module | Existing Sources.

The honest background is that comming from a SVN and Eclipse world, I need to learn the terminology more precisely and get used to the new concepts. I found the Pro Git Book very useful.

Body:
Solution: Git Subtrees

After fidelling around with submodules, I found that git subtrees allow me to achieve what I wanted. I mainly used this page to learn about subtrees and followed the following procedure in order to integrate a submodule (submodule-repo.git) into the parent repository (parent.git)

# Start at the root of the parent repository. Add a new remote repository to the  parent.
# Add a new remote repository location called Submodule-Subtree
git remote add Submodule-Subtree https://github.com/yourname/submodule-repo.git

# Check that the new remote location is there
git remote -v

# Now add the newly added remote location of the submodule to the parent
# by specifying a folder name where you want the submodule to be stored locally.
git subtree add --prefix=NewSubModule/ Submodule-Subtree master

# Save to the parent master
git push origin master

# make changes in the new module
cd NewSubModule/
touch ThisIsANewFile.txt
git add .

# Commit to the parent
commit -m "we added a new file in the submodule from the parent repository"
git push origin master

# So far the changes the changes are only visible in the parent repository,
# but not in the original location. To share your changes with the original
# submodule-repo.git, you need this command:
git subtree push --prefix=NewSubModule/ Submodule-Subtree master

# You also need to update the submodule-repository manually
# git subtree pull —prefix=NewSubModule/ Submodule-Subtree master

As a next step you can import this folder as a module via the File | Import Module | Existing Sources.

The honest background is that comming from a SVN and Eclipse world, I need to learn the terminology more precisely and get used to the new concepts. I found the Pro Git Book very useful.


问:
What is the best way to create dynamically a DOM?
I know that there are plenty answers to this question on stackoverflow, but I can´t find one that give me an answer that can help me to solve a question that came out after read a lot of Javascript, JQuery articles and using those languages for several months.

Here is the deal:

Apparently, I can do a generic site that can charge a Dom dynamically, I read article that says that do this and adding element to the dom at the time the page is loading is dangerous, and use this on framework like Angularjs is almost a sin to think on angular as a jquery background.

So, with that in mind.

Why is such a big deal to make a Dom loading dynamically (input a Json File)?

And the finally Question is, there’s a right way to do it?
Thanks in advance!

答:
Just to give a quick and easiest example using jQuery:

```<code><span id="main"></span>
<button onclick="add();">Click Me</button>

function add(){
$("#main").html("<h1>Hello</h1>");
}
</code>```

The  will be populated with
Hello
 on button click

You can run the above example here: http://jsfiddle.net/29mydshx/

Body:
Just to give a quick and easiest example using jQuery:

<span id="main"></span>
<button onclick="add();">Click Me</button>

function add(){
$("#main").html("<h1>Hello</h1>");
}

The <span> will be populated with <h1>Hello</h1> on button click

You can run the above example here: http://jsfiddle.net/29mydshx/


问:
Is "White-Board-Coding" inappropriate during interviews?
This is a somewhat subjective quesiton but I'd love to hear feedback/opinions from either interviewers/interviewees on the topic.

We split our technical interview into 4 parts. Write Code, Read & Analyse Code, Design Session & Code on the white board.

For the last part what we ask interviewees to do is write a small code snippet (4-5 lines) on the whiteboard and explain as they go through it. Let me be clear the purpose is not to catch people out. We're not looking for perfect syntax. Hell it can even be pseudo-code. but the point is to give them a very simple problem and see if their brain can communicate the solution to us. By simple problems I mean "Reverse a string", "FizzBuzz" etc...

Note that we always ask for an explicit language first. We're a .NET C# house. we've only said "pseudo-code" where someone has been blanking/really struggling with the code.

My question is "Is it inappropriate / unreasonable to expect a programmer to write a code snippet on a whiteboard during an interview ?"

答:
I would say it is appropriate, but in most cases it isn't an efficient way to find out who is good in programming and who isn't. If you want a job done (= hire somebody who is capable), then the interview should focus on measuring real-life skills. So far the best interview I had worked like this:

Greetings, welcome by HR.

Few words about me, about the company, etc... and she explained the rest of the interview.

She gave me a laptop with a program which missed few parts, had failed unit tests because of that. The missing parts were commented there as texts, it was about implementing a basic task, like create connection between few classes, and introduce a simple business logic.

If everything went well, the unit tests became green.

Saying good bye, and agreement of coming back in few days.

On that day the leader met up with me, and asked about the finished program, what did I do, and why.

Also this leader asked about my past experiences, and few other questions.

So to summarize: if you are looking for workforce into a production code, test their skills in real environment. If you are curious about their theoretical knowledge, it is better to ask them about these things. If you are stripped from IDE, or you are nervous because you have to program on white board on front of somebody, I can understand, especially in IT people are sometimes introverted and many of us can't handle these situations well, so on white board our efficiency will look worse than it actually is.


问:
What's the best way to synchronise an event over multiple processes?
Imagine I have two distinct OS processes (the actual OS is unimportant). Process A is responsible for playing a video file. Process B is responsible for playing the audio that accompanies the video file. Both processes are clients, connected via a local area network to a server.

Assuming that the video and audio streams are synchronized at the file level, what mechanisms would I use to ensure that both processes coordinate with the server to absolutely ensure that once instructed they begin and continue playing in sync?

This feels like a common problem but I am struggling to find any detailed, practical solutions.

答: What about having the server send each block of the stream to the clients simultaneously, and not sending the next block until both clients have acknowledged they have completed playing the previous block? You'll probably have to play with some kind of block buffers in the client, but that shouldn't be hard. This way, the server is the one source of playing position, and everything will be synchronized on block boundaries. Block size will probably be determined by your network bandwidth (and possibly your source medium).</p>


问:
Event Storming: How to phrase a command initiated by an actor, and where to put it software-wise
In Event Storming, there are "Commands" (blue sticky notes) which are, in most cases, triggered by an Actor.
How should these commands be named, prosa-wise, especially in relation to the actor? Something like Visitor -> "klicks checkout button" or, Visitor -> "go to checkout" ..?

So: what is the intended naming scheme in terms of grammar and sentence construction of a command?

答:
This may sound weird at first but try using "goal driven" names.

So instead of "klicks checkout button" rephrase it as what the actor wants to achieve. Say Visitor "reviews checkout page". You may decide to implement this as an on screen button but that comes later.

This simple trick of language stops you "implementing" too early in the design. "visitor clicks checkout button" could on really be implemented by a user with a mouse and GUI screen with a labeled button. Voice, gesture, etc. are ruled out of the design before you have even started.


答:
My thinking is that there is no way to guarantee this kind of event at the process level. You can't know what priority is going to be placed on the receipt of any given event, the order of the next relevant event etc.

To me it sounds like you need a third marshalling application whose job is to receive the events, queue up the buffered resource and synchronize the playback locally. So the application's sole responsibility would be to receive the separate network data and then distribute that data simultaneously to the local peripheral resources individually.

As @TMN mentions, you'll absolutely need some kind of buffering because network changes can be unpredictable, and in synchronized media even a single millisecond could make things weird.

Title: What's the best way to synchronise an event over multiple processes?

Body:
Imagine I have two distinct OS processes (the actual OS is unimportant). Process A is responsible for playing a video file. Process B is responsible for playing the audio that accompanies the video file. Both processes are clients, connected via a local area network to a server.

Assuming that the video and audio streams are synchronized at the file level, what mechanisms would I use to ensure that both processes coordinate with the server to absolutely ensure that once instructed they begin and continue playing in sync?

This feels like a common problem but I am struggling to find any detailed, practical solutions.


答:
Usually, this sort of thing is solved by using a transport link with strict timing specifications, like HDMI.  For a TCP/IP network, there are systems like JACK that get you part of the way there for audio, but I'm not aware of a synchronized audio/video solution.

Essentially, you need a very accurate synchronized clock, using something like Precision Time Protocol, then in your packets, you specify precisely what time to play each frame/sample.  Then you need real-time scheduling to make sure the deadlines are hit, and enough buffer to cover any network latency.  Much easier said than done.

That's the hard way.  The easy way is to just make a best effort, then give the user controls to manually adjust the delay.


答:
The most important aspect of named constants and functions isn't so much that they reduce the amount of typing, but rather that they "attach" the different places where they are used.  With regard to your example, consider four scenarios:

It's necessary to change both greetings in the same way, [e.g. to Bonjour, Tom and Bonjour, Mary].

It's necessary to change one greeting but leave the other as it is [e.g. Hi, Tom and Guten Tag, Mary].

It's necessary to change both greetings differently [e.g. Hello, Tom and Howdy, Mary].

Neither greeting ever needs to be changed.

If it's never necessary to change either greeting, it won't really matter which approach is taken.  Using a shared function will have the natural effect that changing any greeting will change them all the same way.  If all greetings should change the same way, that would be a good thing.  If they shouldn't, however, then each person's greeting will have to be coded or specified separately; any work done making them use a common function or specification will have to be undone (and would have been better not done in the first place).

To be sure, it's not always possible to predict the future, but if one has reason to believe that it's more likely that both greetings will need to change together, that would be a factor in favor of using common code (or a named constant); if one has reason to believe that it's more likely that one or both might need to change so that they differ, that would be a factor against trying to use common code.


答:
Existing answers have missed an important point: the OP has already proved some things, and the practice exam question asked him to prove these things first.  Presumably, this is because the things he's already proved are meant to be handy stepping stones towards finishing the proof.

We want to prove that the program outputs n^2.  Since there are no output statements, presumably one of the variables is the output, and it isn't i, so it must be s.

We already have s=i^2, so we're actually really close; wouldn't it be nice if i=n at the end of the loop?  Turns out, i=n is true at the end of the loop.  And we're done.

When proving things, it's very often helpful to look at other things we've already proved and what we're trying to prove.  Similarities between what we have and what we want can be suggestive of things to try.


问:
How to learn Agile as a Solo Developer

Possible Duplicate:

  What good book shoud I buy to learn Agile from scratch?

It seem that Agile for the solo developer is a good idea.

But how to learn it?

Is there any good book, web reference or course that a solo developer could start from?

答:
If you want to practice Test Driven Development and Continuous Integration, which I find to be some of the best agile practices to follow I'd look at these books:

Growing Object Oriented Software, Guided by Tests

Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation

Title: How to learn Agile as a Solo Developer


问:
Facing MemoryError in Python
I wrote a program to find prime factors of a number.
When I give a large number(600851475143) as input, MemoryError pops up.
Below is the code:

```<code>def fact(a):
    factors = []
    for i in range(1,a+1):
        if a%i == 0:
            factors.append(i)
    return factors

num = raw_input(">>  ")
#600851475143
a = b = []
a = fact(long(num))
for i in range(0,len(a)):
    b = fact(a[i])
    if len(b) <= 2:
        print a[i]
</code>```

From browsing I came to know that Python makes use of Computer memory - RAM. I am using Python in Unbuntu without changing its configuration. Should I change anythig to work on 64-bit machine.
Or should I use any additional function(s) to get around this error

答:
There are various ways to measure the memory used by your program, and you may be able increase  per-user limits or something.

However, you don't need to allocate that memory in the first place, since you can just generate the sequence without storing it all:

```<code>def fact(a):
    "just return a generator for the sequence you want"
    return (i for i in xrange(1,a+1) if a % i == 0)
</code>```

Note that you can also iterate directly over sequences without needing to index them repeatedly:

```<code>for b in fact(long(num)):
    print b
</code>```

Title: Facing MemoryError in Python

Body:
There are various ways to measure the memory used by your program, and you may be able increase  per-user limits or something.

However, you don't need to allocate that memory in the first place, since you can just generate the sequence without storing it all:

def fact(a):
    "just return a generator for the sequence you want"
    return (i for i in xrange(1,a+1) if a % i == 0)

Note that you can also iterate directly over sequences without needing to index them repeatedly:

for b in fact(long(num)):
    print b


问:
Is there some sort of systematic strategy for designing and implementing GUIs?
I am using Visual Studio to create a GUI application in C#. The Toolbox serves as a nifty component palette that allows me to easily drag and drop buttons and other elements (for clarity I'll say button whenever I mean "control") onto my form, which makes static forms quite easy to do. However, I run into two problems:

Creating the buttons in the first place is a lot of work. When I have a form that is not static (ie. buttons or other controls are created at run time according to what the user does) I cannot use the palette at all. Instead I have to create each button manually, by calling the constructor in whatever method I am using, and then manually initialize by specifying button height, width, position, label, event handler and so on. This is extremely tedious because I have to guess at all these cosmetic parameters without being able to see what the form will look like, and it also generates many lines of repetitive code for each button.

Making the buttons do something is also a lot of work. Dealing with events in a full-featured application is a huge pain. The only way I know how to do this is to select a button, go to the events tab in its properties, click the OnClick event so that it generates the event in the Form's code, then fill in the body of the event. Since I want to separate logic and presentation, all of my event handlers end up being single-line calls to the appropriate business logic function. But using this for many buttons (for instance, imagine the number of buttons present in an application like MS Word) pollutes the code of my Form with dozens of boilerplate event handler methods and it's difficult to maintain this.

Because of these, any GUI program more complicated than Hello World is very impractical to actually make for me. To be clear, I have no problems whatsoever dealing with complexity in programs that I write which have minimal UI - I feel like I am able to use OOP with a fair degree of competence to neatly structure my business logic code. But when developing the GUI, I'm stuck. It seems so tedious that I feel like I'm reinventing the wheel, and there's a book somewhere out there explaining how to do GUI properly that I haven't read.

Am I missing something? Or do all C# developers just accept the endless lists of repetitive event handlers and button creation code?

As a (hopefully helpful) hint, I expect that a good answer will talk about:

Using OOP techniques (such as the factory pattern) to simplify repeated button creation

Combining many event handlers into a single method that checks Sender to figure out which button called it, and behaves accordingly

XAML and using WPF instead of Windows Forms

You don't have to mention any of these, of course. It's just my best guess as to what sort of answer I'm looking for.

答:
First, I recommend this article series: http://codebetter.com/jeremymiller/2007/07/26/the-build-your-own-cab-series-table-of-contents/ - it does not address the detail problems with your button code, but it gives you a systematic strategy for designing and implementing your own application framework, especially for GUI applications, showing you how to apply MVC, MVP, MVVM to your typical Forms application.

Addressing your question about "dealing with events": if you have a lot of forms with buttons working in a similar manner, it will probably pay off to implement the event handler assignment in your "application framework" by yourself. Instead of assigning the click events using the GUI designer, create a naming convention how a "click" handler has to be named for a button of a specific name. For example - for button MyNiftyButton_ClickHandler for the button MyNiftyButton. Then it is not really hard to write a reusable routine (utilizing reflection) which iterates over all buttons of a form, check if the form contains a related click handler and assign the handler to the event automatically. See here for an example.

And if you just want to use only one event handler for a bunch of buttons, that will be also possible. Since each event handler gets the sender passed, and the sender is always the button which was pressed, you can dispatch to the business code by utilizing the "Name" property of each button.

For the dynamic creation of buttons (or other controls): you can create buttons or other controls with the designer on an unused form just for the purpose of beeing a template. Then, you use reflection (see here for an example) to clone the template control and change only the properties like location or size. That will probably be much simpler than to initialize two or three dozen properties manually in code.

I wrote this above by having Winforms in mind (just as you, I guess), but the general principles should apply to other GUI environments like WPF with similar capabilities.