问:
Tomcat + Spring + CI workflow
We're starting our very first project with Spring and java web stack. This project will be mainly about rewriting quite large ERP/CRM from Zend Framework to Java. Important factor in my question is that I come from php territory, where things (in terms of quality) tend to look different than in java world.

Fatcs:

there will be 2-3 developers,

at least one of developers uses Windows, rest uses Linux,

there is one remote linux-based machine, which should handle test and production instances,

after struggling with buggy legacy code, we want to introduce good programming and development practices (CI, tests, clean code and so on)

client: internal, frequent business logic changes,

scrum, daily deployments

What I want to achieve is good workflow on as many development stages as possible (coding -> commiting -> testing -> deploying). The problem is that I've never done this before, so I don't know what are best practices to do this.

What I have so far is:

developers code locally,

there is vagrant instance on every development machine, managed by puppet. It contains the same linux, jenkins and tomcat versions as production machine,

while coding, developer deploys to vagrant machine,

after local merge to test branch, jenkins on vagrant handles tests,

when everything is fine, developer pushes commits and merges

jenkins on remote machine pulls commit from test branch, runs tests and so on,

if everything looks green, jenkins deploys to test tomcat instance

Deployment to production is manual (altough it can be done using helping scripts) when business logic is tested by other divisions and everything looks fine to client.

Now, the real question: does above make any sense? Things that I'm not sure about:

Remote machine: won't there be any problems with two (or even three, as jenkins might need one) instances of same app on tomcat?

Using vagrant to develop on php environment is just vise. Isn't this overkill while using Tomcat? I mean, is there higher probability that tomcat will act the same on every machine?

Is there sense of having local jenkins on vagrant?

答:
Welcome to the world of CI! (may I suggest this book? It really helped me get my head around all of this CI practice)

Remote machine: won't there be any problems with two (or even three, as jenkins might need one) instances of same app on tomcat?

