问:
What's the difference between computer science and programming?
I'm new at computer science and programming, and I was wondering, is there a difference between computer science and programming? and do you get to choose to study only one of them at the university, or both of them?</p>

答:
Computer Science : It is the study of problem solving with computers/computational methods.

Computer programming : It is the part of this problem solving process that makes up the field of computer science. Computer programming is just a small subset of computer science.


问:
What is the difference in a developer's years of experience with a language?
As stated by the title, what is the difference in years of experience in given language in terms of developers? For example, if one developer has had five years working with language A and the other developer has had two years working with language B followed by three years working with language A, would there be perceivable difference between them?</p>

答:
"Years of experience in X language/platform" is largely a recruitment pathology...

It's open to interpretation and isn't anywhere near as useful as it looks at first glance. As has been said, the Years of Experience Myth is a good read.

Also, crucially, the measurement of "years of experience" itself can be very inaccurate. Here's an example from my current gig: my main task is developing and maintaining a Java web app. However, this runs off a back end which is MFC/C++/SQL Server. Consequently I'm dealing with C++ code on a virtually daily basis too. BUT - this C++ experience is relatively superficial and maintenance-oriented, and I don't really write entire big components or programs from scratch in MFC/C++ anymore (I used to in previous roles though).

Can I still count these last 5 years as "5 years of C++ experience"? Maybe. Maybe not. Depending on how I want to sell it to secure a particular role, I can easily overplay it without outright lying, or I can admit that it wasn't really a 5 solid "years of C++ experience". :) I'm sure plenty of cases out there are similarly open to this kind of "inaccuracy of measurement" problem. Depth of experience can grossly cloud the quality of experience. So an "X amount of time spent with C++" doesn't mean much in itself.

ContentLicense: CC BY-SA 2.5


问:
Setting up a refund policy for a commercial WordPress theme
I'm developing a WordPress theme and am planning to sell it myself. I was thinking of having a 14- or 30-day refund policy for customers, but my concern is that people can essentially get the theme for free, if they: 1) buy it, 2) download the files, and then 3) request a refund. Then they would have both the theme and their money back.

I've been looking into software refund policies and noticed there are a few different schools of thoughts on providing customer refunds:

School of Thought #1 - Provide refunds. If your software is good quality, not many people will request a refund.

My response: But in my case, even if users think the theme is high quality, they can still request a refund and also keep the theme. I have also put a lot of work into the development and testing of the theme, so it is quality work.

School of Thought #2 - Provide refunds, but some customers will abuse the refund process, so have an activation code and only provide refunds to people who have not activated the software.

My response: This sounds like a good idea, but there isn't an activation mechanism for themes in WordPress, so I don't know how I could implement it.

School of Thought #3 - No refunds.

My response: This seems really inflexible. I'm not against refunding customer payments for good reason, but I don't want to give away my work, either.

Have you heard of any other good options in setting up a refund policy?

答:
A good place to start is to check what others are doing.  Here are refund policies from two popular WordPress theme sites:

If you have purchased an item and it does not work as described or is
  faulty, please contact support and tell them which file you purchased
  and exactly what the problem has been with the item. The item will be
  investigated, and if it is found to be faulty or not working as
  described it will be fixed or a refund will be offered.

And

All sales are final. Since we offer non-tangible products which are
  delivered via digital download, we do not issue refunds after a
  purchase is made. If there is a problem with one of our themes or if
  you experience any difficulty with its download, we will fix the
  problem.

It seems the consensus is, refunds are not given (except possibly for a faulty product).  This makes sense because, as you noted, there is nothing to stop someone from getting a refund and still using your product.  They could even make slight changes to your theme and claim it is their own creation.

Also, will you be selling your theme through an established theme site?  If so, the refund policy will likely be set by the site anyway (both of the above policies are at a site level).

ContentLicense: CC BY-SA 3.0


问:
The physical implementation of quantum annealing algorithm
From that question about differences between Quantum annealing and simulated annealing, we found (in comments to answer) that physical implementation of quantum annealing exists (D-Wave quantum computers).

Can anyone explain that algorithm in terms of quantum gates and quantum algorithms, or in physical terms (a part of algorithm that depends on quantum hardware)?

答:
From Wikipedia:

Quantum annealing can be compared to simulated annealing (SA), whose
  "temperature" parameter plays a similar role to QA's tunneling field
  strength. However, in SA the neighborhood stays the same throughout
  the search, and the temperature determines the probability of moving
  to a state of higher "energy". In QA, the tunneling field strength
  determines instead the neighborhood radius, i.e. the mean distance
  between the next candidate state and the current candidate state.

In other words, the "tunneling field" and, indeed, the term "quantum" are just metaphors for the finer points of a completely classical (although randomized) algorithm. QA is not inherently connected with actual quantum computers, it just borrows terms from physics to make a point about computational properties.


问:
SourceTree app, how do I know what is my current branch?
I have branched from my develop branch bugfix/issue2 to work on a bugfix. Now that it's done I want to merge this branch bugfix/issue2 back onto develop but it's asking me if I want to merge into my current branch. And I don't know if my current branch is develop?

See attached screendumps:

答:
For one, the current branch is always the leftmost of the "Graph" lines and the current node you're on is highlighted, secondly the current branch is bold and has a little checkmark icon in the "Branches" sidebar.

You are currently on bugfix/issue2.


问:
Why do bitwise operators have lower priority than comparisons?
Could someone explain the rationale, why in a bunch of most popular languages (see note below) comparison operators (==, !=, <, >, <=, >=) have higher priority than bitwise operators (&, |, ^, ~)?

I don't think I've ever encountered a use where this precedence would be natural. It's always stuff like:

```<code>  if( (x & MASK) == CORRECT ) ...   // Chosen bits are in correct setting, rest unimportant

  if( (x ^ x_prev) == SET )      // only, and exactly SET bit changed

  if( (x & REQUIRED) < REQUIRED )   // Not all conditions satisfied
</code>```

The cases where I'd use:

```<code>  flags = ( x == 6 | 2 );     // set bit 0 when x is 6, bit 1 always.
</code>```

are near to nonexistent.

What was the motivation of language designers to decide upon such precedence of operators?

For example, all but SQL at the top 12 languages are like that on Programming Language Popularity list at langpop.com: C, Java, C++, PHP, JavaScript, Python, C#, Perl, SQL, Ruby, Shell, Visual Basic.

答:
Bitwise operators are related to logical operators both conceptually and in appearance, which probably explains why they are near each other in the precedence table.  Perhaps one could even argue that it would be confusing for & to be higher than ==, yet have && be lower then ==.

Once a precedence precedent (!) was set, it was probably better for other languages to follow it for consistency's sake.

However, I tend to agree with you that this is not optimal.  In actual use, bit operators are more like mathematical operators than logical ones, and it would be better if they were grouped with the mathematical operators in precedence.


问:
Do I need to go back and learn HTML 5 and CSS 3?
I have been working on learning as much as I can before starting college to change my career, and I noticed on the w3schools site that there is now html and html 5, css and css 3. Do I need to go back and learn those newer languages before moving onto PHP and MySQL?</p>

答: I don't like this term "go back" - it implies that you've somehow missed something. Learning is a constant process - you don't miss things, you simply learn them later on. If you approach software engineering in the manner that you always need to be on the bleeding edge, you'll spend all your time learning about new frameworks and never building anything.</p>


答:
Languages have copied that from C, and for C, Dennis Ritchie explains that initially, in B (and perhaps early C), there was only one form & which depending on the context did a bitwise and or a logical one. Later, each function got its operator: & for the bitwise one and && for for logical one. Then he continues

Their tardy introduction explains an infelicity of C's precedence rules. In B one writes

```<code>if (a == b & c) ...
</code>```

to check whether a equals b and c is non-zero; in such a conditional expression it is better that & have lower precedence than ==. In converting from B to C, one wants to replace & by && in such a statement; to make the conversion less painful, we decided to keep the precedence of the & operator the same relative to ==, and merely split the precedence of && slightly from &. Today, it seems that it would have been preferable to move the relative precedences of & and ==, and thereby simplify a common C idiom: to test a masked value against another value, one must write

```<code>if ((a & mask) == b) ...
</code>```

where the inner parentheses are required but easily forgotten.

Title: Why do bitwise operators have lower priority than comparisons?

Body:
Could someone explain the rationale, why in a bunch of most popular languages (see note below) comparison operators (==, !=, <, >, <=, >=) have higher priority than bitwise operators (&, |, ^, ~)?

I don't think I've ever encountered a use where this precedence would be natural. It's always stuff like:

```<code>  if( (x & MASK) == CORRECT ) ...   // Chosen bits are in correct setting, rest unimportant

  if( (x ^ x_prev) == SET )      // only, and exactly SET bit changed

  if( (x & REQUIRED) < REQUIRED )   // Not all conditions satisfied
</code>```

The cases where I'd use:

```<code>  flags = ( x == 6 | 2 );     // set bit 0 when x is 6, bit 1 always.
</code>```

are near to nonexistent.

What was the motivation of language designers to decide upon such precedence of operators?

For example, all but SQL at the top 12 languages are like that on Programming Language Popularity list at langpop.com: C, Java, C++, PHP, JavaScript, Python, C#, Perl, SQL, Ruby, Shell, Visual Basic.

Body:
Languages have copied that from C, and for C, Dennis Ritchie explains that initially, in B (and perhaps early C), there was only one form & which depending on the context did a bitwise and or a logical one. Later, each function got its operator: & for the bitwise one and && for for logical one. Then he continues

