问:
Stack and Heap memory in Java
As I understand, in Java, stack memory holds primitives and method invocations and heap memory is used to store objects.

Suppose I have a class

```<code>class A {
       int a ;
       String b;
       //getters and setters
}
</code>```

Where will the primitive a in class A be stored?

Why does heap memory exist at all? Why can't we store everything on the stack?

When the object gets garbage collected, is the stack associated with the objected destroyed?

答:
Where are primitive fields stored?

Primitive fields are stored as part of the object that is instantiated somewhere. The easiest way to think of where this is - is the heap.  However, this is not always the case.  As described in Java theory and practice: Urban performance legends, revisited:

JVMs can use a technique called escape analysis, by which they can tell that certain objects remain confined to a single thread for their entire lifetime, and that lifetime is bounded by the lifetime of a given stack frame. Such objects can be safely allocated on the stack instead of the heap. Even better, for small objects, the JVM can optimize away the allocation entirely and simply hoist the object's fields into registers.

Thus, beyond saying "the object is created and the field is there too", one cannot say if something is on the heap or on the stack.  Note that for small, short-lived objects, it's possible that the 'object' won't exist in memory as such and may instead have its fields placed directly in registers.

The paper concludes with:

JVMs are surprisingly good at figuring out things that we used to assume only the developer could know. By letting the JVM choose between stack allocation and heap allocation on a case-by-case basis, we can get the performance benefits of stack allocation without making the programmer agonize over whether to allocate on the stack or on the heap.

Thus, if you have code that looks like:

```<code>void foo(int arg) {
    Bar qux = new Bar(arg);
    ...
}
</code>```

where the ... doesn't allow qux to leave that scope, qux may be allocated on the stack instead.  This is actually a win for the VM because it means it doesn't need to ever be garbage collected - it will disappear when it leaves the scope.

More on escape analysis at Wikipedia.  For those willing to delve into papers, Escape Analysis for Java from IBM.  For those coming from a C# world, you may find The Stack Is An Implementation Detail and The Truth About Value Types by Eric Lippert good reads (they're useful for Java types also, as many of the concepts and aspects are the same or similar). Why do .Net books talk about stack vs heap memory allocation? also goes into this.

On the whys of the stack and the heap

On the heap

So, why have the stack or the heap at all? For things that leave scope, the stack can be expensive.  Consider the code:

```<code>void foo(String arg) {
    bar(arg);
    ...
}

void bar(String arg) {
    qux(arg);
    ...
}

void qux(String arg) {
    ...
}
</code>```

The parameters are part of the stack too.  In the situation that you don't have a heap, you would be passing the full set of values on the stack.  This is fine for "foo" and small strings... but what would happen if someone put a huge XML file in that string?  Each call would copy the entire huge string onto the stack - and that would be quite wasteful.

Instead, it is better to put the objects that have some life outside of the immediate scope (passed to another scope, stuck in a structure that someone else is maintaining, etc...) into another area which is called the heap.

On the stack

You don't need the stack.  One could, hypothetically, write a language that doesn't use a stack (of arbitrary depth).  An old BASIC that I learned on in my youth did so, one could only do 8 levels of gosub calls and all variables were global - there was no stack.

The advantage of the stack is that when you have a variable that exists with a scope, when you leave that scope, that stack frame is popped.  It really simplifies what is there and what isn't.  The program moves to another procedure, a new stack frame; the program returns to the procedure, and you've back in the one that sees your current scope; the program leaves the procedure and all the items on the stack are deallocated.

This really makes life easy for the person writing the runtime for the code to use a stack and a heap.  There are simply many concepts and ways of working on the code, allowing the person writing the code in the language to be freed of thinking of them explicitly.

The stack's nature also means it can't become fragmented. Memory fragmentation is a real problem with the heap.  You allocate a few objects, then garbage collect a middle one, and then try finding space for the next large one to be allocated.  It's a mess.  Being able to put things on the stack instead means that you don't have to deal with that.

When something is garbage collected

When something is garbage collected, it's gone.  But it is only garbage collected because it's already forgotten about - there are no more references to the object in the program that can be accessed from the current state of the program.

I'll point out that this is a very large simplification of garbage collection.  There are many garbage collectors - even within Java, you can tweak the garbage collector by using various flags (docs).  These behave differently and the nuances of how each one does things is a bit too deep for this answer.  You may wish to read Java Garbage Collection Basics to get a better idea of how some of that works.

That said, if something is allocated on the stack, it is not garbage collected as part of System.gc() - it is deallocated when the stack frame pops.  If something is on the heap, and referenced from something on the stack, it will not be garbage collected at that time.

Why does this matter?

For the most part, it's tradition.  The text books written and compiler classes and various bits documentation make a big deal about the heap and the stack.

However, virtual machines of today (JVM and similar) have gone to great lengths to try to keep this hidden from the programmer.  Unless you are running out of one or the other and need to know why (rather than just increasing the storage space appropriately), it doesn't matter too much.

The object is somewhere and it's in the place where it can be accessed correctly and quickly for the appropriate amount of time that it exists.  Whether it's on the stack or the heap - it doesn't really matter.

Title: Stack and Heap memory in Java

Body:
Where are primitive fields stored?

Primitive fields are stored as part of the object that is instantiated somewhere. The easiest way to think of where this is - is the heap.  However, this is not always the case.  As described in Java theory and practice: Urban performance legends, revisited:

JVMs can use a technique called escape analysis, by which they can tell that certain objects remain confined to a single thread for their entire lifetime, and that lifetime is bounded by the lifetime of a given stack frame. Such objects can be safely allocated on the stack instead of the heap. Even better, for small objects, the JVM can optimize away the allocation entirely and simply hoist the object's fields into registers.

Thus, beyond saying "the object is created and the field is there too", one cannot say if something is on the heap or on the stack.  Note that for small, short-lived objects, it's possible that the 'object' won't exist in memory as such and may instead have its fields placed directly in registers.

The paper concludes with:

JVMs are surprisingly good at figuring out things that we used to assume only the developer could know. By letting the JVM choose between stack allocation and heap allocation on a case-by-case basis, we can get the performance benefits of stack allocation without making the programmer agonize over whether to allocate on the stack or on the heap.

Thus, if you have code that looks like:

void foo(int arg) {
    Bar qux = new Bar(arg);
    ...
}

where the ... doesn't allow qux to leave that scope, qux may be allocated on the stack instead.  This is actually a win for the VM because it means it doesn't need to ever be garbage collected - it will disappear when it leaves the scope.

More on escape analysis at Wikipedia.  For those willing to delve into papers, Escape Analysis for Java from IBM.  For those coming from a C# world, you may find The Stack Is An Implementation Detail and The Truth About Value Types by Eric Lippert good reads (they're useful for Java types also, as many of the concepts and aspects are the same or similar). Why do .Net books talk about stack vs heap memory allocation? also goes into this.

On the whys of the stack and the heap

On the heap

So, why have the stack or the heap at all? For things that leave scope, the stack can be expensive.  Consider the code:

void foo(String arg) {
    bar(arg);
    ...
}

void bar(String arg) {
    qux(arg);
    ...
}

void qux(String arg) {
    ...
}

The parameters are part of the stack too.  In the situation that you don't have a heap, you would be passing the full set of values on the stack.  This is fine for "foo" and small strings... but what would happen if someone put a huge XML file in that string?  Each call would copy the entire huge string onto the stack - and that would be quite wasteful.

Instead, it is better to put the objects that have some life outside of the immediate scope (passed to another scope, stuck in a structure that someone else is maintaining, etc...) into another area which is called the heap.

On the stack

You don't need the stack.  One could, hypothetically, write a language that doesn't use a stack (of arbitrary depth).  An old BASIC that I learned on in my youth did so, one could only do 8 levels of gosub calls and all variables were global - there was no stack.

The advantage of the stack is that when you have a variable that exists with a scope, when you leave that scope, that stack frame is popped.  It really simplifies what is there and what isn't.  The program moves to another procedure, a new stack frame; the program returns to the procedure, and you've back in the one that sees your current scope; the program leaves the procedure and all the items on the stack are deallocated.

This really makes life easy for the person writing the runtime for the code to use a stack and a heap.  There are simply many concepts and ways of working on the code, allowing the person writing the code in the language to be freed of thinking of them explicitly.

The stack's nature also means it can't become fragmented. Memory fragmentation is a real problem with the heap.  You allocate a few objects, then garbage collect a middle one, and then try finding space for the next large one to be allocated.  It's a mess.  Being able to put things on the stack instead means that you don't have to deal with that.

When something is garbage collected

When something is garbage collected, it's gone.  But it is only garbage collected because it's already forgotten about - there are no more references to the object in the program that can be accessed from the current state of the program.

I'll point out that this is a very large simplification of garbage collection.  There are many garbage collectors - even within Java, you can tweak the garbage collector by using various flags (docs).  These behave differently and the nuances of how each one does things is a bit too deep for this answer.  You may wish to read Java Garbage Collection Basics to get a better idea of how some of that works.

That said, if something is allocated on the stack, it is not garbage collected as part of System.gc() - it is deallocated when the stack frame pops.  If something is on the heap, and referenced from something on the stack, it will not be garbage collected at that time.

Why does this matter?

For the most part, it's tradition.  The text books written and compiler classes and various bits documentation make a big deal about the heap and the stack.

However, virtual machines of today (JVM and similar) have gone to great lengths to try to keep this hidden from the programmer.  Unless you are running out of one or the other and need to know why (rather than just increasing the storage space appropriately), it doesn't matter too much.

The object is somewhere and it's in the place where it can be accessed correctly and quickly for the appropriate amount of time that it exists.  Whether it's on the stack or the heap - it doesn't really matter.

ContentLicense: CC BY-SA 4.0