In my experience: Yes. But I'm sure they're caused by my own lack of knowledge/experience. My testing environment is a crappy old pc and system resources are scarce. I've automated almost all steps from git push to app deployment but every once in a while some .jar doesn't get released by Tomcat, and I get out of memory errors from my builds on Jenkins. (I've already been here, here, here, here and even here).
You might probably have to configure your Jenkins project in such a way that it should undeploy the current app running on Tomcat, restart Tomcat, build the new one and deploy that new build.

Using vagrant to develop on php environment is just vise. Isn't this overkill while using Tomcat? I mean, is there higher probability that tomcat will act the same on every machine?

After reading the book I mentioned, it seems that the best case scenario would be that every developer should run jenkins and tomcat on their machines, build and deploy only with their changes there (after passing the tests, of course) and then push the changes to the common repository where tests are going to be run again along with the changes of everyone else and the app is going to be built and deployed on production/testing. I can't think of any case where an app would run on a tomcat instance in one machine and crash on another but then again remember my lack of knowledge.

Title: Tomcat + Spring + CI workflow


问:
Can unit tests verify software requirements?
I have often heard unit tests help programmers build confidence in their software.  But is it enough for verifying that software requirements are met?  I am losing confidence that software is working just because the unit tests pass.

We have experienced some failures in production deployment due to an untested\unverified execution path.  These failures are sometimes quite large, impact business operations and often requires an immediate fix.

The failure is very rarely traced back to a failing unit test.  We have large unit test bodies that have reasonable line coverage but almost all of these focus on individual classes and not on their interactions.

Manual testing seems to be ineffective because the software being worked on is typically large with many execution paths and many integration points with other software.  It is very painful to manually test all of the functionality and it never seems to flush out all the bugs.

Are we doing unit testing wrong when it seems we still are failing to verify the software correctly before deployment?  Or do most shops have another layer of automated testing in addition to unit tests?

答:
The phase "unit test" began as a description of testing individual functions and
other small bits of code / capabilities. If that is all you are testing--bits of
your system, in isolation from one another--it is no wonder that you are losing
confidence in your tests to be a fair measure of overall code quality or "does
it do what it's supposed to do?"

Very narrow testing helps a little, but just a little. It's great that you
aren't getting production failures that trace back to things that have been
tested. The problem seems to be the white space in between--the untested
execution paths, the combination of elements that happens when all of the parts
come together that are not currently tested. Without being too Pollyannaish,
there is your problem. Or a good part of it, at any rate.

This is perhaps heresy, but it's worked well for me: Unit tests are no longer
about isolated, narrow units. They are a general purpose automated testing
facility that can and should test not only individual functions, classes, and
objects, but combinations of them, at varying levels of composition.

I may be running PHPUnit or py.test or whatever the local "unit test"
framework is, but I eagerly add tests up to and including tests of the entire
integrated application or service. I run complex examples of the entire app
functionality, and do so not just against simple data cases, but also against
some gnarly, ugly, complex edge-cases.

It isn't as easy to test that way. It requires creating some
mock objects, and/or building entire
virtual machines and populating them with servers, data sets, and other glue
logic just to run the tests. It's more work to set up that test scenario, but
with virtualization and cloud instances, tools like
Fabric and Vagrant make
it doable in ways that it just wasn't, five or so years back.

It can even be complicated to determine if a test succeeded or failed. If you're
used to testing small functions, it's hard to see why--but start trying to judge
whether you've properly manipulated a complex data structure and it becomes more
clear. It can be even worse if you're trying to see a particular path through a
GUI or web app to ensure it "did what it's supposed to do." But with modern
tools, it is possible--and the results are extremely helpful at exercising the
whole system.

Testing can never be a proof of correctness under all possible conditions. But
exercising your app or service as a whole, with complex and edge/corner case
examples designed to stress your logic...first it will show you where a lot of
your bugs lie. ("The truth will set you free — but first it will make you
miserable.")

But as you fix those and your system is executing hard cases successfully and
routinely, then your confidence in its correctness and robustness will grow.
As you find new bugs and fix them, you will add tests for them, and other cases
like them you hadn't previously considered. On subsequent passes at the testing
job, you'll find new things you want to test, or new variants you want to test
against. You add them in, and next run, you're testing even more of the total
system.

If anyone wants to argue that I'm not really unit testing--that I'm doing some
form of integration, module, or system testing--well whatever! I use the same
(unit testing) frameworks, test runners, "did it pass?" reporting that I would
for testing a 2-line function. If you want to give fancier names for some of the
tests, knock yourself out. What I care about is that the tests are automated,
that I can run them easily for every software build, and that they test as much
of the total functionality as possible.

Long story short, instead of losing faith in testing, double down on it. Do the
testing that you need, but aren't currently doing. Test things together, in ever
more challenging and complete combinations, against ever more execution
environments. You'll be amazed at the bugs that shake out, and at how much you
learn about your system interactions as a result. Untimately, you'll be amazed
at how you move with confidence from version to version, because your shakedown
has been real and systematic.

ContentLicense: CC BY-SA 3.0


问:
Why does void in C mean not void?
In strongly-typed languages like Java and C#, void (or Void) as a return type for a method seem to mean:

This method doesn't return anything. Nothing. No return. You will not receive anything from this method.

What's really strange is that in C, void as a return type or even as a method parameter type means:

It could really be anything. You'd have to read the source code to find out.  Good luck. If it's a pointer, you should really know what you're doing.

Consider the following examples in C:

```<code>void describe(void *thing)
{
    Object *obj = thing;
    printf("%s.\n", obj->description);
}

void *move(void *location, Direction direction)
{
    void *next = NULL;

    // logic!

    return next;
}
</code>```

Obviously, the second method returns a pointer, which by definition could be anything.

Since C is older than Java and C#, why did these languages adopt void as meaning "nothing" while C used it as "nothing or anything (when a pointer)"?

答:
Let's tighten up the terminology a bit.

From the online C 2011 standard:

6.2.5 Types

...

19 The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

...

6.3 Conversions

...

6.3.2.2 void

1 The (nonexistent) value of a void expression (an expression that has type void) shall not
be used in any way, and implicit or explicit conversions (except to void) shall not be
applied to such an expression. If an expression of any other type is evaluated as a void
expression, its value or designator is discarded. (A void expression is evaluated for its
side effects.)

6.3.2.3 Pointers

1 A pointer to void may be converted to or from a pointer to any object type. A pointer to
any object type may be converted to a pointer to void and back again; the result shall
compare equal to the original pointer.

A void expression has no value (although it may have side effects).  If I have a function defined to return void, like so:

```<code>void foo( void ) { ... }
</code>```

then the call

```<code>foo();
</code>```

doesn't evaluate to a value; I can't assign the result to anything, because there is no result.

A pointer to void is essentially a "generic" pointer type; you can assign a value of void * to any other object pointer type without needing an explicit cast (which is why all the C programmers will yell at you for casting the result of malloc).

You cannot directly dereference a void *; you must first assign it to a different object pointer type before you can access the pointed-to object.

void pointers are used to implement (more-or-less) generic interfaces; the canonical example is the qsort library function, which can sort arrays of any type, as long as you provide a type-aware comparison function.

Yes, using the same keyword for two different concepts (no value vs. generic pointer) is confusing, but it's not like there isn't precedent; static has multiple distinct meanings in both C and C++.

Title: Why does void in C mean not void?

Body:
Let's tighten up the terminology a bit.

From the online C 2011 standard:

6.2.5 Types

...

19 The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

...

6.3 Conversions

...

6.3.2.2 void

1 The (nonexistent) value of a void expression (an expression that has type void) shall not
be used in any way, and implicit or explicit conversions (except to void) shall not be
applied to such an expression. If an expression of any other type is evaluated as a void
expression, its value or designator is discarded. (A void expression is evaluated for its
side effects.)

6.3.2.3 Pointers

1 A pointer to void may be converted to or from a pointer to any object type. A pointer to
any object type may be converted to a pointer to void and back again; the result shall
compare equal to the original pointer.

A void expression has no value (although it may have side effects).  If I have a function defined to return void, like so:

void foo( void ) { ... }

then the call

foo();

doesn't evaluate to a value; I can't assign the result to anything, because there is no result.

A pointer to void is essentially a "generic" pointer type; you can assign a value of void * to any other object pointer type without needing an explicit cast (which is why all the C programmers will yell at you for casting the result of malloc).

You cannot directly dereference a void *; you must first assign it to a different object pointer type before you can access the pointed-to object.

void pointers are used to implement (more-or-less) generic interfaces; the canonical example is the qsort library function, which can sort arrays of any type, as long as you provide a type-aware comparison function.

Yes, using the same keyword for two different concepts (no value vs. generic pointer) is confusing, but it's not like there isn't precedent; static has multiple distinct meanings in both C and C++.


答:
Indeed, as you have found, unit tests are frequently inadequate for this.

What you need is integrated testing that will look to test:

dependencies

interactions

different viewing devices / platforms / versions

You may also need to revisit unit tests and review how much sad path (as opposed to happy path) is currently being tested.  Developers frequently focus on the happy path but often do not anticipate or take the time to cover complex cases and all the sad paths.

Title: Can unit tests verify software requirements?

Body:
I have often heard unit tests help programmers build confidence in their software.  But is it enough for verifying that software requirements are met?  I am losing confidence that software is working just because the unit tests pass.

We have experienced some failures in production deployment due to an untested\unverified execution path.  These failures are sometimes quite large, impact business operations and often requires an immediate fix.

The failure is very rarely traced back to a failing unit test.  We have large unit test bodies that have reasonable line coverage but almost all of these focus on individual classes and not on their interactions.

Manual testing seems to be ineffective because the software being worked on is typically large with many execution paths and many integration points with other software.  It is very painful to manually test all of the functionality and it never seems to flush out all the bugs.

Are we doing unit testing wrong when it seems we still are failing to verify the software correctly before deployment?  Or do most shops have another layer of automated testing in addition to unit tests?


答:
Simply put, there is no difference. Let me give you some examples.

Say I have an class called Car.

```<code>Car obj = anotherCar; // obj is now of type Car
Car* obj = new Car(); // obj is now a pointer of type Car
void obj = 0; // obj has no type
void* = new Car(); // obj is a pointer with no type
</code>```

I believe here the confusion here is based off how you would define void vs void*. A return-type of void means "I return nothing", while a return type of void* means "I return a pointer of type nothing".

This is due to the fact that a pointer is a special case. A pointer object will always point to a location in memory, whether there's a valid object there or not. Whether my void* car references a byte, a word, a Car, or a bicycle doesn't matter because my void* points to something with no defined type. It's up to us to later on define it.

In languages such as C# and Java, memory is managed and the concept of pointers is rolled over into the Object class. Instead of having a reference to an object of type "nothing" we know that at the very least our object is of type "Object". Let me explain why.

In conventional C/C++ if you create an object and delete its pointer, then it's impossible to get access to that object. This is what's known as a memory leak.

In C#/Java, everything is an object and this enables the runtime to keep track of every object. It doesn't necessarily need to know that my object is a Car, it simply needs to know some basic information that is already taken care of by the Object class.

For us programmers, that means that much of the information we would have to manually take care of in C/C++ is taken care of for us by the Object class, removing the need for the special case that is the pointer.

Title: Why does void in C mean not void?

Body:
In strongly-typed languages like Java and C#, void (or Void) as a return type for a method seem to mean:

This method doesn't return anything. Nothing. No return. You will not receive anything from this method.

What's really strange is that in C, void as a return type or even as a method parameter type means:

It could really be anything. You'd have to read the source code to find out.  Good luck. If it's a pointer, you should really know what you're doing.

Consider the following examples in C:

```<code>void describe(void *thing)
{
    Object *obj = thing;
    printf("%s.\n", obj->description);
}

void *move(void *location, Direction direction)
{
    void *next = NULL;

    // logic!

    return next;
}
</code>```

Obviously, the second method returns a pointer, which by definition could be anything.

Since C is older than Java and C#, why did these languages adopt void as meaning "nothing" while C used it as "nothing or anything (when a pointer)"?

Body:
Simply put, there is no difference. Let me give you some examples.

Say I have an class called Car.

Car obj = anotherCar; // obj is now of type Car
Car* obj = new Car(); // obj is now a pointer of type Car
void obj = 0; // obj has no type
void* = new Car(); // obj is a pointer with no type

I believe here the confusion here is based off how you would define void vs void*. A return-type of void means "I return nothing", while a return type of void* means "I return a pointer of type nothing".

This is due to the fact that a pointer is a special case. A pointer object will always point to a location in memory, whether there's a valid object there or not. Whether my void* car references a byte, a word, a Car, or a bicycle doesn't matter because my void* points to something with no defined type. It's up to us to later on define it.

In languages such as C# and Java, memory is managed and the concept of pointers is rolled over into the Object class. Instead of having a reference to an object of type "nothing" we know that at the very least our object is of type "Object". Let me explain why.

In conventional C/C++ if you create an object and delete its pointer, then it's impossible to get access to that object. This is what's known as a memory leak.

In C#/Java, everything is an object and this enables the runtime to keep track of every object. It doesn't necessarily need to know that my object is a Car, it simply needs to know some basic information that is already taken care of by the Object class.

For us programmers, that means that much of the information we would have to manually take care of in C/C++ is taken care of for us by the Object class, removing the need for the special case that is the pointer.


答:
```<code>void describe(void *thing);
void *move(void *location, Direction direction);
</code>```

The first function returns nothing. The second function returns a void pointer. I would have declared that second function as

```<code>void* move(void* location, Direction direction);
</code>```

If might help if you think of "void" as meaning "without meaning". The return value of describe is "without meaning". Returning a value from such a function is illegal because you told the compiler that the return value is without meaning. You can't capture the return value from that function because it is without meaning.  You can't declare a variable of type void because it is without meaning. For example void nonsense; is nonsense and is in fact illegal. Also note that an array of void void void_array[42]; is also nonsense.

A pointer to void (void*) is something different. It is a pointer, not an array. Read void* as meaning a pointer that points to something "without meaning". The pointer is "without meaning", which means it doesn't make sense to dereference such a pointer. Trying to do so is in fact illegal. Code that dereferences a void pointer won't compile.

So if you can't dereference a void pointer, and you can't make an array of voids, how can you use them? The answer is that a pointer to any type can be cast to and from void*. Casting some pointer to void* and casting back to a pointer to the original type will yield a value equal to the original pointer. The C standard guarantees this behavior. The primary reason you see so many void pointers in C is that this capability provides a way to implement information hiding and object-based programming in what is very much a non-object oriented language.

Finally, the reason you often see move declared as void *move(...) rather than void* move(...) is because putting the asterisk next to the name rather than the type is a very common practice in C. The reason is that the following declaration will get you in big trouble: int* iptr, jptr; This would make you think you are declaring two pointers to an int. You are not. This declaration makes jptr an int rather than a pointer to an int. The proper declaration is int *iptr, *jptr; You can pretend the asterisk belongs with the type if you stick to the practice of only declaring one variable per declaration statement. But keep in mind that you are pretending.

Title: Why does void in C mean not void?

Body:
void describe(void *thing);
void *move(void *location, Direction direction);

The first function returns nothing. The second function returns a void pointer. I would have declared that second function as

void* move(void* location, Direction direction);

If might help if you think of "void" as meaning "without meaning". The return value of describe is "without meaning". Returning a value from such a function is illegal because you told the compiler that the return value is without meaning. You can't capture the return value from that function because it is without meaning.  You can't declare a variable of type void because it is without meaning. For example void nonsense; is nonsense and is in fact illegal. Also note that an array of void void void_array[42]; is also nonsense.

A pointer to void (void*) is something different. It is a pointer, not an array. Read void* as meaning a pointer that points to something "without meaning". The pointer is "without meaning", which means it doesn't make sense to dereference such a pointer. Trying to do so is in fact illegal. Code that dereferences a void pointer won't compile.

So if you can't dereference a void pointer, and you can't make an array of voids, how can you use them? The answer is that a pointer to any type can be cast to and from void*. Casting some pointer to void* and casting back to a pointer to the original type will yield a value equal to the original pointer. The C standard guarantees this behavior. The primary reason you see so many void pointers in C is that this capability provides a way to implement information hiding and object-based programming in what is very much a non-object oriented language.

Finally, the reason you often see move declared as void *move(...) rather than void* move(...) is because putting the asterisk next to the name rather than the type is a very common practice in C. The reason is that the following declaration will get you in big trouble: int* iptr, jptr; This would make you think you are declaring two pointers to an int. You are not. This declaration makes jptr an int rather than a pointer to an int. The proper declaration is int *iptr, *jptr; You can pretend the asterisk belongs with the type if you stick to the practice of only declaring one variable per declaration statement. But keep in mind that you are pretending.


问:
If your workmate is quitting his job, would you notify your boss?
If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>

答:
Perhaps if you were in his position, you might do the same thing.

You know only his stated intention, which is to leave, not the reasons behind it.

Gambling, parents sick, sexual abuse, drug problem, new job offer, bundle of documents destined for a brown cardboard box in the back of some Swedish hideaway,  you just don't know.

Now, we have a handy term that means you don't have to be in his situation to see things from his point of view.

Empathy.

This is a life question, not programming, and the thing about life is that you will be the one up, and eventually, the one down.

How did he look when he told you?  Like he wanted to say more?  We got it down to one phrase, and although casual it can mean the world to someone:

"Y'aight?"

Like I said, one day you'll be the one down, regardless of his situation.  When you are, you might remember the day you went a little out of your way to show a little empathy and feel better a little better at that time.  Just a thought.

ContentLicense: CC BY-SA 2.5


答:
I'll try to say how one could think of these things in C. The official language in the C standard is not really at ease with void, and I won't try to be entirely consistent with it.

The type void is not a first class citizen among the types. Although it is an  object type, it cannot be the type of any object (or value), of a field, or of a function parameter; however it can be the return type of a function, and thereby be the type of an expression (basically of calls of such functions, but expressions formed with the conditional operator can also have void type). But even the minimal use of void as a value type that the above leaves the door open for, namely ending a function returning void with a statement of the form return E; where E is an expression of type void, is explicitly forbidden in C (it is allowed in C++ though, but for reasons not applicable to C).

If objects of type void were allowed, they would have 0 bits (that is the amount of information in the value of an expression of void type); it would not be a major problem allowing such objects, but they would be rather useless (objects of size 0 would give some difficulty with defining pointer arithmetic, which would maybe best just be forbidden). The set of different values such an object would have one (trivial) element; its value could be taken, trivially because it does not have any substance, but it cannot be modified (lacking any different value). The standard is therefore confused in saying void comprises an empty set of values; such a type could be useful to describe expressions that cannot be evaluated (such as jumps or non-terminating calls) although the C language does not actually employ such a type.

Being disallowed as value type, void has been used in at least two not directly related ways to designate "forbidden": specifying (void) as parameter specification in function types means providing any arguments to them is forbidden (while '()' would to the contrary mean everything is allowed; and yes, even providing a void expression as argument to functions with (void) parameter specification is forbidden), and declaring void *p means that the dereferencing expression *p is forbidden (but not that it is a valid expression of type void). So you are right that these uses of void are not really consistent with void as a valid type of expressions. However an object of type void* is not really a pointer to values of any type, it means a value that is treated as a pointer although it cannot be dereferenced and pointer arithmetic with it is forbidden. The "treated as a pointer" then really only means it can be cast from and to any pointer type without loss of information. However it can also be used to cast integer values to and from, so it does not have to point to anything at all.

Title: Why does void in C mean not void?


问:
Creating New Scripts Dynamically in Lua
Right now this is just a crazy idea that I had, but I was able to implement the code and get it working properly. I am not entirely sure of what the use cases would be just yet.

What this code does is create a new Lua script file in the project directory.  The ScriptWriter takes as arguments the file name, a table containing any arguments that the script should take when created, and a table containing any instance variables to create by default.  My plan is to extend this code to create new functions based on inputs sent in during its creation as well.

What makes this cool is that the new file is both generated and loaded dynamically on the fly.  Theoretically you could get this code to generate and load any script imaginable.  One use case I can think of is an AI that creates scripts to map out it's functions, and creates new scripts for new situations or environments.  At this point, this is all theoretical, though.

Here is the test code that is creating the new script and then immediately loading it and calling functions from it:

```<code>function Card:doScriptWriterThing()
    local scriptName = "ScriptIAmMaking"

    local scripter = scriptWriter:new(scriptName, {"argumentName"}, {name = "'test'", one = 1})
    scripter:makeFileForLoadedSettings()

    local loadedScript = require (scriptName)
    local scriptInstance = loadedScript:new("sayThis")
    print(scriptInstance:get_name()) --will print test
    print(scriptInstance:get_one()) -- will print 1
    scriptInstance:set_one(10000)
    print(scriptInstance:get_one()) -- will print 10000
    print(scriptInstance:get_argumentName()) -- will print sayThis
    scriptInstance:set_argumentName("saySomethingElse")
    print(scriptInstance:get_argumentName()) --will print saySomethingElse
end
</code>```

Here is ScriptWriter.lua

```<code>local ScriptWriter = {}

local twoSpaceIndent = "  "
local equalsWithSpaces = " = "
local newLine = "\n"

--scriptNameToCreate must be a string
--argumentsForNew and instanceVariablesToCreate must be tables and not nil
function ScriptWriter:new(scriptNameToCreate, argumentsForNew, instanceVariablesToCreate)

    local instance = setmetatable({}, { __index = self })

    instance.name = scriptNameToCreate
    instance.newArguments = argumentsForNew
    instance.instanceVariables = instanceVariablesToCreate
    instance.stringList = {}

    return instance
end
function ScriptWriter:makeFileForLoadedSettings()
    self:buildInstanceMetatable()
    self:buildInstanceCreationMethod()
    self:buildSettersAndGetters()
    self:buildReturn()
    self:writeStringsToFile()
end

--very first line of any script that will have instances
function ScriptWriter:buildInstanceMetatable()
    table.insert(self.stringList, "local " .. self.name .. " = {}" .. newLine)
    table.insert(self.stringList, newLine)
end

--every script made this way needs a new method to create its instances
function ScriptWriter:buildInstanceCreationMethod()
    --new() function declaration
    table.insert(self.stringList, ("function " .. self.name .. ":new("))
    self:buildNewArguments()
    table.insert(self.stringList, ")" .. newLine)

    --first line inside :new() function
    table.insert(self.stringList, twoSpaceIndent .. "local instance = setmetatable({}, { __index = self })" .. newLine)

    --add designated arguments inside :new()
    self:buildNewArgumentVariables()

    --create the instance variables with the loaded values
    for key,value in pairs(self.instanceVariables) do
      table.insert(self.stringList, twoSpaceIndent .. "instance." .. key .. equalsWithSpaces .. value .. newLine)
    end

    --close the :new() function
    table.insert(self.stringList, twoSpaceIndent .. "return instance" .. newLine)
    table.insert(self.stringList, "end" .. newLine)
    table.insert(self.stringList, newLine)
end
function ScriptWriter:buildNewArguments()
     --if there are arguments for :new(), add them
    for key,value in ipairs(self.newArguments) do
      table.insert(self.stringList, value)
      table.insert(self.stringList, ", ")
    end
    if next(self.newArguments) ~= nil then --makes sure the table is not empty first
      table.remove(self.stringList) --remove the very last element, which will be the extra ", "
    end
end
function ScriptWriter:buildNewArgumentVariables()
    --add the designated arguments to :new()
    for key, value in ipairs(self.newArguments) do
      table.insert(self.stringList, twoSpaceIndent .. "instance." .. value .. equalsWithSpaces .. value .. newLine)
    end
end

--the instance variables need separate code because their names have to be the key and not the argument name
function ScriptWriter:buildSettersAndGetters()
    for key,value in ipairs(self.newArguments) do
        self:buildArgumentSetter(value)
        self:buildArgumentGetter(value)
        table.insert(self.stringList, newLine)
    end
    for key,value in pairs(self.instanceVariables) do
        self:buildInstanceVariableSetter(key, value)
        self:buildInstanceVariableGetter(key, value)
        table.insert(self.stringList, newLine)
    end
end
--code for arguments passed in
function ScriptWriter:buildArgumentSetter(variable)
    table.insert(self.stringList, "function " .. self.name .. ":set_" .. variable .. "(newValue)" .. newLine)
    table.insert(self.stringList, twoSpaceIndent .. "self." .. variable .. equalsWithSpaces ..  "newValue" .. newLine)
    table.insert(self.stringList, "end" .. newLine)
end
function ScriptWriter:buildArgumentGetter(variable)
    table.insert(self.stringList, "function " .. self.name .. ":get_" .. variable .. "()" .. newLine)
    table.insert(self.stringList, twoSpaceIndent .. "return " .. "self." .. variable .. newLine)
    table.insert(self.stringList, "end" .. newLine)
end
--code for instance variable values passed in
function ScriptWriter:buildInstanceVariableSetter(key, variable)
    table.insert(self.stringList, "function " .. self.name .. ":set_" .. key .. "(newValue)" .. newLine)
    table.insert(self.stringList, twoSpaceIndent .. "self." .. key .. equalsWithSpaces .. "newValue" .. newLine)
    table.insert(self.stringList, "end" .. newLine)
end
function ScriptWriter:buildInstanceVariableGetter(key, variable)
    table.insert(self.stringList, "function " .. self.name .. ":get_" .. key .. "()" .. newLine)
    table.insert(self.stringList, twoSpaceIndent .. "return " .. "self." .. key .. newLine)
    table.insert(self.stringList, "end" .. newLine)
end

--last line of any script that will have instances
function ScriptWriter:buildReturn()
    table.insert(self.stringList, "return " .. self.name)
end

function ScriptWriter:writeStringsToFile()
    local fileName = (self.name .. ".lua")
    file = io.open(fileName, 'w')
    for key,value in ipairs(self.stringList) do
      file:write(value)
    end
    file:close()
end

return ScriptWriter
</code>```

And here is what the code provided will generate:

```<code>local ScriptIAmMaking = {}

function ScriptIAmMaking:new(argumentName)
    local instance = setmetatable({}, { __index = self })
    instance.argumentName = argumentName
    instance.name = 'test'
    instance.one = 1
    return instance
end

function ScriptIAmMaking:set_argumentName(newValue)
    self.argumentName = newValue
end
function ScriptIAmMaking:get_argumentName()
    return self.argumentName
end

function ScriptIAmMaking:set_name(newValue)
    self.name = newValue
end
function ScriptIAmMaking:get_name()
    return self.name
end

function ScriptIAmMaking:set_one(newValue)
    self.one = newValue
end
function ScriptIAmMaking:get_one()
    return self.one
end

return ScriptIAmMaking
</code>```

All of this is generated with these calls:

```<code>local scripter = scriptWriter:new(scriptName, {"argumentName"}, {name = "'test'", one = 1})
scripter:makeFileForLoadedSettings()
</code>```

I am not sure if I am correct that this could be useful in certain situations.  What I am looking for is feedback on the readability of the code, and following Lua best practices.  I would also love to hear whether this approach is a valid one, and whether the way that I have done things will be extensible.

答:
Why you don't need to generate code

What you are doing here is interesting as a learning exercise. Certainly there are worse ways to learn a language than by generating code in the language, with the language. Outside of that, there may not be many practical applications for generated code in a highly flexible, dynamic language like Lua. Anything you can do with generated code, you can probably do without generating code, in a cleaner and more straightforward way.

When you think of languages where generated code is common, what languages do you think of? Probably classical, strongly-typed languages like Java, C#, and so on. Classes may be generated from a UML model, from a WSDL, or from a wizard in an IDE. It can be useful to generate code for these languages; for example in the case of a WSDL, because you want to have classes that provide the described API, and you want them to just work... you don't want to do the lower-level work of dealing with HTTP traffic and so on, you just want to be able to call the methods provided by the service in a straightforward way.

In languages like that, a lot of work happens at build time. It would be inconvenient or impossible to dynamically build these classes at run time. This is why code generation is necessary. In dynamic languages like Lua, it's a different ballgame. For example, you could easily have a Lua script consume a WSDL and create a bunch of class-like-things on the fly.

A good real-world example of this is the clients that have been written for services implementing the Swagger protocol (essentially, Swagger brings to REST what WSDL is to SOAP). If you look at the canonical Java client, you will see that it generates code from the resource description, to be compiled into your project. If you look at the JavaScript client, you will see that it dynamically generates objects and methods to interface with the service on the fly, because it can. There is no need for generating code (in this scenario, at least) in a dynamic language like JavaScript. The same thing applies to Lua.

What you can do instead

Let's see how we can achieve your goal without generating any code. Breaking the problem down, we need to take some inputs -- the name of a "class," the name of some parameters for the "constructor," and some property names, with initial values, and a getter and setter for each.

Now, let's plan to write a function that can do this. The function will return a value representing the "class." We will store that value in a named variable, so that can be the name of the class; there is no need to pass the name in. So we are left with "constructor" parameters, properties, and getters/setters.

```<code>local function createClass(parameters, properties)
  local class = {}

  function class:new(...)
    local instance = setmetatable({}, { __index = self })
    local arguments = {...}

    for i, param in ipairs(parameters) do
        instance[param] = arguments[i]
    end

    return instance
  end

  for name, value in pairs(properties) do
      class[name] = value
      class['set_' .. name] = function(self, value)
        self[name] = value
      end
      class['get_' .. name] = function(self)
        return self[name]
      end
  end

  return class
end
</code>```

Now you can simply do this to get the ScriptIAmMaking from your example, on the fly, without needing to generate any code:

```<code>ScriptIAmMaking = createClass({"argumentName"}, {name = "'test'", one = 1})
</code>```

Now, generating class-like-things in such a manner may or may not be useful, but the point is that it can be done in a simpler, more concise way, and without generating any code.

OwnerDisplayName: bazola

Title: Creating New Scripts Dynamically in Lua

Body:
Why you don't need to generate code

What you are doing here is interesting as a learning exercise. Certainly there are worse ways to learn a language than by generating code in the language, with the language. Outside of that, there may not be many practical applications for generated code in a highly flexible, dynamic language like Lua. Anything you can do with generated code, you can probably do without generating code, in a cleaner and more straightforward way.

When you think of languages where generated code is common, what languages do you think of? Probably classical, strongly-typed languages like Java, C#, and so on. Classes may be generated from a UML model, from a WSDL, or from a wizard in an IDE. It can be useful to generate code for these languages; for example in the case of a WSDL, because you want to have classes that provide the described API, and you want them to just work... you don't want to do the lower-level work of dealing with HTTP traffic and so on, you just want to be able to call the methods provided by the service in a straightforward way.

In languages like that, a lot of work happens at build time. It would be inconvenient or impossible to dynamically build these classes at run time. This is why code generation is necessary. In dynamic languages like Lua, it's a different ballgame. For example, you could easily have a Lua script consume a WSDL and create a bunch of class-like-things on the fly.

A good real-world example of this is the clients that have been written for services implementing the Swagger protocol (essentially, Swagger brings to REST what WSDL is to SOAP). If you look at the canonical Java client, you will see that it generates code from the resource description, to be compiled into your project. If you look at the JavaScript client, you will see that it dynamically generates objects and methods to interface with the service on the fly, because it can. There is no need for generating code (in this scenario, at least) in a dynamic language like JavaScript. The same thing applies to Lua.

What you can do instead

Let's see how we can achieve your goal without generating any code. Breaking the problem down, we need to take some inputs -- the name of a "class," the name of some parameters for the "constructor," and some property names, with initial values, and a getter and setter for each.

Now, let's plan to write a function that can do this. The function will return a value representing the "class." We will store that value in a named variable, so that can be the name of the class; there is no need to pass the name in. So we are left with "constructor" parameters, properties, and getters/setters.

local function createClass(parameters, properties)
  local class = {}

  function class:new(...)
    local instance = setmetatable({}, { __index = self })
    local arguments = {...}

    for i, param in ipairs(parameters) do
        instance[param] = arguments[i]
    end

    return instance
  end

  for name, value in pairs(properties) do
      class[name] = value
      class['set_' .. name] = function(self, value)
        self[name] = value
      end
      class['get_' .. name] = function(self)
        return self[name]
      end
  end

  return class
end

Now you can simply do this to get the ScriptIAmMaking from your example, on the fly, without needing to generate any code:

ScriptIAmMaking = createClass({"argumentName"}, {name = "'test'", one = 1})

Now, generating class-like-things in such a manner may or may not be useful, but the point is that it can be done in a simpler, more concise way, and without generating any code.

OwnerDisplayName: Hey


问:
Do first-class methods exist?
Okay, I know first-class functions are cool, closures even better, etc. But is there any language with first-class methods?

In my mind, I see a first-class method as an "object" that has both a function pointer and a pointer to a specific instance of the class/object, but the implementation doesn't matter. I just want to know if there is any language that uses them.

And as a bonus, how were they implemented?

答:
In typical OO parlance, methods belong to objects. If methods were themselves objects, then these objects would of course have methods. But those are objects, too, so they have methods. Which are objects which have methods which are objects which have methods which are objects which have methods …

There are ways to deal with this sort of recursion, but the usual way to deal with this problem is to not have methods be first-class.

In Ruby, for example, there are reflective methods that give you proxy objects for methods (those proxy objects are of class Method), but those aren't the methods themselves, they are only proxies that represent the methods.

However, in Self, objects don't have methods, they only have slots (fields in Java-lingo, instance variables in Ruby). Sending a message to an object does not invoke a method, it activates a slot. Slots can be either passive or active. Passive slots simply return the object referenced by them, active slots run the object referenced by them. So, methods are actual first-class objects which simply get assigned to active slots. (If you have used ECMAScript, you might recognize its Self heritage here. ECMAScript doesn't distinguish between passive and active slots, though, instead it uses special syntax for executing the object returned by the property.)

Title: Do first-class methods exist?


答:
Definitely not.

News Flash: Programmers typically find the best jobs by networking.

My Advice: Do not kill your relationship with this colleague.

If you keep a good relationship with
this colleague, he/she can be a
source of information and a reference
going forward.

If you develop a bad
relationship with this colleague,
he/she could sully your name, and
hurt your chances with a prospective
employer.

Title: If your workmate is quitting his job, would you notify your boss?

Body: If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>


问:
Finding the shortest path through a digraph that visits all nodes
I am trying to find the shortest possible path that visits every node through a graph (a node may be visited more than once, the solution may pick any node as the starting node.). The graph is directed, meaning that being able to travel from node A to node B does not mean one can travel from node B to node A. All distances between nodes are equal. I was able to code a brute force search that found a path of only 27 nodes when I had 27 nodes and each node had a connection to 2 or 1 other node. However, the actual problem that I am trying to solve consists of 256 nodes, with each node connecting to either 4 or 3 other nodes. The brute force algorithm that solved the 27 node graph can produce a 415 node solution (not optimal) within a few seconds, but using the processing power I have at my disposal takes about 6 hours to arrive at a 402 node solution.

What approach should I use to arrive at a solution that I can be certain is the optimal one? For example, use an optimizer algorithm to shorten a non-optimal solution? Or somehow adopt a brute force search that discards paths that are not optimal?

EDIT: (Copying a comment to an answer here to better clarify the question) To clarify, I am not saying that there is a Hamiltonian path and I need to find it, I am trying to find the shortest path in the 256 node graph that visits each node AT LEAST once. With the 27 node run, I was able to find a Hamiltonian path, which assured me that it was an optimal solution. I want to find a solution for the 256 node graph which is the shortest.

答:
From your description this seems to be a shortest path problem for a strongly connected directed graph. I'm not entirely sure whether you actually want a single-pair solution or an all-pair solution.

If the latter, it seems the Floyd-Warshall algorithm will do the job, with a complexity of O(n^3). Otherwise look here: http://en.wikipedia.org/wiki/Shortest_path_problem.


答:
C++11 lambdas:

struct Foo{
    int bar(){
        return 42;
    }
};

Foo f;
auto methodobject = [&]{ return f.bar(); };
int i = methodobject(); //calls f.bar
```

Lambdas are implemented as regular classes with the captured objects (in this case Foo &f) as members and an auto operator (){/*whatever is in the lambda declaration*/}. With a bit more typing you can create a regular class that does the capturing and calling and you could change the object and method to call at runtime.

Title: Do first-class methods exist?

Body:
Okay, I know first-class functions are cool, closures even better, etc. But is there any language with first-class methods?

In my mind, I see a first-class method as an "object" that has both a function pointer and a pointer to a specific instance of the class/object, but the implementation doesn't matter. I just want to know if there is any language that uses them.

And as a bonus, how were they implemented?

Body:
C++11 lambdas:

struct Foo{
    int bar(){
        return 42;
    }
};

Foo f;
auto methodobject = [&]{ return f.bar(); };
int i = methodobject(); //calls f.bar

Lambdas are implemented as regular classes with the captured objects (in this case Foo &f) as members and an auto operator (){/*whatever is in the lambda declaration*/}. With a bit more typing you can create a regular class that does the capturing and calling and you could change the object and method to call at runtime.


问:
Performing a Depth First Search iteratively using async/parallel processing?
Here is a method that does a DFS search and returns a list of all items given a top level item id. How could I modify this to take advantage of parallel processing? Currently, the call to get the sub items is made one by one for each item in the stack. It would be nice if I could get the sub items for multiple items in the stack at the same time, and populate my return list faster. How could I do this (either using async/await or TPL, or anything else) in a thread safe manner?

```<code>private async Task<IList<Item>> GetItemsAsync(string topItemId)
{
    var items = new List<Item>();
    var topItem = await GetItemAsync(topItemId);

    Stack<Item> stack = new Stack<Item>();
    stack.Push(topItem);
    while (stack.Count > 0)
    {
        var item = stack.Pop();
        items.Add(item);

        var subItems = await GetSubItemsAsync(item.SubId);

        foreach (var subItem in subItems)
        {
            stack.Push(subItem);
        }
    }

    return items;
}
</code>```

I was thinking of something along these lines, but it's not coming together:

```<code>var tasks = stack.Select(async item =>
{
    items.Add(item);
    var subItems = await GetSubItemsAsync(item.SubId);

    foreach (var subItem in subItems)
    {
        stack.Push(subItem);
    }
}).ToList();

if (tasks.Any())
    await Task.WhenAll(tasks);
</code>```

The language I'm using is C#.

答:
It seems to me that, as you retrieve the list of subitems, rather than pushing them on a stack you should process each subitem asynchronously by processing each on its own Task. Only when all Tasks have completed (Task.WhenAll) do you take their results, push them on the stack and return.

Obviously you don't want a million Tasks so perhaps you only do this to a maximum fan out degree and fall back on the stack-based iterative approach beyond that.


答:
Functions in JavaScript are first-class citizens (objects with methods). There are no methods per se, but every function can be invoked as a method on any object. Functions can also be assigned to fields and invoked in c++-like object-oriented syntax.</p>

```<code>var func = function(arg) {
  this.field = arg;
}

func.apply(null, ["value0"]); // 'func' invoked as a free function
// window.field == "value0"

var obj = {};
func.apply(obj, ["value1"]); // 'func' invoked as a method of 'obj'
// obj.field == "value1"

obj.method = func;
obj.method("value2")
// obj.field == "value2"
</code>```

Title: Do first-class methods exist?

Body:
Functions in JavaScript are first-class citizens (objects with methods). There are no methods per se, but every function can be invoked as a method on any object. Functions can also be assigned to fields and invoked in c++-like object-oriented syntax.

var func = function(arg) {
  this.field = arg;
}

func.apply(null, ["value0"]); // 'func' invoked as a free function
// window.field == "value0"

var obj = {};
func.apply(obj, ["value1"]); // 'func' invoked as a method of 'obj'
// obj.field == "value1"

obj.method = func;
obj.method("value2")
// obj.field == "value2"


答:
Yes, in javascript. That's because in javascript methods are functions and functions are full-fledged objects.

Example:

```<code>// Here's a "class" with method foo.
// Note that javascript don't really have classes,
// we use constructors instead:
function FooTeNator () {
    this.text = "foo";
}
FooTeNator.prototype.foo = function () {return this.text}
</code>```

Notice the first interesting thing: methods are merely first class functions assigned to our constructor's prototype.

Regular method call:

```<code>var foomatic = new FooTeNator();
foomatic.foo(); // returns "foo"
</code>```

Redefining a new method after we've created the object:

```<code>var foomatic = new FooTeNator();
foomatic.foo = function () { return "" }
foomatic.foo(); // returns empty string
</code>```

Letting another object borrow our method:

```<code>var foomatic = new FooTeNator();
var other_object = {}; // {} is a plain object in object literal syntax
other_object.text = "bar";
other_object.foo = foomatic.foo;
other_object.foo(); // returns "bar"
</code>```

Letting another object borrow our method from our constructor:

```<code>var other_object = {text : "bar"};
other_object.foo = FooTeNator.prototype.foo;
other_object.foo(); // returns "bar"
</code>```

Calling our method while temporarily re-assigning the value of this inside it to another object:

```<code>var foomatic = new FooTeNator();
var other_object = {text : "bar"};
foomatic.foo.call(other_object); // returns "bar"
</code>```

I think that qualifies as first-class method. Of course, this is merely first-class function. But with regards to OO the function is not a regular function because we reference this in it.

Side Note:

Javascript has a strange concept of this. Even regular functions can reference this outside of objects. When not bound to any object javascript will bind this to the global scope or DOM object or undefined depending on circumstances.

Side, Side Note:

When I said functions are objects in javascript it really means what it means. Functions (hence methods) have a constructor, the Function function. Functions/methods can also themselves have methods:

```<code>// Creating a method using the Function constructor
var my_object = {
    strange_method : new Function('x','return x');
}
// Assigning a method to our method:
my_object.strange_method.sub_method = function () {return 'HA!'};
</code>```

Title: Do first-class methods exist?

Body:
Yes, in javascript. That's because in javascript methods are functions and functions are full-fledged objects.

Example:

// Here's a "class" with method foo.
// Note that javascript don't really have classes,
// we use constructors instead:
function FooTeNator () {
    this.text = "foo";
}
FooTeNator.prototype.foo = function () {return this.text}

Notice the first interesting thing: methods are merely first class functions assigned to our constructor's prototype.

Regular method call:

var foomatic = new FooTeNator();
foomatic.foo(); // returns "foo"

Redefining a new method after we've created the object:

var foomatic = new FooTeNator();
foomatic.foo = function () { return "" }
foomatic.foo(); // returns empty string

Letting another object borrow our method:

var foomatic = new FooTeNator();
var other_object = {}; // {} is a plain object in object literal syntax
other_object.text = "bar";
other_object.foo = foomatic.foo;
other_object.foo(); // returns "bar"

Letting another object borrow our method from our constructor:

var other_object = {text : "bar"};
other_object.foo = FooTeNator.prototype.foo;
other_object.foo(); // returns "bar"

Calling our method while temporarily re-assigning the value of this inside it to another object:

var foomatic = new FooTeNator();
var other_object = {text : "bar"};
foomatic.foo.call(other_object); // returns "bar"

I think that qualifies as first-class method. Of course, this is merely first-class function. But with regards to OO the function is not a regular function because we reference this in it.

Side Note:

Javascript has a strange concept of this. Even regular functions can reference this outside of objects. When not bound to any object javascript will bind this to the global scope or DOM object or undefined depending on circumstances.

Side, Side Note:

When I said functions are objects in javascript it really means what it means. Functions (hence methods) have a constructor, the Function function. Functions/methods can also themselves have methods:

// Creating a method using the Function constructor
var my_object = {
    strange_method : new Function('x','return x');
}
// Assigning a method to our method:
my_object.strange_method.sub_method = function () {return 'HA!'};


答:
In Python, methods are regular fields, but callable. Also they have a self parameter that is explicitly declared, but implicitly passed; though you can invoke any method on the class object, passing an instance explicitly.

class A:
    def __init__(self, val):
        self._val = val
    def fun(self):
        print(self._val)

def invoke(f):
   f()

def invoke_with_param(f, par):
    f(par)

x1 = A(1)
x2 = A(2)

invoke(x1.fun)
invoke(x1.fun)
A.fun(x1)
A.fun(x2)
invoke_with_param(A.fun, x1)
# etc.
```

Title: Do first-class methods exist?


问:
Tokenizing Text Held in a Rope Data Structure
I am building a text editor which makes use of a Ragel based tokenizer to support syntax highlighting.  I am considering the use of a rope data structure to support efficient modifications and undo/redo operations.  Is there a standard approach for tokenizing or searching text contained in this type of data structure?  Some characters can cause the tokenizer to consume the rest of the stream.    </p>

答:
I'm familiar with the underlying state-machine approach described in your link --- it's been around for decades. It can tokenise/categorise any stream of text that supports a get-next-character operation.

I'm familiar with ropes in the context of a text editor. The usual purpose (as I know it) is to break the strings into portions that have the same display attributes: colour, font, link, line breaks etc. This works well for both editing and display. The major operations are: insert character; delete character; delete token; cut and paste. Maintaining the rope is not easy.

It's not obvious from your question whether you expect the tokeniser to generate the rope. Is it a rope of tokens, where each token has its own display attributes? I would be troubled that editing and tokenisation could interfere with each other. Things like quotes and comments can reach a long way.

No, I don't there is a standard way of combining these ideas. I suspect the right idea is for the tokeniser to generate/regenerate the rope, immediately for the on-screen portion and in the background for the rest. Edits should affect the rope (only) with a short delay before retokenising. The tokenising needs to be interruptible too.

It feels like a reasonable approach, but I'm sure there are many challenges in making it work well. You might want to read some source code (Eclipse? Netbeans?) to see how others do it.

OwnerDisplayName: sesteel


问:
Looking for an algorithm to connect dots - shortest route
I have written a program to solve a special puzzle, but now I'm kind of stuck at the following problem:
I have about 3200 points/nodes/dots. Each of these points is connected to a few other points (usually 2-5, theoretical limit is 1-26). I have exactly one starting point and about 30 exit points (probably all of the exit points are connected to each other). Many of these 3200 points are probably not connected to neither start nor end point in any way, like a separate net, but all points are connected to at least one other point.

I need to find the shortest number of hops to go from entry to exit. There is no distance between the points (unlike the road or train routing problem), just the number of hops counts. I need to find all solutions with the shortest number of hops, and not just one solution, but all. And potentially also solutions with one more hop etc.
I expect to have a solution with about 30-50 hops to go from start to exit.

I already tried:

1) randomly trying possibilities and just starting over when the count was bigger than a previous solution. I got first solution with 3500 hops, then it got down to about 97 after some minutes, but looking at the solutions I saw problems like unnecessary loops and stuff, so I tried to optimize a bit (like not going back where it came from etc.). More optimizations are possible, but this random thing doesn't find all best solutions or takes too long.

