问:
How can I mock this architecture?
This is not a very general question, so it may not exactly be appropriate here, but I could sure use a suggestion if you have one:

I have an object containing a dictionary keyed off of an enum, something like this:

```<code>namespace Application
{
    public enum Material { H20, CO2, Na }
    public class Container
    {
        private Dictionary<Material, ChemicalComponent> dic;
        public Container(Dictionary<Material, ChemicalComponent> d)
        {
            dic = d;
        }
    }
}
</code>```

I now want to create a MockContainer and a MockMaterial, but I can't figure out how to make it all work together. The following code, for example, does not work (see comment):

```<code>using Application;
namespace UnitTesting
{
    public enum mockMaterial { mock1, mock2, mock3 }
    public class mockContainer : Container
    {
        public mockContainer(Dictionary<mockMaterial, ChemicalComponent> d)
            : base(d) // compiler error: the base constructor "has some invalid arguments"
        {
        }
    }
}
</code>```

Originally I had hoped to extend the Material enum inside the UnitTesting namespace; then I could just use the Container's Dictionary, but with different keys. But of course, that isn't legal in C#. Is there some non-kludgy way to overload or inject a Dictionary with the mock enum keys?

Update: One option is to change the dictionary definition to this:

```<code>private Dictionary<Enum, ChemicalComponent> dic;
</code>```

(i.e., change the key type to Enum throughout the code). This works (i.e., eliminates the compiler error), but this solution sacrifices clarity as well as type-safety. (It is no longer clear what the key is intended to be).

Update #2:
Several people have recommended that I create an interface for Container. But that misses the point. The container itself is not all that complex. But the ChemicalComponents that are stored in it are very complex. I need to mock those in my unit tests, but I don't know how to do that without extending the enum that serves as the key.

答:
You could make Container a generic class with one type parameter, constrained to be an enum.

Your mock couldn't subclass that way, so you would need to make an interface.

Title: How can I mock this architecture?


问:
In an Agile Environment, who is responsible for software architecture
In an agile team, who is responsible for making high-level architecture and design decisions that affect the entire system, not just the work being done in the current sprint?

Maybe product owner, scrum master, the scrum team or someone else?

答:
I feel that the answer to ""who is responsible for making high-level architecture and design decisions?" depends on the size and number of teams.

For one or two teams with 3-7 on each team then the self-organized team can do with lead from the senior members.

For 3 or more teams the increased complexity leads to the need for an architecture team that can see if the various sub-teams are doing work that will interface with the other teams.  In my experience that point is reached when there are approximately 8 teams or at about 50 people.

ContentLicense: CC BY-SA 3.0


问:
Define fields only once
I'm looking for a method to describe fields in a structured way, so I am able to reuse it in various languages and levels of my application.

For instance, if I'm developing an Android application about food items, I might be dealing with fields like Name, Description, Price and Kcal. However, these fields will appear multiple times: In the viewholder of my Android application, in the C++ server which handles the messages, in my SQL database which stores them, etc. Imo, this violates the DRY principle, and if I also want to save the barcode of a food item for example, I need to add it to all these places.

I've been thinking about using XML or TDL, but I'm not sure if those languages are intended for this goal. Preferably, I would have a file like this:

```<code>Fieldname   Type        Lower bound Upper bound May be NULL
-----------------------------------------------------------
Name        string      3           100         No
Price       float       0           *           Yes
...
</code>```

Of course I could create such a thing myself, but would that be a good way to go? Or is there something out there which is used for this purpose (I want to avoid beginners mistakes). Preferably, I would have these definitions been read out at compile-time because the definition won't be altered at runtime anyway.

答:
A few of thoughts:

The problem with fields is that they are a code abstraction rather than a business domain abstraction.

Treating name, price, kcal, etc. as types rather than fields [e.g. using typedef in C++ and wrapper classes for primitives in Java] focuses on what is common and black boxes implementation details such as the differences between the representation of strings in Java and C++ and their immutable/mutable natures respectively.

Aspects of the system which boil down to typechecking such as validation requirements (along the lines of name.length being between 3 and 50) can live on their own layers behind API's.

Implicitly, the direction you're heading is toward a Domain Specific Language. Thinking about types and type-checking is a foundation upon which one might be built.

Title: Define fields only once


问:
memory management of multi-dimensional array
Could you please show me an example how to compute the location of an element in a multi-dimensional array.

It is illustrated in Robert Sebesta's book Concept of Programming Languages that location of an element is given by the formula

```<code>location(a[i,j]) = address_of(a[1,1]) + ((i - 1)*n + (j - 1))*element_size
</code>```

where n is the number of elements per row and a[1,1] is the base address (1-based indexing).

I tried to find the location of [5,5] in a 7×7-matrix, assuming element_size=2. By calculating manually I got the value as 66. But while calculating by using the formula I got the value as 64:

```<code>location(a[5,5]) = 0 + ((4*7) + 4)*2 = 64
</code>```

Is this correct or not? Could you tell me how the difference of two occurred.

答: The formula assumes that the array indices are zero based (the first element is at position 0) and it is perfectly correct. I assume that you made the classical mistake we all did in the beginning by counting from point 1, as an older colleague pointed out to me the first time I did it...</p>


答:
A multidimensional array behaves like paging of n elements. Say you have a set of two numbers a and b. You decide, that your pagesize should be 1. Then you find the first element on the first page and the second element on the second page.

This is equivalent to saying, you have an array of arrays; each subarray containing only one element.
This could also be thought of as a one dimensional array.

To get the nth element on the mth page, you need to now:

1) Where to start counting

2) What the page size is

In order to get the first element (of the given set above ) on the second page, you have to know, where the first element lies. From there you have to step m times the pagesize(here =1) forward. Then you are on page m. Then take the first element. Done.

If you are dealing with adresses of elements or pointers to elements, you should take the size of these into account.

Title: memory management of multi-dimensional array

Body:
Could you please show me an example how to compute the location of an element in a multi-dimensional array.

It is illustrated in Robert Sebesta's book Concept of Programming Languages that location of an element is given by the formula

```<code>location(a[i,j]) = address_of(a[1,1]) + ((i - 1)*n + (j - 1))*element_size
</code>```

where n is the number of elements per row and a[1,1] is the base address (1-based indexing).

I tried to find the location of [5,5] in a 7×7-matrix, assuming element_size=2. By calculating manually I got the value as 66. But while calculating by using the formula I got the value as 64:

```<code>location(a[5,5]) = 0 + ((4*7) + 4)*2 = 64
</code>```

Is this correct or not? Could you tell me how the difference of two occurred.


问:
Finding methods of classes from the use case
I know some nouns in the use case scenario are candidate to be class, for example member, customer, student ....

I can find such entities and some attributes of them, but my problem is that I can't easily find any method for these classes.

Which part of use cases are candidate for methods or functions of classes?

Please give some examples.

For example in a system for hospital, Patient or Doctor are classes, what are the functions for these classes?

答: If the nouns are the classes the verbs are the functions. In your use case the nouns presumably do things? These are the candidates for functions of the classes.</p>


问:
Java Desktop Application Requirement - Is sockets the preferred choice ?
I'm currently working on a requirement for a desktop application - using Java

If for some reason the GUI crashes, it shouldn't affect the background
  process. Once the GUI is restarted - the execution status along
  with the log messages should be given back to GUI.

Desktop application is built for both windows & ubuntu 12.04.