Their tardy introduction explains an infelicity of C's precedence rules. In B one writes

if (a == b & c) ...

to check whether a equals b and c is non-zero; in such a conditional expression it is better that & have lower precedence than ==. In converting from B to C, one wants to replace & by && in such a statement; to make the conversion less painful, we decided to keep the precedence of the & operator the same relative to ==, and merely split the precedence of && slightly from &. Today, it seems that it would have been preferable to move the relative precedences of & and ==, and thereby simplify a common C idiom: to test a masked value against another value, one must write

if ((a & mask) == b) ...

where the inner parentheses are required but easily forgotten.


问:
What methods are there to avoid a stack overflow in a recursive algorithm?
Question

What are the possible ways to solve a stack overflow caused by an recursive algorithm?

Example

I'm trying to solve Project Euler problem 14 and decided to try it with a recursive algorithm. However, the program stops with a java.lang.StackOverflowError. Understandably. The algorithm indeed overflowed the stack because I tried to generate a Collatz sequence for a very large number.

Solutions

So I was wondering: what standard ways are there to solve a stack overflow assuming your recursive algorithm was written correctly and would always end up  overflowing the stack? Two concepts that came to mind were:

tail recursion

iteration

Are ideas (1) and (2) correct? Are there other options?

Edit

It would help to see some code, preferably in Java, C#, Groovy or Scala.

Perhaps don't use the Project Euler problem mentioned above so it won't get spoiled for others, but take some other algorithm. Factorial maybe, or something similar.

答:
you could create an Enumeration that will replace the recursion... here is an example for calculating faculty doing that... (wont work for big numbers as i only used long in the example :-))

```<code>public class Faculty
{

    public static IEnumerable<long> Faculties(long n)
    {
        long stopat = n;

        long x = 1;
        long result = 1;

        while (x <= n)
        {
            result = result * x;
            yield return result;
            x++;
        }
    }
}
</code>```

even if this is not memoization, this way you will void a stack overflow

EDIT

I am sorry if I upset some of you. My only intention was to show a way how to avoid a stack overflow. I probably should have written a full code example instead of just a small piece of a quickly written and rough code excerpt.

The following code

avoids recursion as I use calculate the required values iteratively.

includes memoization as Values already calculated are stored away and retrieved if already calculated

also includes a stopwatch, so you can see that memoization works properly

...umm... if you run it make sure you set your command shell window to have a buffer of 9999 lines... the usual 300 will not be enough to run through the results of the below program...

```<code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace ConsoleApplication1
{
    class Program
    {
        static Stopwatch w = new Stopwatch();
        static Faculty f = Faculty.GetInstance();

        static void Main(string[] args)
        {
            Out(5);
            Out(10);
            Out(-5);
            Out(0);
            Out(1);
            Out(4);
            Out(29);
            Out(30);
            Out(20);
            Out(10000);
            Out(20000);
            Out(19999);
            Console.ReadKey();
        }

        static void Out(BigInteger n)
        {
             try
            {
                w.Reset();
                w.Start();
                var x = f.Calculate(n);
                w.Stop();
                var time = w.ElapsedMilliseconds;
                Console.WriteLine(String.Format("{0} ({2}ms): {1}", n, x, time));
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("\n\n");
       }
    }
</code>```

I declare
  * 1 static variable "instance" in the Faculty class to a store a singleton. That way as long as your program is running, whenever you "GetInstance()" of the class you get the instance that has stored all values already calculated.
  * 1 static SortedList which will hold all the values already calculated

In the constructor I also add 2 special values of the list 1 for inputs 0 and 1.

```<code>    public class Faculty
    {
        private static SortedList<BigInteger, BigInteger> _values;
        private static Faculty _faculty {get; set;}

        private Faculty ()
        {
            _values = new SortedList<BigInteger, BigInteger>();
            _values.Add(0, 1);
            _values.Add(1, 1);
        }

        public static Faculty GetInstance() {
            _faculty = _faculty ?? new Faculty();
            return _faculty;
        }

        public BigInteger Calculate(BigInteger n)
        {
            // check if input is smaller 0
            if (n < 0)
                throw new ArgumentException(" !!! Faculty is not defined for values < 0 !!!");

            // if value is not already calculated => do so
            if(!_values.ContainsKey(n))
                Faculties(n);

            // retrieve n! from Sorted List
            return _values[n];
        }

        private static void Faculties(BigInteger n)
        {
            // get the last calculated values and continue calculating if the calculation for a bigger n is required
            BigInteger i = _values.Max(x => x.Key),
                           result = _values[i];

            while (++i <= n)
            {
                CalculateNext(ref result, i);
                // add value to the SortedList if not already done
                if (!_values.ContainsKey(i))
                    _values.Add(i, result);
            }
        }

        private static void CalculateNext(ref BigInteger lastresult, BigInteger i) {

            // put in whatever iterative calculation step you want to do
            lastresult = lastresult * i;

        }
    }
}
</code>```

Body:
you could create an Enumeration that will replace the recursion... here is an example for calculating faculty doing that... (wont work for big numbers as i only used long in the example :-))

public class Faculty
{

    public static IEnumerable<long> Faculties(long n)
    {
        long stopat = n;

        long x = 1;
        long result = 1;

        while (x <= n)
        {
            result = result * x;
            yield return result;
            x++;
        }
    }
}

even if this is not memoization, this way you will void a stack overflow

EDIT

I am sorry if I upset some of you. My only intention was to show a way how to avoid a stack overflow. I probably should have written a full code example instead of just a small piece of a quickly written and rough code excerpt.

The following code

avoids recursion as I use calculate the required values iteratively.

includes memoization as Values already calculated are stored away and retrieved if already calculated

also includes a stopwatch, so you can see that memoization works properly

...umm... if you run it make sure you set your command shell window to have a buffer of 9999 lines... the usual 300 will not be enough to run through the results of the below program...

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace ConsoleApplication1
{
    class Program
    {
        static Stopwatch w = new Stopwatch();
        static Faculty f = Faculty.GetInstance();

        static void Main(string[] args)
        {
            Out(5);
            Out(10);
            Out(-5);
            Out(0);
            Out(1);
            Out(4);
            Out(29);
            Out(30);
            Out(20);
            Out(10000);
            Out(20000);
            Out(19999);
            Console.ReadKey();
        }

        static void Out(BigInteger n)
        {
             try
            {
                w.Reset();
                w.Start();
                var x = f.Calculate(n);
                w.Stop();
                var time = w.ElapsedMilliseconds;
                Console.WriteLine(String.Format("{0} ({2}ms): {1}", n, x, time));
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("\n\n");
       }
    }

I declare
  * 1 static variable "instance" in the Faculty class to a store a singleton. That way as long as your program is running, whenever you "GetInstance()" of the class you get the instance that has stored all values already calculated.
  * 1 static SortedList which will hold all the values already calculated

In the constructor I also add 2 special values of the list 1 for inputs 0 and 1.

    public class Faculty
    {
        private static SortedList<BigInteger, BigInteger> _values;
        private static Faculty _faculty {get; set;}

        private Faculty ()
        {
            _values = new SortedList<BigInteger, BigInteger>();
            _values.Add(0, 1);
            _values.Add(1, 1);
        }

        public static Faculty GetInstance() {
            _faculty = _faculty ?? new Faculty();
            return _faculty;
        }

        public BigInteger Calculate(BigInteger n)
        {
            // check if input is smaller 0
            if (n < 0)
                throw new ArgumentException(" !!! Faculty is not defined for values < 0 !!!");

            // if value is not already calculated => do so
            if(!_values.ContainsKey(n))
                Faculties(n);

            // retrieve n! from Sorted List
            return _values[n];
        }

        private static void Faculties(BigInteger n)
        {
            // get the last calculated values and continue calculating if the calculation for a bigger n is required
            BigInteger i = _values.Max(x => x.Key),
                           result = _values[i];

            while (++i <= n)
            {
                CalculateNext(ref result, i);
                // add value to the SortedList if not already done
                if (!_values.ContainsKey(i))
                    _values.Add(i, result);
            }
        }

        private static void CalculateNext(ref BigInteger lastresult, BigInteger i) {

            // put in whatever iterative calculation step you want to do
            lastresult = lastresult * i;

        }
    }
}


问:
High performance and/or real time java open source applications
Which open source java projects do you know to be high performance or real time performance? I tried hard to find them on github or google, but couldn't find suitable.

I want to learn from this projects, so will not be as a newbie on my interviews ;)

So far I am going to stick to Play Framework project.
Are there better options?

P.S. I've seen possible duplicate, but I am looking for a very load intensive applications. As people in Deutsche Bank write.

答:
Cassandra is extremely performant and open source. https://github.com/apache/cassandra

It's a pretty huge open source project that focuses on high writes, no single point failure and has a good feature set (including distributed, eventually consistent counters).

HBase is another extremely good distributed, noSQL BigData replica. https://github.com/apache/hbase


答:
Keep in mind that the language implementation must support tail recursion optimization.  I don't think the major java compilers do.

Memoization means you remember the result of a calculation rather than recalculating it every time, like:

```<code>collatz(i):
    if i in memoized:
        return memoized[i]

    if i == 1:
        memoized[i] = 1
    else if odd(i):
        memoized[i] = 1 + collatz(3*i + 1)
    else
        memoized[i] = 1 + collatz(i / 2)

    return memoized[i]
</code>```

When you're calculating every sequence less than a million, there's going to be a lot of repetition at the end of the sequences.  Memoization makes it a quick hash table lookup for previous values instead of having to make the stack deeper and deeper.