2) Recursively run through all ways from start (chess-problem-like) and breaking the try when it reached a previous point. This was looping at about a length of 120 nodes, so it tries chains that are (probably) by far too long. If we calculate 4 possibilities and 120 nodes, we're reaching 1.7E72 possibilities, which is not possible to calculate through. This is called Depth-first search (DFS) as I found out in the meantime. Maybe I should try Breadth-first search by adding some queue?

The connections between the points are actually moves you can make in the game and the points are how the game looks like after you made the move.

What would be the algorithm to use for this problem? I'm using C#.NET, but the language shouldn't matter.

答:
generally this is called path finding

You seemed to have tried 2 depth first searches.

I suggest using a breadth first search (keep all paths of length n and then use those to find all paths of length n+1).

If this exceeds your memory then instead you can use a iterative deepening approach. This is a depth first that you break off at length n and if you don't find a solution then try again with n' = n+k and repeat


问:
Alternatives to multiple inheritance for my architecture (NPCs in a Realtime Strategy game)?
Coding isn't that hard actually. The hard part is to write code that makes sense, is readable and understandable. So I want to get a better developer and create some solid architecture.

So I want to do create an architecture for NPCs in a video-game. It is a Realtime Strategy game like Starcraft, Age of Empires, Command & Conquers, etc etc.. So I'll have different kinds of NPCs. A NPC can have one to many abilities (methods) of these: Build(), Farm() and Attack().