问:
Should a list or array of objects be represented as a lifeline in sequence diagram?
I have the following sequence diagram to add a student to a list of students.
the implementation could be like

```<code>List<Student> Students = new List<Student>();
Students.Add(aStudent);
</code>```

I drew the following sequence diagram for it:

In this diagram Students is actually the list of students mentioned in the code.

I would like to know is it a correct way to show a list of objects as a object lifeline? I mean as a conceptual and analysis approach and also at syntax.

For example maybe the List<Student> could be the object of a general class named  Storage which is responsible to store and retrieve a list of objects like a database...

答:
Description of lifeline from UML 2.4.1 standard:

A Lifeline is shown using a symbol that consists of a rectangle forming its “head” followed by a vertical line (which may
  be dashed) that represents the lifetime of the participant. Information identifying the lifeline is displayed inside the
  rectangle in the following format:

```<code><lifelineident> ::= ([<connectable-element-name>[‘[‘ <selector> ‘]’]] [: <class_name>] [decomposition]) | ‘self’
<selector> ::= <expression>
<decomposition> ::= ‘ref’ <interactionident> [‘strict’]
</code>```

So, you should rename Students to Students : List<Student> or just :List<Student>. The part after colon (:) represents a type (<class_name> from notation above).

There is no special syntax for representing lists.

EDIT: as for "Student Storage/Adapter"

If List does the job, just use it. It is object-oriented enough as it is. No need to introduce a pattern for the sake of introducing a pattern, and more than so for the sake of writing a busy-sounding class name to a diagram. Keep it simple.

ContentLicense: CC BY-SA 3.0

Body:
Description of lifeline from UML 2.4.1 standard:

A Lifeline is shown using a symbol that consists of a rectangle forming its “head” followed by a vertical line (which may
  be dashed) that represents the lifetime of the participant. Information identifying the lifeline is displayed inside the
  rectangle in the following format:

<lifelineident> ::= ([<connectable-element-name>[‘[‘ <selector> ‘]’]] [: <class_name>] [decomposition]) | ‘self’
<selector> ::= <expression>
<decomposition> ::= ‘ref’ <interactionident> [‘strict’]

So, you should rename Students to Students : List<Student> or just :List<Student>. The part after colon (:) represents a type (<class_name> from notation above).

There is no special syntax for representing lists.

EDIT: as for "Student Storage/Adapter"

If List does the job, just use it. It is object-oriented enough as it is. No need to introduce a pattern for the sake of introducing a pattern, and more than so for the sake of writing a busy-sounding class name to a diagram. Keep it simple.


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
Good Clever -- high ratio between clever lines of code vs lines of in a non-clever alternative. 20 lines of code that saves you from writing 20000 is Extremely Good Clever. Good Clever is about saving yourself work.

Bad Clever -- low ratio between lines of code written written vs. lines of code saved. One line of clever code that saves you from writing five lines of code is Bad Clever. Bad clever is about "syntactic masturbation".

Just to note: Bad Clever is almost never called "Bad Clever"; it will often travel under the aliases "beautiful", "elegant", "concise", or "succinct."

ContentLicense: CC BY-SA 2.5


问:
Simulated Annealing Contradiction?
The entire idea of simulated annealing is to avoid getting stuck in local optimums, which is why sometimes, a worse solution is accepted.

However, simulated annealing will automatically accept a superior solution to the current one. Thus if you are in a local optimum, then simulated annealing will get you out of it for one iteration, and then put you right back in it since it will accept the local optimum with probability 1, right?

I know that yes, if the temperature is still high, then you can escape out of that local optimum, but if the temperature has cooled and you are still at the wrong local optimum, then you are pretty much stuck there, correct??

答:
If it's in a local optimum, any choice of neighbor is worse and accepted with a probability depending on the temperature, yes. Note the wording any choice of neighbor: There are typically dozens of neighbors or more, and at every iteration only one is examined. Thus the state can easily get several steps away from the previous local optimum. Since it's rather unlikely to pick the exact neighbors again and go back on the same path, it may slide towards a different minimum (the search space is usually high-dimensional, so 2D intuition underestimates the number of paths available).

And yes, even after many iterations it may still be in a local optimum rather than the global one. That's okay. SA is a meta-heuristic, it's used when an exact solution is not feasible. A local minimum found after many iterations, with good choice of parameters, will still be far better than what more simplistic approaches can produce. Perhaps its cost is only ε away from the global optimum, but extremely far removed spatially. (Of course, in other cases the solution is simply crap and different parameters or a different metaheuristic may work better.)

Title: Simulated Annealing Contradiction?


问:
Callback functions: Semantics and maintainability, when they aren't necessary
Within the context of JavaScript/Node.JS; Will using Callback functions improve the maintainability of source code, when there is no need for async programming?

For example does the plain code sound semantically more correct and will be easier to maintain/extend, rather than the second one that unnecessarily uses callback functions?

Plain

```<code>var validateId = function ( id ) {

    if ( undefined !== id ) {
        return true;
    } else {
        return false;
    }
}

var setId = function ( id ) {

    if ( true === validateId(id) ) {
        userId = id;
        console.log( "success" );
    } else {
        console.log( "failed: ", "invalid id" );
    };
}
</code>```

Callback-ed

```<code>var validateId = function ( id, success, fail ) {

    if ( undefined !== id ) {
        success( id );
    } else {
        fail( "invalid id" );
    }
}

var setId = function ( id ) {

    validateId( id, function success (validatedId) {
        userId = validatedId;
        console.log( "success" );
    }, function fail ( error ) {
        console.log( "failed: ", error );
    });
}
</code>```

Update #1

I'm not looking for a general advise on how to write readable and maintainable code. As written in the first line, I'm specifically looking to see if using Callbacks (not even in any programming languages, but specifically in JavaScript) will improve the maintainability of the code? And if that makes the source code semantically more correct? (invoke validateId and if the result was true set the userId comparing to invoke validateId and assign the userId on success)

答:
Both solutions can make sense. Using functions as parameters is useful in many cases, and this generally makes it easier to write correct code because you're forced to provide callbacks for all circumstances. However, an API that requires callbacks tend to create unnecessarily deep indentation. This becomes more obvious when we have more than one validation, and all must pass:

```<code>// simple solution
function validateA(a) { return a !== undefined }
function validateB(b) { return b !== undefined }
function validateC(c) { return c !== undefined }

function frobnicate(a, b, c) {
  if (! validateA(a)) {
    console.log("failed: ", "invalid a");
    return;
  }
  if (! validateB(b)) {
    console.log("failed: ", "invalid b");
    return;
  }
  if (! validateC(c)) {
    console.log("failed: ", "invalid c");
    return;
  }
  console.log("success");
}
</code>```

```<code>// naive callback solution
function validateA(a, onSuccess, onError) {
  return (a !== undefined) ? onSuccess(a) : onError("invalid a");
}
function validateB(b, onSuccess, onError) {
  return (b !== undefined) ? onSuccess(b) : onError("invalid b");
}
function validateC(c, onSuccess, onError) {
  return (c !== undefined) ? onSuccess(c) : onError("invalid c");
}

function frobnicate(a, b, c) {
  return validateA(a, function successA(a) {
    return validateB(b, function successB(b) {
      return validateC(c, function successC(c) {
        console.log("success");
      }, function failC(msg) { console.log("failed: ", msg) });
    }, function failB(msg) { console.log("failed: ", msg) });
  }, function failA(msg) { console.log("failed: ", msg) });
}
</code>```

With this callback-based validation, control flow is incomprehensible, and because the success handler comes before the error handler, error handling is visually separated from the problem it's handling. This is a hindrance to maintenance. Simply slapping callbacks on functions doesn't scale.

Patterns do exist to solve this. For example, we could write a combinator that takes care of correctly composing the callback-based validation functions:

```<code>function multipleValidations(validations, onSuccess) {
   function compose(i) {
     if (i >= validations.length) {
       return onSuccess;
     }
     var cont = compose(i + 1);
     var what       = validations[i][0];
     var validation = validations[i][1];
     var onError    = validations[i][2] || function(msg) {};
     return function(x) { return validation(what, cont, onError) };
  }
  return compose(0)();
}

function frobnicate(a, b, c) {
  return multipleValidations([
    [a, validateA, function failA(msg) { console.log("fail: ", msg) }],
    [b, validateB, function failB(msg) { console.log("fail: ", msg) }],
    [c, validateC, function failC(msg) { console.log("fail: ", msg) }]
  ], function success() {
    console.log("success");
  });
}
</code>```

Well, it's now much nicer to use validation, but the multipleValidations helper is ugly (and non-obvious, and difficult to maintain). That same interface would have been much easier to implement if each validation was just a predicate which returns a boolean (except that now the validation can't define the error message itself, and must depend on the error callback instead):

```<code>function multipleValidations(validations, onSuccess) {
   for (var i = 0; i < validations.length; i++) {
     var what     = validations[i][0];
     var validate = validations[i][1];
     var onError  = validations[i][2] || function fail() {};
     if (! validate(what)) {
       return onError();
     }
   }
   return onSuccess();
}
</code>```

Using callbacks where they are not required is not only a KISS violation (keep it simple and stupid). They sometimes actively get in the way and obfuscate code. Some patterns do require callbacks, and using them there is OK.

Another reason why we should prefer the simpler solution is that we can easily transform both representations of validation into each other:

```<code>function predicateToCallback(predicate, errorMessage) {
  return function validate(x, onSuccess, onError) {
    return (predicate(x)) ? onSuccess(x) : onError(errorMessage);
  };
}

function callbackToPredicate(validate) {
  return function predicate(x) {
    return validate(x, function onSuccess() {
      return true;
    }, function onError() {
      return false;
    });
  };
}
</code>```