As per my knowledge in Java, this could be achieved using Sockets. Keeping GUI as client, and executing background code in a Server.( But again i'm still trying to understand how the server stays alive if the GUI crashes, - I mean if server is started from the GUI instance @ any point, and if the GUI crashes, the server is dead too, bcz it still belongs to the same JVM instance, right ? )

The question really comes down to - how to start a server(tcp) in a new process from the gui instance. Can someone throw some light on - how to implement this requirement?

答:
Sockets, RMI, Protocol Buffers, Thrift, CORBA, DCOM, ... the number of RPC systems is long and extensive. They all have a similar goal though: provide a system to allow a client process and another server process talk to each other.

Today the possible best practice is to use a standard communication system, one where you can change the client to a different technology and the server will not need any modification. The system used by a lot of people is web services.  Its still another form of remote communication, but if you implement the server using it, you'll be able to write a web-based client very easily, or open your server to other clients using a standard API.

If you need raw speed though, a socket is best, but its low-level. You'll have to make the protocol (ie the messages) you send yourself. I never found that to be a problem TBH, but many people prefer a framework that does that for you - protocol buffers can do this, or you can go even higher level and use something like RMI which will tie you into Java and will make it slightly easier.


问:
A good generic type system
It's commonly accepted that Java generics failed in some important ways. The combination of wildcards and bounds led to some seriously unreadable code.

However, when I look at other languages, I really can't seem to find a generic type system that programmers are happy with.

If we take the following as design goals of a such a type system:

Always produces easy-to-read type declarations

Easy to learn (no need to brush up on covariance, contravariance, etc.)

maximizes the number of compile-time errors

Is there any language that got it right? If I google, the only thing I see is complaints about how the type system sucks in language X. Is this kind of complexity inherent in generic typing? Should we just give up on trying to verify type safety 100% at compile time?

My main question is which is the language that "got it right" the best with respect to these three goals. I realize that that's subjective, but so far I can't even find one language where not all it's programmers agree that the generic type system is a mess.

Addendum: as noted, the combination of subtyping/inheritance and generics is what creates the complexity, so I'm really looking for a language that combines both and avoids the explosion of complexity.

答:
While Generics have been mainstream in the functional programming community for decades, adding generics to object oriented programming languages offers some unique challenges, specifically the interaction of subtyping and generics.

However, even if we focus on object oriented programming languages, and Java in particular, a far better generics system could have been designed:

Generic types should be admissible wherever other types are. In particular, if T is a type parameter, the following expressions should compile without warnings:

```<code>object instanceof T;
T t = (T) object;
T[] array = new T[1];
</code>```

Yes, this requires generics to be reified, just like every other type in the language.

Covariance and contravariance of a generic type should be specified in (or inferred from) its declaration, rather than every time the generic type is used, so we can write

```<code>Future<Provider<Integer>> s;
Future<Provider<Number>> o = s;
</code>```

rather than

```<code>Future<? extends Provider<Integer>> s;
Future<? extends Provider<? extends Number>> o = s;
</code>```

As generic types can get rather long, we should not need to specify them redundantly. That is, we should be able to write

```<code>Map<String, Map<String, List<LanguageDesigner>>> map;
for (var e : map.values()) {
    for (var list : e.values()) {
        for (var person : list) {
            greet(person);
        }
    }
}
</code>```

rather than

```<code>Map<String, Map<String, List<LanguageDesigner>>> map;
for (Map<String, List<LanguageDesigner>> e : map.values()) {
    for (List<LanguageDesigner> list : e.values()) {
        for (LanguageDesigner person : list) {
            greet(person);
        }
    }
}
</code>```

Any type should be admissible as a type parameter, not just reference types. (If we can have an int[], why can we not have a List<int>)?

All of this is possible in C#.

Title: A good generic type system

Body:
While Generics have been mainstream in the functional programming community for decades, adding generics to object oriented programming languages offers some unique challenges, specifically the interaction of subtyping and generics.

However, even if we focus on object oriented programming languages, and Java in particular, a far better generics system could have been designed:

Generic types should be admissible wherever other types are. In particular, if T is a type parameter, the following expressions should compile without warnings:

object instanceof T;
T t = (T) object;
T[] array = new T[1];

Yes, this requires generics to be reified, just like every other type in the language.

Covariance and contravariance of a generic type should be specified in (or inferred from) its declaration, rather than every time the generic type is used, so we can write

Future<Provider<Integer>> s;
Future<Provider<Number>> o = s;

rather than

Future<? extends Provider<Integer>> s;
Future<? extends Provider<? extends Number>> o = s;

As generic types can get rather long, we should not need to specify them redundantly. That is, we should be able to write

Map<String, Map<String, List<LanguageDesigner>>> map;
for (var e : map.values()) {
    for (var list : e.values()) {
        for (var person : list) {
            greet(person);
        }
    }
}

rather than

Map<String, Map<String, List<LanguageDesigner>>> map;
for (Map<String, List<LanguageDesigner>> e : map.values()) {
    for (List<LanguageDesigner> list : e.values()) {
        for (LanguageDesigner person : list) {
            greet(person);
        }
    }
}

Any type should be admissible as a type parameter, not just reference types. (If we can have an int[], why can we not have a List<int>)?

All of this is possible in C#.


问:
Is there a good name for this pointer template?
I'm looking for a proper name of a class template with the following features:

It's interface would look something like this, where Foo is a placeholder for the name I'm looking for.

```<code>template<typename T>
struct Foo
{
    T* operator->();
    T* operator*();
}
</code>```

So, it imitates a pointer to an object, much like std::unique_ptr<> and std::shared_ptr<> do. Unlike them, having a Foo<T> to an object doesn't imply ownership over this object. Everything Foo<T> does is provide a pointer to this object and, this is the important part, once the object Foo<T> points to is deleted both operators return nullptr instead of the now invalid pointer.

I'm looking for a descriptive name for this class. Maybe it has intersecting semantics with a well defined pattern I am not aware of?

答:
It's a weak pointer.

It's common in GC languages for cached values that are allowed to be deleted and the map that holds it can detect it and recreate it.

C++ has a weak_ptr that works in conjunction with shared_ptr. You can assign a shared_ptr to a weak_ptr and get the shared_ptr from it again later with lock as long as the last shared_ptr hasn't been destroyed yet, after it has then lock returns a shared_ptr that holds a null pointer.


问:
Name for this type of parser, OR why it doesn't exist
Conventional parsers consume their entire input and produce a single parse tree.  I'm looking for one that consumes a continuous stream and produces a parse forest [edit: see discussion in comments regarding why this use of that term may be unconventional].  My gut says that I can't be the first person to need (or think I need) such a parser, but I've searched off and on for months to no avail.

I recognize that I may be ensnared by the XY problem.  My ultimate purpose is to parse a stream of text, ignoring most of it, and produce a stream of parse trees from the sections that are recognized.

So my question is conditional: if a class of parsers with these characteristics exists, what is it called?  And if not, why not?  What is the alternative?  Perhaps I'm missing some way I can make conventional parsers do what I want.

答:
In a nutshell

It seems that the fast solution to your problem is to define a REGEX,
or a FSA (finite state automaton), that recognizes all the possible
beginnings of documents (false positives are allowed, that would not
actually correspond to a document). You can then run it very fast on
your input to identify the next place where a document could start
with few errors. It may cause a few erroneous position for a document start, but they
will be recognized by the parser and abandonned.

So Finite State Automaton may be the parser name you were looking
for. :)

The problem

It is always difficult to understand a practical problem, especially
when the vocabulary may have many interpretation. The word parse
forest was coined (afaik) for Context-Free (CF) parsing of ambiguous
sentences that have several parse-trees. It can be generalized
somewhat to parsing a lattice of sentences, or to other types of
grammar. Hence all the answers about Earley, GLR, Marpa and derivative
parsers (there are many others) that were not relevant in this case.

But that is apparently not what you have in mind. You want to parse a
unique string that is a sequence of unambiguous documents, and get a
parse-tree for each, or some kind of structured representation, since
you do not really say how the syntax of your documents is
defined, where it stand from a formal language point of view. What you have is
an algorithm and tables that will do the parsing job when started at
the beginning of a document. So be it.

The actual problem is that your stream of document contains
considerable garbage that separates the documents. And it seem that
your difficulty is to scan this garbage quickly enough. Your current
technique is to start at the beginning, and try to scan from the first
character, and skip to the restart at the next character whenever it
fails, until you get a whole document scanned. Then you repeat stating
from the first character after the document just scanned.

That is also the solution suggested by @amon in the second part of his
answer.

It may not be a very fast solution (I have no way to test),
because it is unlikely that the code of the parser is optimized to
be very efficiently started on the beginning of a document.  In
normal use it does this only once, so that it is not a hot spot from
an optimization point of view. Hence, your moderate happiness with this solution
is not too surprising.

So what you really need is an algorithm that can quickly find the
beginning of a document that starts with a mass of garbage. And you
are lucky: such algorithms do exist. And I am sure you know it: it is called searching for a REGEX.

The simple solution

What you have to do is to analyze the specification of your documents
to find how these documents start. I cannot exactly tell you how, as I
am not sure how their syntax specification is organized
formally. Possibly they all start with some word from a finite list,
possibly mixed with some punctuation or numbers. That is for you to
check.

What you have to do is to define a finite state automaton (FSA), or
equivalently for most programmers a regular expression (REGEX) that
can recognize the first few characters of a document: the more, the
better, but it need not be very large (as that may take time and
space). This should be relatively easy to do from the specification of
your documents, and can probably be done automatically with a program
that reads the specification of your documents.

Once you have produced your regexp, you can run it on your input
stream to get very quickly to the beginning of your first (or next)
document as follows:

I assume:

- docstart is a regex that matches the beginning of all documents

- search(regex, stream) is a function that searches the stream for
  a substring that matches regex. When it returns, the stream is
  reduced to its suffix substream starting at the beginning of the
  first matching substring, or to the empty stream is no match is
  found.

- parse(stream) attempts to parse a document from the beginning of
  the stream (what is left of it), and returns the parse tree in
  whatever format, or fails. When it returns, the stream is reduced to
  its suffix substream starting at the position immediately following
  the end of the parsed document.  It calls an exception if the parse
  fails.

```<code>forest = empty_forest
search(docstart, stream)
while stream is not empty:
  try:
    forest = forest + parse(stream)
  except
    remove first character from stream
  search(docstart, stream)
</code>```

Note that the removal of first character is necessary so that the next
search will not find again the same match.

Of course, shortening of the stream is an image. It may just be an
index on the stream.

A final note is that your regex does not need to be too accurate, as
long as it recognizes all beginnings. If it recognizes occasionally a
string that cannot be the beginning of a document (false positive),
then the only penalty is the cost of one useless call to the parser.

So that may possibly help simplifying the regex, if useful.

About the possibility of a faster solution

The above solution should work pretty well in most cases. However, if
you have really a lot of garbage and terabytes of file to process,
there might be other algorithms that run faster.

The idea is derived from the Boyer-Moore string search algorithm. This
algorithm can search a stream for a single string extremely fast
because it uses a structural analysis of the string to skip reading
most of the stream, jumping over fragments without even looking at
them. It is the fastest searching algorithm for a single string.

Thr difficulty is that its adaptation to search regex, rather than a
single string, seems very delicate and might not work as well, depending on
the features of the regex you are considering. That might in turn
depend on the syntax of the documents you are parsing. But do not trust me too much on this since I did not have time to do a careful reading of the documents I found.