Examples:

Worker can Build() and Farm()

Warrior can Attack()

Citizen can Build(), Farm() and Attack()

Fisherman can Farm() and Attack()

I hope everything is clear so far.

So now I do have my NPC Types and their abilities. But lets come to the technical / programmatical aspect.

What would be a good programmatic architecture for my different kinds of NPCs?

Okay I could have a base class. Actually I think this is a good way to stick with the DRY principle. So I can have methods like WalkTo(x,y) in my base class since every NPC will be able to move. But now lets come to the real problem. Where do I implement my abilities? (remember: Build(), Farm() and Attack())

Since the abilities will consists of the same logic it would be annoying / break DRY principle to implement them for each NPC (Worker,Warrior, ..).

Okay I could implement the abilities within the base class. This would require some kind of logic that verifies if a NPC can use ability X. IsBuilder, CanBuild, .. I think it is clear what I want to express.

But I don't feel very well with this idea. This sounds like a bloated base class with too much functionality.

I do use C# as programming language. So multiple inheritance isn't an option here. Means: Having extra base classes like Fisherman : Farmer, Attacker won't work.

答:
I'd put all the abilities in separate classes that inherit from Ability. Then in the unit type class have a list of abilities and other stuff like attack, defence, max health etc. Also have a unit class that has current health,  location, etc. and has unit type as a member variable.