In your original code, the callback-based solution does not return a value, so transforming a callback into a predicate becomes marginally more difficult:

```<code>function callbackToPredicate(validate) {
  return function predicate(x) {
    val result;
    validate(x, function onSuccess() {
      result = true;
    }, function onError() {
      result = false;
    });
    return result;
  };
}
</code>```

Because it is so simple to transform one representation of the same concept into the other one, we ought to start out with the more simple one. If for some reason needed, the callback based solution is just a function call away. But quite likely, you ain't gonna need it (YAGNI).

Body:
Both solutions can make sense. Using functions as parameters is useful in many cases, and this generally makes it easier to write correct code because you're forced to provide callbacks for all circumstances. However, an API that requires callbacks tend to create unnecessarily deep indentation. This becomes more obvious when we have more than one validation, and all must pass:

// simple solution
function validateA(a) { return a !== undefined }
function validateB(b) { return b !== undefined }
function validateC(c) { return c !== undefined }

function frobnicate(a, b, c) {
  if (! validateA(a)) {
    console.log("failed: ", "invalid a");
    return;
  }
  if (! validateB(b)) {
    console.log("failed: ", "invalid b");
    return;
  }
  if (! validateC(c)) {
    console.log("failed: ", "invalid c");
    return;
  }
  console.log("success");
}

// naive callback solution
function validateA(a, onSuccess, onError) {
  return (a !== undefined) ? onSuccess(a) : onError("invalid a");
}
function validateB(b, onSuccess, onError) {
  return (b !== undefined) ? onSuccess(b) : onError("invalid b");
}
function validateC(c, onSuccess, onError) {
  return (c !== undefined) ? onSuccess(c) : onError("invalid c");
}

function frobnicate(a, b, c) {
  return validateA(a, function successA(a) {
    return validateB(b, function successB(b) {
      return validateC(c, function successC(c) {
        console.log("success");
      }, function failC(msg) { console.log("failed: ", msg) });
    }, function failB(msg) { console.log("failed: ", msg) });
  }, function failA(msg) { console.log("failed: ", msg) });
}

With this callback-based validation, control flow is incomprehensible, and because the success handler comes before the error handler, error handling is visually separated from the problem it's handling. This is a hindrance to maintenance. Simply slapping callbacks on functions doesn't scale.

Patterns do exist to solve this. For example, we could write a combinator that takes care of correctly composing the callback-based validation functions:

function multipleValidations(validations, onSuccess) {
   function compose(i) {
     if (i >= validations.length) {
       return onSuccess;
     }
     var cont = compose(i + 1);
     var what       = validations[i][0];
     var validation = validations[i][1];
     var onError    = validations[i][2] || function(msg) {};
     return function(x) { return validation(what, cont, onError) };
  }
  return compose(0)();
}

function frobnicate(a, b, c) {
  return multipleValidations([
    [a, validateA, function failA(msg) { console.log("fail: ", msg) }],
    [b, validateB, function failB(msg) { console.log("fail: ", msg) }],
    [c, validateC, function failC(msg) { console.log("fail: ", msg) }]
  ], function success() {
    console.log("success");
  });
}

Well, it's now much nicer to use validation, but the multipleValidations helper is ugly (and non-obvious, and difficult to maintain). That same interface would have been much easier to implement if each validation was just a predicate which returns a boolean (except that now the validation can't define the error message itself, and must depend on the error callback instead):

function multipleValidations(validations, onSuccess) {
   for (var i = 0; i < validations.length; i++) {
     var what     = validations[i][0];
     var validate = validations[i][1];
     var onError  = validations[i][2] || function fail() {};
     if (! validate(what)) {
       return onError();
     }
   }
   return onSuccess();
}

Using callbacks where they are not required is not only a KISS violation (keep it simple and stupid). They sometimes actively get in the way and obfuscate code. Some patterns do require callbacks, and using them there is OK.

Another reason why we should prefer the simpler solution is that we can easily transform both representations of validation into each other:

function predicateToCallback(predicate, errorMessage) {
  return function validate(x, onSuccess, onError) {
    return (predicate(x)) ? onSuccess(x) : onError(errorMessage);
  };
}

function callbackToPredicate(validate) {
  return function predicate(x) {
    return validate(x, function onSuccess() {
      return true;
    }, function onError() {
      return false;
    });
  };
}

In your original code, the callback-based solution does not return a value, so transforming a callback into a predicate becomes marginally more difficult:

function callbackToPredicate(validate) {
  return function predicate(x) {
    val result;
    validate(x, function onSuccess() {
      result = true;
    }, function onError() {
      result = false;
    });
    return result;
  };
}

Because it is so simple to transform one representation of the same concept into the other one, we ought to start out with the more simple one. If for some reason needed, the callback based solution is just a function call away. But quite likely, you ain't gonna need it (YAGNI).


问:
Did Java avoid multiple inheritance here?
I learnt that Java did not allow multiple inheritance using abstract classes for simplicity.

In java, after a good design of class hierarchy, SubType would not get into trouble of same method prototypes or same name variable, coming from both interface and abstract class as parent types, Because abstract class and interface are discovered(but not designed) based on implementation classes. I guess this is what it meant.

Here is the problem Java code, that still has multiple inheritance issue, using interface keyword:

```<code>abstract class SuperType1 {
    protected int item;
}

interface SuperType2{
    final float item=2.0;
}
public class SubType extends SuperType1 implements SuperType2{
    public static void main(String[] args){
        SubType s = new SubType();
        //s.item = 2; //Compiler knows that 'item' is only mutable in 'class SuperType1', this code should not fail.
    }
}
</code>```

So,

As per above program, What exactly does it mean to say that, Java omits multiple inheritance?

答:
The item field in SuperType2 class is static so there is no inheritance; there is just an ambiguous reference . All fields from interfaces are static and public by default. Java would have been better designed if static fields and methods can only be accessed through class name and not through a reference; but this is not a major flaw.

Since version 8, Java has the diamond problem and multiple inheritance because interfaces can have default methods. In the case of multiple inheritance the code won't compile unless you overwrite the problematic method and specify how it should behave (you can also choose the implementation from a supperclass/interface by using the syntax SuperType.super.method() in the subclass implementation).


问:
Is it normal for a programmer to not have 100% clarity over their own code at times?
I'm not an expert programmer so this may be why, but I've come to notice that whenever I create complex code (like a Chess game I recently made), I am able to write the correct code to get the program working, although I find that later on- or even a few seconds after!- I often have to pause, and think, how does this work?

Not only that, but I also tend to not think about the code, and instead I just type away.  For example, in my Chess game, I decided to use a  five dimensional array for processing moves, and I found I could do this without too much conscious thinking. However, when I stopped and read over it, I found it challenging to get my head round the whole five-dimensional concept, and it did take me a few a minutes to fully understand what I did, and how the code itself works.

Is it normal for programmers when writing complex code to not understand what they are doing half of the time?

答:
I think this is something that'll go away with experience.

If you're writing complex systems, you need to have the ability to write clean, maintainable code that both you in the future, and someone else in the future, can understand. So, in essence, the thing you're doing now isn't scalable.

You'll have lots of moments where you're looking at some code you wrote 6 months ago and thinking "what the heck is going on here?", but if it happens a day after you wrote the code, you gotta think 'clean code' more.

Source: never used a 5 dimensional array :)


答:
No, it is not normal 1. At least, it's not normal for good programmers. It probably is normal for someone learning to program.

Writing software isn't just slapping lines of code together until it works. You need to consciously work on making the code easy to understand. A programmer I respect highly once told me "code is read way more times than it is written". While that should be completely obvious, it was a fact that I hadn't been aware of until he told me. Much of your code is written only once, maybe rewritten once or twice more, but you'll end up reading the code often over the lifetime of the software.

If you're finding the code hard to understand minutes after writing it, that's a signal that your code is too complex. Stop adding code, and figure out a better way. For example, a five dimensional array is almost never a good idea. Even really, really smart programmers have a hard time understanding such a complex data structure.

The same programmer who told me about code readability also said "show me your data structures and I can tell you how your code works". Meaning, good code starts with clean, understandable data structures. If you design your data right, the code is almost a secondary concern. Admittedly, this statement is a bit of hyperbole because software is obviously more than just data, but it starts with data. So, work on creating clean, easy to grasp data structures and the code will be considerably easier to understand.

1 Certainly there is code out there that is very complex and hard to understand even by the smartest of programmers. Some problems are inherently complex. However, I would venture to say that the vast majority of code written by the vast majority of programmers is not that type of code.

Title: Is it normal for a programmer to not have 100% clarity over their own code at times?

Body:
I'm not an expert programmer so this may be why, but I've come to notice that whenever I create complex code (like a Chess game I recently made), I am able to write the correct code to get the program working, although I find that later on- or even a few seconds after!- I often have to pause, and think, how does this work?

Not only that, but I also tend to not think about the code, and instead I just type away.  For example, in my Chess game, I decided to use a  five dimensional array for processing moves, and I found I could do this without too much conscious thinking. However, when I stopped and read over it, I found it challenging to get my head round the whole five-dimensional concept, and it did take me a few a minutes to fully understand what I did, and how the code itself works.

Is it normal for programmers when writing complex code to not understand what they are doing half of the time?


问:
How do you go about training a replacement?
I recently asked about leaving a position and got a lot of great answers. One of the common threads was that being around to train the new person would be expected and could go a long way.

Now considering that (I think) most people don't stay at a company for a long time after they've given notice, and it will take time for the company to interview/hire one - that leaves for a short amount of time to get someone up to speed.

I've also never trained anyone before. I did a bunch of tutoring in University and College, but teaching a language/technology is far different from training someone to replace you on your job.

So the question is: how do you go about training someone to replace you in a, potentially, short amount of time?