I am leaving you with one or two pointers I found on the web, including one that is apparently a refereed research paper,
but you
should consider this as more speculative, possibly researchy, to be
considered only if you had strong performance problems. And there is
probably no of the shelf program that will do it.

Body:
In a nutshell

It seems that the fast solution to your problem is to define a REGEX,
or a FSA (finite state automaton), that recognizes all the possible
beginnings of documents (false positives are allowed, that would not
actually correspond to a document). You can then run it very fast on
your input to identify the next place where a document could start
with few errors. It may cause a few erroneous position for a document start, but they
will be recognized by the parser and abandonned.

So Finite State Automaton may be the parser name you were looking
for. :)

The problem

It is always difficult to understand a practical problem, especially
when the vocabulary may have many interpretation. The word parse
forest was coined (afaik) for Context-Free (CF) parsing of ambiguous
sentences that have several parse-trees. It can be generalized
somewhat to parsing a lattice of sentences, or to other types of
grammar. Hence all the answers about Earley, GLR, Marpa and derivative
parsers (there are many others) that were not relevant in this case.

But that is apparently not what you have in mind. You want to parse a
unique string that is a sequence of unambiguous documents, and get a
parse-tree for each, or some kind of structured representation, since
you do not really say how the syntax of your documents is
defined, where it stand from a formal language point of view. What you have is
an algorithm and tables that will do the parsing job when started at
the beginning of a document. So be it.

The actual problem is that your stream of document contains
considerable garbage that separates the documents. And it seem that
your difficulty is to scan this garbage quickly enough. Your current
technique is to start at the beginning, and try to scan from the first
character, and skip to the restart at the next character whenever it
fails, until you get a whole document scanned. Then you repeat stating
from the first character after the document just scanned.

That is also the solution suggested by @amon in the second part of his
answer.

It may not be a very fast solution (I have no way to test),
because it is unlikely that the code of the parser is optimized to
be very efficiently started on the beginning of a document.  In
normal use it does this only once, so that it is not a hot spot from
an optimization point of view. Hence, your moderate happiness with this solution
is not too surprising.

So what you really need is an algorithm that can quickly find the
beginning of a document that starts with a mass of garbage. And you
are lucky: such algorithms do exist. And I am sure you know it: it is called searching for a REGEX.

The simple solution

What you have to do is to analyze the specification of your documents
to find how these documents start. I cannot exactly tell you how, as I
am not sure how their syntax specification is organized
formally. Possibly they all start with some word from a finite list,
possibly mixed with some punctuation or numbers. That is for you to
check.

What you have to do is to define a finite state automaton (FSA), or
equivalently for most programmers a regular expression (REGEX) that
can recognize the first few characters of a document: the more, the
better, but it need not be very large (as that may take time and
space). This should be relatively easy to do from the specification of
your documents, and can probably be done automatically with a program
that reads the specification of your documents.

Once you have produced your regexp, you can run it on your input
stream to get very quickly to the beginning of your first (or next)
document as follows:

I assume:

- docstart is a regex that matches the beginning of all documents

- search(regex, stream) is a function that searches the stream for
  a substring that matches regex. When it returns, the stream is
  reduced to its suffix substream starting at the beginning of the
  first matching substring, or to the empty stream is no match is
  found.

- parse(stream) attempts to parse a document from the beginning of
  the stream (what is left of it), and returns the parse tree in
  whatever format, or fails. When it returns, the stream is reduced to
  its suffix substream starting at the position immediately following
  the end of the parsed document.  It calls an exception if the parse
  fails.

forest = empty_forest
search(docstart, stream)
while stream is not empty:
  try:
    forest = forest + parse(stream)
  except
    remove first character from stream
  search(docstart, stream)

Note that the removal of first character is necessary so that the next
search will not find again the same match.

Of course, shortening of the stream is an image. It may just be an
index on the stream.

A final note is that your regex does not need to be too accurate, as
long as it recognizes all beginnings. If it recognizes occasionally a
string that cannot be the beginning of a document (false positive),
then the only penalty is the cost of one useless call to the parser.

So that may possibly help simplifying the regex, if useful.

About the possibility of a faster solution

The above solution should work pretty well in most cases. However, if
you have really a lot of garbage and terabytes of file to process,
there might be other algorithms that run faster.

The idea is derived from the Boyer-Moore string search algorithm. This
algorithm can search a stream for a single string extremely fast
because it uses a structural analysis of the string to skip reading
most of the stream, jumping over fragments without even looking at
them. It is the fastest searching algorithm for a single string.

Thr difficulty is that its adaptation to search regex, rather than a
single string, seems very delicate and might not work as well, depending on
the features of the regex you are considering. That might in turn
depend on the syntax of the documents you are parsing. But do not trust me too much on this since I did not have time to do a careful reading of the documents I found.

I am leaving you with one or two pointers I found on the web, including one that is apparently a refereed research paper,
but you
should consider this as more speculative, possibly researchy, to be
considered only if you had strong performance problems. And there is
probably no of the shelf program that will do it.


问:
What exactly is this Python statement doing?
I'm trying to port a very basic dual contouring algorithm written in Python (here) to C++. I'm not a Python programmer so some of the language syntax is a bit foreign to me.

Specifically, this block of code is giving me trouble:

```<code># Estimate hermite data
h_data = [estimate_hermite(f, df, o+cube_verts[e[0]], o+cube_verts[e[1]])
          for e in cube_edges if cube_signs[e[0]] != cube_signs[e[1]]]
</code>```

The part that doesn’t make sense is that e is defined in the third line for the for loop, but is then used in the second line. In this case, is the declaration of the loop defined after the content of the loop? I've tried to find other cases of this in Python, but have failed so far.

答:
That is a list comprehension. Spread out a bit, it would look something like:</p>

```<code>h_data = []
for e in cube_edges:
    if cube_signs[e[0]] != cube_signs[e[1]]:
        h_data.append(estimate_hermite(f, df, o+cube_verts[e[0]], o+cube_verts[e[1]]))
</code>```

Body:
That is a list comprehension. Spread out a bit, it would look something like:

h_data = []
for e in cube_edges:
    if cube_signs[e[0]] != cube_signs[e[1]]:
        h_data.append(estimate_hermite(f, df, o+cube_verts[e[0]], o+cube_verts[e[1]]))


问:
Tell, Don't Ask and Immutability in a non-directional network
I'm working on a small project in which I'm attempting to practice relatively strict adherence to two ideas:

Tell, don't ask (TDA)

Immutability

The main concept in this project is a Map (as in a geographical map, not the data structure), which holds a 2D array of Tiles. The tiles can be thought of like squares on a chessboard, with their position in the array being their position on the board.

One operation that can be performed is a line segment can be drawn, starting at one tile, and passing through one or more other tiles, before ending when it hits the edge of the map or another line already containing a tile. Drawing a line through a Tile in this case essentially just means marking the Tile with a boolean property saying that it contains a line.

To maintain immutability, a Tile does not mutate its state when a line is drawn through it, instead returning a new Tile with the line drawn. The entry point for drawing a line is a method on the map itself, which looks like:

```<code>public Map DrawLine(Tile from, Direction direction)
</code>```

So the problem here is how to draw a line while adhering to the two ideas I mentioned before?

One way to draw the line, maintaining immutability but forgetting TDA, is for the Map to take charge of the whole drawing process, working out which tiles need to be marked as containing a line, and doing that update for each one, replacing them with the newly created Tiles in its array.

Another way, maintaining TDA but forgetting immutability, is for the Map to tell the Tile to draw a line, and in which direction, and then for each tile to notify the next one, until one decides that the line has to end (for example because it already contains a line). In this case, I don't see any simple way to make sure that all of the updated Tiles are replaced in the Map, which is why I say that this approach sacrifices immutability. The Map itself is also supposed to be immutable, so even passing itself to the Tiles with some kind of void UdpateTile(int x, int y, Tile replacement) callback method wouldn't work.

So my question is: are there any techniques or patterns which would allow me to do the above, adhering to both TDA and immutability? Or, are there any more appropriate high-level designs which would allow me to tackle these requirements while also adhering to both principles? I understand that the TDA violation in this case is relatively small, so on a practical level it wouldn't be a huge sacrifice. I'm just interested in better alternatives that I may be missing.

答:
The main point of objects is to encapsulate change of state to just one local scope. If it was possible to change object's data from anywhere, it would be extremely hard to debug. Immutability and objects doesn't make sense together, because if your objects are immutable, the possibility of state being changed from different scope disappears and so does need for encapsulation.

"Tell, don't ask" is a principle that should remind you not to break encapsulation. But if you don't need encapsulation, you don't need this principle either.

So it doesn't make sense to try to follow both principles at the same time.


问:
Choosing the right Release management & Branching strategy
I am working on a project wherein we are to use SVN as a source repository and we need to identify a branching strategy. I am aware of branch by release  & branch by feature strategies to certain extent but I am no expert and I am not sure which one or if at all either is more suitable to our requirement.

We have 2 environments, Production and Pre-Production. Once a feature is released it is first deployed in pre-production and tested rigorously before moving to production. So production environment is typically a couple of versions behind latest code version. We might receive bugs on both Production and Pre-production simultaneously. If a bug is reported on production, we need to deliver the fix on top of its current version while if on pre-production it needs to be delivered on that particular release latest version.

Has anyone had similar requirement and experience of handling such a situation. It will be good to understand the candidate solutions with pros and cons of each.

答:
Seems like we use similar staging/pre-production routine in our company.

Our branching strategy is (we use Git):