Define all unit types in a config file or a database, rather than hard coding it.

Then the level designer can easily adjust the abilities and stats of unit types without recompiling the game, and also people can write mods for the game.

ContentLicense: CC BY-SA 4.0


答:
I recommend a depth-first search like you already tried, but put some additional constraints on it. For example, a path that loops (revisits nodes) is clearly undesirable when looking for the shortest path: simply remove that loops, and you found a path shorter by N where N is the number of nodes in the loop.

With any algorithm it makes sense to set up the preconditions, including the problem to be solved: the steps of the algorithm: and the exit condition (success or failure).

The Problem

Consider a graph consisting of an arbitrary number of nodes. One node is the start node and there are multiple exit nodes. The goal is to find all paths of the same length that traverse from the start node to one of the exit nodes and that are the shortest length.

Each traversal of the graph will necessarily maintain a list of all the nodes traversed from start to the current node. This defines the path.

There will be storage to contain the completed paths which contains zero or more paths representing traversal from the start node to an exit node.

Algorithm

Current node is the start node.

Pick one edge not yet traversed: that is not part of the current path; that was not traversed and backtracked; that does not connect to the current node (does not loop).

If there are no edges to traverse and the current node is the start node, the algorithm terminates.

If there are no edges to traverse and the current node is not the start node, backtrack one node and repeat this step.