答:
Simply speaking it is impossible to fully train a new person. The knowledge of 2-3 years can not be passed to new person in 1-2 weeks. It is the responsibility of the new person to take interest and learn by himself most of the things.

According to me you should distribute the time like this :-

Sharing the documents and explaining them - 30%

This will include explaining the high level, low level designs and classes etc.

Sharing the code and explaining it - 70%

This means going through the important part of the code.

In between you will have to give time to the new person, to learn the things and come up with the doubts. Your main aim should be to make the person independent, that he/she should understand what part of the code does what. You can not explain each and everything, and even if you explain it won't be much useful. The new person will have a limited capacity to understand the new system. So don't bombard with lot of things. Just explain important things.


答:
I wouldn't call it normal, but it can definitely happen. If it happens to you shortly after you wrote the piece of code in question, I guess that either your code is needlessly complex and should be simplified, or you're just easily distracted. :)

But if you put your code away, concentrate on other projects, and return to it after weeks, months or even years, it's not much of a surprise that you'll have to figure it all out again.

But there's something you can do about this. From what you say, it seems that you don't think enough about your code as you are writing it, and thus you're making it difficult for your future self to understand what's going on. Use that knowledge to your advantage: This is the best motivation for producing well-structured, well-documented, understandable code there is. You know from first-hand experience what happens when you don't take care of the quality of your code. Knowing that should make you a better programmer in the long run. When you collaborate on software projects, your colleagues will thank you for producing understandable code. And the defect rate of your code will improve as well.


问:
Software licensing of free abandonware
I recently found the game that was my first encounter with a computer, a DOS game running in text mode. It was released in 1984 and is available on abandonware sites, but I've started to wonder if I may make a modern version of it (hopefully being able to release it as open source).

In the game, there's a copyright notice, and a message that it's a "free copy" which may be copied and given away. All I've got is the binary file, i.e. no source code.

Am I allowed to disassemble the program to study it?

Does the copyright apply to the code (implementation), the behavior, or both?

Does a clone need to be different or can I make a virtually exact duplicate as long as I write my own code?

Assuming that I'm allowed to create a clone: Can't, may or must I include the original copyright owners in the new copyright notice?

Finally, may I publish the code under a permissive license, or would that be a bad idea given that the original game was closed source?

答:
Looks like you're not the only one who's ever had this problem. This may be helpful:

... You can copy all of gameplay without any issues at all. That is
  not copyrightable or enforceable. The things that matter are assets -
  art, sound, music, video, etc. For example if you take ZX game and
  clone it with your own assets you will be perfectly fine doing that.
  But if you take some asset and use it in different kind of game all
  together, it could be enforceable. There are loads of examples of this
  in the industry, for example first Warcraft basically copied Dune 2
  gameplay mechanics and the genre was totally new at the time. For a
  more recent example - check out Gameloft company, the developer for
  iphone. What they do is copy successful game ideas as close as
  possible to the original but without using any art assets from
  originals. That is their successful business model. They copied games
  like Halo, Starcraft, World of warcraft and so on with huge success in
  their field. It is even funny that if you check their wow clone you
  may see that animations of orcs and their looks are very close to the
  original.

TL;DR version: As long as you copy gameplay and don't copy any assets
  (art, music, animation) you are 100% fine.

Title: Software licensing of free abandonware


答:
There are two kinds of this:
1.) confusion
2.) blissful ignorance

The first one is bad and may disappear with time and experience.

The second is a good one if projects become larger: If you have to remember every implementation detail just to be able to work with your code, there's something wrong with it (see "information hiding").

Every developer is going to forget how code was working, so he writes it in a way that another new developer would understand and be able to maintain it without breaking other parts of the programm which is unknown to him as well.

So "not knowing" is actually a constant in software development - it's just how or whether you manage it.


问:
Batching immutable object changes?
With immutable models, what would be the best way to batch several changes?

For example, let's have a Book that is immutable. I need to change both title and year. I could change one by one, but that would just create one additional object that is not going to be used. Is there any better way for this?

I can imagine only something with constructor:

```<code>new Book(oldBook, newTitle, newYear);
</code>```

or to have external tool for cloning books, that we can use.

答:
Here's a twist on Matt's answer, using the builder pattern combined with Java 8's new functional capabilities:

Book.java

```<code>import java.util.*;
import java.util.function.Consumer;

public class Book
{
    private String title;
    private List<String> authors;
    private int year;

    public Book(String title, List<String> authors, int year) {
         this.title = title;
         this.authors = new ArrayList<>(authors);
         this.year = year;
    }

    /*
     * Start with the current Book, create a BookBuilder with all the same properties, then send that through a functional lambda for changing what needs changed.
     */
    public Book cloneWith(Consumer<BookBuilder> bookRebuilder) {
        BookBuilder bookBuilder = new BookBuilder(getTitle(), getAuthors(), getYear());
        bookRebuilder.accept(bookBuilder);
        return new Book(bookBuilder.getTitle(), bookBuilder.getAuthors(), bookBuilder.getYear());
    }

    public String getTitle() {
        return title;
    }

    public int getYear() {
        return year;
    }

    public List<String> getAuthors() {
        return new ArrayList<String>(authors);
    }

    public String toString() {
        StringBuilder str = new StringBuilder();

        str.append(title);

        str.append(", by ");
        for(String author : authors) {
            str.append(author);
            str.append(", ");
        }

        str.append("published ");
        str.append(year);

        return str.toString();
    }
}
</code>```

BookBuilder.java (this could just as easily be a static internal class)

```<code>import java.util.*;

public class BookBuilder
{
    private String title;
    private List<String> authors;
    private int year;

    public BookBuilder(String title, List<String> authors, int year) {
        this.title = title;
        this.authors = authors;
        this.year = year;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<String> getAuthors() {
        return authors;
    }

    public void setAuthors(List<String> authors) {
        this.authors = authors;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }
}
</code>```

Main.java

```<code>import java.util.*;

public class Main
{
    public static void main(String[] args) {
        Book book1 = new Book("Pride and Prejudice", Arrays.asList("Jane Austen"), 1813);

        Book book2 = book1.cloneWith((baseBook)-> {
            baseBook.setTitle("Pride and Prejudice and Zombies");
            baseBook.setYear(2009);
            List<String> authors = baseBook.getAuthors();
            authors.add("Seth Grahame-Smith");
            baseBook.setAuthors(authors);
        });

        System.out.println(book1.toString());
        System.out.println(book2.toString());
    }
}
</code>```

One big difference is that, instead of having to use a chain of fluent calls that might be hard to break, we can interject other logic within the lambda closure. Here BookBuilder could also be made fluent so it can be just as terse.

Title: Batching immutable object changes?

Body:
Here's a twist on Matt's answer, using the builder pattern combined with Java 8's new functional capabilities:

Book.java

import java.util.*;
import java.util.function.Consumer;

public class Book
{
    private String title;
    private List<String> authors;
    private int year;

    public Book(String title, List<String> authors, int year) {
         this.title = title;
         this.authors = new ArrayList<>(authors);
         this.year = year;
    }

    /*
     * Start with the current Book, create a BookBuilder with all the same properties, then send that through a functional lambda for changing what needs changed.
     */
    public Book cloneWith(Consumer<BookBuilder> bookRebuilder) {
        BookBuilder bookBuilder = new BookBuilder(getTitle(), getAuthors(), getYear());
        bookRebuilder.accept(bookBuilder);
        return new Book(bookBuilder.getTitle(), bookBuilder.getAuthors(), bookBuilder.getYear());
    }

    public String getTitle() {
        return title;
    }

    public int getYear() {
        return year;
    }

    public List<String> getAuthors() {
        return new ArrayList<String>(authors);
    }

    public String toString() {
        StringBuilder str = new StringBuilder();

        str.append(title);

        str.append(", by ");
        for(String author : authors) {
            str.append(author);
            str.append(", ");
        }

        str.append("published ");
        str.append(year);

        return str.toString();
    }
}

BookBuilder.java (this could just as easily be a static internal class)

import java.util.*;

public class BookBuilder
{
    private String title;
    private List<String> authors;
    private int year;

    public BookBuilder(String title, List<String> authors, int year) {
        this.title = title;
        this.authors = authors;
        this.year = year;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<String> getAuthors() {
        return authors;
    }

    public void setAuthors(List<String> authors) {
        this.authors = authors;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }
}

Main.java

import java.util.*;

public class Main
{
    public static void main(String[] args) {
        Book book1 = new Book("Pride and Prejudice", Arrays.asList("Jane Austen"), 1813);

        Book book2 = book1.cloneWith((baseBook)-> {
            baseBook.setTitle("Pride and Prejudice and Zombies");
            baseBook.setYear(2009);
            List<String> authors = baseBook.getAuthors();
            authors.add("Seth Grahame-Smith");
            baseBook.setAuthors(authors);
        });

        System.out.println(book1.toString());
        System.out.println(book2.toString());
    }
}

One big difference is that, instead of having to use a chain of fluent calls that might be hard to break, we can interject other logic within the lambda closure. Here BookBuilder could also be made fluent so it can be just as terse.


答:
"Normal" is very subjective, so I say: it is very common, but should be avoided.

One of the features of "the good code" (I heard such thing exists) is clarity: it should be as clear as underlying problems allows it to be. If problem is complex, the code would be complex as well, but that's inherent complexity, as opposed to accidental complexity (I first heard of this distinction in Rich Hickey's talk) introduced by mis- or not using the right tools, patterns, techniques and practices.

There are cases when lack of clarity is acceptable even when problem is not very complex, e.g. if you write a promo-site which you know is going to last as long as the marketing campaign goes. That's a throw-away code which must not be maintainable. For other (and most of) cases, it is not acceptable, because maintaining such code will cost a lot. Yet, it is common.