master contains releases, marked by tags (1.0.0, 1.0.1, ...)

small bugfixes (1 commit) go directly onto master

next versions go to branches like "devel-x.y.z"

features and bigger fixes are branched off version branches ("feature-foo" on top of "devel-x.y.z"), so noone steps on others' toes

Project managers decide which fixes/features must go into next release, then we merge all selected branches into master and roll out the next release semi-automatically with Maven release plugin. We often do rebases to keep repository's history as linear as possible.

So, in short, we do both branch-by-release (because we support different versions of our products) and branch-by-feature/bugfix. There is no contradiction.

branch-by-release

Pros:

we can reject or skip a release without touching master because we merge feature branches into release branches, not into master

you see which release you are working on

Cons: none I see

branch-by-feature

Pros:

you don't step on other's toes: just merge when you're done

you can track progress of each feature (we use Jira)

you can track changes of each feature in the past (we name branches after Jira issues and leave them be after merging and also we prefix commit message with the issue name)

Cons:

gets messy if there are a lot of features going at the same time and you merge something in the middle. It is kinda because of the fact that you CAN have as many branches as you want - you're not forced to implement features sequentially. Maybe it is not really a contrary, but it wouldn't be possible otherwise

SVN

Since you mentioned it... SVN will not work for what I described. I have just a little experience with it, and it was pain. Speaking of branching, SVN branches are heavy and slow, and you cannot commit offline. I'm not a hater, it's just lacks many features I need. I recommend Git, but you might also look at Mercurial or other DVCS's.


问:
Is this a secure solution for RESTful authentication?
I need to quickly implement a RESTful authentication system for my JavaScript application to use. I think I understand how it should work, but I just want to double check. Here's what I'm thinking -- what do you guys think?

Database schema

users

id : integer

first_name : varchar(50)

last_name : varchar(50)

password : varchar(32) (MD5 hashed)

etc.

user_authentications

id : integer

user_id : integer

auth_token : varchar(32) (AES encrypted, with keys outside database)

access_token : varchar(32) (AES encrypted, with keys outside database)

active : boolean

Steps

The following happens over SSL. I'm using Sinatra for the API.

JavaScript requests authentication via POST to /users/auth/token.

The /users/auth/token API method generates an auth_token hash, creates a record in user_authentications, and returns auth_token.

JavaScript hashes the user's password and then salts it with auth_token -- SHA(access_token + MD5(password))

POST the user's username and hashed+salted password to /users/auth/authenticate.

The /users/auth/authenticate API method will verify that SHA(AES.decrypt(access_token) + user.password) == what was received via POST.

The /users/auth/authenticate will generate, AES encrypt, store, and return an access token if verification is successful; otherwise, it will return 401 Unauthorized.

For any future requests against the API, JavaScript will include access_token, and the API will find the user account based on that.

答:
No, it's not secure, and it seems unnecessary complex.

In particular:

No reason to encrypt tokens on a database level. If an attacker can get password hash (has access to DB), he can get brand new tokens.

No session expiration described.

This can help: OWASP REST Security Cheat Sheet, Authentication Cheat Sheet


问:
What is the relationship between lambda calculus and programming languages?
I am starting my first year (in college) in Computer Science next year and I write mostly in C (if that is to matter). I have tried searching but most of what I find assumes knowledge of lambda calculus. Why is lambda calculus considered so much more useful than single variable calculus in prograrmming? Is there a relationship between lambda expressions and functional programs? Was it Alonzo Church's work on lambda calculus that influenced the development of programming languages?

Everyone outside school keeps buzzing about it and I have no clue what they will be talking about even though I am eager to learn it and see how it directly relates to my programming and understanding of programming languages.

答:
Lambda calculus has nothing to do with differential/integral calculus. Calculus in the most generic sense of the word just means a system of calculation.

At a very high level lambda calculus is a model of computation the same way a turing machine is a model of computation. The reason programming language researchers study lambda calculus is because as a model it has strong connections to formal methods in mathematics like logic and category theory. So methods from those domains can be applied to studying various aspects and extensions of lambda calculus which in turn helps design better programming languages with certain properties.

The most direct influence of lambda calculus in programming languages usually appears in the form of first class functions and closures. C does not have support for closures and so you'll need to explore the concept in a more high-level language like Lisp, Python, Ruby, JavaScript, etc. Historically Lisp is considered the first concrete implementation of lambda calculus as a programming language.


答:
The Lambda Calculus is interesting, elegant, and makes it much easier to understand functional programming languages. However, you won't encounter the LC in a typical CS Bachelor course, so you don't have to learn it right now – I would recommend to experiment with functional languages first before revisiting the Lambda Calculus. I believe OCaml is a good starting point into functional programming for a C programmer, and that Scheme is a good starting point to dive into the Lambda Calculus.

The Lambda Calculus is not associated with Calculus (which ought to be called Analysis instead). In general, a calculus is a “formal system”, i.e. a set of rules to do something. While Differential Calculus provides rules regarding the change of values, the rules of the Lambda Calculus describe computation itself. From this set of very basic rules, we can build arbitrary computations, data representations such as booleans, integers, or lists, and even control flow constructs such as conditionals or loops. The LC is equivalent to Turing Machines, but either model has different strengths.

Lambda Calculus had an immense impact on programming languages. The second high-level language to be implemented was Lisp, which can be understood as a direct encoding of the LC into a programming language. This “functional programming” has immense effect on the evolution of programming languages. Features such as anonymous functions, function pointers, closures (nested functions), garbage collection, variable scope, metaprogramming, advances in type systems, type inference, interpreted languages, dynamically-typed languages, object-oriented programming are all owed to a large part to the functional programming branch of programming languages. There's a joke that any new (non-academic) programming language only adds features that Lisp has already had for decades.

Beyond that, the Lambda Calculus and other related calculi are indispensable tools in programming language theory and in certain compiler construction techniques.

Any language that has anonymous functions which behave as closures and can be passed around freely immediately contains an encoding of the lambda calculus. Anonymous functions correspond a lambda expressions, except that in the LC functions always have exactly one argument. However, any Turing-complete language is equivalent to the LC, so the LC can always be implemented on top of such languages. This tends to happen in rule-matching systems or overly intelligent configuration formats, giving rise to “Greenspun's tenth rule” (in jest – mostly): “Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.”

Title: What is the relationship between lambda calculus and programming languages?

Body:
I am starting my first year (in college) in Computer Science next year and I write mostly in C (if that is to matter). I have tried searching but most of what I find assumes knowledge of lambda calculus. Why is lambda calculus considered so much more useful than single variable calculus in prograrmming? Is there a relationship between lambda expressions and functional programs? Was it Alonzo Church's work on lambda calculus that influenced the development of programming languages?

Everyone outside school keeps buzzing about it and I have no clue what they will be talking about even though I am eager to learn it and see how it directly relates to my programming and understanding of programming languages.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
For SQL:

The first big indicator is the use of implied joins.

Next is the use of a left join on tableB combined with a WHERE clause like:

WHERE TableB.myField = 'test'
```

If you don't know that will give incorrect results then I can't trust that any query you write will give correct results.

ContentLicense: CC BY-SA 2.5

Body:
For SQL:

The first big indicator is the use of implied joins.

Next is the use of a left join on tableB combined with a WHERE clause like:

WHERE TableB.myField = 'test'

If you don't know that will give incorrect results then I can't trust that any query you write will give correct results.


问:
Why is inheritance generally viewed as a bad thing by OOP proponents
I keep hearing the phrase "Favour Composition over Inheritance" from GoF, which is being annoyingly mentioned repeatedly by my friend, who thinks it is a valid blanket statement. But is it not more sensible to consider that the real reason why inheritance exists is not just for behaviour reuse, but for the case where a hierarchy of classes inheriting from the same ancestor need to be passed as arguments to a function? That is: to implicitly implement polymorphism, and these descendent classes have methods which are polymorphisms of a funtion in the ancestral class. Use of inheritance in this manner is the sole reason why herds and fleets of programmers find it pleasurable to write UI with Microsoft's WPF with (Visual) C#. How would composition fit nicely into the picture of UI framework design, without being too verbose?

I know compatibility clashes may arise from the usage of inheritance, which is one of the things the statement aims to protect one from, but is it not a question of bad design on the programmer's part (failure to discern when to inherit and when to compose) rather than on the paradigm or language?

P.S.: I used the terms ancestor and descendent to avoid implying inheritance depth through the usage of parent and child.

答:
...my friend who thinks it is a valid blanket statement but is it not more sensible to...

Yes, it is always more sensible (time permitting) to understand why things are the way they are rather than following some mantra blindly.

real reason why inheritance exists is not just for behaviour reuse but for the case where a hierarchy of classes inheriting from the same ancestor need to be passed as arguments to a function

Not correct. That is an implementation detail of languages, and while a fairly significant one - not what you should focus on.

to implicitly implement polymorphism and these descendent classes have methods which are polymorphisms of a funtion in the ancestral class.

And that too is not quite correct.

is it not a question of bad design on the programmer's part (failure to discern when to inherit and when to compose) rather than on the paradigm or language?

It entirely is a question of bad design on the programmer's part. The general disdain for inheritance isn't for inheritance the concept, it's for inheritance being used in code that causes pain.

Because inheritance (and all subtyping) is a specialization of some super-type. Not just that, but well done inheritance is a specialization of the contracts defined by the super type (else the whole Rectangle/Square thing would actually work). Even when programmers know that they're supposed to do that (and very few do). It's hard to refine the contracts of the type without breaking other parts of the contracts (see the Width/Height behaviors in Rectangle/Square for an example). And worse yet, it's not particularly common that you want to actually do that limited specialization since it rarely is useful.

So instead, there's a boatload of programmers misusing inheritance, just to do polymorphism, or to have XY and Z (tacking on an extra field is a fragile and often dangerous use of inheritance), or to kinda sorta specialize things (yes, Penguin is a Bird, but it's .Fly() method doesn't work...), or...

So inheritance is viewed as a generally bad thing since it generally yields bad results.

ContentLicense: CC BY-SA 4.0


答:
You ask why, as if the whether is decided. Lets consider your supposition:

Why is inheritance generally viewed as a bad thing by OOP proponents

I disagree with the premise of the question. Inheritance isn't generally viewed as bad, it is viewed as misused and overused.

GoF Design Patterns says no such thing about it being bad.

Let's see what GoF Design Patterns actually says...

p20 - In the discussion of Favor composition over inheritance, that Inheritance and object composition thus work together.

p22 - Object composition lets you change the behavior being composed at run-time, but it also requires indirection and can be less efficient.

p25 - ... on the other hand, heavy use of object composition can make designs harder to understand.

And so on. Now, there are also plenty of downsides to inheritance that I could quote, but the point is, GoF doesn't claim inheritance is bad, and clearly teaches the pros and cons of various techniques. What does favour mean in this context? Don't make inheritance your first choice. Kinda like don't make the crowbar your first choice, try the key first.

As far as inheritance, there are two major types, Class inheritance and Interface inheritance (subtyping). Both are appropriate for particular patterns but the latter has come into favor since GoF was published. If you were learning OOP back in the early 90s, you would know about Booch Method and Rumbaugh Method, but nowadays you hear little of those. Yet they were teaching a generation of C++ (and Java) programmers to inherit and override.  But state of the art has moved on. We have, through collective experience, found that loose coupling is really found through use of interfaces and dependency injection, and not merely by using encapsulation.

The problem with inheritance is too many "OO" programmers think of problems first as potential inheritance solutions. Inheritance is a concrete concept that people understand quickly early on, so many latch onto that and never really grow much more as system modelers. When everything in a system is wedged into an inheritance hierarchy, and code is reused by class inheritance, it makes for some disastrous results and the benefits of OO are outweighed by actually wrestling with the hierarchy itself. I've seen many projects, and been responsible for some myself, that spent more time wrestling a huge hierarchy than actually maintaining the sub-system interfaces. This is a sign of inheritance misuse.

But that aside, inheritance is invaluable for accomplishing many good things. Polymorphism (specifically sub-type polymorphism) is a very powerful tool and single and double dispatch are key for patterns such as Visitor pattern. Interface inheritance is key to designing to interfaces, not implementations. Abstract classes or interfaces are only useful with inheritance.

If your friend thinks that "favour composition over inheritance" is a mantra for avoiding inheritance altogether, he is mistaken and doesn't understand the concept of a complete toolset.

Sounds as if he hasn't actually read GoF. If he did claim to read it, then it sounds as if he misunderstood it and should read it again.

Body:
I keep hearing the phrase "Favour Composition over Inheritance" from GoF, which is being annoyingly mentioned repeatedly by my friend, who thinks it is a valid blanket statement. But is it not more sensible to consider that the real reason why inheritance exists is not just for behaviour reuse, but for the case where a hierarchy of classes inheriting from the same ancestor need to be passed as arguments to a function? That is: to implicitly implement polymorphism, and these descendent classes have methods which are polymorphisms of a funtion in the ancestral class. Use of inheritance in this manner is the sole reason why herds and fleets of programmers find it pleasurable to write UI with Microsoft's WPF with (Visual) C#. How would composition fit nicely into the picture of UI framework design, without being too verbose?

I know compatibility clashes may arise from the usage of inheritance, which is one of the things the statement aims to protect one from, but is it not a question of bad design on the programmer's part (failure to discern when to inherit and when to compose) rather than on the paradigm or language?

P.S.: I used the terms ancestor and descendent to avoid implying inheritance depth through the usage of parent and child.


问:
Ship of Theseus applied to GPL - Can I relicense my program if I replace all of the derivative parts?
I translated a GPLv2 C program to Python, but found it was hard to extend as designed and rewrote significant portions of it. The program is now structurally completely different, but there are several verbatim translated functions in use.

The Ship of Theseus Paradox (as stated from Wikipedia) "raises the question of whether an object which has had all its components replaced remains fundamentally the same object."

If I did manage to write replacements for the verbatim functions, would I be able to relicense to a license I prefer?

Related, would I be able to pull the evolved architecture out and reuse it with a different license? I think it would be very useful on its own, but do not like the idea that it is now "tainted" with the GPL license.

Followup: I decided to contact the copyright holder and received permission to relicense.  Sometimes the best way is to interact socially rather than programmatically!

答:
First, the answer is no (for a translation), you cannot legally relicense it or do anything outside of the original license legalities. You may very well have done 10 times the work of the original author, but it doesn't matter, it is viral. Not just because it is GPL, but because it isn't clean design or rewrite.

I struggled briefly with this in 1992 when I had done massive rewrite of an old MUD codebase. We had a successful game, but wanted to do our own thing, and people were willing to pay for it, yet the DikuMUD license strictly forbid us to make money. A competitor, at the time, also had based theirs on the same codebase, and they opted to blatantly ignore the copyright, rip out all traces of it, and basically lie to everyone including themselves. Their logic was "none of the original code exists" and "we have done massive rewrites and improvement" and generally ignoring the fact that they started with 20,000 lines of code. They were charging for items in the game, and making too much money to stop.

I was admittedly envious. But I researched copyright law, and consulted my conscience, and decided I could not even use the code I had written because I honestly did not architect the game server from scratch.

So I decided to put my money where my mouth was and write from scratch, with a copy of W. Richard Steven's UNIX Network Programming with me at all times, I started. Writing from scratch, my way, taught me so much more than when I had rewritten DikuMUD, and it also taught me that I didn't really understand what it meant to stand on someone else's shoulders. Within six months I had 50,000 lines of operational code that I could call mine. I named it MUD++ and released it under BSD. Badly written in early style C++, it was still the first free, open source C++ MUD that I am aware of. To this day nobody can take it away from me. I had the best TCP server at the time, nobody else could do a "hot reboot" without dropping players, and soon everyone was stealing the feature (and I've noted many GPL MUDs have snippets of my BSD code -- always interesting how GPL can hijack BSD-ware but not vice-versa). Eventually, I moved on, so it wasn't like the decision was a make or break for my fortune, but while the other guys made a lot of money for a while, last I looked they had dwindled, in a world of graphical games there isn't much mass demand for text anymore.

The story doesn't end... a few years later, I was working for IBM and Disney hired us to write a realtime 3D multiplayer game for Epcot center, and I was able to use the TCP core from MUD++ as a base for that game server! Had I not owned my own code, I wouldn't have been allowed to use it, and it honestly saved me weeks of coding time. In the end, I am proud of the choices I made and I have a story to tell my kids.

People understate and underestimate the benefit of starting with someone else's framework to build on.

If you think you "own" it, test yourself. Start over, with a Python book beside you. See how it feels. Don't cheat and don't look at the old codebase. Look at the output. Force yourself to think through every aspect on your own, doing the honest research. You'll be better for it, and likely have a better product.

Before you do that, though, try to contact the original author. Ask them if they would be willing to relicense. If you plan to sell binaries, offer royalties. Many authors who released things GPL in the 90s and 2000s, are now in their 30s, 40s and 50s and understand what it means to make a living at software. I've seen more than one relicense their stuff from GPL to MIT, Apache, Boost or BSD.

Lastly, a license doesn't override prior rights to code you may have. Or if you wrote a clean add-on independently, for example, if you wrote a TCP engine as an add-on to a single player Tetris game, and it can cleanly stand alone (especially if you previously released under another license) then you can reuse your code in other projects. You have authorship rights too.

My belief is free is FREE. If you gotta attach strings, don't call it free. Someone mailed me years later and said that they had used my game in a commercial engine, mainly the TCP and possibly the bytecode interpreter. They were making money. I didn't mind one bit. I was happy as I still am now, as a proud father.


问:
How do I localize my game?
My team and I are making a game to support multiple languages, and we want to work on localizing the game to reach a wider audience.

Where would I start? How would this be accomplished? I would work on providing different scripts with multiple languages and there would be more than one language to translate to.

What are the techniques and tools used to localize games?

答:
I don't know why people down-voted your answer. "Localization in gaming" is an interesting topic.

More precisely, we call this task "localization the game". Localization in gaming is the process of translating and releasing your game in other languages (or accents, depends on your needs). Localization lets your game reach a larger audience, increasing your fan base and potential sales.

I recommend that you start reading this thread How to prepare a game for localization?, there are some good insights in the comments.

Check these articles as well:

http://company.plarium.com/news/featured/how-game-developers-can-overcome-localization-challenges/

http://www.localization.it/the-future-of-game-localization-interview-with-localizedirects-christoffer-nilsson

http://translation-blog.com/?s=game

Check this course:

http://www.udemy.com/course-introduction-to-game-localization/

I am not sure which technology you use, Unity, .. but you can be inspired by Mozilla localization tools

Title: How do I localize my game?


答:
It is doubtful, even if you rewrote the entire library from scratch, that it would pass legal scrutiny. The code would be considered "tainted" because you have seen the code in the GPL licensed library.

The standard approach to this problem is called "clean room implementation". You write a requirements document and have someone else implement it (who hasn't seen the GPL code).

Also see this question: Rewriting GPL code to change license

As someone aptly put it there, a Chinese translation of Harry Potter is still a derivative work, even though all the information has been replaced.

Of course, the probability of you getting sued over rewriting a GPL licensed library (and the morality of relying on that low probability) are entirely different discussions.

As far as adding functionality to the original code, this is (part of) the very definition of derivative works: adding to the original work. It doesn't matter how much you added, or how small the initial work was - it's still derivative.

Title: Ship of Theseus applied to GPL - Can I relicense my program if I replace all of the derivative parts?

Body:
I translated a GPLv2 C program to Python, but found it was hard to extend as designed and rewrote significant portions of it. The program is now structurally completely different, but there are several verbatim translated functions in use.

The Ship of Theseus Paradox (as stated from Wikipedia) "raises the question of whether an object which has had all its components replaced remains fundamentally the same object."

If I did manage to write replacements for the verbatim functions, would I be able to relicense to a license I prefer?

Related, would I be able to pull the evolved architecture out and reuse it with a different license? I think it would be very useful on its own, but do not like the idea that it is now "tainted" with the GPL license.

Followup: I decided to contact the copyright holder and received permission to relicense.  Sometimes the best way is to interact socially rather than programmatically!


问:
What is the name of a type that is defined from a template?
To give a complete example, let's say I have a template class that I now use to generate a type definition:

```<code>template <typename T>
struct A {};