Traverse the edge to the next node and add it to the path.

If the current node is an exit node: copy the path to the completed paths and backtrack to the previous node.

Go to step 2.

Notes

This is a basic depth-first algorithm that will be relentless in finding all of the paths. This is necessary in order to find the shortest one: the last path traversed could be the shortest, we don't know.

This algorithm:

Will find all paths.

Will not traverse the same edge twice in one path. That is, will not loop.

Does not care about nodes or systems of nodes that are not reachable from the start node. Such nodes will take up memory, but will not matter to the running time of the algorithm.

Might be able to be improved on. Specifically, it might be possible to run a different algorithm to prune nodes and edges ahead of time which might help reduce the number of nodes in the graph. Perhaps there is a chain of nodes a thousand long that ends in a non-exit node, for example. Sometimes the time and effort to do this helps, sometimes not.

Title: Looking for an algorithm to connect dots - shortest route

Body:
I have written a program to solve a special puzzle, but now I'm kind of stuck at the following problem:
I have about 3200 points/nodes/dots. Each of these points is connected to a few other points (usually 2-5, theoretical limit is 1-26). I have exactly one starting point and about 30 exit points (probably all of the exit points are connected to each other). Many of these 3200 points are probably not connected to neither start nor end point in any way, like a separate net, but all points are connected to at least one other point.

I need to find the shortest number of hops to go from entry to exit. There is no distance between the points (unlike the road or train routing problem), just the number of hops counts. I need to find all solutions with the shortest number of hops, and not just one solution, but all. And potentially also solutions with one more hop etc.
I expect to have a solution with about 30-50 hops to go from start to exit.

I already tried:

1) randomly trying possibilities and just starting over when the count was bigger than a previous solution. I got first solution with 3500 hops, then it got down to about 97 after some minutes, but looking at the solutions I saw problems like unnecessary loops and stuff, so I tried to optimize a bit (like not going back where it came from etc.). More optimizations are possible, but this random thing doesn't find all best solutions or takes too long.

2) Recursively run through all ways from start (chess-problem-like) and breaking the try when it reached a previous point. This was looping at about a length of 120 nodes, so it tries chains that are (probably) by far too long. If we calculate 4 possibilities and 120 nodes, we're reaching 1.7E72 possibilities, which is not possible to calculate through. This is called Depth-first search (DFS) as I found out in the meantime. Maybe I should try Breadth-first search by adding some queue?

The connections between the points are actually moves you can make in the game and the points are how the game looks like after you made the move.

What would be the algorithm to use for this problem? I'm using C#.NET, but the language shouldn't matter.


问:
Why are private variables described in the publicly accessible header file?
OK, so hopefully this is a subjective enough question for Programmers, but here goes.  I am continuously broadening my knowledge of languages and software engineering practices... and I've run into something that just makes no sense to me whatsoever.

In C++, class declarations include private: methods and parameters in the header file, which, theoretically, is what you pass to the user to include if you make them a lib.