Related:

When Understanding means Rewriting - article about the problem of understanding the code.

Effective ML - a long talk about, amongst ML/OCaml, how to write the code for "readers" (i.e. maintainers): "Favor readers over writers." I recommend watching that no matter which language you use.


问:
Why do people disable JavaScript?
I asked a question yesterday Should I Bother to Develop For JavaScript Disabled?. I think the consencus is: Yes, I should develop for JavaScript Disabled. Now I just want to understand why users disable JS. It seems many developers (I guess people who answered the questions are developers) disable JS. Why is that. Why do users disable JS? For security? Speed? or what?</p>

答:
My main reason is that it suppresses the most annoying ads.  I'd rather not use AdBlock Plus, since that can affect revenue for the sites I visit (and I've used a site or two where the terms of service said I was not to disable ads).  NoScript limits the potential obnoxiousness of ads, and I'm willing to live with the rest of them.

There's also the security consideration, and that's largely related to ads also, since any site that sells ads has to be considered potentially hostile.

Moreover, I don't necessarily know a site is dodgy before I visit it.  Some people enjoy sending out links to sites, and aren't necessarily honest.

Title: Why do people disable JavaScript?


答:
I'd say it's more common than people care to admit.  Even Brian Kernighan alluded to it:

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

When we drive to the store, we make a sequence of detailed adjustments to the positions of the pedals and the steering wheel.  This is very easy in the moment.  Now, imagine if you recorded those adjustments onto paper and gave them to a friend who needed directions to the store.

Similarly, we like to write code at one level of abstraction, but we like to read it in multiple higher layers of abstraction.  Our favored way to write and read code is therefore in conflict.  That means making code easy to read is usually a separate, conscious step, with a different set of skills.

What makes a good programmer is when they have difficulty reading what they just wrote, they create an abstraction at that point.  A better programmer does that multiple times, getting pickier each time.  Eventually, experienced programmers start off further along the process, but they often can still see room for improvement after reading what they just wrote.


答:
I don't think it is normal, but for very complex programs, like the chess program you mention, I think it certainly possible.

Many years ago, when I was just out of grad school (so I was still relatively inexperienced writing large programs), I wrote my first real compiler.  The parsing was straightforward, but then I needed to target it for four different microprocessor instruction sets.  I intended to write the compiler in its own language, so I first used just the features of the language I absolutely needed, wrote the first code generator in assembly language, and tested that it generated correct code for the subset of the language.  I was then able to use the compiler to compile itself from then on, and add the remaining features and also use them in the compiler itself

I then wrote the backend code generators for each microprocessor, and tested that they all generated correct code, but while correct it was not very optimal.  So I then proceeded to write optimizers for each code generator.

When I was testing the output of the code generators after adding all the optimization, I was frequently surprised at the code the compiler generated.  It was often not the way I would have written the code by hand, but it was correct and pretty concise.

When it was not obvious to me how the code generator produced some of the code that it did, I tried to follow through the logic by hand but there were times I just gave up.  If I had added a lot of trace output I would have been able to follow it, but I didn't bother since the generated code was satisfactory and I needed to get on to other projects.


答:
Note: This is more of a law question than a programming question. Consult a lawyer of your country if you need to be 100% certain.

On your questions:

Am I allowed to disassemble the program to study it?

No. You are not allowed to disassemble or reverse engineer for that purpose.

Does the copyright apply to the code (implementation), the behavior, or both?

The copyright only applies to the implementation. However, depending on the lawyers, judges and country, sometimes suing on the behavior can be successful. For example, Nintendo successfully sued the makers of The Great Giana Sisters over copying from Super Mario Brothers despite that (to my knowledge) no copyrightable assets were copied.

Does a clone need to be different or can I make a virtually exact duplicate as long as I write my own code?

Exact duplicate will not be possible, if you create your own assets there will inevitably be differences.

Assuming that I'm allowed to create a clone: Can't, may or must I include the original copyright owners in the new copyright notice?

Attribution is not required if your code does not violate the original copyright owners' copyrights.

Finally, may I publish the code under a permissive license, or would that be a bad idea given that the original game was closed source?

Given that you do not violate the original copyright owners' copyrights, the new stuff is yours, and you can do with it what you like. It's yours, you decide on the license terms.

Note that some game mechanics, although they look like behavior, might be protected by copyright law. If they are very original ideas, or if the game mechanics are easily encoded as a lot of data, they could be copyrighted.

Disclaimer: I am not a lawyer, if you want to be sure, consult a lawyer.

Title: Software licensing of free abandonware

Body:
I recently found the game that was my first encounter with a computer, a DOS game running in text mode. It was released in 1984 and is available on abandonware sites, but I've started to wonder if I may make a modern version of it (hopefully being able to release it as open source).

In the game, there's a copyright notice, and a message that it's a "free copy" which may be copied and given away. All I've got is the binary file, i.e. no source code.

Am I allowed to disassemble the program to study it?

Does the copyright apply to the code (implementation), the behavior, or both?

Does a clone need to be different or can I make a virtually exact duplicate as long as I write my own code?

Assuming that I'm allowed to create a clone: Can't, may or must I include the original copyright owners in the new copyright notice?

Finally, may I publish the code under a permissive license, or would that be a bad idea given that the original game was closed source?


问:
What makes for a bad case for quick sort?
I am learning about quicksort and want to illustrate different arrays that quicksort would have a hard time on. The quicksort I have in mind does not have an initial random shuffling, does 2 partition, and does not compute the median.

I thought up of three examples so far:

```<code>[1,2,3,4,5,6,7,8,9,10] - when the array is sorted
[10,9,8,7,6,5,4,3,2,1] - when the array is reversed
[1,1,1,1,1,1,1,1,1,1] - when the array is the same values
[1,1,1,2,2,2,3,3,3,3] - when there are few and unique keys
</code>```

For instance, I'm not too sure about this one:

```<code>[1,3,5,7,9,10,8,6,4,2]
</code>```

So what makes for an array that quicksort has difficulty with compared to one where it is (nearly) ideal?

答:
An algorithm escapes from most bad cases using a randomized pivot,
excluding continuous elements equals to a pivot from partitioning,
and asymmetric search.
It searches forward an element greater or equals to a pivot,
and searches backward an element less than a pivot.

I thank MichaelT, Asymmetric search is devised to resolve [2,1,2,1,2,1,2,1].

The following result is generated by my function qsort_random(). N = 100,000

```<code>usec    call   compare   copy    pattern
80132   62946  1971278   877143  random
47326   57578  1606067   215155  sorted : 0,1,2,3,...,n-1
49927   63578  1628883   338715  sorted in reverse : n-1,n-2,...,2,1,0
55619   63781  1596934   377330  nearly reverse : n-2,n-1,n-4,n-3,...,2,3,0,1
54714   66667  1611454   290392  median-3-killer : n-1,0,1,2,...,n-2
1491    1      99999     4       all values the same : n,n,n,...
1577    1      99999     4       first is higher : n,1,1,1,...
2778    2      156159    10      last is lower : n,n,n,...,n,1
2994    3      199996    100009  a few data : n,...,n,1,...,1
3196    3      199996    50012   zigzag : n,1,n,1,...,n,1
917796  56284  67721985  673356  valley(sawtooth?) : n-1,n-3,...,0,...,n-4,n-2
</code>```

Most cases are faster than a random pattern.
Valley pattern is a bad case for most pivot selection.

```<code>qsort(3)       usec = 14523   call = 0      compare = 884463    copy = 0
qsort_head()   usec = 138609  call = 99999  compare = 8120991   copy = 1214397
qsort_middle() usec = 664325  call = 99999  compare = 52928111  copy = 1036047
qsort_trad()   usec = 118122  call = 99999  compare = 6476025   copy = 1337523
qsort_random() usec = 295699  call = 58806  compare = 19439952  copy = 732962
qsort_log2()   usec = 66411   call = 63987  compare = 1597455   copy = 944821
</code>```

qsort_log2() escapes from bad case by selecting a pivot in log2(N) elements.

qsort(3) use GNU library which is a merge sort of index sorting.

qsort_trad() select a pivot in first, middle and last elements.

qsort_random() and qsort_log2() don't use swapping.

Source C programs and scripts are posted in github.

Body:
An algorithm escapes from most bad cases using a randomized pivot,
excluding continuous elements equals to a pivot from partitioning,
and asymmetric search.
It searches forward an element greater or equals to a pivot,
and searches backward an element less than a pivot.

I thank MichaelT, Asymmetric search is devised to resolve [2,1,2,1,2,1,2,1].

The following result is generated by my function qsort_random(). N = 100,000

usec    call   compare   copy    pattern
80132   62946  1971278   877143  random
47326   57578  1606067   215155  sorted : 0,1,2,3,...,n-1
49927   63578  1628883   338715  sorted in reverse : n-1,n-2,...,2,1,0
55619   63781  1596934   377330  nearly reverse : n-2,n-1,n-4,n-3,...,2,3,0,1
54714   66667  1611454   290392  median-3-killer : n-1,0,1,2,...,n-2
1491    1      99999     4       all values the same : n,n,n,...
1577    1      99999     4       first is higher : n,1,1,1,...
2778    2      156159    10      last is lower : n,n,n,...,n,1
2994    3      199996    100009  a few data : n,...,n,1,...,1
3196    3      199996    50012   zigzag : n,1,n,1,...,n,1
917796  56284  67721985  673356  valley(sawtooth?) : n-1,n-3,...,0,...,n-4,n-2

Most cases are faster than a random pattern.
Valley pattern is a bad case for most pivot selection.