using X = // I'm not asking about this
  A<int>; // I want to know what this is
</code>```

What is the name of A<int>? My initial thoughts were that it was a generic specialisation of A, because I recall reading that somewhere in reference to the standard, but I can't find it now.

The answer should make reference to the standard or, if that is not possible, cite an authoritative source that sets some sort of precedent for how it is named.

I know these kinds of questions are borderline but I don't know of any other place to ask them and I've done my best to address the points raised in this meta discussion about questions on naming.

答:
It's just an alias: it takes A<T> , instantiate it with T=int and calls it X

Declare X a; and a will be an A<int>.

The documentation is as cppreference

Here are some references.

About A it is a "template instantiation": the generic type A is compiled using int in the place of T.

It is like vector<int> respect to vector<double> starting from vector<T>


答:
This scenario is covered in the GPL FAQ:

What does the GPL say about translating some code to a different programming language?

Under copyright law, translation of a work is considered a kind of modification. Therefore, what the GPL says about modified versions applies also to translated versions.


问:
Pattern / methodology for representing large database records as objects
A bit of background information: We have an old database application written in Access that lets users monitor their workload, and the code is... 'procedural' might be too kind. The vast majority of code is hard-wired to form events, there's a lot of duplication, and little to no abstraction. If it needs to fetch data from the database, it'll just do it right there and then, even if that means roughly the same bit of code repeated 6 times for 6 similar buttons (and 6 practically identical database requests). It's not pretty.

I want to rebuild the application in VB.NET, but I'm hitting a bit of a design snag when it comes to writing classes to represent database records as objects - I don't have a huge amount of experience in OO programming (written a few small apps, read lots of books and material, regular SE lurker), so this is my first OO database application.

The problem is that a given 'job' for a user has a lot of fields on the database. About 30 or so - ID, Title, Requestor, Request Date, Target Date, Priority, Type, Approval... and so on. First pass: Whack everything into a dirty great Job class:

```<code>Public Class Job
    Private mID As String
    Private mTitle As String
    Private mRequestorName As String
    Private mRequestorEmail As String
    ...

    Public Property ID() As String
        Get
            Return mID
        End Get
        Set(value As String)
            Me.mID = value
        End Set
    End Property
    ...
End Class
</code>```

Yikes. I'm sure you can see my hesitance at having such an enormous class sitting front-and-center of the application. All those properties seem to be violating encapsulation too - the Private members might as well be Public, but conversely I need to be able to alter fields and later write back to the database.

Second pass: There's a few things in here that could be extracted and situated elsewhere: for example, all those Requestor___ members could sit in a Requestor class

```<code>Public Class Job
    Private mID As String
    Private mTitle As String
    Private mRequestor As Requestor
    ...
End Class

Public Class Requestor
    Private mName As String
    Private mEmail As String
    ...
End Class
</code>```

So now I have half a dozen of these. Smaller classes? Feels nice. But it feels like all I've really achieved is essentially database normalisation, which doesn't feel like it should live in the application. And the only real change to the structure is that it takes more steps to get to data items.

And I still have all those properties (which are forcing me to use hungarian notation on my private members, which I'm not a fan of, but VB.NET isn't case-sensitive so I can't use the same names), which still aren't sitting right with me.

Is there a standard pattern or methodology for moving large data items to and from a database? My current best idea is the above with commit() and read() methods in the Job class - alterations are made to the objects and then later commited to the database.

答:
The reference to the object-relational impedance mismatch is an interesting read. However when we look at it more carefully, it is basically complaining why a square peg is not fitting a round hole.

That is what a really good ORM product resolves. Unfortunately having been part of two separate ORM's design and development, I can say that many ORM's bring their own challenges.

Even though the question is a year old, the principles mentioned here are learnt over the years and they still apply and may be helpful to someone.

Use the DRY principal

Always fetch the full record (or only the key fields, of the index you're using to search). There can be exceptions in case of reporting, but for general OLTP applications, do this as a principle because you will change logic often and shouldn't have to go back and change your base record objects (as suggested in the next two principles). The speed penalty rarely applies and coding benefit is much higher.

Accept the fact that a database is meant to give you sets of rows (tuples), and use them as they are instead of fighting the structure.

Make sure the very first layer of objects that deal with the database is "record aware" (i.e. previous principle). This means objects each handle one type of record only, usually from one table, or one view.

You can optionally add a layer of objects that are multi-table aware, i.e. aware of the relationships between tables. This makes things easier. But then you HAVE to use that new layer only, and not go direct to the lower layer for consistency, otherwise you'll have a lot of Code Smell http://blog.codinghorror.com/code-smells/

Now write your business logic, in separate objects from the ones that deal with the database. Except put all the validation type constraint checking in the first layer. This means keep the data validation separated from business rules or business functionality.

Never "not implement" validation at the database itself, in other words, never skimp/skip on validation but put as much as the database engine will allow. This means from as basic as implementing simple validation like "CHECK constraints" to complex cross table DML triggers. In other words, never let junk into the database (I see a ton of systems by well meaning developers with this flaw). Hmm.. Did I say it loud enough.. I guess not... so... what I'm SAYING :-) is "Don't rely on your UI objects for data integrity that can be done by the database engine". And if you HAVE to allow unvalidated data somewhere in your business process because the "operator/user" may not have it at first use, e.g. a patient is not conscious to give you all the information in an ER scenario, then make sure some process is in place that regularly requires someone to go and back-fill missing data.

Records with BLOB fields or other large fields should be handled by the main object meant for the record, but only fetch the blob by key reference as needed. This implementation should be hidden and other objects using the "record" object shouldn't have to care when and how the BLOB is fetched or saved to the database.

This list is deceptively small but will make life easier for the developer and for the DBA who has to live with the design, in any project where Object to relational mapping is needed.


答:
Scott Meyers' Effective Modern C++ mentions "function templates (i.e., templates that generate functions) and template functions (i.e., the functions generated from function templates)."

A can be called a struct template, and A<int> can be called a template struct.

Title: What is the name of a type that is defined from a template?

Body:
To give a complete example, let's say I have a template class that I now use to generate a type definition:

```<code>template <typename T>
struct A {};

using X = // I'm not asking about this
  A<int>; // I want to know what this is