In Objective-C, @interfaces do pretty much the same thing, forcing you to list your private members (at least, there's a way to get private methods in the implementation file).

From what I can tell, Java and C# allow you to provide an interface/protocol which can declare all the publicly accessible properties/methods and gives the coder the ability to hide all implementation details in the implementation file.

Why?  Encapsulation is one of the main principles of OOP, why do C++ and Obj-C lack this basic ability?  Is there some kind of best-practices work-around for Obj-C or C++ that hides all implementation?

Thanks,

答:
This all comes down to the design choice.

If you truly wish to hide the private implementation details of the C++ or Objective-C class, then you either provide one or more interfaces that the class supports (C++ pure virtual class, Objective-C @protocol) and/or you make the class able to construct itself by providing a static factory method or a class factory object.

The reason that the private variables are exposed in the header file/class declaration/@interface is that a consumer of your class might need to create a new instance of it and a new MyClass() or [[MyClass alloc]init] in the client code needs the compiler to understand how big a MyClass object is in order to do the allocation.

Java and C# also have their private variables detailed in the class - they are no exception to this, but IMO the interface paradigm is much more common with those languages. You may not have the source code in each case, but there's enough metadata in the compiled/byte-code to deduce this information. As C++ and Objective-C don't have this metadata, the only option is the actual details of the class/@interface.  In the C++ COM world, you don't expose the private variables of any classes yet can provide the header file - because the class is pure virtual. A class factory object is registered to create the actual instances too, and there's some metadata in various forms.

In C++ and Objective-C, it is less work to hand out the header file compared to writing and maintaining an additional interface/@protocol file. This is one reason that you see the private implementation exposed so often.

Another reason in C++ is templates - the compiler needs to know the details of the class in order to generate a version of that class specialized to the parameters provided. The size of the class's members would vary with the parameterization, so it needs to have this information.


问:
Should one reject over-scoped projects?
I spoke to my first potential client today and he told me about the requirements of his project - an Android app. He is a well-known designer / photographer in my country and now wants me to "convert the website into an app, custom-tailored".

So the requirements, details stripped out, are as follows:

eCommerce

Aggregating all his content like videos, blogs, tweets, etc. into the app

Live streaming any of his studio demos

Augmented reality. So that people can see what his painting will look like on their wall before they buy it

Taxi Sharing

Now, for a freelance project, it seems too over-scoped.

I am not saying that I cannot do it. I can. But let me be realistic:

There is a steep learning curve when it comes to VR.

I am not a tester. I have never white-box tested my own apps. I always black-box test.

Since he is a renowned artist, something short of perfect might harm his public image

So, I asked him for 2 weeks' worth of time before I give him the final answer. Now knowing whom to consult for advise, I am posting the question here.

Although interesting and personally challenging, I am split-minded about accepting a project like this. I will be the only developer for this.

Should one reject a project that seems to be over-scoped for one's own abilities?

答:
If you want the project you ought

Split the project into discrete subtasks. Selling point: if all but AR and "Taxi Sharing" are complete and running, wouldn't that be better than the whole thing on hold waiting for AR? If everything was running, but you never found an AR that you liked, wouldn't that be better?

Prioritize the subtasks as I implied in (1).

Remember the iron triangle. I'm sure you know this stuff, just apply it to the contract: of course you can do this project given sufficient personnel and time, specifications, and money. If you need to subcontract a QA person or team, do it. If you can be working on commerce while someone else handles the VR, budget the VR engineer in. Too expensive? We can certainly remove or defer the VR part or the "Taxi Sharing".

You say you are to be the only developer? If he's alloted you two years to complete it, go for it. This spec is the scariest one for me. I suspect he wants one person because he doesn't want to pay two. This entails he wants fabulous work completed in no time and only your labor to bear on it.

Give him an accurate appraisal of the time, labor, personnel it will need. Many plastic artists are of the mistaken impression that people are far more interested in him than they actually are. I have no idea who this guy is; I guarantee you that I'm not (yet) interested in his blog.

Another conjecture, he imagines the the VR stuff will be nifty enough to actually drive sales. I really doubt it, but his fancy could cost him considerably with no expectation that it will be used. This indicates to me that he needs to have his expectations reined in, and you're the one with the reins.

Title: Should one reject over-scoped projects?


问:
Is client side JavaScript capable of replicating the Node.JS module loading system?
I like the Node.JS style of JavaScript, where I can write all of my functionalities into smaller files and then require those neatly from within my code. I'm even thinking about trying to write a framework to mimic that behavior in client-side JS.

My goal would be to implement the module loading system as accurately as possible - See Module docs.

For require(), I can use things detailed in answers to this question, most notably JQuery's $.getScript(). It seems to me that other aspects of the module loading system should be possible as well.

So I'm asking more experienced programmers here first, before I waist my time: Is there something that I'm missing that's going to cause such an attempt to fail miserably, or can  this be successfully done?

答: You should look at browserify it probably does exactly what you are looking for.  You can write code the node way and with a simple command build it all into one file.  I think it is a great tool and paradigm. I wrote my little framework  using this pattern, it works naively on node and all major browsers including IE 6.</p>


问:
Why do we need to include the .h while everything works when including only the .cpp file?
Why do we need to include both the .h and .cpp files while we can make it work solely by including the .cpp file?

For example: creating a file.h containing declarations, then creating a file.cpp containing definitions and including both in main.cpp.

Alternatively: creating a file.cpp containing declaration/definitions ( no prototypes ) including  it in main.cpp.

Both work for me. I can't see the difference. Maybe some insight into the compiling and linking process may help.

答:
Read more on the role of the C and C++ preprocessor, which is conceptually the first "phase" of the C or C++ compiler (historically it was a separate program /lib/cpp; now, for performance reasons it is integrated inside the compiler proper cc1  or cc1plus). Read in particular the documentation of the GNU cpp preprocessor. So in practice the compiler conceptually first preprocesses your compilation unit (or translation unit) and then work on the preprocessed form.

You'll probably need to always include the header file file.h if it contains (as dictated by conventions and habits):

macro definitions

types definitions (e.g. typedef, struct, class etc, ...)

definitions of static inline functions

declarations of external functions.

Notice that it is a matter of conventions (and convenience) to put these in a header file.

Of course, your implementation file.cpp need all the above, so wants to #include "file.h"  at first.

This is a convention (but a very common one). You could avoid header files and copy and paste their content into implementation files (i.e. translation units). But you don't want that (except perhaps if your C or C++ code is automatically generated; then you could make the generator program doing that copy & paste, mimicking the role of the preprocessor).

The point is that the preprocessor is doing textual only operations. You could (in principle) avoid it entirely by copy & paste, or replace it by another "preprocessor" or C code generator (like gpp or m4).

An additional issue is that the recent C (or C++) standards define several standard headers. Most implementations really implement these standard headers as (implementation specific) files, but I believe that it would be possible for a conforming implementation to implement standard includes (like #include <stdio.h> for C, or #include <vector> for C++) with some magic tricks (e.g. using some database or some information inside the compiler).

If using GCC compilers (e.g. gcc or g++) you can use the -H flag to get informed about every inclusion, and the -C -E flags to obtain the preprocessed form. Of course there are many other compiler flags affecting preprocessing (e.g. -I /some/dir/ to add /some/dir/ for searching included files, and -D to predefine some preprocessor macro, etc, etc....).

NB. Future versions of C++ (perhaps C++20, perhaps even later) might have C++ modules.


答:
I would

A) give a time estimate of how much it can take to complete the project (say it is two years).

B) notify him that, of course, such time estimates do not include anything that he may think of in the following two years.

C) tell him that, given the time spent, you need to get sure you will be paid in full. So you will want a substantital of the money upfront. And not your ordinary rate (in a project that lasts two months, you can afford accepting only half pay in advance because that means that you will only have to live from savings for a month; but in a project that takes two years you cannot afford living off savings for a whole year).

Given that he should not be happy to hear about A, B and C(*) gladly, offer him to separate the project into smaller iterations; the most basic first.

At the beginning of each iteration, he only needs to pay the upfront money for that iteration. Also, he will only need to give detailed specs for that module, so one can expect that they will give be more detailed.

He will get the results sooner. In fact, he will have something that can be distributed in a few months, instead of a couple of years.

At the end of each iteration, he can check the quality of the product, and decide if he has the money/will to continue for the next iteration, stop the process altogether or even move it to a different contractor later (which would help if you want to "chicken out" the VR part).

Bonus points if you may sell the idea to modularize the application and make each iteration a module, so users may chose which modules/plugin they will use.

(*) If he does not care about A, B & C... Run for your life, the man is a lunatic

Title: Should one reject over-scoped projects?

Body:
I spoke to my first potential client today and he told me about the requirements of his project - an Android app. He is a well-known designer / photographer in my country and now wants me to "convert the website into an app, custom-tailored".

So the requirements, details stripped out, are as follows:

eCommerce

Aggregating all his content like videos, blogs, tweets, etc. into the app

Live streaming any of his studio demos

Augmented reality. So that people can see what his painting will look like on their wall before they buy it

Taxi Sharing

Now, for a freelance project, it seems too over-scoped.

I am not saying that I cannot do it. I can. But let me be realistic:

There is a steep learning curve when it comes to VR.

I am not a tester. I have never white-box tested my own apps. I always black-box test.

Since he is a renowned artist, something short of perfect might harm his public image

So, I asked him for 2 weeks' worth of time before I give him the final answer. Now knowing whom to consult for advise, I am posting the question here.

Although interesting and personally challenging, I am split-minded about accepting a project like this. I will be the only developer for this.

Should one reject a project that seems to be over-scoped for one's own abilities?


答:
In Java and C#, void as a return type for a method seem to mean: this method doesn't return anything. Nothing. No return. You will not receive anything from this method.

That statement is correct. It is correct for C and C++ as well.

in C, void as a return type or even as a method parameter type means something different.

That statement is incorrect. void as a return type in C or C++ means the same thing that it does in C# and Java.  You are confusing void with void*. They are completely different.

Isn't it confusing that void and void* mean two completely different things?

Yep.

What is a pointer? What is a void pointer?

A pointer is a value which may be dereferenced. Dereferencing a valid pointer gives a storage location of the pointed-to type.  A void pointer is a pointer which has no particular pointed-to type; it must be converted to a more specific pointer type before the value is dereferenced to produce a storage location.

Are void pointers the same in C, C++, Java and C#?

Java does not have void pointers; C# does. They are the same as in C and C++ -- a pointer value which does not have any specific type associated with it, that must be converted to a more specific type before dereferencing it to produce a storage location.

Since C is older than Java and C#, why did these languages adopt void as meaning "nothing" while C used it as "nothing or anything (when a pointer)"?

The question is incoherent because it presupposes falsehoods. Let's ask some better questions.

Why did Java and C# adopt the convention that void is a valid return type, instead of, for instance, using the Visual Basic convention that functions are never void returning and subroutines are always void returning?

To be familiar to programmers coming to Java or C# from languages where void is a return type.

Why did C# adopt the confusing convention that void* has a completely different meaning than void ?

To be familiar to programmers coming to C# from languages where void* is a pointer type.

Title: Why does void in C mean not void?


问:
Isolated Unit Tests and Fine Grained Failures
One of the reasons often given to write unit tests which mock out all dependencies and are thus completely isolated is to ensure that when a bug exists, only the unit tests for that bug will fail. (Obviously, an integration tests may fail as well). That way you can readily determine where the bug is.

But I don't understand why this is a useful property. If my code were undergoing spontaneous failures, I could see why its useful to readily identify the failure point. But if I have a failing test its either because I just wrote the test or because I just modified the code under test. In either case, I already know which unit contains a bug.