qsort(3)       usec = 14523   call = 0      compare = 884463    copy = 0
qsort_head()   usec = 138609  call = 99999  compare = 8120991   copy = 1214397
qsort_middle() usec = 664325  call = 99999  compare = 52928111  copy = 1036047
qsort_trad()   usec = 118122  call = 99999  compare = 6476025   copy = 1337523
qsort_random() usec = 295699  call = 58806  compare = 19439952  copy = 732962
qsort_log2()   usec = 66411   call = 63987  compare = 1597455   copy = 944821

qsort_log2() escapes from bad case by selecting a pivot in log2(N) elements.

qsort(3) use GNU library which is a merge sort of index sorting.

qsort_trad() select a pivot in first, middle and last elements.

qsort_random() and qsort_log2() don't use swapping.

Source C programs and scripts are posted in github.


问:
Who is responsible to challenge a product owner?
I am relatively new to Scrum and I am not clear on the boundaries of a product owner.

The product owner that I am currently working with seems to behave more like a manager than someone who gives requirements to developers. When talking to me or other members of the team without the team lead present, he behaves differently e.g. does not allow us to question any requests or the value of what is being asked. When we question about what is the need or urgency of something while he can not really support his case, it is evident that he is upset mainly because I think he considers that developers are “lower” rank than he is.

While I could take it up with my team lead, I would prefer to understand if that is how product owners normally behave since I don't have experience in Agile.

Is the team lead the only one responsible to “challenge” a product owner in Scrum?

答:
In Scrum there is no TL as official role, so let me first answer the question from a Scrum perspective. Everyone in the team can "challenge" a PO in order to get more information, but it is the PO who is responsible for deciding "what" needs to be done. It's important that the team trusts the PO's decisions about "what" needs to be done, and the PO trusts the team about "how" it is done. If there are conflicts, the Scrum Master comes into picture. He's the "defender of the process", and the process is defined in a way that in most cases conflicts can be turned into discussions based on the agreed process and facts, so the Scrum Master would act as a kind of moderator in such a case.

But Scrum does not say that roles that it does not define have no authority whatsoever. If you have a TL (Team Lead), you can ask your Team Lead for help as well. Which way is best depends on your situation and the actual role of the Team Lead. Usually, I'd first try myself, then via an expert developer in the team, then via the Scrum Master, then via the Team Lead.

It is not just your right, but your duty as a Scrum Dev Team member to ask for details and more information about the requirements / user stories, as well as about the value. The Product Backlog is to be sorted by Business Value per User Story, and if there is something unclear about this, it is not just your right, it is your duty to ask questions about it.


问:
What are the advantages of using async JavaScript modules (like AMD) for traditional sites?
This is specific to JS in the browser for a traditional multi-page site (i.e. not a single-page app).

For single-page apps, the advantages are pretty clear: the main view page is going to be long-lived, and it will load any number of sub-views which may all have different JS dependencies. Loading all your JS up front is not ideal for something of non-trivial size, so having explicit, structured dependency declarations and using an async script loader seems like the way to go.

However for a more traditional, multi-page design, where each page is a full, separate HTML page, I'm not seeing the benefit. In this design all your JS dependencies are known at page load. So ideally you'd just put those all together into a single script on the server side and download it in one go - loading separate modules with separate requests would be bad for performance.

So when you guarantee that all needed JS modules are there on page load, I don't see the need for something like AMD. You can use the module pattern to create modules - you can use simple objects to create namespaces. Is there something that I'm missing?

答:
The difference you make between single-page applications and multi-page sites may not be particularly relevant today. Most web apps are between those two: they have multiple pages, a common JavaScript code which is used on every or nearly every page, and some code used on specific pages only.

This makes your suggestion of serving a single minified JavaScript file per page less practical. You'll end up with large files, and different files for every page, resulting in poor performance and increased bandwidth usage.

From here, there are three generic solutions:

Just throwing all JavaScript into one big minified file which is called from every page of the web app.

This works well in most cases, but would become problematic if there is too much JavaScript or in some specific situations, such as a case where the home page doesn't contain a lot of interactivity and is expected to be extremely fast.

Having one big minified file of common code called on every page and dedicated code on specific pages.

This is an improvement when performance becomes an issue, but increases maintenance complexity. If the architecture is poor and/or inexperienced programmers are working on JavaScript code, this may quickly result in a mess.

Using require.js to load JavaScript on-demand. Here, all the complexity is handled by require.js, which means that developers can achieve performance similar to the second solution while focusing on the code rather than on the organization.

So to answer your question, using something like AMD simply allows to mitigate some of the complexity from developers while keeping performance footprint low.


问:
How to break up a programming project into tasks for other developers?
I have recently joined a development project and was suddenly given the job of lead developer. My primary responsibility is to break up the programming part of the project into tasks, give these tasks to the other developers, and then make sure that the pieces work together.

The problem though is I haven't a clue how to do this. I've spent my weekend with a pencil and paper trying to figure it out but I keep coming up with a list of tasks to be worked on sequentially instead of in parallel. I've thought of maybe splitting it up into features but then you end up with tasks that require editing the same files, which could require an entire task to be completely rewritten because of how early in development we are. I could have some developers wait until the program is a bit more complete and easier to create tasks for, but then I would have people sitting on their hands for who knows how many weeks.

I had a conversation with my boss about my qualifications to do this and I wasn't given a choice in the matter.  I have no idea what I'm doing, so any tips and nudges in the right direction would be greatly appreciated.

答:
What it comes down to is that you have to break your application down into functional modules and then introduce contracts (interfaces and data contracts) between the different modules. Each module can then be handed out to a different developer. When you put everything back together the contracts will ensure that these modules communicate correctly with one another.

Make sure you enforce TDD on the developers, in order to guarantee that the modules all work individually.

To give you an example of what I mean:

Let's say you want one of your developers to build a SQL logger.