</code>```

What is the name of A<int>? My initial thoughts were that it was a generic specialisation of A, because I recall reading that somewhere in reference to the standard, but I can't find it now.

The answer should make reference to the standard or, if that is not possible, cite an authoritative source that sets some sort of precedent for how it is named.

I know these kinds of questions are borderline but I don't know of any other place to ask them and I've done my best to address the points raised in this meta discussion about questions on naming.


问:
What would be the return type of a cartesian product of a multiset
I am writing a Multiset in Ruby. The Union, Intersection operations where simple and return a MultiSet. But, I am not sure what the return type of the cartesian product should be, should I return an array of tuples? is that a good api?

```<code> MultiSet.new([1,1]) * (MultiSet.new([1,2])
</code>```

In Math it is

```<code>{1,1}*{1,2} = {(1,1),(1,1),(1,2),(1,2)}
</code>```

答:
I'm not sure why you think the product of two multisets should be an array. It should obviously be a multiset. A multiset of ordered pairs, to be precise.

Ruby doesn't have a prebuilt representation of ordered pairs (or more generally tuples), so you could do one of two things:

provide your own pair implementation

do what Hash#each does and represent pairs as two-element arrays

I believe the second option is the more sensible one, so your return type should be a MultiSet of two-element Arrays.

But I'm not convinced of your code example, either. In your example, you are implying that

```<code>MultiSet.new([1, 1]) * MultiSet.new([1, 2])
</code>```

and

```<code>{1, 1} * {1, 2} = {(1, 1), (1, 1), (1, 2), (1, 2)}
</code>```

are the same thing, but they are not!

```<code>MultiSet.new([1, 1]) * MultiSet.new([1, 2])
</code>```

is the same as

```<code>{[1, 1]} * {[1, 2]} = {([1, 1], [1, 2])}
</code>```

and

```<code>{1, 1} * {1, 2} = {(1, 1), (1, 1), (1, 2), (1, 2)}
</code>```

is the same as

```<code>MultiSet.new(1, 1) * MultiSet.new(1, 2) ==
  MultiSet.new([1, 1], [1, 1], [1, 2], [1, 2])
</code>```

Body:
I'm not sure why you think the product of two multisets should be an array. It should obviously be a multiset. A multiset of ordered pairs, to be precise.

Ruby doesn't have a prebuilt representation of ordered pairs (or more generally tuples), so you could do one of two things:

provide your own pair implementation

do what Hash#each does and represent pairs as two-element arrays

I believe the second option is the more sensible one, so your return type should be a MultiSet of two-element Arrays.

But I'm not convinced of your code example, either. In your example, you are implying that

MultiSet.new([1, 1]) * MultiSet.new([1, 2])

and

{1, 1} * {1, 2} = {(1, 1), (1, 1), (1, 2), (1, 2)}

are the same thing, but they are not!

MultiSet.new([1, 1]) * MultiSet.new([1, 2])

is the same as

{[1, 1]} * {[1, 2]} = {([1, 1], [1, 2])}

and

{1, 1} * {1, 2} = {(1, 1), (1, 1), (1, 2), (1, 2)}

is the same as

MultiSet.new(1, 1) * MultiSet.new(1, 2) ==
  MultiSet.new([1, 1], [1, 1], [1, 2], [1, 2])


问:
Java Licenses, GPL, GNU Questions
I would like to ask a few questions about software licenses, with regards to a (Java) program I am making. I am very very new to licenses, so please bear with me.

1. If I produce a Java program using 'internal' libraries (such as JavaFX), am I allowed to sell my program? Do I need to include (distribute) my source code?

2. If I produce a Java program using 'external' libraries (in addition to 'internal ones') which are licensed under the GPL license, am I able to sell my program? Do I need to include (distribute) my source code OR the external library source OR both?

3. Does selling a program which makes use of GPL licensed 'external' library, give the purchaser the option of reselling and charging any price ($0.00-$infinite), (and making potentially infinite, copies of) my program?

4. Are there any other notable constraints that using a external library (licensed under this GPL license) in my program, will incur?

答:
With internal libraries, you don't need to distribute them at all. The end
user will have their own copy in their JRE. You only distribute code you own
so you doesn't have any constraints.

If you distribute code using GPL libraries, your code would need to be compatible
with the GPL license which includes making all the code of the combined work available.

You're free to sell GPL software but since others can redistribute too
you'll need to provide a reason why people should buy it from you, like extra support.

Yes, people who obtain your software can redistribute it under the terms of
the GPL. This allows charging any price.

Check the actual text of the GPL carefully before releasing software to make
sure you understand what you're agreeing to. Anyone that obtains your software
would be able to modify and distribute it under the GPL.

Other licenses like the LGPL are quite common for libraries because they only cover changes to the library itself and not you own code. You might want to look for libraries with that style of license instead.

Title: Java Licenses, GPL, GNU Questions


问:
How to manually detect deadlocks
I understand the concepts of deadlock well enough, but when I'm given a problem like the one below I'm not sure how to go about solving it. I can draw a resource allocation graph, but I'm not sure how to solve it from there.

Is there a better more formal way of solving this?

```<code>Consider  a  system  with  five  processes,  P1  through P5,  and  five
resources, R1 through R5. Resource ownership is as follows.

•  P1 holds R1 and wants R3
•  P2 holds R2 and wants R1
•  P3 holds R3 and wants R5
•  P4 holds R5 and wants R2
•  P5 holds R4 and wants R2

Is this system deadlocked? Justify your answer. If  the system is deadlocked, list
the involved processes.
</code>```

答:
For this problem, I used a Place/Transition (P/T) Net. I used the “standard” graphics for P/T Net with two modifications: changed the token colour from black to “reddish-orange”, added a bounding box with dashed lines to represent a process. I modified the labels you used for processes and resources – instead of starting from 1, I started from 0.

Then I marked the net according to the conditions you specified: P0 holds R0, P1 holds R1, etc.

Next I manually computed the status of each transition in the net (by visually inspecting the marked net). I did not find any enabled transition. So I left each transitions colourless. Since no transition is enabled, the system is deadlocked.

I included the situation where all resources available – in this case, some of the transitions are enabled (and coloured green).

I will include an interactive version in PDF using JavaScript. I'll post it later.

Title: How to manually detect deadlocks


问:
Unit testing method that calls multiple private methods
I've been reading a lot about unit testing recently and there seems to be a debate online about whether private methods should be tested or not.

If I have an interface that exposes one method, but that method is quite complex and calls multiple other private methods and also makes use of other objects, how do I go about testing that method? Surely I should be testing the smallest units possible, even though many of these will be private methods belonging to the class under test?

Is testing a method that is made up of multiple smaller methods really an integration test?

答:
First off, there seem to be many approaches to testing code automatically. The term "unit testing" seems to have been bastardized to mean any automated testing. In its pure form, a unit test tests only one method. A test for a method that calls other methods or library functions is often called a functional test. Integration testing usually spans multiple components, process or thread boundaries.

The questions you have to ask yourself are:

Could any of the private methods fail to work?

Might any of the private methods be useful for other methods in the class?

If the master method is treated as a black box, are there parts of the code that won't be tested?

If you decide you want to test the private methods, there are several approaches:

Change the scope to public (I shudder when this is suggested, but I do it for completeness sake).

Change the scope to protected and create a subclass that accesses the formerly private methods for testing purposes.

Use introspection to access the private methods for testing purposes (again, I shudder, but it may be required).


答:
No, it's not an integration test. A unit test tests one unit of executable code, and in procedural languages that usually equates to a method.

The test must make sure that this unit of code does its own task correctly, and nothing else. If our method calls multiple private methods, then you must test the effect of all those private bits of code. For instance, if it constructs a complex object with many different attributes, then you must test the value of all those attributes. If it does different things in different circumstances, then you must exercise all those different circumstances - probably in multiple tests. There is no reason for writing only one test for one method; if the circumstances are different enough, then it's almost always clearer to write multiple tests with different fixtures than to cram it all into one test.

Of course, if your method really is too complicated, there may be a very good case for refactoring it into multiple smaller methods. But that is true completely independent of testing; the fact that one method should do exactly one thing is a good principle to follow to begin with. The main reason for refactoring is that it makes the business code easier to understand and extend. The fact that it makes testing easier is just a collateral benefit.

Title: Unit testing method that calls multiple private methods

Body:
I've been reading a lot about unit testing recently and there seems to be a debate online about whether private methods should be tested or not.

If I have an interface that exposes one method, but that method is quite complex and calls multiple other private methods and also makes use of other objects, how do I go about testing that method? Surely I should be testing the smallest units possible, even though many of these will be private methods belonging to the class under test?

Is testing a method that is made up of multiple smaller methods really an integration test?


答:
there seems to be a debate online about whether private methods should be tested or not.

Really? Where is this supposed debate?

If it's part of your software, it needs to work. Usually, that means testing it to make sure it works.

If I have an interface that exposes one method, but that method is quite complex and calls multiple other private methods and also makes use of other objects, how do I go about testing that method?

Step 1 - make it less complex. Seriously. If you find it hard to pull out the different bits to test them in isolation, it's going to be double touch to modify or reuse those different bits in a non-test scenario. Do yourself a favor and clean up the function.

Yes, yes, "but I've done all I can! This is an exceptional circumstance!", I've heard it before... Odds are, it's not really exceptional. So question 2:

Surely I should be testing the smallest units possible, even though many of these will be private methods belonging to the class under test?

Absolutely. But you also need to test the responsibility of the thing that aggregates those private methods together, to make sure it did that aggregation properly to get you your correct result. In an ideal world, that would mean treating it like a black box. Take some inputs, check that the outputs are as expected. In the real world, you'll likely have a lot of inputs/setup - but that's what you get for not simplifying the method in the first place.


答:
Observation: The GPL is only relevant if you release your work. Have you released it yet?

Observation: This is not a legal-counsel website, so throw out all that legal FUD, and apply common sense.

Opinion: The GPL, or any license, does not copyright ideas, it claims the sourcecode, not matter how small its part. So, if, and only if your "derivative" work cannot be identified as being derived from the original, because you changed the structure of the code and reimplemented all functionality, it is for all practical purposes no longer derivative, because, well it would be indistiguishable from a clean room implementation.

This is very hard (impossible?) to acheive though when you have an existing codebase you modify, instead of starting from scratch.


问:
Design Question - System Integration
Guidance on good application architecture / design is not in short supply however most of the examples focus on some business object, like Customer and its behaviour and persistence.

There is little guidance on software that is focus on integrating existing systems. For example integrating SharePoint with an application deployment system. Say I have a Windows service that reads a SharePoint list and adds packages to SCCM.

Is the general consensus for solving this is to have object that represent the data from SharePoint and objects that represent the data in SCCM. The main program flow is then using SharePoint objects to create new SCCM objects and save them back to SCCM?

Or is it simpler and cleaner to just have a routing the reads from one and writes to the other in the one step.

答:
Use a simple Adapter to bridge the connection between the two systems. This is a basic Enterprise Integration pattern and it specifically addresses your concern by kind of mixing your two approaches.

Think of the link between Sharepoint and the other application as a Message Channel (or "routing" as you've put it). The adapter can sit at any end of the channel, to convert the source datatype to the destination datatype (and vice versa). Here, you don't need to have an intermediate datatype, just the source and destination datatype. The data enters as one type and leaves as the other

Title: Design Question - System Integration


问:
Decide the type of an object during runtime
I try to implement a PriorityQueue with C#:

```<code>public class PriorityQueue<T> : Heap<T> where T : IComparable<T> {
    ...
}
</code>```

The Heap is abstract. I have MinHeap and MaxHeap that are derived from Heap.

```<code>public abstract class Heap<T> where T : IComp ...
public class MinHeap<T> : Heap<T> ...
public class MaxHeap<T> : Heap<T> ...
</code>```

Is there a possibility to decide in the constructor of PriorityQueue during runtime, if the PrioQueue becomes a MinHeap or MaxHeap?
Like:

```<code>public PriorityQueue(bool type) {
    if (type = smallestFirst) { this = MinHeap ... }
    else { this = MaxHeap ... }
}
</code>```

If I try like this, then he says that "this" is writeprotected.
Any other ideas?

答:
No, it is not possible.

You should be using composition instead of inheritance here. Have Heap<T> as field and assign specific instance into this field.

```<code>public class PriorityQueue<T> where T : IComparable<T> {
    Heap<T> _heap;

    public PriorityQueue(bool type) {
        if (type == smallestFirst) { _heap = new MinHeap<T>(); }
        else { _heap = new MaxHeap<T>(); }
     }
}
</code>```

Body:
No, it is not possible.

You should be using composition instead of inheritance here. Have Heap<T> as field and assign specific instance into this field.

public class PriorityQueue<T> where T : IComparable<T> {
    Heap<T> _heap;

    public PriorityQueue(bool type) {
        if (type == smallestFirst) { _heap = new MinHeap<T>(); }
        else { _heap = new MaxHeap<T>(); }
     }
}


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
"Do not use C++ comment style for C code".

While this may still have a small value if there is risk of needing to port your program to an obsolete compiler, it's mostly just a hassle.   My biggest objection is that it makes it really hard to use /* to block comment out a large region during development or unit testing. */


问:
An example of a beginner-level Algorithm, intermediate level Algorithm and a complex/expert level Algorithm?
I'd like to get a sense for the range of complexity that algorithms fall into. I think it would be interesting and helpful for those, like me, trying to better understand how algorithms are formulated and how to deconstruct them.

Can you offer a basic algorithm with explanation, an intermediate algorithm with explanation, and maybe an expert level one (with or without) an explanation?

答:
From the Programmer Competency Matrix:

Beginner

Basic sorting, searching and data structure traversal and retrieval algorithms

Intermediate

Tree and Graph data structures, simple greedy and divide and conquer algorithms.

Advanced

graph algorithms, numerical computation algorithms, etc.


问:
How to save entities relations using unit of work pattern
I use Unit of work pattern to commit all new, dirty, deleted entities to the DB (using a db_mapper).

Example of entities are: Student and Class

So Student->registerDirty() will add this entity to the dirty pool that will be saved to the DB when commit() will be called.

My problem is that Student can also hold collection of classes (Student->getClasses) and I am not sure how to integrate this into the unit of work pattern so it will only commit the new, updated or deleted.

Can any one recommend me how to integrate this?

答: Simple : the collection of Classes will record what was added or removed and will commit those items accordingly.


问:
Should all programmers know how to solve algorithms, etc
I'm 15 and have been programming for about 3-4 years. I mostly program in Java as it was my first language.

I would like to be a programmer when I'm older, but I'm not sure about the differences. I've used a website, named hackerrank.com, and struggled immensely on the EASY questions. I can program games, applications, etc. But solving algorithms on this website is extremely difficult for me. If I were to be a programmer, would I have to be able to solve extremely difficult algorithms, or not? I understand Computer Scientists would have to, but a back-end game developer, or application developer for large aviation companies need to?

答:
If I were to be a programmer, would I have to be able to solve extremely difficult algorithms, or not?

Maybe, maybe not. There are many professional programmers who do nothing noteworthy, yet are still employed (and horrible).

I understand Computer Scientists would have to, but a back-end game developer, or application developer for large aviation companies need to?

Absolutely. If anything, skilled developers in these fields will face even more challenging problems, because they won't nearly be so well defined.


问:
Implementation Coupling
This question is regarding Interface Segregation Principle Best-Practices.  I use abstract examples below, but the question arises from actual code I've seen that performs what I can only call "Implementation Coupling".

If I were to break my concrete MilkMan class into his respective roles, I would see that MilkMan has three roles.  He plays the role of a Person (walks and chews bubblegum), He plays the role of a Deliverer (Inventory & Accounting functions?), and He hits on my wife when I'm not at home.

Then when I am writing/reviewing my Accounting logic (or Unit Testing it), I see that some methods in my accounting class(es) can take a MilkMan parameter.  When I see this, I obviously have something wrong.  The only thing my accounting class (Or Unit-Tests of such) cares about is his Deliverer role.

So what I do is identify the roles of my MilkMan, and segregate some interfaces:

IPerson

IDeliverer

ICovetThyW

Now when my accounting class (or its Unit-Tests) needs to mock or pass around Deliverer functionality, the relationships are clear.  I can now have my MailMan, UpsMan, and PoolBoy talk to my Accounting logic by clearly passing around IDeliverer.

So now Unit Testing is much easier to mock, and relationships become more clear in my code.  Everything is great.

What if one method in one implementation is making calls to another method in the same class, but which is part of another implementation?  Take the following code into consideration:

namespace HomeAccounting.KeepAnEyeOnPayments.Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            IDeliverer jose = new MilkMan();
            double paymentAmount = 69;
            if (jose.AcceptPaymentFromCustomer(paymentAmount))
            {
                System.Console.WriteLine("He got " + paymentAmount.ToString());
            }
        }
    }

    public class MilkMan : IPerson, IDeliverer, ICovetThyW
    {
        public bool CanWalk { get; set; }
        public bool CanChewBubblegum { get; set; }

        public bool AcceptPaymentFromCustomer(double amountDue)
        {
            if (GetPaymentFromCustomer(amountDue) == amountDue)
            {
                return true;
            }
            else
            {
                if (AlternativePaymentMethod(amountDue) == amountDue)
                {
                    return true;
                }
            }
            return false;
        }

        private double GetPaymentFromCustomer(double amountDue)
        {
            return 0; //Not willing and/or able to give money.
        }

        public double AlternativePaymentMethod(double amountDue)
        {
            return amountDue;
        }

    }

    public interface IPerson
    {
        bool CanWalk { get; set; }
        bool CanChewBubblegum { get; set; }
    }

    public interface IDeliverer
    {
        bool AcceptPaymentFromCustomer(double amountDue);
    }

    public interface ICovetThyW
    {
        double AlternativePaymentMethod(double amountDue);
    }
}
```

The question is: Does anybody see anything wrong with this?  But in all seriousness: I'd like to know if there is a term or discussion or best-practice listed out there that says you shouldn't be coupling your implementations together.

I want to point out that explicit interface implementation (Which I push for) makes this not even possible to do.  But I've honestly never seen that in a professional environment in 15 years.

答:
Does anybody see anything wrong with this? ...

I think I see an over-use of interfaces because ...

in all seriousness

When I read this: What if one method in one implementation is making calls to another method in the same class, but which is part of another implementation? the code smell is clear.

I see a natural inheritance situation being corrupted by mis-application of the interface segregation principle. You're disconnecting what an object is from what it does via ISP. "Delivery" behavior is a natural extension of what the object is. An interface is used to give common behavior to unrelated classes. This is not your situation.

Redesign to inherit delivery behavior

Seems to me you have one customer delivery/payment system. One process that can be embodied in a base class. This better expresses, reflects, and simulates your real world. With multiple implementations of the same thing you are asking for  maintenance headaches.

I see that some methods in my accounting class(es) can take a MilkMan parameter. When I see this, I obviously have something wrong.

... because of the design you're trying to force. If instead MilkMan inherits DeliveryPerson inherits Person then that Milkman parameter doesn't need casting and he just does his delivery thing. And likewise for any DeliveryPerson subclass.

Separate Accounting functionality

The milkman delivers the milk and then uses the payment process to collect.
Consider making CustomerPayment a separate class - this is what you are really after I suspect. First, as its own class we are more explicitly modeling this particular accounting process. Second, if the DeliveryPerson has some kind of account, or ledger, or sales book or... then the CustomerPayment process (class) merely uses that.

Or maybe each customer has a separate account; but still the CustomerPayment class uses that. Maybe both - it updates the delivery person's sales and the customer account.

I'm imagining that the DeliveryPerson has a reference to the CustomerPayment class (i.e. the milkman is holding a hand-held device to process the customers order). And the milkman presses buttons on the hand-held (calls CustomerPayment methods) to process the order.

Other Points

Milkman violates the single responsibility principle. He has no business having account processing implementation.

That you're duplicating this accounting behavior is a code smell, and it stinks far more than interface separation issues.

The undesirable coupling you should worry about is with the user interface and database. This is coupling that prevents unit testing.

Good separation of class responsibilities, primarily, should allow your unit test setup to easily build any composite objects. Then mocking becomes less of an issue.

Interface-segregation principle does not say "favor lots of itty-bitty interfaces over inheritance." I'll be the first to say that unit testing helps refine my design but for crying out loud, dear reader - design first.

Other thoughts on the over-use of interfaces

Title: Implementation Coupling