What is the useful in ensuring that a test only fails due to bugs in the unit under test? I don't see how it gives me any more precision in identifying the bug than I already had.

答:
But if I have a failing test its either because I just wrote the test or because I just modified the code under test. In either case, I already know which unit contains a bug.

But, "the code under test" is not only the code of the class/module being tested, but also the code executed by its dependencies.

If I have

```<code>public TaxCalculator {
  public Currency getTaxAmount(Currency barePrice) {
     ...
  }

  public Currency getFinalPrize(Currency barePrize) {
     return barePrize.add(getTaxAmount(barePrize));
  }
}
</code>```

and I test getFinalPrize without mocking getTaxAmount and I get a failure, then all I know is that either there is a failure in getFinalPrize or in getTaxAmount.

Granted, for a situation this simple you would see that getTaxAmount test has also failed and maybe you will automatically link both fails. But if you think of a bug in some class that is widely used, and you suddenly get tens or hundred of test failures, stablishing that relationship would not be that easy.

Body:
But if I have a failing test its either because I just wrote the test or because I just modified the code under test. In either case, I already know which unit contains a bug.

But, "the code under test" is not only the code of the class/module being tested, but also the code executed by its dependencies.

If I have

public TaxCalculator {
  public Currency getTaxAmount(Currency barePrice) {
     ...
  }

  public Currency getFinalPrize(Currency barePrize) {
     return barePrize.add(getTaxAmount(barePrize));
  }
}

and I test getFinalPrize without mocking getTaxAmount and I get a failure, then all I know is that either there is a failure in getFinalPrize or in getTaxAmount.

Granted, for a situation this simple you would see that getTaxAmount test has also failed and maybe you will automatically link both fails. But if you think of a bug in some class that is widely used, and you suddenly get tens or hundred of test failures, stablishing that relationship would not be that easy.


问:
Avoid Code Repetition in Condition Statements
I have been programming for over 15 years now.  I consider myself a very good programmer, but I understand (like all of us) there are things that I need to work on.  One of these things is code repetition when dealing with conditions.  I will give a generic sample:

```<code>if(condition1)
{
     //perform some logic
     if(condition2)
     {
          //perform some logic
          if(condition3)
          {
               //Perform logic
          }
          else
          {
               //MethodA(param)
          }
     }
     else
     {
          //MethodA(param)
     }
}
else
{
     //MethodA()
}
</code>```

Now, I cannot make it easy by doing the following:

```<code>if(condition1 && condition2)
{

}
else
{

}
</code>```

I cannot do this since I need to perform some logic if condition1 is true and before I test condition2.

Is there a way to structure if...else blocks to where if you need to call a method in each else blocks, you are not repeating yourself?

答:
Your piece of code can easily be rewritten into:

if(not condition1)
{
    MethodA()
    return
}

//perform some logic
if(condition2)
{
     //perform some logic
     if(condition3)
     {
          //Perform logic
          return
     }
}

MethodA(param)
```

<p>Then, a part of the code can be extracted into a method:</p>

<pre class="lang-java prettyprint-override"><code>int Hello()
{
    if(condition1)
    {
        World()
    }
    else
    {
        MethodA()
    }
}

void World()
{
    //perform some logic
    if(condition2)
    {
        //perform some logic
        if(condition3)
        {
            //Perform logic
            return
        }
    }

    MethodA(param)
}
</code>```

The custom logic in conditions is preserved, but you don't have code duplication.

Also, when code duplication is just a call of a method, this is not so annoying as if there was several LOCs repeated or if you were repeating a call with the same five arguments. Refactor it if it's easy; if not, duplication is fine.

Body:
Your piece of code can easily be rewritten into:

if(not condition1)
{
    MethodA()
    return
}

//perform some logic
if(condition2)
{
     //perform some logic
     if(condition3)
     {
          //Perform logic
          return
     }
}

MethodA(param)

Then, a part of the code can be extracted into a method:

int Hello()
{
    if(condition1)
    {
        World()
    }
    else
    {
        MethodA()
    }
}

void World()
{
    //perform some logic
    if(condition2)
    {
        //perform some logic
        if(condition3)
        {
            //Perform logic
            return
        }
    }

    MethodA(param)
}

The custom logic in conditions is preserved, but you don't have code duplication.

Also, when code duplication is just a call of a method, this is not so annoying as if there was several LOCs repeated or if you were repeating a call with the same five arguments. Refactor it if it's easy; if not, duplication is fine.


问:
What do I have to do when using libraries with BSD license?
I am making a game using LWJGL and this is their license. What I don't understand is what must I do?

I plan on making a game and distributing it, not the source code just the .jar file and maybe sell it for a few dollars.

It said that I must retain the copyright, so would that mean I must include the doc folder that the library comes with in the jar or do I have to make something in-game like credits and say "made with LWJGL"?

答:
The requirements are really quite simple: Somewhere in your game or the documentation that you distribute along with it, you must mention that you use the Lwjgl library and reproduce its license text.

If your game can already display credits, then that is also where you should mention Lwjgl and its license.

Otherwise, if you have a file describing your game and which Jar files are needed (like a README file), then that is also a good place to mention Lwgjl and its license. If you don't have such a file, consider creating one.


问:
How do developers verify that software requirement changes in one system do not violate a requirement of downstream software systems?
In my work, I do requirements gathering, analysis and design of business solutions in addition to coding.  There are multiple software systems and packages, and developers are expected to work on any of them, instead of being assigned to make changes to only 1 system or just a few systems.

How developers ensure they have captured all of the necessary requirements and resolved any conflicting requirements?

An example of this type of scenario:

Bob the developer is asked to modify the problem ticket system for a hypothetical utility repair business.  They contract with a local utility company to provide this service.  The old system provides a mechanism for an external customer to create a ticket indicating a problem with utility service at a particular address.  There is a scheduling system and an invoicing system that is dependent on this data.  Bob's new project is to modify the ticket placement system to allow for multiple addresses to entered by a landlord or other end customer with multiple properties.  The invoicing system bills per ticket, but should be modified to bill per address.  What practices would help Bob discover that the invoicing system needs to be changed as well?  How might Bob discover what other systems in his company might need to be changed in order to support the new changes\business model?  Let's say there is a documented specification for each system involved, but there are many systems and Bob is not familiar with all of them.

End of example.

We're often in this scenario, and we do have design reviews but management places ultimate responsibility for any defects (business process or software process) on the developer who is doing the design and the work.

Some organizations seem to be better at this than others.  How do they manage to detect and solve conflicting or incomplete requirements across software systems?

We currently have a lot of tribal knowledge and just a few developers who understand the entire business and software chain.  This seems highly ineffective and leads to problems at the requirements level.

答:
Two ways:

By using well-defined interfaces between the connected systems having clear, unambiguous and documented behaviors, and

By writing unit tests that codify behavior at the class and method level, integration tests that verify functionality across multiple systems, and acceptance tests that validate successful fulfillment of the software requirements.

The process for discovering and identifying the capabilities of an internal system, so that you can write software against it, is no different than that of evaluating any other foreign system.  Documentation will take you a certain distance, but the only way to be sure is to poke the foreign system and see how it behaves.

In your example, you already know that your invoicing system needs to be able to support billing by address.  So, you test the system to see if it does.  In your hand is the list of functionality and features that the foreign system needs to support your new software, because you already identified them through a series of requirement gathering and software planning meetings.

Having a comprehensive test suite for each system helps this process, because the tests are a form of documentation.  If they are written well, you can tell what capabilities the system (is supposed to) have, because the tests specify the desired behaviors.


答:
In my experience two things help with this kind of challenge, which exists for pretty much every system:

Deep knowledge about the system in the team. Yes it does sound scary and it actually is when the knowledge is concentrated in very few people. You want to spread that knowledge between developers. Pair programming and ensuring that multiple people work on each and every piece of the software is crucial

integration tests. Every interface should have it's integration tests, which should fall flat on their face when an incompatible change happens. Good automated integration tests are difficult to create and maintain, so they are often manual, although automatic tests are to be preferred.

Stuff that doesn't help:

Documentation. Ok it does help, but only a little, because most of the time it is either out of date or gets ignored, or both.

Unit Tests. They by definition don't test this kind of behavior between systems.

Title: How do developers verify that software requirement changes in one system do not violate a requirement of downstream software systems?

Body:
In my work, I do requirements gathering, analysis and design of business solutions in addition to coding.  There are multiple software systems and packages, and developers are expected to work on any of them, instead of being assigned to make changes to only 1 system or just a few systems.

How developers ensure they have captured all of the necessary requirements and resolved any conflicting requirements?

An example of this type of scenario:

Bob the developer is asked to modify the problem ticket system for a hypothetical utility repair business.  They contract with a local utility company to provide this service.  The old system provides a mechanism for an external customer to create a ticket indicating a problem with utility service at a particular address.  There is a scheduling system and an invoicing system that is dependent on this data.  Bob's new project is to modify the ticket placement system to allow for multiple addresses to entered by a landlord or other end customer with multiple properties.  The invoicing system bills per ticket, but should be modified to bill per address.  What practices would help Bob discover that the invoicing system needs to be changed as well?  How might Bob discover what other systems in his company might need to be changed in order to support the new changes\business model?  Let's say there is a documented specification for each system involved, but there are many systems and Bob is not familiar with all of them.

End of example.

We're often in this scenario, and we do have design reviews but management places ultimate responsibility for any defects (business process or software process) on the developer who is doing the design and the work.

Some organizations seem to be better at this than others.  How do they manage to detect and solve conflicting or incomplete requirements across software systems?

We currently have a lot of tribal knowledge and just a few developers who understand the entire business and software chain.  This seems highly ineffective and leads to problems at the requirements level.