You define an interface and ask one of your developers (or create a story if you're using Agile) that you would like a SQL specific logger according to the following specification:

interface ILogger
{
    void Log(string message, int level);
}
```

<p>What I then expect back from a developer is the following:</p>

<ol>
<li><p>The SQL specific implementation for logger</p>

<pre class="lang-cs prettyprint-override"><code>class SqlLogger : ILogger
{
    private readonly SqlLogRepository _logRepository;

    public SqlLogger(SqlLogRepository _logRepository)
    {
        this._logRepository = _logRepository;
    }

    public void Log(string message, int level)
    {
        _logRepository.CreateLog(message,level);
    }
}
</code>```

Any dependant code, such as an implementation for SqlLogRepository

Unit or mock tests depending of what was asked for. A mock test in the case above (where we have other external dependencies), or if it's e.g. a simple utility function such as String.ReverseCharacters(string input), then I would simply like to see unit tests that test a few different scenarios.

This means that:

You and your team can now continue development using this interface. e.g.

class SomeModuleThatUsesLogging
{
    private readonly ILogger logger;

    public SomeModuleThatUsesLogging(ILogger logger)
    {
        this.logger = logger;
    }

    public void DeleteFiles()
    {
        logger.Log("user deleted files",1);
    }
}
```

<p>and if you need to run your code before the <code>SqlLogger</code> is in place, you could simple create a <code>NullLogger</code>:</p>

<pre class="lang-cs prettyprint-override"><code>class NullLogger : ILogger
{
    public void Log(string message, int level)
    {
    }
}
</code>```

And this is how you could test it in the meantime (I suggest looking at an ICO for dependency injection)

void Run()
{
    var someModuleThatUsesLogging = new SomeModuleThatUsesLogging(new NullLogger());
    someModuleThatUsesLogging.DeleteFiles();
}
```

Summary

I have no idea of the size of your project but this could be quite a daunting task and if you have never done development lead before, I would suggest that you take this task very serious and spend the next few weeks reading up as much as you can on software design and archtecture. And be very transparent about your work (software quality etc) otherwise you will quickly find yourself in a deep mess that you don't know how to get out of.

I also highly suggest that you read up on design and the object oriented paradigm. You will rely heavily on OOP for this project.

Body:
What it comes down to is that you have to break your application down into functional modules and then introduce contracts (interfaces and data contracts) between the different modules. Each module can then be handed out to a different developer. When you put everything back together the contracts will ensure that these modules communicate correctly with one another.

Make sure you enforce TDD on the developers, in order to guarantee that the modules all work individually.

To give you an example of what I mean:

Let's say you want one of your developers to build a SQL logger.

You define an interface and ask one of your developers (or create a story if you're using Agile) that you would like a SQL specific logger according to the following specification:

interface ILogger
{
    void Log(string message, int level);
}

What I then expect back from a developer is the following:

The SQL specific implementation for logger

class SqlLogger : ILogger
{
    private readonly SqlLogRepository _logRepository;

    public SqlLogger(SqlLogRepository _logRepository)
    {
        this._logRepository = _logRepository;
    }

    public void Log(string message, int level)
    {
        _logRepository.CreateLog(message,level);
    }
}

Any dependant code, such as an implementation for SqlLogRepository

Unit or mock tests depending of what was asked for. A mock test in the case above (where we have other external dependencies), or if it's e.g. a simple utility function such as String.ReverseCharacters(string input), then I would simply like to see unit tests that test a few different scenarios.

This means that:

You and your team can now continue development using this interface. e.g.

class SomeModuleThatUsesLogging
{
    private readonly ILogger logger;

    public SomeModuleThatUsesLogging(ILogger logger)
    {
        this.logger = logger;
    }

    public void DeleteFiles()
    {
        logger.Log("user deleted files",1);
    }
}

and if you need to run your code before the SqlLogger is in place, you could simple create a NullLogger:

class NullLogger : ILogger
{
    public void Log(string message, int level)
    {
    }
}

And this is how you could test it in the meantime (I suggest looking at an ICO for dependency injection)

void Run()
{
    var someModuleThatUsesLogging = new SomeModuleThatUsesLogging(new NullLogger());
    someModuleThatUsesLogging.DeleteFiles();
}

Summary

I have no idea of the size of your project but this could be quite a daunting task and if you have never done development lead before, I would suggest that you take this task very serious and spend the next few weeks reading up as much as you can on software design and archtecture. And be very transparent about your work (software quality etc) otherwise you will quickly find yourself in a deep mess that you don't know how to get out of.

I also highly suggest that you read up on design and the object oriented paradigm. You will rely heavily on OOP for this project.


答:
For single-page apps, the advantages are pretty clear ... having explicit, structured dependency declarations and using an async script loader seems like the way to go.

Those aren't the only advantages, though. AMD-style modules don't just remove the need for namespaces, they provide other benefits, like eliminating hard-coded dependencies and facilitating dependency injection for mocking/testing. This question goes into more detail.

However for a more traditional, multi-page design ... you'd just put those all together into a single script on the server side and download it in one go - loading separate modules with separate requests would be bad for performance.

A source tree of AMD-style modules can easily be compiled into a single resource with a tool like RequireJS Optimizer. This gives you the best of both worlds; while developing and testing you can load the modules separately, and get meaningful debugging information without resorting to source maps. You can make changes to a script and test it without rebuilding your project. In production, you can compile the modules into a single resource.

So when you guarantee that all needed JS modules are there on page load, I don't see the need for something like AMD.

How do you guarantee that all needed modules are there on page load? If you use AMD modules, each module knows its own dependencies and you can point a tool like RequireJS Optimizer at a single entrypoint module and be done with it. You could also reuse the same modules in other apps (including single-page apps) without changing anything; the modules can be loaded individually or combined into single resources.

If you go the namespace route, you'll need to track which modules are needed for each page, manage the entire dependency graph for each entrypoint module, and manage the compilation process yourself somehow.

In other words, the script loader is not the only benefit of AMD. The other major benefit is that each module is responsible for its own dependencies (rather than just assuming that some namespaces exist, and leaving it up to the developer to ensure that the required namespaces are set up before the module can do its thing).

Title: What are the advantages of using async JavaScript modules (like AMD) for traditional sites?

Body:
This is specific to JS in the browser for a traditional multi-page site (i.e. not a single-page app).

For single-page apps, the advantages are pretty clear: the main view page is going to be long-lived, and it will load any number of sub-views which may all have different JS dependencies. Loading all your JS up front is not ideal for something of non-trivial size, so having explicit, structured dependency declarations and using an async script loader seems like the way to go.

However for a more traditional, multi-page design, where each page is a full, separate HTML page, I'm not seeing the benefit. In this design all your JS dependencies are known at page load. So ideally you'd just put those all together into a single script on the server side and download it in one go - loading separate modules with separate requests would be bad for performance.

So when you guarantee that all needed JS modules are there on page load, I don't see the need for something like AMD. You can use the module pattern to create modules - you can use simple objects to create namespaces. Is there something that I'm missing?


答:
Editing the same files isn't by itself a problem. It's only a problem if you edit the same function to do two different things.

Basically what I would do is, divide the project into 'features' that are separate. One could be something related to network protocol handling and another one to a configuration file, and yet another to DB handling. Features are big things.

Next, you want to divide those features into tasks (stories).
Those should be simple things, like "when the user clicks a button, the program will load the file", "when the program starts, it will load the configuration file" etc.

Some tasks will have to be completed sequentially ("the program will parse all the fields in the configuration file" will have to come after "the program will load the configuration file"). Others won't (you can work on the DB and network at the same time).

But most likely, you'll do it wrong, and that's where experience comes into place. You'll fail just a tiny bit (or a lot), get the time estimations wrong and your project will take a bit more time than it should have. Next time you'll be better.

I would also suggest reading "Extreme Programming" by Kent Beck. Great book that helped me when I was about to be a project manager.

Title: How to break up a programming project into tasks for other developers?

Body:
I have recently joined a development project and was suddenly given the job of lead developer. My primary responsibility is to break up the programming part of the project into tasks, give these tasks to the other developers, and then make sure that the pieces work together.

The problem though is I haven't a clue how to do this. I've spent my weekend with a pencil and paper trying to figure it out but I keep coming up with a list of tasks to be worked on sequentially instead of in parallel. I've thought of maybe splitting it up into features but then you end up with tasks that require editing the same files, which could require an entire task to be completely rewritten because of how early in development we are. I could have some developers wait until the program is a bit more complete and easier to create tasks for, but then I would have people sitting on their hands for who knows how many weeks.

I had a conversation with my boss about my qualifications to do this and I wasn't given a choice in the matter.  I have no idea what I'm doing, so any tips and nudges in the right direction would be greatly appreciated.


答:
A proper answer to your question fills several books. I'll come up with a bullet list of buzz words which come into my mind about this, Google and books will do the rest for you.

Basics

Don't go alone. Try to involve your team-mates as much as possible.

Travel lightweight.

Democracy, but not too much. Sometimes, it's not about what satisfies the biggest number of people, but what hurts the least number of people.

Cynefin: Understand your domain - chaotic, complex, complicated, or clear? And beware of confusion.

Keep what (needs to be done) and how (it is done) separate.

Learn about Scrum ("what"), XP (Extreme Programming, "how"), Kanban ("how much", Flow), Lean ("what not") and DevOps ("with whom").

Lean is avoiding TIMWOODS, the 8 wastes (Transport, Inventory, Motion, Waiting, Overprocessing, Overproduction, Defects, and Skill), or DOWNTIME (Defects, Overproduction, Waiting, Non-utilized talent, Transportation, Inventory, Motion, Extra processing)

Lean also is about flow: For overall efficiency, flow efficiency is usually more important than individual efficiency.

Learn about Software Craftsmanship, Clean Code and Pragmatic Programming.

Good architecture is about maximizing the number of decisions not taken.

Scrum / XP / Lean / Agile is about maximizing the amount of work not done: YAGNI.

The Primary Value of Software is that you can easily change it. That it does what it should do is important but that's only its Secondary Value.

Prefer an iterative and incremental approach, use time boxes for almost everything, especially meetings, make Parkinson's Law your friend because Hofstadter's Law applies.

Balance team structure with an understanding of Conway's Law and Tuckman's Stages of Team Development.

Programming is a quaternity, it is science, engineering, art and craft all at the same time, and those need to be in balance.

Just because Scrum / XP / XYZ is good for someone (including me) doesn't necessarily mean it's good for you / suits your environment. Don't blindly follow the hype, understand it first.

Inspect and Adapt! (Scrum Mantra)

Avoid Duplication - Once and only Once! (XP Mantra) aka DRY - Don't Repeat Yourself aka SPOT - Single Point of Truth

"What world" work breakdown process

Collect Requirements as User Stories / Job Stories into a Product Backlog.

User (of User Story) similar to Actor (in UML) similar to Persona similar to Role.

Refine User Stories until they meet your team's Definition of Ready based on INVEST (Independent, Negotiable, Valuable, Estimable, Small, Testable). (Scrum Meeting: Backlog Refinement)

Sort the Product Backlog by Business Value.

Don't start work on a Story before it's Ready Ready (ready according to the definition of ready).

Use Planning Poker to estimate the effort of Stories in Story Points. Use Triangulation Comparison to ensure consistency of the estimates.

The value of estimates isn't the number that comes out. It's the shared understanding.

Yesterday's weather is the best estimate, hope the worst.

Split Stories if they are too big.

Improve delivery culture with a Definition of Done.

Don't accept the implementation of a User Story before it's Done Done (done according to the Definition of Done).

Multiple teams on the same code base should agree on and share the same Definition of Done (especially the Coding Standards).

Check your progress with Burndown Charts.

Regularly check with your Stakeholders whether what the team delivers is what's really needed. (Scrum Meeting: Sprint Review)

Story Breakdown

List and Describe Users / Personas / Actors / Roles (Product Owner)

Epic -> Stories (User Story or Job Story) (Product Owner)

Story -> Acceptance Criteria (Product Owner)

Story -> Subtasks (Dev Team)

Acceptance Criteria -> Acceptance Tests (Spec: Product Owner, Impl: Dev Team)

Start with a Walking Skeleton which is a minimalistic End-to-(Half-End).

Create an MVP - Minimum Viable Product.

Expand the MVP using SMURFS - Specifically Marketable, Useful, Releasable Feature Sets.

"How world" realization

Apply the 4 Rules of Simple Design: 1. Passes the tests. 2. Communicates intent. 3. No redundancy. 4. Fewest elements. (And understand why J. B. Rainsberger argues that no redundancy is more important than communicating intent, and why I (Christian Hujer) argue that communicating intent is more important than passing the tests.)

Use OOA/D, UML and CRC Cards, but avoid the big design upfront.

Implement object-oriented, structured and functional at the same time as much as possible, regardless of the programming language.

Use Version Control (preferably distributed).

Start with Acceptance Tests.

Apply TDD, letting the Three Laws of TDD drive you through the Red-Green-Refactor-Cycle in the steps from the TPP (Transformation Priority Premise), with Single-Assert-Rule, 4 A's, GWT (Given When Then) from BDD.

"Unit Tests are tests which run fast." — Michael Feathers

Apply the SOLID and the package principles to manage Coupling and Cohesion.
Example: S in SOLID is SRP = Single Responsibility Principle, significantly reduces the number of edit- resp. merge-conflicts in teams.

Know Law of Demeter / Tell, Don't Ask.

Use Continuous Integration, if applicable even Continuous Delivery (DevOps).

Use Collective Code Ownership based on an agreed common Coding Standard (which should be part of the Definition of Done).

Apply Continuous Design Improvement (fka Continuous Refactoring).

The Source Code is the Design. Still upfront thinking is indispensable, and nobody will object a few good clarifying UML diagrams.

XP doesn't mean no day is architecture day, it means every day is architecture day. It's a focus on architecture, not a defocus, and the focus is in the code.

Keep your Technical Debt low, avoid the five design smells: Fragility, Rigidity, Immobility, Opacity, and Viscosity.

Architecture is about business logic, not about persistence and delivery mechanisms.

Architecture is a team sport (there is no 'I' in Architecture).

Design Patterns, Refactoring and the Transformation Priority Premise.

Project Code is the ATP-Trinity with priorities: 1. Automation Code, 2. Test Code, 3. Production Code.

Regularly check with your team peers whether how the team delivers can be improved. (Scrum Meeting: Sprint Retrospective)

Tests should be FIRST - Fast, Independent, Repeatable, Self-Validating and Timely.

Above list is certainly incomplete, and some parts might even be disputable!

If all this scares you - don't worry, because it should scare you! Succeeding software development projects in teams is not an easy task, and rarely are people properly trained and educated in this art. If this scares you, your intuition is working properly, listen to it. You want to be prepared. Talk to your boss, get some time and training.

See Also

Who writes the technical 'user stories' in scrum

Further reading (online)

Portland Pattern Repository by Ward Cunningham et al

Principles of OOD by Robert "Uncle Bob" C. Martin

Pragmatic Programmer Tips

Further reading (books)

Clean Code by Robert C. Martin

Agile Software Development: Principles, Patterns, and Practices by Robert C. Martin

The Pragmatic Programmer - From Journeyman to Master by Andrew Hunt and David Thomas

Working Effectively with Legacy Code by Michael Feathers

Refactoring - Improving the Design of Existing Code by Martin Fowler

Refactoring to Patterns by Joshua Kerievsky

The Ten Day MBA by Steven Silbiger (sic!)

Domain-Driven Design by Eric Evans

User Stories Applied by Mike Cohn

Object-Oriented Analysis and Design with Applications by Gray Booch et al

Design Patterns by the Gang of Four

Test Driven Development by Kent Beck

Extreme Programming by Kent Beck

[if Java] Effective Java by Joshua Bloch


答:
There are a lot of decent answers here.

I have a couple of takes on this.

One is that if you don't understand why your code seems to work, then a) it probably doesn't (it probably only seems like it works), and b) you either didn't understand the problem domain well enough when you started coding, or didn't break the problem domain down into smaller, simplified units before you started.

My other take on this is that the real key is to use common sense patterns and conventions in your code. That's a far bigger topic than one little post can address. But look for good literature on the subject, including some of the old standbys like the books "Code Complete" and "Writing Solid Code."

Implementation details change. The only real constant is the functional objective of the code. If you ever write more than one function, you're going to forget specific, granular implementation details over time. But you should certainly understand how the pieces work when you construct them, and you should be able to draw a diagram of the whole and understand how the pieces work together.

If you use patterns, and follow common sense conventions, it will be far easier to pick the specific implementation details back up when you look at the code again. Or when somebody who has never seen the code before looks at it for the first time. Also, following those conventions and patterns over the course of time will mean that implementation details will stand out from the conventions and patterns themselves, which is another factor that will make the code easier to comprehend.

Most of the problems that we tackle with software are complex by nature. Software design is an exercise in managing complexity.


问:
Function guaranteed to never return the same value twice
This is a question I was asked at a job interview, and I can't figure out the answer they were looking for, so I'm hoping someone here might have some ideas. The goal is to write a function that is guaranteed to never return the same value twice. Assume that this function will be accessed by multiple machines concurrently.

My idea was to assign each machine a unique id and pass that value into the unique value generator function:

```<code>var i = 0;
function uniq(process_id, machine_id) {
   return (i += 1).toString() + machine_id + "-" + process_id;
}
</code>```

This would avoid the fallout from race conditions since even if two or more processes read the same value for i, each return value is tagged a unique combination of process id and machine id. However, my interviewer didn't like this answer because bringing another machine online involves assigning it an id.

So can anybody think of another way to solve this that doesn't involve configuring each machine to have a unique id? I'd like to have an answer in case this question comes up again. Thanks.

答: If I were asked that question, and they made it clear that it has to be unique across reboots and across different machines, I'd give them a function that calls into the standard mechanism for creating a new GUID, whatever that happens to be in the language being used.</p>


问:
Exceptions in ANSI C
Would it be possible to implement exception mechanism in pure ANSI C similar to the one used in popular OOP languages (with familiar try-catch-finally clauses)?

If yes then how?

I'm especially interested how would anyone jump from function to the catch block bypassing all remaining code in try block?

答:
This is possible but has limitations. An implementation would utilize setjmp() / longjmp(). You can see an example implementation here: http://aceunit.sourceforge.net/doxygen/ExceptionHandling_8h.html
Beware: return within try-blocks would be a bug!

Title: Exceptions in ANSI C


问:
Why is polling accepted in web programming?
I am currently working on a Ruby on Rails project which shows a list of images.

A must-have for this project is that it shows new posts in realtime without the need of refreshing the web page. After searching for a while, I've stumbled upon some JavaScript solutions and services such as PubNub; however, none of the provided solutions made sense at all.

In the JavaScript solution (polling) the following happens:

User 1 views the list of photos.

In the background the JavaScript code is polling an endpoint every second to see if there is a new post.

User 2 adds a new photo.

There is a delay of 50 ms before the new cycle is triggered and fetches the new data.

The new content is loaded in the DOM.

This seems odd when translated to a real world example:

User 1 holds a pile of pictures on his/her desk.

He/she walks to the photographer every second and asks if he has a new one.

The photographer makes a new photo.

This second when he/she walks in, she can take the picture and put it on the pile.

In my opinion the solution should be as following:

User 1 holds a pile of pictures on his/her desk.

The photographer takes a new picture.

The photographer walks to the pile and puts it with the rest.

The PubNub solution is basically the same, however this time there is an intern walking between the parties to share the data.

Needless to say, both solutions are very energy consuming as they are triggered even when there is no data to load.

As far as my knowledge goes there is no (logic) explanation why this way of implementation is used in almost every realtime application.

答:
For some reason, these days, all the younger web developers seem to have forgotten the lessons of the past, and why some things have evolved the way they did.

Bandwidth was an issue

Connection might be intermittent.

Browsers did not have as much computing power

There were other methods of accessing content. The web is is not w3.

In the face of these constraints, you might not have a constant 2 way communication. And if you looked at the OSI model, you'd find most considerations are meant to decouple persistency with the underlying connection.

With that in mind, a polling method of pulling information is a great way to reduce bandwidth and computation on the client side. The rise of push is really for the most part just the client doing constant polling, or web sockets. Personally if i was everyone else out there, i'd appreciate the regularity of polling as a means of traffic analysis, where an out of time GET/POST request would signal a man in the middle situation of some sort.


问:
My class diagram needs to model a relationship with varying quantities
I am trying to design a restaurant ordering system in UML, which should also include the stock system.

One of the classes is a Dish (i.e. a dish on the menu), and another is an Ingredient.

My initial idea was to place an aggregation of Ingredients within Dish, but I've also read that a many to many relationship is more appropriate.

My problem is that in this case, simply having a relationship isn't enough. For instance a Dish could have 30g of Ingredient A, while another Dish could have 20g of Ingredient A.

How can I model this kind of dependency in UML?

答:
Create a Many to Many relationship; call it DishIngredients.

Include Amount and Units fields in DishIngredients; this will let you specify the amount (e.g. 30) and units (e.g. grams) for each Dish/Ingredient combination.


答:
Don't get fancy, just toss a simple (threadsafe) counter behind some communication endpoint (WCF, web service, whatever):

```<code>   long x = long.MinValue;
   public long ID(){
       return Interlocked.Increment(ref x);
   }
</code>```

Yes, it will eventually overflow. Yes, it doesn't handle reboots. Yes, it's not random. Yes, someone could run this on multiple servers.

This is the simplest thing that satisfies practical requirements. Then let them be the ones that follow up with those problems (to make sure they understand the limitations, do they really think you need more than 2^64 ids), so you can then ask about what trade-offs are okay. Does it need to survive reboots? What about hard drive failure? What about nuclear war? Does it need to be random? How random?

Title: Function guaranteed to never return the same value twice

Body:
This is a question I was asked at a job interview, and I can't figure out the answer they were looking for, so I'm hoping someone here might have some ideas. The goal is to write a function that is guaranteed to never return the same value twice. Assume that this function will be accessed by multiple machines concurrently.

My idea was to assign each machine a unique id and pass that value into the unique value generator function:

```<code>var i = 0;
function uniq(process_id, machine_id) {
   return (i += 1).toString() + machine_id + "-" + process_id;
}
</code>```

This would avoid the fallout from race conditions since even if two or more processes read the same value for i, each return value is tagged a unique combination of process id and machine id. However, my interviewer didn't like this answer because bringing another machine online involves assigning it an id.

So can anybody think of another way to solve this that doesn't involve configuring each machine to have a unique id? I'd like to have an answer in case this question comes up again. Thanks.

Body:
Don't get fancy, just toss a simple (threadsafe) counter behind some communication endpoint (WCF, web service, whatever):

   long x = long.MinValue;
   public long ID(){
       return Interlocked.Increment(ref x);
   }

Yes, it will eventually overflow. Yes, it doesn't handle reboots. Yes, it's not random. Yes, someone could run this on multiple servers.

This is the simplest thing that satisfies practical requirements. Then let them be the ones that follow up with those problems (to make sure they understand the limitations, do they really think you need more than 2^64 ids), so you can then ask about what trade-offs are okay. Does it need to survive reboots? What about hard drive failure? What about nuclear war? Does it need to be random? How random?