Title: What methods are there to avoid a stack overflow in a recursive algorithm?

Body:
Question

What are the possible ways to solve a stack overflow caused by an recursive algorithm?

Example

I'm trying to solve Project Euler problem 14 and decided to try it with a recursive algorithm. However, the program stops with a java.lang.StackOverflowError. Understandably. The algorithm indeed overflowed the stack because I tried to generate a Collatz sequence for a very large number.

Solutions

So I was wondering: what standard ways are there to solve a stack overflow assuming your recursive algorithm was written correctly and would always end up  overflowing the stack? Two concepts that came to mind were:

tail recursion

iteration

Are ideas (1) and (2) correct? Are there other options?

Edit

It would help to see some code, preferably in Java, C#, Groovy or Scala.

Perhaps don't use the Project Euler problem mentioned above so it won't get spoiled for others, but take some other algorithm. Factorial maybe, or something similar.

Body:
Keep in mind that the language implementation must support tail recursion optimization.  I don't think the major java compilers do.

Memoization means you remember the result of a calculation rather than recalculating it every time, like:

collatz(i):
    if i in memoized:
        return memoized[i]

    if i == 1:
        memoized[i] = 1
    else if odd(i):
        memoized[i] = 1 + collatz(3*i + 1)
    else
        memoized[i] = 1 + collatz(i / 2)

    return memoized[i]

When you're calculating every sequence less than a million, there's going to be a lot of repetition at the end of the sequences.  Memoization makes it a quick hash table lookup for previous values instead of having to make the stack deeper and deeper.


答:
If you are using a language and compiler that recognize tail recursive functions and handles them properly (i.e. "replaces the caller in place with the callee"), then yeah, the stack should not grow out of control. This optimization essentially reduces a recursive method to an iterative one. I don't think Java does this, but I know that Racket does.

If you go with an iterative approach, rather than a recursive approach, you are removing much of the need to remember where calls are coming from, and practically eliminating the chance of a stack overflow (from recursive calls anyway).

Memoization is great and can cut down on the overall number of method calls by looking up previously calculated results in a cache, given that your overall calculation will incur many smaller, repeated calculations. This idea is great -- it's also independent of whether or not you are using an iterative approach or a recursive one.


问:
Is it allowed to make multiple instances of a singleton class?
I am confused when I read this (regarding singleton design pattern):

How do we ensure that a class has only one instance and that the instance is easily
  accessible? A global variable makes an object accessible, but it doesn't keep you from
  instantiating multiple objects.

So what is the use of singleton pattern if we can create multiple instances?

SOURCE:

Design Patterns - Elements Of Reusable Object Oriented Software (1995) - Gamma, Helm, Johnson, Vl

答:
Without the full text this is not sure, but my (somehow educated) guess:

They only warn that a global variable is not the right way to ensure that you have a singleton. The following text should then show how to do this inside the class that should be a singleton.


问:
How meaningful is the Big-O time complexity of an algorithm?
Programmers often talk about the time complexity of an algorithm, e.g. O(log n) or O(n^2).

Time complexity classifications are made as the input size goes to infinity, but ironically infinite input size in computation is not used.

Put another way, the classification of an algorithm is based on a situation that algorithm will never be in: where n = infinity.

Also, consider that a polynomial time algorithm where the exponent is huge is just as useless as an exponential time algorithm with tiny base (e.g., 1.00000001^n) is useful.

Given this, how much can I rely on the Big-O time complexity to advise choice of an algorithm?

答:
Asymptotic complexity is very meaningful indeed.  Do you know the story about the inventor of chess, who asked the king to give him 2^65-1 grains of wheat as his reward? :)

You are correct, a polynomial algorithm of a high degree is likely to be useless. And to know that your algorithm's time complexity is a high degree polynomial, you have to look at the big-O.  Also, a time complexity of O(1.00000001^n) is rare. But you see O(2^n) all the time, such as in the Boolean satisfiability problem.

If you do not understand the complexity of your algorithm, you can easily find yourself in a situation where your program works fine on a test input, but hangs when your customer gives it an input that is only twice as large.


答:
In the quote they don't talk about how to do it, but how not to do it.

Some approach for getting a singleton is to make the constructor private and write a own static method, that creates a new element on the first call, saves it in a static variable and always returns this object when called again.

Title: Is it allowed to make multiple instances of a singleton class?

Body:
I am confused when I read this (regarding singleton design pattern):

How do we ensure that a class has only one instance and that the instance is easily
  accessible? A global variable makes an object accessible, but it doesn't keep you from
  instantiating multiple objects.

So what is the use of singleton pattern if we can create multiple instances?

SOURCE:

Design Patterns - Elements Of Reusable Object Oriented Software (1995) - Gamma, Helm, Johnson, Vl


答:
As others said, big-O matters if n can get large.
The problem is, it's of such academic interest that it's taught heavily, so students end up predisposed to think it's the only thing that matters.

So if they get into projects where the constant factors are larger than necessary by orders of magnitude, they are so unprepared they often don't even recognize there might be a problem.

Constant factors are treated as an irrelevant afterthought, and students are told "use a profiler"  (typically gprof), despite a poor track record of actually producing speedups.

Title: How meaningful is the Big-O time complexity of an algorithm?

Body:
Programmers often talk about the time complexity of an algorithm, e.g. O(log n) or O(n^2).

Time complexity classifications are made as the input size goes to infinity, but ironically infinite input size in computation is not used.

Put another way, the classification of an algorithm is based on a situation that algorithm will never be in: where n = infinity.

Also, consider that a polynomial time algorithm where the exponent is huge is just as useless as an exponential time algorithm with tiny base (e.g., 1.00000001^n) is useful.

Given this, how much can I rely on the Big-O time complexity to advise choice of an algorithm?


答:
There are very few languages that prevent you from shooting your foot if you really want to do it. The singleton pattern makes maintaining exactly one instance of the class quite trivial and creating multiple instances of it quite difficult; creating multiple instances unintentionally - impossible.

Most design patterns are to make programmer's life easier and remove their headaches. They can be circumvented and exceptions to them can be made. The singleton is to remove the headache of watching when and where you instantiate a class there should be only one instance of.

It's the kind of thinking "I'll catch cold on purpose, to spite my parents" if you try to create more than one instance of a class designated as singleton. Adult people don't do this.


答:
Tail call optimization is present in many languages and compilers.  In this situation, the compiler recognizes a function of the form:

```<code>int foo(n) {
  ...
  return bar(n);
}
</code>```

Here, the language is able to recognize that the result being returned is the result from another function and change a function call with a new stack frame into a jump.

Realize that the classic factorial method:

```<code>int factorial(n) {
  if(n == 0) return 1;
  if(n == 1) return 1;
  return n * factorial(n - 1);
}
</code>```

is not tail call optimizatable because of the inspection necessary on the return.  (Example source code and compiled output)

To make this tail call optimizeable,

```<code>int _fact(int n, int acc) {
    if(n == 1) return acc;
    return _fact(n - 1, acc * n);
}

int factorial(int n) {
    if(n == 0) return 1;
    return _fact(n, 1);
}
</code>```

Compiling this code with gcc -O2 -S fact.c (the -O2 is necessary to enable the optimization in the compiler, but with more optimizations of -O3 it gets hard for a human to read...)

```<code>_fact(int, int):
    cmpl    $1, %edi
    movl    %esi, %eax
    je  .L2
.L3:
    imull   %edi, %eax
    subl    $1, %edi
    cmpl    $1, %edi
    jne .L3
.L2:
    rep ret
</code>```

(Example source code and compiled output)

One can see in segment .L3, the jne rather than a call (which does a subroutine call with a new stack frame).

Please note this was done with C.  Tail call optimization in Java is hard and depends on the JVM implementation (that said, I haven't seen any that do it, because it is hard and implications of the required Java security model requiring stack frames - which is what TCO avoids) -- tail-recursion + java and tail-recursion + optimization are good tag sets to browse.  You may find other JVM languages are able to optimize tail recursion better (try clojure (which requires the recur to tail call optimize), or scala).

That said,

There is a certain joy in knowing that you wrote something right - in the ideal way that it can be done.

And now, I'm going to get some scotch and put on some German electronica...

To the general question of "methods to avoid a stack overflow in a recursive algorithm"...

Another approach is to include a recursion counter.  This is more for detecting infinite loops caused by situations beyond one's control (and poor coding).

The recursion counter takes the form of

```<code>int foo(arg, counter) {
  if(counter > RECURSION_MAX) { return -1; }
  ...
  return foo(arg, counter + 1);
}
</code>```

Each time you make a call, you increment the counter.  If the counter gets too big, you error out (in here, just a return of -1, though in other languages you may prefer to throw an exception).  The idea is to prevent worse things from happening (out of memory errors) when doing a recursion that is much deeper than expected and likely an infinite loop.

In theory, you shouldn't need this.  In practice, I've seen poorly written code that has hit this because of a plethora of small errors and bad coding practices (multithreaded concurrency issues where something changes something outside the method that makes another thread go into an infinite loop of recursive calls).

Use the right algorithm and solve the right problem.  Specifically for the Collatz Conjecture, it appears that you are trying to solve it in the xkcd way:

You are starting at a number and doing a tree traversal.  This rapidly leads to a very large search space.  A quick run to calculate the number of iterations for the correct answer results in about 500 steps.  This shouldn't be an issue for recursion with a small stack frame.

While knowing the recursive solution is not a bad thing, one should also realize that many times the iterative solution is better.  A number of ways of approaching converting a recursive algorithm to an iterative one can be seen on Stack Overflow at Way to go from recursion to iteration.

Body:
Tail call optimization is present in many languages and compilers.  In this situation, the compiler recognizes a function of the form:

int foo(n) {
  ...
  return bar(n);
}

Here, the language is able to recognize that the result being returned is the result from another function and change a function call with a new stack frame into a jump.

Realize that the classic factorial method:

int factorial(n) {
  if(n == 0) return 1;
  if(n == 1) return 1;
  return n * factorial(n - 1);
}

is not tail call optimizatable because of the inspection necessary on the return.  (Example source code and compiled output)

To make this tail call optimizeable,

int _fact(int n, int acc) {
    if(n == 1) return acc;
    return _fact(n - 1, acc * n);
}

int factorial(int n) {
    if(n == 0) return 1;
    return _fact(n, 1);
}

Compiling this code with gcc -O2 -S fact.c (the -O2 is necessary to enable the optimization in the compiler, but with more optimizations of -O3 it gets hard for a human to read...)

_fact(int, int):
    cmpl    $1, %edi
    movl    %esi, %eax
    je  .L2
.L3:
    imull   %edi, %eax
    subl    $1, %edi
    cmpl    $1, %edi
    jne .L3
.L2:
    rep ret

(Example source code and compiled output)

One can see in segment .L3, the jne rather than a call (which does a subroutine call with a new stack frame).

Please note this was done with C.  Tail call optimization in Java is hard and depends on the JVM implementation (that said, I haven't seen any that do it, because it is hard and implications of the required Java security model requiring stack frames - which is what TCO avoids) -- tail-recursion + java and tail-recursion + optimization are good tag sets to browse.  You may find other JVM languages are able to optimize tail recursion better (try clojure (which requires the recur to tail call optimize), or scala).

That said,

There is a certain joy in knowing that you wrote something right - in the ideal way that it can be done.

And now, I'm going to get some scotch and put on some German electronica...

To the general question of "methods to avoid a stack overflow in a recursive algorithm"...

Another approach is to include a recursion counter.  This is more for detecting infinite loops caused by situations beyond one's control (and poor coding).

The recursion counter takes the form of

int foo(arg, counter) {
  if(counter > RECURSION_MAX) { return -1; }
  ...
  return foo(arg, counter + 1);
}

Each time you make a call, you increment the counter.  If the counter gets too big, you error out (in here, just a return of -1, though in other languages you may prefer to throw an exception).  The idea is to prevent worse things from happening (out of memory errors) when doing a recursion that is much deeper than expected and likely an infinite loop.

In theory, you shouldn't need this.  In practice, I've seen poorly written code that has hit this because of a plethora of small errors and bad coding practices (multithreaded concurrency issues where something changes something outside the method that makes another thread go into an infinite loop of recursive calls).

Use the right algorithm and solve the right problem.  Specifically for the Collatz Conjecture, it appears that you are trying to solve it in the xkcd way:

You are starting at a number and doing a tree traversal.  This rapidly leads to a very large search space.  A quick run to calculate the number of iterations for the correct answer results in about 500 steps.  This shouldn't be an issue for recursion with a small stack frame.

While knowing the recursive solution is not a bad thing, one should also realize that many times the iterative solution is better.  A number of ways of approaching converting a recursive algorithm to an iterative one can be seen on Stack Overflow at Way to go from recursion to iteration.


问:
Factory Method: does the Product have to be a different class than the Creator?
I want to build three sites in PHP. I'm doing this as slowly, thoughtfully and carefully as I can, to learn as much about things like OOP and software architecture as possible.

From past experience I already know there will be a time when I will be glad to have logging functionality. I probably want to have different types of logs, by which I mean that in a .ini file, I want to be able to specify if logging should go to a text file (perhaps a tab-delimited or CSV file), a database table, or smoke signals. I'd have (let's say) a Logger class, which would define, for example, an AddEntry() method. For each log type, I'd make a subclass that knows how to log to CSV file, write to a database or kindle a fire, respectively.

Since I know I will want to have an instance of a subclass, but I won't know which subclass to instantiate until runtime, I figured I'd use the Factory Method pattern. However, When I look at its Wikipedia article I'm noticing that the Creator and ConcreteCreator have a different type than the Product, if I'm reading the UML correctly. My question comes down to this:

I want to have the factory method as a static method of the Logger base class itself. If I do that, am I setting myself up for a trap that I'm not seeing yet? Is there a reason why the Creator and ConcreteCreator should be of a different type than the Product?

答:
The Factory and Product should be different classes.

The single responsibility principle states that every class should have a single responsibility. If a class was responsible for both implementing factory as well as logging, that would be two responsibilities.

More at http://en.wikipedia.org/wiki/Single_responsibility_principle


问:
Is HTTPS enough to avoid replay attacks?
I am exposing a few REST methods on a server for an mobile app.

I would like to avoid that users can sniff how HTTP methods are built (from the mobile app) and then send them again to the server. Example :

The mobile app send a request

The user uses a proxy and can check what's going on on the network

The user sees and save the request that the mobile just sent

=> Now I don't want the user to be able to send over manually that request

Is it enough to secure the server over HTTPS?

答:
HTTPS can be enough to secure the server from replay attacks (the same message being sent twice) if the server is configured to only allow the TLS protocol as per rfc2246 section F.2.

Outgoing data is protected with a MAC before transmission. To prevent
     message replay or modification attacks, the MAC is computed from the
     MAC secret, the sequence number [...]


答:
Have a read of Joel On Software's blog post about 7 steps to customer service.

In particular, Step 7 is apropos to your concerns.

They run with a 90 day policy for requesting refunds, and per the article, it's cost them 2%.  Joel Spolsky also creates a correlation between the customers feeling empowered in the transaction; being nice to customer service reps; and no real abuse of their refund system.

The entire article is well worth reading, and I think you'll pick up some gems as you build your business.

Title: Setting up a refund policy for a commercial WordPress theme

Body:
I'm developing a WordPress theme and am planning to sell it myself. I was thinking of having a 14- or 30-day refund policy for customers, but my concern is that people can essentially get the theme for free, if they: 1) buy it, 2) download the files, and then 3) request a refund. Then they would have both the theme and their money back.

I've been looking into software refund policies and noticed there are a few different schools of thoughts on providing customer refunds:

School of Thought #1 - Provide refunds. If your software is good quality, not many people will request a refund.

My response: But in my case, even if users think the theme is high quality, they can still request a refund and also keep the theme. I have also put a lot of work into the development and testing of the theme, so it is quality work.

School of Thought #2 - Provide refunds, but some customers will abuse the refund process, so have an activation code and only provide refunds to people who have not activated the software.

My response: This sounds like a good idea, but there isn't an activation mechanism for themes in WordPress, so I don't know how I could implement it.

School of Thought #3 - No refunds.

My response: This seems really inflexible. I'm not against refunding customer payments for good reason, but I don't want to give away my work, either.

Have you heard of any other good options in setting up a refund policy?


问:
How do you manage the testing of your Android software on physical devices?
I'm in charge of managing mobile application development at my company, and I am currently building a mobile device "library" for testing. Essentially, we want to have a representative device in-house for each of the OSes we are developing for, currently iOS (iPhone-only), Blackberry, and Android. Simulators only go so far, but I'm placing into the process a step to test software on the devices themselves.

The problem we're finding is with Android. I don't think any of us here ever really understood just how fragmented the whole platform is until we started looking at devices to acquire. We are going to wait until v2.3 of Android is released, but which products to choose? Do we go by the most popular by market share? Do we get a small range of products by specs from least to most powerful overall?

We're trying to avoid having to manage a dozen different devices to test each app, if not because of cost if only for the repeated time sink.

How do you manage the testing of your Android software on physical devices?

UPDATE: To bring some context to what I am asking, the applications being created are for educational purposes only, and there are no plans to use any of the hardware features of the devices themselves. We are simply displaying content in a variety of ways: eBooks, test questions, flash cards, etc. that may or may not be downloadable content. So, no cameras, GPS, user-driven content management, or anything like that; just as device-agnostic as we can possibly make it.

答: Presumably, you won't have to code exceptions for various devices (i.e. all of the Android devices should behave the same).  Accordingly, you should only need one Android device; it should be a relatively popular one.  By the time v2.3 of Android is released, maybe the market will be less fragmented.


问:
In Unit Testing, why would I create a Repository twice?
The other day I was reading a little about Unit Testing and I saw some examples where people create a repository interface (i.e. IExampleRepository) and then create the real repository (public class ExampleRepository : IExampleRepository) and a repository to be used for unit testing (FakeExampleRepository : IExampleRepository).

In the IExampleRepository they were implementing the same methods as in the ExampleRepository, however with different Linq queries.

What is exactly the objective here? I thought one part of unit testing your code is make sure that a method works correctly? But when I use two totally different queries, one for 'real' and one in the test, how much sense does the test make?

答:
What is exactly the objective here?

Isolation.

The idea of a unit test it to test the smallest possible unit of code. You do this by isolating it from all other production code in the test.

By creating fake classes the only production code is the class under test.

If you create a fake repository properly and the test fails you know that the issue is with the code-under-test. This gives you the benefit of diagnosis for free.

Have a look at isolation frameworks (like Moq as suggested by @Allan) to be able to generate these fakes quickly to setup test conditions and use them to assert against.


问:
Best Practices for Maintaining Uppercase vs Proper Case Data
We have several years of customer data that has been collected over time. I'd guess that 95% of the data (Names, Business Names & Addresses) is in all UPPERCASE format.

The data entry tool used within our organization offers an "Export as Proper Case" function. We do not have the ability to modify this data import function. It's an all or nothing switch. We flipped this switch on in January 2013 and since then have discovered numerous data abnormalities:

```
Original Data          Proper Case Import
-------------          ------------------
McDonald               Mcdonald
MacDonald              Macdonald
O'Neil                 O'neil
My First LLC           My First Llc
my.email@test.com      My.Email@Test.Com
John Smith III         John Smith Iii
```

Our data is stored within a closed environment on an iSeries. We have a web interface that allows for single record changes to the data. Unfortunately I do not have the ability to run an update database query to update our data and make mass changes.

What are the Best Practices that you have adopted within your organization with regard to maintaining Proper Case Data vs UPPERCASE Data?

I've got two or three people in the organization that are pushing for Proper Case data on the system. The majority of other people want UPPERCASE data on the system. I'm trying to put together a presentation that states how unrealistic it is to move to a total Proper Case data environment.

What are some good talking points or arguments that support all UPPERCASE data?

答: People's names aren't capitalized using proper case rules. In your example, the correct capitalization of O'neil is O'Neil. Depending on the individual, incorrect capitalization of one's name could be somewhat offensive. There is no sense running the risk of offending a potential customer or (worse!) an existing client by incorrectly capitalizing their name in print and electronic communications with them.


问:
Should we use a Maven Multi-Module Project in our Scenario?
The Situation

I'm currently working in project that develops several RESTful services that partly interact with each other. As an example:

Service A uses Service B

Service C uses nothing

Service D uses Service C

most of the Services use a common Utillities project.

There is NO actual code sharing between the services, they strictly rely on the defined RESTful API. Util contains helpers for test, helpers for the security lib, ....

Currently every project is stand alone in their own git repository. During development there were some moments when this was slightly anoying:

multiple places to do dependency management (services share dependencies to third-party libs)

every project has to be (maven) released seperately (personaly i like that)

when working "between" projects (working on a service and working on util because of that) lead to 2 review requests, because of  2 project (pull-requests)

The Question

One in the Team proposed as a solution to above problems to merge all git repositories and projects into one git repository and one maven multi module projects.

Beside my own misgivings about the idea (no code sharing, only util as a common dependency, reliance on APIs between some (not all) services,...) i would like to know:

Are there known Advantages/Disadvantages of this Plan?

I don't like it makes a bad argument.

答:
If all projects have to be (always, or almost always) released simultaneously, like service-a-1.2.3, service-b-1.2.3, service-c-1.2.3 etc, then multi-module project is what doctor ordered because it gives you these simultaneous releases out of the box, instead of having to manually repeat releases for each module every time.

Otherwise, you better think twice before going there. It could be quite cumbersome and confusing to have something like 10 identical releases of service-a only because there were 10 releases of service-b - because, well, multi-module project would force you release a every time you release b.

In one of my past projects, troubles with redundant releases of loosely coupled modules have been the main reason to split a multi-module project.

"Hey guys, why do we have 10 releases of module-a? Oh wait, 2 of these were because of changes in module-b, 3 because of module-c, 4 because of module-d. And, yeah, there was one release because of changes in module-a, right." Seeing stuff like that go away after split was quite a relief.

On the other hand, that very experience taught me that if I ever need synchronous releases of several modules, I'll go for multi-module project without a doubt.

Just think of it - no need to memorize involved modules, no need to design complicated release scripts - you just shoot mvn -B clean release:prepare release:perform, relax for a while and get it all done for you in a perfect harmony. It just can't get better than that.


答:
I would suggest not coercing user-entered strings into any "correct" format, except for trimming leading and trailing spaces. In the case of data transfer, leave it in the existing format, but store new data as it is entered.

If there is a need for a "correct" case for the purpose of performance, you can coerce both the data and the criteria into an arbitrary case. Better would be to index on an arbitrary case function applied to the data (or create a duplicate arbitrary case column if your database doesn't support that kind of index) and the coerce criteria into that case as well.

For strings, I think the best practice is to trust the user means what they say, because any guessing you perform is going to be wrong frequently. The exception would be when they are given instructions to enter in a particular format, in that case perform the formatting on their behalf wherever possible (i.e.: if they enter in the wrong case, just fix it rather than generating an error).

Title: Best Practices for Maintaining Uppercase vs Proper Case Data

Body:
We have several years of customer data that has been collected over time. I'd guess that 95% of the data (Names, Business Names & Addresses) is in all UPPERCASE format.

The data entry tool used within our organization offers an "Export as Proper Case" function. We do not have the ability to modify this data import function. It's an all or nothing switch. We flipped this switch on in January 2013 and since then have discovered numerous data abnormalities:

```
Original Data          Proper Case Import
-------------          ------------------
McDonald               Mcdonald
MacDonald              Macdonald
O'Neil                 O'neil
My First LLC           My First Llc
my.email@test.com      My.Email@Test.Com
John Smith III         John Smith Iii
```

Our data is stored within a closed environment on an iSeries. We have a web interface that allows for single record changes to the data. Unfortunately I do not have the ability to run an update database query to update our data and make mass changes.

What are the Best Practices that you have adopted within your organization with regard to maintaining Proper Case Data vs UPPERCASE Data?

I've got two or three people in the organization that are pushing for Proper Case data on the system. The majority of other people want UPPERCASE data on the system. I'm trying to put together a presentation that states how unrealistic it is to move to a total Proper Case data environment.

What are some good talking points or arguments that support all UPPERCASE data?


问:
Ext JS licensing issue
First of all I'm not asking for legal advice but just checking if anyone agrees with my suspicions. That might help in convincing Sencha to change their license.

Their commercial license says:

The Open Source version of the Software (“GPL Version”) is licensed under the terms of the GNU General Public License versions 3.0 (“GPL”) and not under this License Agreement. If You, or another third party, has, at any time, developed all (or any portions of) the Application(s) using the GPL Version, You may not combine such development work with the Software and must license such Application(s) (or any portions derived there from) under the terms of the GNU General Public License version 3, a copy of which is located at http://www.gnu.org/copyleft/gpl.html.

Meanwhile there exist libraries licensed under MIT or BSD, that use ExtJS. GeoExt is one example. It's likely some contributors of those libraries have not bought the commercial license of Ext JS, and are using its GPL-licensed version. Reasonably GPL-licensed Ext JS shouldn't "infect" GeoExt code if it's distributed without the Ext JS library.

Now the problem is, if I use GeoExt then likely "portions" of it have been "developed using" the GPL version. Specifically Sencha clarifies what they mean by "develop using" in their FAQ:

The license prohibits combining code that you develop using a GPL licensed version of the software with code that you develop using a commercial licensed version. In other words, you may not begin development with our GPL version and then "convert" it to our commercial version.

My interpretation is that it's not allowed by the Sencha commercial license to combine Ext JS with GeoExt and who knows what other libraries whose contributors at some point may have "developed using" a GPL version of Ext JS. This may or may not include OpenLayers, jQuery and other libraries developers would likely also need to use in their commercial projects.

If Sencha then so desires, according to their commercial contract they can demand commercial customers who combined Ext JS with other libraries, to release their software under the GPL, since the commercial license doesn't offer any other resolution.

My question is: do you agree that this sounds like developing commercial software using Ext JS may be risky, or is my interpretation incorrect?

答:
IANAL, but here's how I see it.

The GPL uses a simple model of pay it forward. All your changes, modifications, improvements are shared with the same understanding which you created them. I believe it's the purest of all open source licenses. It's also the most popular.

The "permissive" open source licenses don't care about future changes. The author feels fine that their work can commercialized or forked. Here corporations can make improvements, modifications, and changes that add value only for them and NEVER give back.

In this case, Sencha allows third-party developers to build and deploy new works under an permissive license (a FLOSS-exception). The only reason to do this is to support a community.  Their is no good reason to have a FLOSS exception other than to be a good open source citizen to those using your product under a permissive license. Case in point here - GeoExt.

GeoExt is MIT/BSD licensed thanks to the FLOSS-exception. Which affords commercial license holders to use this with their commercial applications without fear of the GPL "pay it forward" philosophy so long as they have a commercial license of the dependent software (in this case, Ext JS).

This is a huge win all around. It enables the author to have a commercial business while allowing open source, in all flavors, the ability to use the original software.

Title: Ext JS licensing issue


答:
This issue is entirely an issue of what the consumers of the data need. It is not a programming issue as either can be accomplished (albeit the propercasing is harder).  In the company I work for the users do not ever want to see all uppercase and thus we propercase everything on import. It they wanted all uppercase, we would do that.

You could have a business rule that uppercases the character to the right of the ' or that uppercases the chareter to the right of Mac or Mc (when these appear at the beginning of the name). It would also uppcase II, IV or III when they are at the end of a name.  That handles the majority of the people name problems.

If you find exceptions you want handled as you go, you can create an exception table with the propercased version of the name. You can use that fix any names that come to the attention of the company that are not part of the normal rules. This will eventually include almost all of the name problems you have.

Company names and address are more difficult and we just accept whatever our normal propercasing function hands out for imports and whatever is typed in for records added by the GUI. If someone obects to the capitalization we can fix it through the GUI and the import will not update it.


问:
Why does Scala use the '_' operator for package import instead of '*' as in Java?
In my opinion, one of the greatest things about Scala is its interoperability with Java and its similar syntax. One thing that I found strange is the use of the _ operator for package wilcard imports instead of the * operator that is used in Java.

Is there a technical reason for using _ instead of *? If not, then why was this change done?

答: In functional languages, the _ character is commonly used to say, "I don't care about this parameter" or "anything can go here". Extending that value to namespace imports only makes sense.</p>


答: In Scala there are dozens of places where the underscore is used. Using it for wildcard imports is just a logical consequence.</p>

Title: Why does Scala use the '_' operator for package import instead of '*' as in Java?

Body:
In my opinion, one of the greatest things about Scala is its interoperability with Java and its similar syntax. One thing that I found strange is the use of the _ operator for package wilcard imports instead of the * operator that is used in Java.

Is there a technical reason for using _ instead of *? If not, then why was this change done?


答:
In Scala, the * is a valid identifier. One could write:

```<code>val * = "trollin'"
println(*)
</code>```

With the result being:

```<code>trollin'
</code>```

One could write a class named * as such:

```<code>class * {
  def test():String = {
    "trollin'"
  }
}
</code>```

So with that being the case, when I have a class * in the package us.hexcoder and I write:

```<code>import us.hexcoder.*
</code>```

You would be saying that you wish to import a class with the name *. Because of this, Scala needed to use another symbol to indicate a wildcard import. For whatever reason, they decided to use _ as the wildcard symbol.

Body:
In Scala, the * is a valid identifier. One could write:

val * = "trollin'"
println(*)

With the result being:

trollin'

One could write a class named * as such:

class * {
  def test():String = {
    "trollin'"
  }
}

So with that being the case, when I have a class * in the package us.hexcoder and I write:

import us.hexcoder.*

You would be saying that you wish to import a class with the name *. Because of this, Scala needed to use another symbol to indicate a wildcard import. For whatever reason, they decided to use _ as the wildcard symbol.


答:
An argument for all uppercase data is that it's the most amenable to internationalization of all the formats. This is why Microsoft recommends uppercasing as opposed to lowercasing in the .NET framework:

Use the String.ToUpperInvariant method instead of the String.ToLowerInvariant method when you normalize strings for comparison.

This may or may not matter for your case.

There are some secondary benefits as well, for example, uppercase letters tend to be easier to read for those with non-ideal vision.

Overall, I can't think of a large number of considerations. Name data is just name data, the casing of it doesn't usually change the context unless you're applying the names into a context rather than just having the name for reporting or statistics-type purposes. So if you were creating welcome messages or something, then the case is probably a lot more important.


问:
What is the ideal length of a method for you?
In object-oriented programming, there is of course no exact rule on the maximum length of a method , but I still found these two quotes somewhat contradicting each other, so I would like to hear what you think.

In Clean Code: A Handbook of Agile Software Craftsmanship, Robert Martin says:

The first rule of functions is that they should be small. The second
  rule of functions is that they should be smaller than that. Functions
  should not be 100 lines long. Functions should hardly ever be 20 lines
  long.

and he gives an example from Java code he sees from Kent Beck:

Every function in his program was just two, or three, or four lines
  long. Each was transparently obvious. Each told a story. And each led
  you to the next in a compelling order. That’s how short your functions
  should be!

This sounds great, but on the other hand, in Code Complete, Steve McConnell says something very different:

The routine should be allowed to grow organically up to 100-200 lines,
  decades of evidence say that routines of such length no more error
  prone then shorter routines.

And he gives a reference to a study that says routines 65 lines or long are cheaper to develop.

So while there are diverging opinions about the matter, is there a functional best-practice for you?

答:
If I find long method, I could bet this method is not properly unit-tested or most time it hasn't unit test at all. If you start doing TDD you will never build up 100-lines methods with 25 different responsibilities and 5 nested loops.
Tests oblige you constantly refactor your mess and write uncle Bob's clean code. </p>

OwnerDisplayName: iPhoneDeveloper

ContentLicense: CC BY-SA 4.0


问:
My proposed design is usually worse than my colleague's - how do I get better?
I have been programming for couple of years and am generally good when it comes to fixing problems and creating small-to-medium scripts, however, I'm generally not good at designing large scale programs in object oriented way. Few questions

Recently, a colleague who has same number of years of experience as me and I were working on a problem. I was working on a problem longer than him, however, he came up with a better solution and in the end we're going to use his design. This really affected me. I admit his design is better, but I wanted to come up with a design as good as his. I'm even contemplating quitting the job. Not sure why but suddenly I feel under some pressure e.g. what would juniors think of me and etc? Is it normal? Or I'm thinking a little too much into this?

My job involves programming in Python. I try to read source code but how do you think I can improve me design skills? Are there any good books or software that I should study?

Please enlighten me. I will really appreciate your help.

答:
Recognizing a better design is an important ability. You should foster this as you follow some of the earlier suggestions regarding looking at designs.

On what criteria did you judge the other design better? Was it simpler and easier to understand? Did it provide a performance advantage? Was it more extensible? There are many design principles such as decomposition, abstraction, information hiding, and component modularity which you can use to judge designs and which you might already recognize.

Try to name your criteria, understand them, expand them and reuse them as you look at other designs. When you design things yourself, make it part of your process to use those criteria and consciously measure your designs against them. Then, be prepared to completely modify or throw out your design if it doesn't meet your criteria.

You will get ideas on different principles for designs from some of the following sources:
http://www.cs.wustl.edu/~schmidt/PDF/design-principles4.pdf
Software Design on wikipedia
Google "Software design principles"

Understand different models for software design, such as Object Oriented Design or Functional Design or Structured Analysis Design. These can be entirely different mindsets from which to approach a design task and they each have areas where they excel. Learn these as tools for your toolbox. http://userpages.umbc.edu/~khoo/survey2.html

Make sure you are separating design from implementation, try to diagram things you see as good designs, to separate the language and implementation specifics from the higher-level design principles. And to develop your "design eye" and communication abilities.

Last, but perhaps most importantly, reading widely is a very good tool - there are many interesting things from Fractals to Bayesian analysis to Fuzzy Logic to Natural Language Processing, which can provide fodder for ideas which will emerge later and unexpectedly. With the web you can peruse topics far and wide, just for your amusement and edification and it will benefit. You don't need to become expert, just familiar with terms and ideas.

Have some fun - don't do it if you don't enjoy it at least a little!


答:
One possibility which have not been mentioned yet is to have recursion, but without using a system stack. Of course you can overflow your heap as well, but if your algorithm really need backtracking in one form or another (why using recursion at all otherwise?), you've got no choice.

There are stackless implementations of some languages, e.g. Stackless Python.


问:
Efficient way to create a code estimation/technical specification in a fast-moving environment
To better understand my question, let me elaborate the background of the subject matter.

I work in a financial institution where the business module (credit finance) is constantly changing. In the IT world, however, the developers have a 6 week cycle taking list of projects/enhancements, put it in a timeline and business expect delivery on those projects.

During each cycle, each developer gets assigned work that needs to be completed by a certain date. That date is already finalized by IT Change Managers and codes must be done by then. The code will then be synced, built to create a package and deployed to the test environment for QC (Quality Centre) team to test.

The problem, however, is that developers get given the code 3 weeks before the code cycle ends. We are then told to do a technical specification and work estimation for each project/enhancements/bug fixes we are going to do. I have constantly talked to my managers that that is a backward mentality having to do estimations knowing when we need to deliver the finished code.

My challenge: Is there a better estimation/technical specification model that cater for this kind of environment? If not, how can I tackle this issue such that it doesn't conflict with the deadline.

Thanks.

PS: I totally disagree in providing a business requirement to developers and expecting them to do a technical specification document as well as estimations during a code cycle. I do believe that technical specification document should be done before-hand and completed as well with functional/non-functional document and signed off by business. This is not happening currently.

答:
The idea of doing a schedule estimate at the phase of the cycle where you get to do it is ludicrous.

Since you are time-boxed from the outset, you should look at an Agile methodology like SCRUM which tries to provide visibility and transparency for project progress in hopes of simple forecasting based on prior code deliveries.

See article When to Use Scrum for software projects?

Scrum is often contrasted with the so-called “Waterfall” approach, which emphasizes up-front planning and scheduling of activities, followed by execution. Both approaches require careful planning, followed by execution and tracking, but the details of how these steps are accomplished are different...

Why Choose Scrum versus Waterfall for Software Projects?

The two approaches make different assumptions about the priorities and practicalities of the work to be accomplished...

In general, if you have to figure out how to do a significant amount of the work in the project because you haven’t done it before, so you cannot estimate accurately, go with a Scrum process. If you’ve done it many times before, and know how to do it again, go with a waterfall process...


问:
How to get a Web Application to communicate between users
I am developing a multipalyer web Application for Anti-Chess. It would be hosted on Google App Engine.

I have a few questions:

How do I get two different users who have opened the webapp on their browser to communicate moves with each other. P2P or through the server. If through the server, can I store some moves on it (specifically talking about GAE), to test bots later?

How to implement this P2P/Server connection. As a developer I know jack about Networking. But I hav heard of things like Socket programming, HTTP request etc, what can/should I use. And where can I read up on that!

If I don't go for GAE, would it cost me too much to get some server space and hosting capabilities? And people tell me that then deploying the application is tougher than on GAE. Is that so. Where can I read up on deploying the web Application on Servers.

Where does the code for networking go? I will be using Django with python as the web framework, front-end would be HTML, CSS, and JavaScript. Should I make a separate module for the networking methods and then introduce a method calls wherever needed in the game play?

Someone suggested me on using Unity software for developing. Is it good, Does it make it simple to do work? Will it cover all the parts of the development, the front end and the back end and the deployment?

Note: I am a first timer in web Application, I have coded games before, but always without GUI. And also with no multiplayer over the network capabilities!

答:
Well Time is a great "answerer"! Please bear with me as it is the first time I am answering my own question, and I am not much sure of First/Second/third person!

What can be done is: (I will answer to the specific questions I posted in the same order as asked)

Through Server: One first has to understand, that the web browser only loads the HTML,CSS and JavaScript. With the help of HTML and CSS you can make the UI look like whatever you want it to be. The JavaScript enables you to add the dynamic part to it (the part which changes).
Using AJAX would be better! Learn HTML, CSS, JavaScript, JSON for dummies here.
Through P2P: It wouldn't be so great! For this, one would have to write all the game functions in JavaScript (something I would not chose over Death). And as I didn't read up much on it, I don't have much idea.
GAE supports storing data, but you can only write it to a database (upto 1 GB of data) and not to files. I still have to study about exporting the moves database from GAE to my hard Disk (as in downloading) and reset the database so that I can reuse that space by periodically downloading the database contents.

To learn the client side of HTTP requests after learning HTML, CSS, and JavaScript one can learn this here (in the first lecture itself, of the udacity course).
I will list the server side of networking in point 4.

Yes, hosting is costly, as compared to free, it is too costly, especially for a student like me, who doesn't intend to generate revenue of ads/sign ups!

The server side can be dealt with the Django framework, which can be learnt on djangoproject.org or various other web resources (preferably crash courses, for small webapps like mine). Other than that, I can really not comment about the learning curve and ease, as I haven't yet got to that point.

Unity is! OverKill!


问:
HTTP Session or Database approach
I am confused a little as what should be my approach, Working on a design of shopping cart and i need to store shopping cart either in session or in database but not sure which approach would be best.here are the use case

User is not logged in and adding product to cart (Anonymous user)

User is logged in and adding product to cart.

First case is more confusing to me, since there can be many cases where user just visiting web-shop and adding product without logging in and can be quite possible that he might not going for a checkout process.

But still we need to create a Shopping-Cart for this user, in order to create and save shopping-cart i have two option.

When user adding a product, create a cart in the database and associate this cart with this user, moment he logged in move this cart to logged in user.

Create Cart, add product to it and save it to the Session, when user logged in create Cart in the database and associated logged in user with this cart with User.

I know that both database driven Cart system as well Session based can have there positive as well negative aspects, but not sure which one might be the best approach taking in to account following points

Scalability

Flexibility

Extensibility

Application Should take care of speed

Looking for input on this aspect to decide the path.

答:
Both methods have advantages and disadvantages, but the way I see it, database storage has two pretty large advantages.

Reporting. You can't report on abandoned carts, conversion rates, etc. if the data is in the session.

Session timeouts. I would be annoyed if I went to eat dinner and came back to find my cart was emptied because the session expired. I would imagine the retailer wouldn't like that either. We want to nudge the user toward buying, not toward giving up and leaving.

OwnerDisplayName: Umesh Awasthi

Title: HTTP Session or Database approach


问:
What methods are there to avoid a stack overflow in a recursive algorithm?
Question

What are the possible ways to solve a stack overflow caused by an recursive algorithm?

Example

I'm trying to solve Project Euler problem 14 and decided to try it with a recursive algorithm. However, the program stops with a java.lang.StackOverflowError. Understandably. The algorithm indeed overflowed the stack because I tried to generate a Collatz sequence for a very large number.

Solutions

So I was wondering: what standard ways are there to solve a stack overflow assuming your recursive algorithm was written correctly and would always end up  overflowing the stack? Two concepts that came to mind were:

tail recursion

iteration

Are ideas (1) and (2) correct? Are there other options?

Edit

It would help to see some code, preferably in Java, C#, Groovy or Scala.

Perhaps don't use the Project Euler problem mentioned above so it won't get spoiled for others, but take some other algorithm. Factorial maybe, or something similar.

答:
I'm surprised that no one has mentioned trampolining yet. A trampoline (in this sense) is a loop that iteratively invokes thunk-returning functions (continuation passing style) and can be used to implement tail-recursive function calls in a stack-oriented programming langauge.

This StackOverflow question goes into quite a bit more detail about various implementations of trampolining in Java: Handling StackOverflow in Java for Trampoline


问:
Should a User class only contain attributes and no methods apart from getters/setters?
I'm trying to improve my OOP code and I think my User class is becoming way too fat.

In my program a user has rights over "lists". Read, Write, Update, Delete.
So I made a User class

```<code>class User
{
protected $_id;
protected $_email;
protected $_username;
protected $_hashedPassword;

//...Various setters/getters

public function canRead(List $list){
    //Database query verifies if user has READ rights
}

public function canUpdate(List $list){
    //Database query verifies if user has UPDATE rights
}
//etc...
}
</code>```

Should canRead, canUpdate, canWrite, canDelete methods be moved to another class (UserAccessCheck or something...)?

If not, should the actual SQL be moved into the List object (listCanBeReadByUser()) ?

答:
Abstraction is one of the main principles of OOP

proper mapping of physical objects to the abstract ones that are programmed is key.

It helps to determine how you want to represent this objects.


问:
What is the difference in a developer's years of experience with a language?
As stated by the title, what is the difference in years of experience in given language in terms of developers? For example, if one developer has had five years working with language A and the other developer has had two years working with language B followed by three years working with language A, would there be perceivable difference between them?</p>

答:
I would agree that language is language and concepts are concepts.

My problem is that there are a large number of programmers these days that without a sophisticated IDE they could not program at all.  They are really not programmers but are really more like designers.

I know from personal experience that there are a lot of people that have been seduced by the draggy - droppy Microsoft development environment.  It is not Wrong that they drop a textbox onto the screen then set the properties with the wizard and drag the data from a picture of the database, but are they really coders in any language if all they do is set up basic equality tests?

Those folks are never going to be able to take the Concepts they have learned and apply them to another language.

When I Interview folks  I am more interested in how they did their development and what frameworks they used.  I like to ask questions like, "How do you write an event handler?", "How exactly do you put the data into the DB?", or even "How do I turn this particular button purple when I click it?"  this will quickly weed out the designers and leave the programmers.  I have found that 3 or 4 years actually programming with a year in my language of choice is sufficient for what I need.

Just another opinion,

Tal


答:
In addition to Glenn's answer, import is a valid statement anywhere in Scala and you can import an object or an instance members into scope. As * is obviously a member of many classes, it can not be used as a wildcard for the import statement. So you end up with a string which must not be a valid identifier.

_ comes to mind. The fact that it is used in other places for a different meaning (existential type, function as an instance) is also due to the same issue.


问:
Are "normal order" and "call-by-name" the same thing?
I was studying the book Structure and Interpretation of Computer Programs and in section 1.1.5 The Substitution Model for Procedure Application the author explains the concepts of normal order and applicative order, which I believe I have understood well.

Now, I am taking a course on Coursera called Function Programming Principles in Scala and there the professor Martin Odersky (who based much of his course in the book cited above) explains the same concepts under the names of call-by-name and call-by-value.

In his course, professor Odersky says the substitution model is based on the Lambda Calculus, so I consulted a book on my library An Introduction to Functional Programming Though Lambda Calculus and in page 22, the author does define the terms as applicative order and normal order. Interestingly in his definition he says that applicative order is like Pascal's call-by-value whereas normal order is like Algol's call-by-name.

The use of the words "is like" in his explanation is what made me doubt. Thus my questions:

Are these two terms equivalent or are there any
subtle differences?

Can I use one or the other interchangeably
without risking making a mistake in the meaning they convey?

Are there any reasons you know about that justify the existence of different terminology to refer to the same thing?

答:
Normal order evaluation and call-by-name evaluation are not quite the same thing. In normal order evaluation, the outermost function is evaluated before any of its arguments, and those arguments are evaluated only if needed. In call-by-name evaluation, the arguments are effectively copied into the body of the outermost function and then that function is evaluated. In both cases, the outermost function is technically evaluated before the arguments, but in pure call-by-name, the arguments are evaluated each time they are used (either zero, one, or many times). In normal order, the function arguments are evaluated at the very least only when first needed (typically zero or one times).

Thus normal order evaluation leaves open the possibility of memoizing the arguments as an optimization (sometimes called call-by-need), while call-by-name does not. Thus one could say that call-by-name evaluation is a special case of normal order evaluation. In other words, normal order evaluation refers to the general approach of evaluating a function before its arguments, while call-by-name evaluation refers to a specific technique for implementing normal order evaluation.

As an example, given f(x, y) = sqrt(x*x + y*y) we could have two ways of implementing f(a+b, c+d) with normal order evaluation:

Memoized:

```<code>t1 = a+b;
t2 = c+d;
return sqrt(t1*t1 + t2*t2);
</code>```

Call-by-name:

```<code>return sqrt((a+b)*(a+b) + (c+d)*(c+d));
</code>```

As you can see, if the call to f included other function calls (i.e. f(random(1,100), ask_user_for_value()) ), the two will have very different behavior. The memoized version will square a single random number and ask the user for a value only once, while the call-by-name version will multiply two random numbers and ask the user for a value twice.

To learn more about these concepts, I recommend reading the evaluation strategy Wikipedia page, and https://cs.stackexchange.com/questions/7702/applicative-order-and-normal-order-in-lambda-calculus.

Body:
Normal order evaluation and call-by-name evaluation are not quite the same thing. In normal order evaluation, the outermost function is evaluated before any of its arguments, and those arguments are evaluated only if needed. In call-by-name evaluation, the arguments are effectively copied into the body of the outermost function and then that function is evaluated. In both cases, the outermost function is technically evaluated before the arguments, but in pure call-by-name, the arguments are evaluated each time they are used (either zero, one, or many times). In normal order, the function arguments are evaluated at the very least only when first needed (typically zero or one times).

Thus normal order evaluation leaves open the possibility of memoizing the arguments as an optimization (sometimes called call-by-need), while call-by-name does not. Thus one could say that call-by-name evaluation is a special case of normal order evaluation. In other words, normal order evaluation refers to the general approach of evaluating a function before its arguments, while call-by-name evaluation refers to a specific technique for implementing normal order evaluation.

As an example, given f(x, y) = sqrt(x*x + y*y) we could have two ways of implementing f(a+b, c+d) with normal order evaluation:

Memoized:

t1 = a+b;
t2 = c+d;
return sqrt(t1*t1 + t2*t2);

Call-by-name:

return sqrt((a+b)*(a+b) + (c+d)*(c+d));

As you can see, if the call to f included other function calls (i.e. f(random(1,100), ask_user_for_value()) ), the two will have very different behavior. The memoized version will square a single random number and ask the user for a value only once, while the call-by-name version will multiply two random numbers and ask the user for a value twice.

To learn more about these concepts, I recommend reading the evaluation strategy Wikipedia page, and https://cs.stackexchange.com/questions/7702/applicative-order-and-normal-order-in-lambda-calculus.


问:
Should I retrieve one large set of data to filter or smaller individual sets of data?
I have a company intranet that utilizes a similar set of data across many different pages and many different methods.

Speaking in generalities, is it closer to "best practice" to retrieve a large dataset and filter it for each specific page or method or retrieve many smaller specific sets of data to use?  I cannot really test both approaches, as I would like to pick a design approach from the beginning and use it throughout.  This is for a redesign.  Thanks.

答:
The ideal is to define a single, unified, structure for your data.  Then to put the data into a database with appropriate indexes so that each specific page or method can efficiently retrieve exactly that subset of records that it needs.

There are lots of reasons why people do not follow this ideal in practice.  But it is what you should do if you can.


问:
How to show an "or includes" relationship - UML Use case diagram
I haven't come across this issue before and can't find it in my Schaum's Outline UML book and was wondering if someone here could help.

I'm making a use case diagram for e-commerce, and in it I want to describe that in order to add a book to your shopping basket, you have to either search products (using the websites search engine) or browse products (using navigation).

But the thing is that it can be either one, and not both.

Is there a way to show that adding a product to the basket needs to include either this or that? Because otherwise it would look like it needs to include both.

Or should I join the two use cases (search products and browse products) into one?

答:
The most important is that it is clear from the use case description that a choice must be made between the search and the browse functionality.

In your diagram, the 'add to basket' use case should <<include>> both the 'search products' and 'browse products' use cases (assuming that the choice for searching or browsing is made from the 'add to basket' use case). If you really want to show that those included use cases are mutually exclusive, you can add a UML constraint { mutually exclusive } linked to the inclusion arrows, but that is completely optional.


问:
Keeping test and release version numbers in sync
I'm currently beta-testing an iPhone app. Right now I have sent out the first beta-test for my users and I have labeled that release as 1.0 for my testers.

Now since the testers have tested the app we have discovered some bugs that I have fixed and I'm ready to send out a new beta-test for my users. Should I label the release as 1.0.1 then?

Another question related to this is, when my testers have tested this 1.0.1 release and they do not find any bugs it would be a good time to release this version to the public in the App Store. What version number should I release this under in the App Store? First thought is that since it's the first release to the App Store it should have version number 1.0 but then it will be "out of sync" with the version that has been tested (1.0.1).

答:
Rules of thumb.  Always use increasing version numbers.  Always keep version numbers in sync across releases.  Never, ever declare anything final until it truly is final.

In your case if you want your initial iPhone release to be 1.0, then you have to break one of those rules.  If you're going to break rules, do it all at once.  So make your next version 0.9, explain it to your beta users (who, with luck, are the smallest group you will ever have to deal with), and proceed from there.  Do not label anything 1.0 until it is ready for release.  (Not just you think it is ready, actually ready.)

Incidentally it would be surprising if you don't have to do this bugfix dance a few more times.  There is always more to do than we think there will be.


答:
There's really only one rule with version numbers - consistency.

While it would be "nice" to have the first official version of your product as 1.0 (which is why beta versions are often labeled "0.something") there's no hard and fast rule that says they have to be.

If you've already called your beta version 1.0 then just start incrementing from there using your "1.0.1" scheme so that the first version uploaded to the App Store is at least 1.0.something.

Years ago a product I was working on was labeled "4.0" for it's first release - to make the product seem "more mature" to potential customers. You probably couldn't get away with that these days, but it didn't raise any questions we couldn't answer.

Title: Keeping test and release version numbers in sync

Body:
I'm currently beta-testing an iPhone app. Right now I have sent out the first beta-test for my users and I have labeled that release as 1.0 for my testers.

Now since the testers have tested the app we have discovered some bugs that I have fixed and I'm ready to send out a new beta-test for my users. Should I label the release as 1.0.1 then?

Another question related to this is, when my testers have tested this 1.0.1 release and they do not find any bugs it would be a good time to release this version to the public in the App Store. What version number should I release this under in the App Store? First thought is that since it's the first release to the App Store it should have version number 1.0 but then it will be "out of sync" with the version that has been tested (1.0.1).


问:
How can I evaluate a candidate's knowledge of Html/CSS during an interview?
I am trying to determine some good interview questions to assess the ability of people coming in for a Html/CSS job, however that topic is extremely broad, and I'm not sure what sort of questions I can ask to properly evaluate someone's HTML/CSS knowledge.

What sort of questions can I ask to evaluate a candidate's Html/CSS abilities during an interview?

Ideally I would like to ask few questions and then give them a real life scenario to combat.

答:
If you conduct live interview, then the best way is to ask the developer to write some html/css code.

Example (very common in real development). Ask developer to write html/css code of page with:

Fluid width.

Header with height 100px;

Login button at the right corner of header

Left-side and Right-side panels with 100px width and 200px height;

Center panel for the article text.

Footer, which allways will be at the bottom. Even if article has 1 row.

UPD: Of cource, ask the developer to write the code using divs only (without tables).

It should looks like:

But prior to live interview, I would suggest you to test candidates online. Because it's easier to test candidates online and invite to the interview only good skilled developers, than spend your time on every candidate.


问:
Multi-user Configuration Settings design
I am designing a flexible and extensible way to store configuration settings for users.

Database Table Design:

```<code>╔═════════════════════════════╗
║ ConfigurationItemDefinition ║
╠═════════════════════════════╣
║ ID                          ║
║ Name                        ║
║ Type                        ║
║ DefaultValue (varchar)      ║
║ ConfigurationItemAdapterID  ║
╚═════════════════════════════╝
              |
╔═══════════════════════════════╗
║ ConfigurationItem             ║
╠═══════════════════════════════╣
║ ID                            ║
║ UserID                        ║
║ ConfigurationItemDefinitionID ║
║ Value (varchar)               ║
╚═══════════════════════════════╝
</code>```

Explanation:

The ConfigurationItemDefinition table holds the definition for configuration settings.  Type is the .NET type which the value would be parsed/serialized into when queried in the code.

The ConfigurationItem table is where configuration values are set for each user.  If there is no value explicitly set for a specific user for some configuration item definition, then the DefaultValue value from ConfigurationItemDefinition is used.

ConfigurationItemAdapterID is determines what technique is to be used to 'get' and 'set' the configuration value.  For example, an int value would use a basic Parse (from string -> int).  A CultureInfo object would need to use a serialization adapter.  The way in which configuration values are get and set is determined by the adapter (examples below).

C# Code

In C#, a setting would be acquired like this:

```<code>// This would use the Parse adapter
int timeout = someUser.GetConfigurationValue<int>("TimeoutValue");

// This would use the Serialization adapter
CultureInfo cultureInfo = someUser.GetConfigurationValue<CultureInfo>("CultureInformation");
</code>```

And set like this:

```<code>// This would use the Parse adapter
someUser.SetConfigurationValue<bool>("IsLive", true);
</code>```

Please critique this design.  Are there more standard ways of dealing with such a problem?

答:
That solution looks altogether workable to me.

One nitpick: I find that when I have to store different types of things in a uniform way, and there are only a small, non-expandable number of types that can exist, I'd rather have separate methods readInt(), readString() etc. and live with a small amount of duplication rather than specify the generic parameter on every access. At least, I would write "syntactic sugar" wrappers in that style. But that really is a question of what you consider more readable. Obviously, if there are an unbounded number of types that you have to support, the generic solution is the way to go.


答:
It probably would have been better to have your beta version start as 0.something, as this is a de facto standard indicating something is not yet released.  It is not really a big deal, though.  Once you have started version numbers, it is not really worth changing.

I would probably just release the app at 1.1.4 or whatever version you are at after the bug fixes.  No one will really care about this.

In the future, you may want to beta test updated versions of the software before releasing them.  You should think of a consistent way to handle that in your versioning scheme.  One common way is 1.2-b1, etc.  However, there is no standard for this at all.  There is a ridiculous number of versioning schemes.


答:
One approach to this is to have the official App Store version number be "1.0" and have a separate build number that you use to keep track of changes. As long as the build number is easily accessible and everyone understands the system, it gives you some useful flexibility.

(and Apple requires you to give each version you release on the App Store a new version number, so you can never end up with two different live apps labelled "1.0")