答:
Both approaches bundle the initialization code into a single function call. So far, so good.

However, there are two issues with the second approach:

The second one does not actually construct the resulting object, it initializes another object on the stack, which is then copied over to the final object. This is why I would see the second approach as slightly inferior. The push-back you have received is likely due to this extraneous copy.

This is even worse when you derive a class Derived from Foo (structs are largely used for object orientation in C): With the second approach, the function ConstructDerived() would call ConstructFoo(), copy the resulting temporary Foo object over into the superclass slot of a Derived object; finish the initialization of the Derived object; only to have the resulting object copied over again on return. Add a third layer, and the entire thing becomes completely ridiculous.

With the second approach, the ConstructClass() functions do not have access to the address of the object under construction. This makes it impossible to link up objects during construction, as it is needed when an object needs to register itself with another object for a callback.

Finally, not all structs are fully fledged classes. Some structs effectively just bundle a bunch of variables together, without any internal restrictions to the values of these variables. typedef struct Point { int x, y; } Point; would be a good example of this. For these use of an initializer function seems overkill. In these cases, the compound literal syntax may be convenient (it's C99):

```<code>Point = { .x = 7, .y = 9 };
</code>```

or

```<code>Point foo(...) {
    //other stuff

    return (Point){ .x = n, .y = n*n };
}
</code>```

Title: Should I initialize C structs via parameter, or by return value?

Body:
The company I work at is initializing all of their data structures through an initialize function like so:

```<code>//the structure
typedef struct{
  int a,b,c;
} Foo;

//the initialize function
InitializeFoo(Foo* const foo){
   foo->a = x; //derived here based on other data
   foo->b = y; //derived here based on other data
   foo->c = z; //derived here based on other data
}

//initializing the structure
Foo foo;
InitializeFoo(&foo);
</code>```

I've gotten some push back trying to initialize my structs like this:

```<code>//the structure
typedef struct{
  int a,b,c;
} Foo;

//the initialize function
Foo ConstructFoo(int a, int b, int c){
   Foo foo;
   foo.a = a; //part of parameter input (inputs derived outside of function)
   foo.b = b; //part of parameter input (inputs derived outside of function)
   foo.c = c; //part of parameter input (inputs derived outside of function)
   return foo;
}

//initialize (or construct) the structure
Foo foo = ConstructFoo(x,y,z);
</code>```

Is there an advantage to one over the other?

Which one should I do, and how would I justify it as a better practice?

Body:
Both approaches bundle the initialization code into a single function call. So far, so good.

However, there are two issues with the second approach:

The second one does not actually construct the resulting object, it initializes another object on the stack, which is then copied over to the final object. This is why I would see the second approach as slightly inferior. The push-back you have received is likely due to this extraneous copy.

This is even worse when you derive a class Derived from Foo (structs are largely used for object orientation in C): With the second approach, the function ConstructDerived() would call ConstructFoo(), copy the resulting temporary Foo object over into the superclass slot of a Derived object; finish the initialization of the Derived object; only to have the resulting object copied over again on return. Add a third layer, and the entire thing becomes completely ridiculous.

With the second approach, the ConstructClass() functions do not have access to the address of the object under construction. This makes it impossible to link up objects during construction, as it is needed when an object needs to register itself with another object for a callback.

Finally, not all structs are fully fledged classes. Some structs effectively just bundle a bunch of variables together, without any internal restrictions to the values of these variables. typedef struct Point { int x, y; } Point; would be a good example of this. For these use of an initializer function seems overkill. In these cases, the compound literal syntax may be convenient (it's C99):

Point = { .x = 7, .y = 9 };

or

Point foo(...) {
    //other stuff

    return (Point){ .x = n, .y = n*n };
}


问:
Programming to multiple backends
My current project is a high-level abstraction package for GPIO programming on those nifty little SoC-Computers (Raspberry Pi, Cubieboard, Beaglebone Black, Pandaboard etc.). One of my goals is to make it possible to run the same code on different Boards using different GPIO modules as backends, like RPi.GPIO on the Raspberry Pi, or SUNXI_GPIO on the Cubieboard.

At the moment I have code like this:

```<code>class Pin(object):
    def __init__(self, gpio, direction, pud=None):
        self.gpio = gpio
        self.direction = direction
        self.pud = pud
        _GPIO_BACKEND.setuppin(self.gpio, self.direction, self.pud)

    def __str__(self):
        return self.gpio

class InputPin(Pin):
    """docstring for InputPin"""
    def read(self):
        _GPIO_BACKEND.read(self.gpio)

class OutputPin(Pin):
    """docstring for OutputPin"""
    def high(self):
        _GPIO_BACKEND.high(self.gpio)

    def low(self):
        _GPIO_BACKEND.low(self.gpio)
</code>```

I'd like _GPIO_BACKEND to get setup by a context manager that loads the backend. The Backend itself looks like this (RPi.GPIO example):

```<code>from RPi import GPIO as _GPIO

def init(numberscheme='bcm'):
    """docstring for init"""
    if numberscheme.lower() == 'bcm':
        _GPIO.setup(_GPIO.BCM)
    elif numberscheme.upper() == 'board':
        _GPIO.setup(_GPIO.BOARD)

def setuppin(id, direction, pullupdown=None):
    """docstring for setuppin"""
    if direction.lower() == 'in':
        dir = _GPIO.IN
    elif direction.lower() == 'out':
        dir = _GPIO.OUT
    else:
        raise ValueError

    if pullupdown is None:
        pud = _GPIO.PUD_ # TODO
    elif pullupdown.lower() == 'up':
        pud = _GPIO.PUD_UP
    elif pullupdown.lower() == 'down':
        pud = _GPIO.PUD_DOWN
    else:
        raise ValueError

    _GPIO.setmode(id, dir, pud)

def cleanup():
    """docstring for cleanup"""
    _GPIO.cleanup()

def high(id):
    """docstring for high"""
    _GPIO.output(id, _GPIO.HIGH)

def low(id):
    """docstring for low"""
    _GPIO.output(id, _GPIO.LOW)

def read(id):
    """docstring for read"""
    return _GPIO.input(id)
</code>```

What I don't like about this is reliance on a pseudo-invisible global variable (_GPIO_BACKEND).

What is a good, proper, and pythonic way to program towards multiple backends like this?

答: Would you not be able to handle this with classical object-oriented concepts? For example, each backend could be implemented as a class with a common interface, and InputPin and OutputPin classes would used them in a composed manner.</p>

ContentLicense: CC BY-SA 3.0

Title: Programming to multiple backends


问:
The difference between bind and _.curry
So JavaScript's bind supports currying, but most people use some other library like lodash or ramda to do currying.

From first impression It seems like bind supports context changing, since that is it's intended role, e.g.

```<code>var replaceTest = replace.bind(this, 'test')

replaceTest('beta', environments)
</code>```

The other curry methods don't have this.

```<code>var replace = _.curry(function (a, b, list) {
  // implementation
})
var replaceTest = replace('test')

replaceTest('beta', environments)
</code>```

So are there any other difference between the two methods? Mainly I want to know if it makes sense to use one of those implementations when there is a native implementation present.

答:
bind() doesn't actually do currying. What it does is partial application. lodash and rambda have a method called _.partial() that does partial application without setting the context object.

A function f is curried if calling f with one or more arguments is equivalent to calling f with one argument, then calling the return value with the next argument, and so on until you run out of arguments. Currying can be implemented with partial application, but it's a different thing.

If you genuinely want a curried function, it's probably best to use one of these libraries rather than roll your own. If all you want is partial application, bind() should be good enough, but if you're already using a library like lodash or rambda I'd consider using _.partial(). Also, it's worth noting that currying doesn't work so well with variadic functions.

P.S. This blog post does a much better job explaining it.

Title: The difference between bind and _.curry


问:
Returning a Flag Indicating Success
Whenever I'm writing code, I always stub out my methods like this (not necessarily using generics):

```<code>public T MyMethod()
{
    T result = default(T); // or null

    return result;
}
</code>```

This always puts me in the right place to fill out the logic and make sure that I have a return variable to track throughout the process. After having done this long enough I've found a development pattern arose, and I'm not sure which direction to take. Usually in some relatively trivial operation:

```<code>public bool AddRecord(Record r)
{
    bool result = false;

    if(_collection != null)
    {
        _collection.Add(r);

        result = true;
    }

    return result;
}
</code>```

As an aside, I'd generally assign the result of the inner callee to result but some methods (such as Add) don't have any result.

This method, as it exists, is fine. But for some systems, I would write it a little different.

```<code>public bool AddRecord(Record r)
{
    bool result = false;

    if(_collection == null)
    {
        _collection = new List<Record>();
    }

    _collection.Add(r);

    result = true;

    return result;
}
</code>```

And it's here that I ponder what I should do. Always returning true provides no value to the end user, in my opinion. But then I say, "Well if, in the future, this method grows in complexity, would you want to have to change the method signature and have all callers update their reaction to this? Or would you rather just return true for now?" to which I tend to favor the latter, unless it's something so trivially straightforward that I have high confidence it will not change (which, in itself, has ~50% chance of being wrong). Another option would be to assume that, although this interior logic can't generate a false-y condition, it could throw an exception. Should my method handle that and return a flag indicating whether an exception was thrown? Thinking about this, I think:

Eating exceptions is bad, and unless I can do something with the information given to me, I shouldn't do it and I should let the caller handle it.

Does the caller even care about this exception, or do they only care whether this operation succeeded as a whole?

This leads me to this state where I have a method in which I'm not sure what to do, so I typically return a constant true and do not eat the exception.

My question is: In the general case, what is the best way to approach this?

I understand that specific cases require specific consideration, and while writing my code I always consider the unique case each method presents. But when I realize a method is not any more unique than another, I'd like have some additional insight as to what I should do. Many thanks in advance for your opinion.

答:
In my opinion, methods should either return a value or have a side effect, but not both.

In this answer to another question the author quotes the source of that practice.

In your examples, you handle a situation in which you try to add an element to a collection that could be or could not be initialized. My suggestion is that you either throw an exception if the collection is not initialized, or initialize it if it is null and then add the item, but don't return a value.

In this answer to yet another question you can see the disadvantages of return codes as compared to exceptions.

To summarize it:

Return codes are more verbose

Return codes are more brittle

Return Codes must sometimes be translated

Return Codes means you can't chain expressions

Exception are typed

Exception are... synchronous

Title: Returning a Flag Indicating Success


答:
You're right that it's generally best to let other code's exceptions propagate through yours unimpeded. Where I work, this is called being "exception-agnostic".

Now for the hard part. The return values of your functions are part of your public API. Having a return value that doesn't mean anything is a lot like having a method that doesn't do anything when called. It just shouldn't be there.

More importantly, let's say you did publish a function that always returned true because it could not fail. Then one day you change it so it can fail, and the function sometimes returns false. You may not have changed the function signature, but you have changed the contract. As a result, all existing code using that function will probably be broken, because it was written against the old "this function cannot fail" contract. That could be much worse than simply failing to compile.

So make the signature match the contract. If it can't fail, don't return a success/failure value. Anything else merely causes confusion, or fear that you might make backwards-incompatible changes someday. When you need to make a massive semantic change like introducing the possibility of failure, that needs to go into a brand new function.

Incidentally, when some methods can fail in a variety of meaningfully different ways, it's often a good idea to group them together into one method so you can return a single enum describing every possible kind of failure. A typical example would be the executeQuery() function for a database library.

P.S. I think AddRecord would be more readable with an early return (if(_collection == null) { return false; }) but maybe that's just me.

Title: Returning a Flag Indicating Success

Body:
Whenever I'm writing code, I always stub out my methods like this (not necessarily using generics):

```<code>public T MyMethod()
{
    T result = default(T); // or null

    return result;
}
</code>```

This always puts me in the right place to fill out the logic and make sure that I have a return variable to track throughout the process. After having done this long enough I've found a development pattern arose, and I'm not sure which direction to take. Usually in some relatively trivial operation:

```<code>public bool AddRecord(Record r)
{
    bool result = false;

    if(_collection != null)
    {
        _collection.Add(r);

        result = true;
    }

    return result;
}
</code>```

As an aside, I'd generally assign the result of the inner callee to result but some methods (such as Add) don't have any result.

This method, as it exists, is fine. But for some systems, I would write it a little different.

```<code>public bool AddRecord(Record r)
{
    bool result = false;

    if(_collection == null)
    {
        _collection = new List<Record>();
    }

    _collection.Add(r);

    result = true;

    return result;
}
</code>```

And it's here that I ponder what I should do. Always returning true provides no value to the end user, in my opinion. But then I say, "Well if, in the future, this method grows in complexity, would you want to have to change the method signature and have all callers update their reaction to this? Or would you rather just return true for now?" to which I tend to favor the latter, unless it's something so trivially straightforward that I have high confidence it will not change (which, in itself, has ~50% chance of being wrong). Another option would be to assume that, although this interior logic can't generate a false-y condition, it could throw an exception. Should my method handle that and return a flag indicating whether an exception was thrown? Thinking about this, I think:

Eating exceptions is bad, and unless I can do something with the information given to me, I shouldn't do it and I should let the caller handle it.

Does the caller even care about this exception, or do they only care whether this operation succeeded as a whole?

This leads me to this state where I have a method in which I'm not sure what to do, so I typically return a constant true and do not eat the exception.

My question is: In the general case, what is the best way to approach this?

I understand that specific cases require specific consideration, and while writing my code I always consider the unique case each method presents. But when I realize a method is not any more unique than another, I'd like have some additional insight as to what I should do. Many thanks in advance for your opinion.


问:
Should I initialize C structs via parameter, or by return value?
The company I work at is initializing all of their data structures through an initialize function like so:

```<code>//the structure
typedef struct{
  int a,b,c;
} Foo;

//the initialize function
InitializeFoo(Foo* const foo){
   foo->a = x; //derived here based on other data
   foo->b = y; //derived here based on other data
   foo->c = z; //derived here based on other data
}

//initializing the structure
Foo foo;
InitializeFoo(&foo);
</code>```

I've gotten some push back trying to initialize my structs like this:

```<code>//the structure
typedef struct{
  int a,b,c;
} Foo;

//the initialize function
Foo ConstructFoo(int a, int b, int c){
   Foo foo;
   foo.a = a; //part of parameter input (inputs derived outside of function)
   foo.b = b; //part of parameter input (inputs derived outside of function)
   foo.c = c; //part of parameter input (inputs derived outside of function)
   return foo;
}

//initialize (or construct) the structure
Foo foo = ConstructFoo(x,y,z);
</code>```

Is there an advantage to one over the other?

Which one should I do, and how would I justify it as a better practice?

答:
Depending upon the contents of the structure and the particular compiler being used, either approach could be faster.  A typical pattern is that structures meeting certain criteria can get returned in registers; for functions returning other structure types the caller is required to allocate space for the temporary structure somewhere (typically on the stack) and pass its address as a "hidden" parameter; in cases where a function's return is stored directly to a local variable whose address is not held by any outside code, some compilers may be able to pass the address of that variable directly.

If a structure type satisfies a particular implementation's requirements to be returned in registers (e.g. being either no larger than one machine word, or filling precisely two machine words) having a function return the structure may be faster than passing the address of a structure, especially since exposing the address of a variable to outside code that might keep a copy of it could preclude some useful optimizations.  If a type does not satisfy such requirements, the generated code for a function that returns a struct will be similar to that for a function that accepts a destination pointer; the calling code would likely be faster for the form that takes a pointer, but that form lay lose some optimization opportunities.

It's too bad C doesn't provide a means of saying that an function is forbidden from keeping a copy of a passed-in pointer (semantics similar to a C++ reference) since passing such a restricted pointer would be gain the direct performance advantages of passing a pointer to a pre-existing object, but at the same time avoid the semantic costs of requiring a compiler to consider a variable's address "exposed".


问:
Coding style issue: Should we have functions which take a parameter, modify it, and then RETURN that parameter?
I'm having a bit of a debate with my friend over whether these two practices are merely two sides of the same coin, or whether one is genuinely better.

We have a function which takes a parameter, fills out a member of it, and then returns it:

```<code>Item predictPrice(Item item)
</code>```

I believe that as it works on the same object that is passed in, there is no point going on to return the item. In fact, if anything, from the perspective of the caller, it confuses matters as you could expect it to return a new item which it doesn't.

He claims that it makes no difference, and it wouldn't even matter if it did create a new Item and return that. I strongly disagree, for the following reasons:

If you have multiple references to the item passes in (or pointers or whatever), it allocating a new object and returning it is of material importance as those references will be incorrect.

In non-memory managed languages, the function allocating a new instance claims ownership of the memory, and thus we would have to implement a cleanup method which is called at some point.

Allocating on the heap is potentially expensive, and therefore it is important to whether the called function does that.

Hence, I believe it to be very important to be able to see via a methods signature whether it modifies an object, or allocates a new one. As a result, I believe that as the function merely modifies the object passed in, the signature should be:

```<code>void predictPrice(Item item)
</code>```

In every codebase (admittedly C and C++ codebases, not Java which is the language we are working in) I have worked with, the above style has essentially been adhered to, and kept to by considerably more experienced programmers. He claims that as my sample size of codebases and colleagues is small out of all the possible codebases and colleagues, and thus my experience is no true indicator over whether one is superior.

So, any thoughts?

答:
When coding in Java, one should try to make the usage of each object of mutable type match one of two patterns:

Exactly one entity is considered the "owner" of the mutable object and regards that object's state as part of its own.  Other entities may hold references, but should regard the reference as identifying an object which is owned by someone else.

Despite the object being mutable, nobody who holds a reference to it is allowed to mutate it, thus making the instance effectively immutable (note that because of quirks in Java's memory model, there's no good way to make an effectively-immutable object have thread-safe immutable semantics without adding an extra level of indirection to each access).  Any entity which encapsulates state using a reference to such an object and wants to change the encapsulated state must create a new object which contains the proper state.

I don't like to have methods mutate the underlying object and return a reference, since they give the appearance of fitting the second pattern above.  There are a few cases where the approach may be helpful, but code which is going to mutate objects should look like it's going to do so; code like myThing = myThing.xyz(q); looks a lot less like it mutates the object identified by myThing than would simply myThing.xyz(q);.


答:
If I came across a method called AddRecord, I'd conclude - from it's name - that it was a statement, not a yes/no question. It's not asking me if I want to add a record; I'm telling it to do so. Therefore I'd expect one of two possible return types, depending on whether I'm thinking OO or functional:

void - I've commanded it to do something. If there's a problem, it'll throw an exception.

ICollectionOfSomeSort - I've asked my collection to be added to, so I'll expect a collection back (ideally a brand new read-only one).

Getting a boolean back doesn't make much sense. A true might reassure me that it worked, but what does false mean? "Couldn't be bothered"? "Sorry, I don't add to collections on a Friday"? No failure reason is provided; just a "computer says no" response.

However, care needs to be given to when and why an exception would be thrown. In various examples, you are testing the state of _collection. In one case you return false if it's null. Other answers have suggested you should throw an exception in this case. This implies that it's the caller's responsibility to initialise the internal state of your class before calling AddRecord and that you'll fail the call if they don't. This is a leaky abstraction: you are exposing the inner workings of your class through these failure messages. Any internal setup like this should happen without the need for the API user to initiate it. If a NullReferenceException occurs, it should indicate a bug in the code, ie it should only ever be your fault (as the API creator), rather than mine (as the API user).

Title: Returning a Flag Indicating Success


问:
Average commits per merge to Master using gitflow
I'm currently working alone on a project, but I still use Git since it is a really powerful tool. I use gitflow workflow methodology, and today I have merged to master with 77 commits. I was surprised since I wasn't expecting this big number, but it made sense since I had added over 4 features in a 2 week iteration.

What's the average commit number per merge to master in a project, let's say with 2 developers working on it? If there's any statistical study that back this up, it would be a great resource.

答:
It's not about how many commits, and not about how many features either. It's about when you want to make a release. You merge to master when you want to stick a version number to the current state of the project and let your users upgrade(actually, according to formal git-flow you need a release branch for that - but that's usually an overkill for small projects).

Even if all your users are using the bleeding edge version in develop, it helps to think that you have users that download stable versions not via Git. To allow these users to upgrade you need to close the version, tag it with a version number, archive it and upload it to the download server. When you would want to do all this to allow your users to upgrade - then you merge to master. Not when the commit count reaches some arbitrary number...


问:
What is the right testing strategy in Agile Scrum/Kanban teams?
The problem is:

The team , I am working in has 10 developers to 2 testers ratio which means we are going to churn out code more quickly than it is "Test" done.

So, What should be the right approach to track activities in such scenarios according to agile experts?

My fear is that soon the day will come , when there is a lot of stuff which will be called as "Done" in previous sprints (with no testing done) but when it actually comes to testing, there might be some potential defects.

How can I track the efforts seamlessly? Should testing be part of "Done Definition"? What are the pitfalls if it is not?

As per me, it is sort of 'Waterfall' as you are calling stories "Done" before it is actually functionally tested.

答:
This is fairly common, if not typical.  To answer what are several questions:

What should be the right approach to track activities in such scenarios?

Will features get done without QA but with defects?

How can I track the efforts seamlessly?

Should testing be part of "Done Definition"?

What are the pitfalls if it is not?

I would take an overall approach that:

enables the testers to add value

gives them authority

maximizes their value

encourages QA folks to train developers

and to do that (and answer your questions) I would:

make sure they can enter bugs in an easy to use bug tracking system that also contains the features such as Jira, Trello, Pivotal Tracker, etc.

make sure they are trained on creating good bug reports that describe:

steps to reproduce

initial/setup values

entered values

screenshots when appropriate

server logs when appropriate

make sure they see bugs get assigned, worked on and completed.

train them in best practices and send them to conferences.

train them in programming and using a test framework.

allow them to teach programmers on good approaches and mindset for testing.

Also, yes, some features may get done without QA but with defects.  I often find QA is a second set of eyes.  Sometimes this role can be filled by another developer.  Personally I find this finds some errors, but not all the ones that a different QA mindset might find.

Testing should be part of done but that does not mean that the QA person has to do the testing.  Given the shortness of resources and an Agile environment that eschews specs that QA can look at, QA need to be involved with learning the users domain, design meetings, point grooming meetings, standups, retrospectives, etc.

As for the big question of testing strategy, use the Agile testing quadrants to guide you:

```<code>                   |
      Integrated   |     Performance
_________________________________________
                   |
           Unit    |     Exploratory
</code>```

The developers may already be doing Unit Tests.  A key area that QA may add value by covering is in Integrated testing and by using UI automation.
Good exploratory testing is also very valuable - it's not just clicking every link on the page, it's about learning the end users domain and what using the application means to them.

For the ratio of QA's to testers also consider the testing triangle:

```<code>    Exploratory
  Integrated Tests
Individual Unit Tests
</code>```

whereby one exploratory or integrated test can represent dozens if not hundreds of unit tests by exercising the whole 'stack'.

Also consider that as in Agile teams there should generally be an approach of anyone can code, anyone can test.  The key of course is giving folks the guidance and structure so that they can do what is needed and giving them training for the other area.

In terms of the actual ratio, I disagree about the preciseness of David's answer of 3:1 or 4:1  In some organization where developers are writing good unit and integrated tests this might be ok to be 7:1  In an organization with very little testing done by developers this might need to be 1:1  It really 'depends' on the organization, structure, knowledge, industry, etc, etc.

Body:
This is fairly common, if not typical.  To answer what are several questions:

What should be the right approach to track activities in such scenarios?

Will features get done without QA but with defects?

How can I track the efforts seamlessly?

Should testing be part of "Done Definition"?

What are the pitfalls if it is not?

I would take an overall approach that:

enables the testers to add value

gives them authority

maximizes their value

encourages QA folks to train developers

and to do that (and answer your questions) I would:

make sure they can enter bugs in an easy to use bug tracking system that also contains the features such as Jira, Trello, Pivotal Tracker, etc.

make sure they are trained on creating good bug reports that describe:

steps to reproduce

initial/setup values

entered values

screenshots when appropriate

server logs when appropriate

make sure they see bugs get assigned, worked on and completed.

train them in best practices and send them to conferences.

train them in programming and using a test framework.

allow them to teach programmers on good approaches and mindset for testing.

Also, yes, some features may get done without QA but with defects.  I often find QA is a second set of eyes.  Sometimes this role can be filled by another developer.  Personally I find this finds some errors, but not all the ones that a different QA mindset might find.

Testing should be part of done but that does not mean that the QA person has to do the testing.  Given the shortness of resources and an Agile environment that eschews specs that QA can look at, QA need to be involved with learning the users domain, design meetings, point grooming meetings, standups, retrospectives, etc.

As for the big question of testing strategy, use the Agile testing quadrants to guide you:

                   |
      Integrated   |     Performance
_________________________________________
                   |
           Unit    |     Exploratory

The developers may already be doing Unit Tests.  A key area that QA may add value by covering is in Integrated testing and by using UI automation.
Good exploratory testing is also very valuable - it's not just clicking every link on the page, it's about learning the end users domain and what using the application means to them.

For the ratio of QA's to testers also consider the testing triangle:

    Exploratory
  Integrated Tests
Individual Unit Tests

whereby one exploratory or integrated test can represent dozens if not hundreds of unit tests by exercising the whole 'stack'.

Also consider that as in Agile teams there should generally be an approach of anyone can code, anyone can test.  The key of course is giving folks the guidance and structure so that they can do what is needed and giving them training for the other area.

In terms of the actual ratio, I disagree about the preciseness of David's answer of 3:1 or 4:1  In some organization where developers are writing good unit and integrated tests this might be ok to be 7:1  In an organization with very little testing done by developers this might need to be 1:1  It really 'depends' on the organization, structure, knowledge, industry, etc, etc.


问:
How to model table and column objects and their relation
I'm working on a small application where I need to model tables and columns from a relational DB.

I've been reading some material on nested classes, which is recommended to be used sparsely. However I'm thinking that this might be such a scenario.

I wish to implement these objects as follow:

 1. Table contains List<Column>

 2. Preferably it is not possible to create a Column object unless you use a method on the Table object (eg Table.addColumn()).

 3. Existing columns should be available outside the Table object in such a way that you may reference the column and it's public methods and properties from anywhere in your code.

 4. Column must know of the Table object it belongs to.

 5. Both Columnand Table implements IEquatable and maybe IEnumerable.

The options I see are:

 1. Use nested classes where Column is enclosed in Table, protecting the constructor of Column from being called by external code.

 2. Implement Column and Table as regular classes, injecting the Table object into the constructor of Column. This could be handled by a method in the Table object taking care of the "injection" and returning the resulting Columnobject. This does however, expose the constructor of Column to the rest of the implementation.

 3. Create a separate DLL combined with the Internal access modifier to protect the Column constructor.

What would you say is the best solution here?

Cheers

答:
I would start by providing the right API to add columns to the table.  If tableObject.addColumn (...) is appropriate then build that.

You don't have to allow arbitrary column objects to be added to tables: you can control every aspect of the creation of an appropriate Column object via the Table addColumn instance method implementations.  These methods can take Column creation parameters and create and attach the Column themselves.

Therefore, I wouldn't worry about preventing people from creating a Column object.  If someone creates one independently, they won't be able to use it for anything Table related, so it is harmless.  There's a lot arbitrary objects people can create (an array of int, ...) that are so harmless to your code, there's no point in preventing them from trying to do so.

On the other hand, you could create an abstract Column class (or interface) and then subclass that (say as TableColumn), and nest that within Table.  This way you separate the Column API people will need to see when enumerating the columns, without providing a specific constructor.  The TableColumn nested class can have any private linkages and constructors it needs.

You still can't necessarily prevent someone from subclassing the abstract Column on their own and providing a constructor to create instances, but so what, it is harmless to your Table.


答:
One argument in favor of the "output-parameter" style is that it allows the function to return an error code.

```<code>struct MyStruct {
    int x;
    char *y;
    // ...
};

int MyStruct_init(struct MyStruct *out) {
    // ...
    char *c = malloc(n);
    if (!c) {
        return -1;
    }
    out->y = c;
    return 0;  // Success!
}
</code>```

Considering some set of related structs, if initialization can fail for any of them, it can be worth to have all of them use the out-parameter style for consistency’s sake.

Body:
One argument in favor of the "output-parameter" style is that it allows the function to return an error code.

struct MyStruct {
    int x;
    char *y;
    // ...
};

int MyStruct_init(struct MyStruct *out) {
    // ...
    char *c = malloc(n);
    if (!c) {
        return -1;
    }
    out->y = c;
    return 0;  // Success!
}

Considering some set of related structs, if initialization can fail for any of them, it can be worth to have all of them use the out-parameter style for consistency’s sake.


问:
Best practice for buffering when posting to a web-service that has gone offline
If I am collecting data that needs to be posted to a web service on a regular (~5 minutes) basis, and that service has temporarily gone offline, what is the best practice to ensure we don't lose any data?

Of course, we could simply buffer in memory until the service is back online, but what if the service is offline for a great period of time?  Should we fall back to simply storing the serialized data to the local file system until the service is back online?

Are there other considerations/practices?

Any 'out of the box' frameworks that handle this for C#?

EDIT:

It's business critical that we don't lose any, or very minimal, data as it's for auditing for sensitive temperature controlled environments. We'll be using Json, and they will simply be sensor readings (not a large amount of data). We'll be using Web API, probably hosted on Azure, so the availability of the service should be good. Of course there are other factors such as localised network concerns. Everything will be under our control, apart from the infrastructure where the sensor software will be installed, this will be at client sites.

答:
Since you mention that "It's business critical that we don't lose any, or very minimal, data" IMHO buffering in memory is not really a good idea - it's volatile and if your machine/process dies for whatever reason that data is lost. Plus in-memory buffering needs extra care (unknown downtime duration, chewing memory resources, etc).

On upload failure I'd always fallback to storing the data in a local persistent location which can survive a server reboot. Whenever the "current" upload attempt succeeds (i.e. the server is back online) I'd retry uploading all "outstanding" data from the persistent location, maybe in multiple chunks if needed.

Shouldn't be that complex to warrant an 'out of the box' framework solely for this purpose.


问:
Definition of network connection
In discussing push vs polling with a colleague, we were trying to figure out if there is a well-defined difference between two sides of a conversation being 'connected' vs being 'disconnected'. For an example, think of a TCP connection being 'open'.

We ended up deciding that the notion of 'being connected' is really just a question of degree. In other words, if communication seems relatively easy between the sides, then the phrases 'a connection is open' or 'the sides are currently connected' are used.

Is this view correct?  Or is there some qualitative, well-defined difference between being two sides being connected vs disconnected?

答:
In basic networking you have end to end. That is what I would call connected.  TCP is an end to end protocol.  You get a delivery receipt.  That is nice but there is overhead with an end to end communication.

You also have connectionless communication such as UDP or IP. You send it but do not get a delivery receipt.

A good book is Computer Networks and Internets by Douglas Comer. You can get it used quite cheaply.  The fundamentals of networking have not changed much.

Poll versus push are typically both connected it is just which end initiates the connection.  You don't typically send out a payload hoping it finds the destination.

Title: Definition of network connection


答:
In networking, the technical term "connection" refers to a session where data is streamed (transmitted & received in-order). Sessions have a set-up and a tear-down phase where a channel (which can be virtual) is created & destroyed. TCP and ATM have connections, UDP doesn't.

If you're not using the technical term and wanted to include all types of network communications (e.g. UDP), you can still define "connected" concretely: two hosts are connected if they and intervening network devices have the necessary open data structures to send & receive messages to each other.

Here, "open" means the structures are in the correct states to send & receive messages to & from the other host. For example, consider the TCP state machine:

A TCP socket in a "LISTEN" state receives from any host on the network and can't send messages, so isn't part of a connection to another host.

Similarly, "CLOSED", "CLOSING", "TIME_WAIT" and "LAST_ACK" sockets can't send or receive* data, so aren't connected.

In opening states ("SYN_SENT" and "SYN_RCVD"), data can be sent along with a SYN packet, so you might be tempted to considered them "open". However, in practice data isn't sent with SYN packets and additional data can't be sent until the handshake completes. The latter especially means these states aren't "open".

Once a TCP socket enters the "ESTABLISHED" state, a connection exists.

With some of the closing states ("FIN_WAIT_1", "FIN_WAIT_2", "CLOSE_WAIT"), one side can only send, the other only receive. Thus, these opening and states shouldn't be considered to be fully "open".

That some data can be sent & received (with limitations) during opening and closing states suggests additional terms would be useful. In addition to "connected" and "not-connected", hosts can be "partially connected". During opening, the host has an "embryonic connection". The term "half-open" is often used for opening and closing states, though in a couple different ways: it can refer to half-duplex connections (such as TCP during closing), to connections where one host has closed without the knowledge of the other, and to embryonic connections.

Intervening network devices must be considered because devices on some network segments (e.g. the NAT on a home router, an ATM switch) may need to keep track of the connection to allow communication. If it's necessary but doesn't happen, the hosts won't be able to send or receive, so can't be said to be connected.

*: delayed, duplicate packets may still arrive during most of these states, but the packets are discarded and the application already received the data earlier, so (in a strict sense) the sockets aren't receiving data.

Title: Definition of network connection

Body:
In discussing push vs polling with a colleague, we were trying to figure out if there is a well-defined difference between two sides of a conversation being 'connected' vs being 'disconnected'. For an example, think of a TCP connection being 'open'.

We ended up deciding that the notion of 'being connected' is really just a question of degree. In other words, if communication seems relatively easy between the sides, then the phrases 'a connection is open' or 'the sides are currently connected' are used.

Is this view correct?  Or is there some qualitative, well-defined difference between being two sides being connected vs disconnected?


问:
Is there a purpose for using pull requests on my own repo if I am the only developer?
So I got started with a real project of mine on GitHub and things are going pretty well and ideas are flowing a lot faster than I initially thought. In order to keep things organized, I setup some branches so I can develop different features separately.

Now when I push my branch to GitHub, I have that section where I have two buttons : Pull Request and Compare with the name of the branch I recently pushed to. I understand the purpose of the Compare button but I don't get why I would want to create a pull request on my own repo.

Can someone explain me why I would do that? Is it useful to make pull request on my own repo if I am the only developer?

答:
Pull requests vs git push ultimately come down to one of individual or shared history.  The main repository is the source for all changes, if others are pulling from and potentially making local changes, then a push request can cause those users issues as the tree they are deriving from changes.

The pull request model (either from custom branches or personal repositories) serves as a way to provide consistent history for all those using and deriving from the code.

Part of the reason you are putting code on github would be to make the code available for forking, and pull requests.  You never known when it will happen, and keeping your co-developers histories consistent would be a big plus.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答: Increasing the total cost of the system for insufficient benefit. It could be too much copying and pasting, too complex an architecture, or using pricey but ineffective commercial products. Generally speaking all software techniques are aimed at reducing the total cost of a system, and if we end up with a overly expensive system then we have done wrong.</p>

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?


问:
Entity Framework Domain Object as Business Object
If I am not concerned with unit testing and switching my data access out at a later time, would using my entity framework objects as my business objects be okay?

I have an existing database for which I generated entities and a datacontext, and have partial classes for holding my methods and any additional (non-database) properties. I have read quite a bit about repository pattern and other seemingly complex ways of setting this up, but I'm not sure all of that is necessary. It is a .NET Web Forms app using Entity Framework 6.1.3 and will not have unit testing.

Are there other reasons why I should avoid such a simplistic approach?

答:
I don't think you should use them as business objects. According to Vaughn Vernon  EF is too inflexible be used directly as business objects

Instead use them as state objects. That is wrap them with a better encapsulation of your business logic. In the link I provided he i talking about DDD. What you refer to as business objects are called aggregate roots in DDD but the point still stands.


问:
Bad idea to use the same test cases for multiple parts of a contiguous algorithm?
I'm working on an algorithm that's split up into multiple parts, each of which performs different tasks but is more or less separate from the others, by which I mean the only interaction between the parts is the passage of a single piece of data from one part to the next like a conveyor belt. I was doing some unit tests for the algorithm and I was wondering, is it a bad idea to use the same tests cases to test each part of the algorithm?

I thought it might be a good idea at first, since it saves me having to rewrite a whole new set of test cases for each step in the algorithm, but as I got further into it I realized some parts of the algorithm were more specific to certain tasks than others.

For example, one step in the algorithm reads a file and spits out a set of strings, which is then used by a later step in the algorithm to produce another set of completely different objects. Should separate tests be designed to specifically test the integrity of this first step?

Another thing that turned me off to the idea of using the same tests cases for multiple steps in the algorithm is that the output of one step might be complete gibberish to the step proceeding it. So a test case could pass for one step in the algorithm, but fail in the next step because despite the fact that the previous step was able to correctly parse the input data, the output is unusable to the next step.

tl;dr should the same tests be used for all the steps in an algorithm?

EDIT (In response to possible duplicate): From what I can tell, that question doesn't seem to be asking about a linear algorithm (like the conveyor belt model I described above), it seems instead to be talking about combining data from multiple individual non-contiguous components. It's also not asking about whether or not the same tests should be used for all steps.

答:
A good guideline is that your tests should exercise all the code that you've written.

If different inputs cause different code paths to be executed, it is a good idea to choose your test inputs so that every path is covered. More thorough testing also tries to ensure that every path is covered under different circumstances, particularly with extreme values, boundary conditions, etc.

The fact that your algorithm is in multiple parts doesn't change these principles. Since you say that you have a choice which input data to use for testing different phases of processing, I'm assuming that te steps of your algorithm can already be called in isolation. That is an excellent design, and it simplifies testing because you can achieve coverage with less effort (if three steps have four paths each, you need only 12 test cases, not 64).

If your test cases reflect real uses that your algorithm will be put to, then it's a good idea to use them for all steps - after all, that's what is actually going to happen.

It's true that if part of your algorithm fails and prevents the next stage from working, that will prevent you from catching bugs in the second stage. However, you'll have to fix the first part anyway before you publish the code, and the test suite is supposed to succeed 100% before you're done, so there is little point in choosing test cases to work around known defects. The defects shouldn't be there in the first place, so you have to work on the first stage no matter what, and it's simpler to do this first. It saves you the effort of making your tests robust against errors that can't be allowed to stay in the code anyway.


问:
Less PHP request to REST API
I had an argument with my PHP developer today who tried to convince me that REST API has to provide all the request from PHP since a server is faster than client devices such as desktop.

As I am a REST API developer, I told him that it would be better if client can reduce the number of API request since since client devices can handle more stuff these days with powerful CPU power and greater memory. This is what we are trying to do. The REST API will provide a list of sale items for e-commerce site with a category of each items.

I was asking PHP developer to generate filtering option based on provided categories in the item list. The PHP developer asked me to to provide the filtering option as a JSON.

He wants to request two for this transaction, but I told him he can do it by only one request. Which way is right?

答:
If I'm understanding you correctly, you are providing a list of items with 2 (or more) categories and you want to display them sorted or separated in some way.

The options are multiple requests, one for each selected category. Or a single request allowing the client to specify multiple categories.

If that's in any way close to the correct understanding, this is how I would look at it...

Primarily, right or wrong, seems to be a harsh way to look at it. Advantages and disadvantages might be a less confrontational way to approach it and it might make it easier to come to an agreement.

The advantages of multiple requests:

API simplicity, Requesting a list of Categories in a single request would add (presumably a small amount) of complexity to the API which may be unnecessary if you don't expect complex requests

Interface simplicity, No filtering code in the interface.

Fairly large records (lots of data, compared to the overhead of the connection) in a situation where multi category requests are the exception would be one situation where this would work.

Advantages of a single request:

There is a non-trivial amount of overhead to the additional connections. This is compounded by things like cookies which on some sites can add up to a significant percentage of the request/response bandwidth for small images and ajax requests.

An environment where multiple category requests are the norm especially if the records (and number of results) are small would favor this approach.

In general, I would say less requests is absolutely what you would want to aim for. But you really need to evaluate your individual situation and take into account a wider picture of the system and how it is likely to be used. And this may change over time. A system designed with a total of 3 categories, that grows over time to hundreds of categories would probably need to be reevaluated.

Title: Less PHP request to REST API


问:
PHP mysql checking for relational equivalence
Suppose I have a users table and in that users table I have a role_id.

In my roles table I have:

users
  - id
  - role_id

roles
  - id
  - name

roles
id   |  name
1    |  admin
2    |  normal

Now in code I want to disallow access to the admin.php page.  So at the top I put

```<code>if ($user->role_id != 1){
    header('location: forbidden.php');
}
</code>```

It seems like bad practice to rely on role_id being 1.  I would think it is better to do something like:

```<code>if ($user->role_name == 'admin'){ ...
</code>```

Now I am relying on the text of the role, which isn't great.  So I have created const classes like:

```<code>class RoleType{
    const ADMIN = "admin";
    const NORNAML = "normal";
}
....
if ($user->role_name == RoleType::ADMIN){ ...
</code>```

The issue here is now if I change it in the database I have to change my RoleType class.

I feel like none of these is ideal.

What is the best way to handle this?

答:
As designed with roles being a one to one relationship with users, my personal preference would be to ditch the lookup table for roles entirely and go with an enum data type in the users table. Internally in MySql it's going to be stored in a similar way, so it will not take more space. But it will return the string representation in the results making it clear that you intend to use the string as the key.

Of course, you'll still need to store those strings in your code, and I believe your solution of the constants in the RoleType class is a clean way to do it. Of course you'd want to put that in some shared shared and included file somewhere.

https://dev.mysql.com/doc/refman/5.7/en/enum.html


答:
Firstly, a ratio of 10:2 is bad. From experience, a ratio of 3:1 or 4:1 developers to testers works well. You'll likely need at least one more tester therefore, otherwise the testing backlog will grow and either never get cleared, or you're cut corners somewhere.

If you test tasks in the next sprint, you are implementing mini-waterfall or "scrumfall" as you are separating out testing from development. You are right in that testing absolutely should form part of the done-definition. If a task isn't tested, how can it be declared "done"?

The right approach therefore would be:

Add a tester to the team if possible, otherwise have the developers perform some testing (though they likely won't do as good a job as a professional tester).

Modify your scrum/kanban board to include "ready for test" and "in test" columns and agree with the team that part of the workflow must be having all tasks go through these lanes.

Tasks only make it to the "Done" column when they have been acceptable by testing.

Title: What is the right testing strategy in Agile Scrum/Kanban teams?

Body:
The problem is:

The team , I am working in has 10 developers to 2 testers ratio which means we are going to churn out code more quickly than it is "Test" done.

So, What should be the right approach to track activities in such scenarios according to agile experts?

My fear is that soon the day will come , when there is a lot of stuff which will be called as "Done" in previous sprints (with no testing done) but when it actually comes to testing, there might be some potential defects.

How can I track the efforts seamlessly? Should testing be part of "Done Definition"? What are the pitfalls if it is not?

As per me, it is sort of 'Waterfall' as you are calling stories "Done" before it is actually functionally tested.


问:
How to structure a reservations system in a document based database?
I really don't know if this is the right forum for this but I need help designing my database. Also I apologize for the horrible title: I don't know how to summarize the issue below in a single title.

I am building a reservation system where one reservation can have multiple services. Something like the following (single document):

```<code>{
    name: 'Gasim',
    start_date: '2015-07-24 1:30pm',
    services: [
      {member_id: 'member1', start_date: '2015-07-14 1:30pm', duration: '40 mins'},
      {member_id: 'member2', start_date: '2015-07-14 2:30pm', duration: '60 mins'}
    ]
}
</code>```

I was going to go with this design but after having lots of debates with a number of people, I lost confidence in going with this design. I was told multiple times that, I should create a separate reservation for each service instead of aggregating services under a single reservation. Even though I like the idea that I have been proposed, I have one major problem with it and I would like you to shed a light on this issue for me.

All these services are being assigned in a single time period. So, let's say the example above, the whole time for a reservation is 100 minutes with 20 minute wait time = 2 hours.

If I separate them, that means I actually have two reservations. In a programming scenario this can be a good idea but let's look at it from a real world scenario. After I made a reservation, I come to the facility and say that I have a reservation under my name. Why would the front desk see two separate reservations under my name?

I am going to give some background information on how this thing become an issue. My system has the ability to query all the reservations, go through their services, and generate a list of available times based on the services that a user wants. I really expect this algorithm to be slow as I am going through lots of nested arrays and loops. However, this specific operation will be fetched at a very small rate even at large scales (I don't believe it will ever exceed 1000 requests/second, period).

Question

Is this design correct? Not performance-wise, just pure logic-wise. I don't want my design to be logically faulty just because it makes some operations fast. If this is not a correct design, can you please explain why?

答:
get rid of the document-based DB, its a horrible system for the kind of query you'll be doing. Go back to boring old RDBMS and you'll be a lot happier.

If you do this, you can not only make reservations individually (which also help when someone adds a service to their reservation) but you can query all services assigned with a single reservation id. Simply and efficiently.

So I have a library with books. I can checkout a book and it writes an entry to the DB against that book with my userid to say who has it reserved, and can write the time I should return it. Next day I go back and check out another book, this writes an entry as before. The front desk, when looking at my user id can then see both books I have checked out because the query to return my details is a simple select * from reservations where user id = x.

You can extend this easily to include many reservations by including a table of reservations I make (linking my user id with the reservations) and then linking services within those reservations with the reservation id. Eg I have a separate account for books and for music at the library, each book gets associated with my 'book lending' account and not me - still works very easily with a traditional RDBMS.


问:
My algorithm that extracts the largest box that can be made from smaller boxes, is too slow
Imagine a cube based world (such as Minecraft, Trove, or Cube World) where everything is made up of identically sized cubes and all the cubes are of the same kind.

The goal is to represent the world with the fewest number of rectangular boxes (by merging cubes but retaining convex shape (aka, a rectangular box shape)). My algorithm succeeds at this, but its performance is too slow for its intended purpose. Are there faster algorithms?

The pseudo-C#-code for my algorithm is basically:

```<code>struct Coordinate { int x,y,z; }; //<-- integer based grid
HashSet<Coordinate> world; // <-- contains all the cubes

//width, height, and length represent how many cubes it spans
struct RectangularBox { Coordinate coord; int width,height,length; }

void Begin()
{
    List<RectangularBox> fewestBoxes = new List<RectangularBox>();
    while(world.Count > 0)
    {
         RectangularBox currentLargest = ExtractLargest();
         fewestBoxes.Add(currentLargest);
         world.RemoveRange(currentLargest.ContainedCubes());
    }
    //done; `fewestBoxes` contains the fewest rectangular boxes needed.
}

private RectangularBox ExtractLargest()
{
    RectangularBox largestBox = new RectangularBox();
    foreach (Coordinate origin in world)
    {
        RectangularBox box = FindMaximumSpan(origin);
        if (box.CalculateVolume() >= largestBox.CalculateVolume())
            largestBox = box;
    }
    return largestBox;
}

private RectangularBox FindMaximumSpan(Coordinate origin)
{
    int maxX, maxY,maxZ;
    while (world.Contains(origin.Offset(maxX, 0, 0))) maxX++;
    while (world.Contains(origin.Offset(0, maxY, 0))) maxY++;
    while (world.Contains(origin.Offset(0, 0, maxZ))) maxZ++;

    RectangularBox largestBox;
    for (int extentX = 0; extentX <= maxX; extentX++)
        for (int extentY = 0; extentY <= maxY; extentY++)
            for (int extentZ = 0; extentZ <= maxZ; extentZ++)
            {
                int lengthX = extentX + 1;
                int lengthY = extentY + 1;
                int lengthZ = extentZ + 1;
                if (BoxIsFilledWithCubes(origin, lengthX, lengthY, lengthZ))
                {
                    int totalVolume = lengthX * lengthY * lengthZ;
                    if (totalVolume >= largestBox.ComputeVolume())
                        largestBox = new RectangularBox(origin, lengthX, lengthY, lengthZ);
                }
                else
                    break;
            }
    return largestBox;
}

private bool BoxIsFilledWithCubes(Coordinate coord,
    int lengthX, int lengthY, int lengthZ)
{
    for (int gX = 0; gX < lengthX; gX++)
        for (int gY = 0; gY < lengthY; gY++)
            for (int gZ = 0; gZ < lengthZ; gZ++)
                if (!world.Contains(coord.Offset(gX, gY, gZ)))
                    return false;
    return true;
}
</code>```

Essentially, for every block in the world, it first finds how many contigious blocks there are in each of the three positive dimensions (+X, +Y, +Z). And then it kinda flood-fills that volume and checks which is the largest filling that isn't missing any blocks.

Update: Since I seemed to have implied this was for a game's rendering engine, I just want to clarify, this isn't for a game's rendering engine; it's for a file-converter; no GUI.

答: Build up an octree with a leaf node aabb size of the size of your box. While traversing the octree you can cheaply merge nodes. Completely filled nodes are trivial to merge (new box = parent aabb), while for partially filled nodes, you can use a variant of your current algorithm to check merge-ability.


问:
Efficient way to handle foreign keys
I am building a script that checks a large network of sites for invalid links. The idea is to flag links that continuously show as not available so that they can be cleaned by the administration team.

The basic process is this:

Grab a set of pages - approximately 30K per day, not the same 30K each day - and extract all links from the pages

Insert Unique URLs into the Links Table

Insert records into LinksInPage containing the anchor text for each link as well as the associated LinkID for each link

Check the status of each link utilizing HEAD/GET methods and inserting results into the LinkResults table

I am currently planning on building this database structure in an relational database.

Tables:

Links

LinkID     (auto inc)

URL    (varchar)

LinksInPage

LinkID (foreign key to Links.LinkID)

AnchorText (varchar)

Page URL   (varchar)

LinkResults

LinkID (foreign key to Links.LinkID)

DateOfCheck (date)

StatusCode (int)

NumFailures (int)

My question:

How can I efficiently handle non-unique links in this situation (I'm open to completely changing how the database is laid out)?

For example, on day one if I check example.com, I insert a record into the Links table. On day two, if I have another page that also links example.com, I don't want
a duplicate entry in the Links table, but I do need a record in LinksInPage that points to the same LinkID. At, assuming at least one link per page, 30K links daily I don't think querying for a LinkID at each insert is going to be efficient.
Storing everything in memory also seems like it will lead to problem in the future as the number of links gets larger.

I also need to be able to handle the LinkID when inserting link results. Again, looking up the LinkID at each insert seems inefficient.

The plan is to build this utilizing Python.

答:
As Doc Brown says, joining properly indexed tables is efficient

You make it easier on your application by defining appropriate views and dealing with the views rather than the underlying tables

e.g. (Tested on SQL-SERVER, you didn't specify an RDBMS)
See Fiddle

```<code>CREATE VIEW URLsInPage AS
    SELECT Links.[Name], LinksInPage.[Page URL], LinksInPage.[AnchorText]
    FROM Links
    JOIN LinksInPage ON Links.[LinkId] = LinksInPage.[LinkId]
GO

CREATE TRIGGER AddLinksInPage ON URLsInPage INSTEAD OF INSERT
AS
DECLARE @Temp INT

MERGE INTO Links USING Inserted AS New ON Links.[Name] = New.[Name]
WHEN MATCHED THEN
    UPDATE SET @Temp = 1
WHEN NOT MATCHED THEN
    INSERT ([Name]) VALUES (New.[Name])
OUTPUT inserted.[LinkId], New.[AnchorText] , New.[Page URL] INTO LinksInPage ([LinkId], [AnchorText] , [Page URL]);
</code>```

Title: Efficient way to handle foreign keys

Body:
As Doc Brown says, joining properly indexed tables is efficient

You make it easier on your application by defining appropriate views and dealing with the views rather than the underlying tables

e.g. (Tested on SQL-SERVER, you didn't specify an RDBMS)
See Fiddle

CREATE VIEW URLsInPage AS
    SELECT Links.[Name], LinksInPage.[Page URL], LinksInPage.[AnchorText]
    FROM Links
    JOIN LinksInPage ON Links.[LinkId] = LinksInPage.[LinkId]
GO

CREATE TRIGGER AddLinksInPage ON URLsInPage INSTEAD OF INSERT
AS
DECLARE @Temp INT

MERGE INTO Links USING Inserted AS New ON Links.[Name] = New.[Name]
WHEN MATCHED THEN
    UPDATE SET @Temp = 1
WHEN NOT MATCHED THEN
    INSERT ([Name]) VALUES (New.[Name])
OUTPUT inserted.[LinkId], New.[AnchorText] , New.[Page URL] INTO LinksInPage ([LinkId], [AnchorText] , [Page URL]);


答:
You can make use of the fact that when

```<code> BoxIsFilledWithCubes(c,x,y,z)
</code>```

returns true, then it is not necessary to check in BoxIsFilledWithCubes(c,x+1,y,z) all those cubes in the coordinate range "(c,x,y,z)" again. You need only to check those cubes with the new x-coordinate  c.x + (x+1). (Same is true for y+1, or z+1). More generally, by splitting up a box into two smaller boxes (for which you might already know if they are both filled with cubes, or not both filled), you can apply a divide-and-conquer technique here, which becomes faster than your original approach when you cache the intermediate results.

To accomplish this, you start implementing BoxIsFilledWithCubes(c,x,y,z) recursively, for example:

```<code> bool BoxIsFilledWithCubes(coord,lx,ly,lz)
 {
     if(lx==0|| ly==0 || lz==0)
        return true;
     if(lx==1 && ly==1 && lz==1)
          return world.Contains(coord);
     if(lx>=ly && lx>=lz)  // if lx is the maximum of lx,ly,lz ....
         return BoxIsFilledWithCubes(coord,lx/2,ly,lz)
             && BoxIsFilledWithCubes(coord.Offset(lx/2,0,0), lx-lx/2, ly, lz);
     else if(ly>=lz && ly>=lx)
         // ... analogously when ly or lz is the maximum

 }
</code>```

and then use memoization (like it is discussed here) to avoid any repeated calls to BoxIsFilledWithCubes with the same parameters. Note you will have to clear the memoization cache when you apply a change to your world container, like by world.RemoveRange. Nevertheless I guess this will make your program faster.

Title: My algorithm that extracts the largest box that can be made from smaller boxes, is too slow

Body:
Imagine a cube based world (such as Minecraft, Trove, or Cube World) where everything is made up of identically sized cubes and all the cubes are of the same kind.

The goal is to represent the world with the fewest number of rectangular boxes (by merging cubes but retaining convex shape (aka, a rectangular box shape)). My algorithm succeeds at this, but its performance is too slow for its intended purpose. Are there faster algorithms?

The pseudo-C#-code for my algorithm is basically:

```<code>struct Coordinate { int x,y,z; }; //<-- integer based grid
HashSet<Coordinate> world; // <-- contains all the cubes

//width, height, and length represent how many cubes it spans
struct RectangularBox { Coordinate coord; int width,height,length; }

void Begin()
{
    List<RectangularBox> fewestBoxes = new List<RectangularBox>();
    while(world.Count > 0)
    {
         RectangularBox currentLargest = ExtractLargest();
         fewestBoxes.Add(currentLargest);
         world.RemoveRange(currentLargest.ContainedCubes());
    }
    //done; `fewestBoxes` contains the fewest rectangular boxes needed.
}

private RectangularBox ExtractLargest()
{
    RectangularBox largestBox = new RectangularBox();
    foreach (Coordinate origin in world)
    {
        RectangularBox box = FindMaximumSpan(origin);
        if (box.CalculateVolume() >= largestBox.CalculateVolume())
            largestBox = box;
    }
    return largestBox;
}

private RectangularBox FindMaximumSpan(Coordinate origin)
{
    int maxX, maxY,maxZ;
    while (world.Contains(origin.Offset(maxX, 0, 0))) maxX++;
    while (world.Contains(origin.Offset(0, maxY, 0))) maxY++;
    while (world.Contains(origin.Offset(0, 0, maxZ))) maxZ++;

    RectangularBox largestBox;
    for (int extentX = 0; extentX <= maxX; extentX++)
        for (int extentY = 0; extentY <= maxY; extentY++)
            for (int extentZ = 0; extentZ <= maxZ; extentZ++)
            {
                int lengthX = extentX + 1;
                int lengthY = extentY + 1;
                int lengthZ = extentZ + 1;
                if (BoxIsFilledWithCubes(origin, lengthX, lengthY, lengthZ))
                {
                    int totalVolume = lengthX * lengthY * lengthZ;
                    if (totalVolume >= largestBox.ComputeVolume())
                        largestBox = new RectangularBox(origin, lengthX, lengthY, lengthZ);
                }
                else
                    break;
            }
    return largestBox;
}

private bool BoxIsFilledWithCubes(Coordinate coord,
    int lengthX, int lengthY, int lengthZ)
{
    for (int gX = 0; gX < lengthX; gX++)
        for (int gY = 0; gY < lengthY; gY++)
            for (int gZ = 0; gZ < lengthZ; gZ++)
                if (!world.Contains(coord.Offset(gX, gY, gZ)))
                    return false;
    return true;
}
</code>```

Essentially, for every block in the world, it first finds how many contigious blocks there are in each of the three positive dimensions (+X, +Y, +Z). And then it kinda flood-fills that volume and checks which is the largest filling that isn't missing any blocks.

Update: Since I seemed to have implied this was for a game's rendering engine, I just want to clarify, this isn't for a game's rendering engine; it's for a file-converter; no GUI.

Body:
You can make use of the fact that when

 BoxIsFilledWithCubes(c,x,y,z)

returns true, then it is not necessary to check in BoxIsFilledWithCubes(c,x+1,y,z) all those cubes in the coordinate range "(c,x,y,z)" again. You need only to check those cubes with the new x-coordinate  c.x + (x+1). (Same is true for y+1, or z+1). More generally, by splitting up a box into two smaller boxes (for which you might already know if they are both filled with cubes, or not both filled), you can apply a divide-and-conquer technique here, which becomes faster than your original approach when you cache the intermediate results.

To accomplish this, you start implementing BoxIsFilledWithCubes(c,x,y,z) recursively, for example:

 bool BoxIsFilledWithCubes(coord,lx,ly,lz)
 {
     if(lx==0|| ly==0 || lz==0)
        return true;
     if(lx==1 && ly==1 && lz==1)
          return world.Contains(coord);
     if(lx>=ly && lx>=lz)  // if lx is the maximum of lx,ly,lz ....
         return BoxIsFilledWithCubes(coord,lx/2,ly,lz)
             && BoxIsFilledWithCubes(coord.Offset(lx/2,0,0), lx-lx/2, ly, lz);
     else if(ly>=lz && ly>=lx)
         // ... analogously when ly or lz is the maximum

 }

and then use memoization (like it is discussed here) to avoid any repeated calls to BoxIsFilledWithCubes with the same parameters. Note you will have to clear the memoization cache when you apply a change to your world container, like by world.RemoveRange. Nevertheless I guess this will make your program faster.


答:
I'm presuming that your focus is on initialization via output parameter vs. initialization via return, not the discrepancy in how construction arguments are supplied.

Note that the first approach could allow Foo to be opaque (although not with the way you currently use it), and that's usually desirable for long-term maintainability.  You could consider, for example, a function that allocates an opaque Foo struct without initializing it.  Or perhaps you need to re-initialize a Foo struct that was previously initialized with different values.

ContentLicense: CC BY-SA 4.0


问:
We are publishing an app using open source apache licensed software, Need some help understanding provisions
We are using some open source code licensed as Apache License 2.0. From what I understand, we cannot endorse the company that made the code.

We are using it to develop an free app with micro purchases, but the code isn't actually located on the app, it's located in the cloud on our processing servers. Our app doesn't actually use any of the code, it uses our AWS servers for processing that use the code. It sends images to the AWS API then it returns them back after we have used the open source code.

Now, I understand we have to retain the license used so we plan on including it in our terms and condition page and making users accept it upon opening the app for the first time. My question is, can we mention in our app description that we are using the code?

Here is an example, can we do this or is this endorsement?

Our app uses a modified version of [original OS company ex. Twitter's] [open source package name ex. Mask API] to digitally transform the code into [whatever the code + modifications do]."

答:
The Apache website's license FAQ has a very good non-laywer summary of what the license actually means. The part that's relevant to your question is this:

It forbids you to:

redistribute any piece of Apache-originated software without proper    attribution;

use any marks owned by The Apache Software Foundation in any way that    might state or imply that the Foundation endorses your
  distribution;

use any marks owned by The Apache Software Foundation in any way that    might state or imply that you created the Apache software in question.

Your example statement does not appear to be making any such implication, so I wouldn't worry about it. In fact, you are required to have "proper attribution", in addition to reproducing the license, so you not only can, but  must include a statement like that with your application.

There's also an item on their FAQ which clarifies what does and doesn't imply endorsement:

For example, it would be acceptable to use a name like 'SuperWonderServer powered by Apache', but never a name like 'Apache SuperWonderServer'. This is similar to the distinction between a product named 'Microsoft Burp' and 'Burp for Microsoft Windows'.

Just to be thorough, I believe the relevant part of the actual license is section 6:

Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor,
  except as required for reasonable and customary use in describing the
  origin of the Work and reproducing the content of the NOTICE file.

Implying that the entity known as "the Apache Software Foundation" endorses your derivative work is clearly not required when "describing the origin of the work".


答:
You seem to be at least O(n^2) (see big O notation) as you loop over all boxes in the world in “Begin()”, then for each box, you loop over all boxes in the world in ExtractLargest().   So a world with 10 unrelated boxes will take 4 times longer than a world with 5 unrelated boxes.

You therefore need to limit the number of boxes that ExtractLargest() has to look at, to do that you need to use some type of spatial search, as you are working in 3d, you may need a 3d spatial search.   However first start by understanding 2d spatial search.

Then consider if you will ever have many boxes over the top of each other, if not then a 2d spatial search that just covers x,y may be enough to cut down your looping.

Octree/quadtree are one option, but there are many other options for space partitioning,

But you may be able to just use a 2 dimensional array of lists (Grid spatial index), where all boxes that cover the point (a, b) are in array[a,b].list.  But most lickly that would lead to too large an array, so what about array[mod(a,100),mob(b,100)].list?   This all depends on what your data is like.

(I have seen the grid solution work very well in real life.)

Or do what Wilbert says with an octree with a leaf node aabb size of the size of your box, but later on you are likely to have to find the box that the user’s mouse is pointing at etc, once again a case of spatial search.

(You must decide if you are just trying to get this software to work, or if you are trying to understand how to be a better programmer and hence are more interested in the learning then a quick solution.)


问:
Creating a Java project without using any objects and just calling static methods on input?
I'm creating a program which takes a document, extracts it, and then moves this into a database. I've done most of this now and I've realised that I haven't made any instances of classes I've made (I have made instances of other thing such as buffered readers and arrays etc). </p>

<p>Is this bad? I seem to just have classes which are a collection of related methods which are called statically to manipulate my data (which is stored as a string) until it is then added to a database. How would an experienced programmer go about this if my technique is considered naive or bad form? </p>

答:
The point of object-orientation is not to count the user-defined classes and judge via "more == better".

Instantiating an object is useful if you really do have multiple things in your problem field that have identical behaviour but a distinct identity. You saw how that works with streams: one reads from one source, the next one from another; reading and writing streams are different but closely related, so it makes sense that they both inherit from the same class, etc. Those are all good reasons to use OOP idioms; it is better to write the logic for doing something once and then reuse it, and if the logic is bound up with instance-specific data (e.g. the source file name), then the logical way of bundling them is to create a class out of the data and the methods that work on it.

However, if your problem is so small that you don't repeat anything, i.e. if you really read a couple things from one place, perform one transformation and then write them to another place, there's little use in defining objects and classes to do that when it's really just a list of steps to be performed. (Separating the phases into smaller methods, even if each is called only once, is still a good idea, but that isn't strictly related to OOP - it's a good idea even in non-object languages.)

Briefly, don't beat yourself up about not having created your own class. Once you've met our first problem class where it does make sense to define a class with multiple instances, it becomes easier to judge when this makes sense and when it would just be window dressing for a fundamentally non-dynamic problem solution.


答:
For this particular problem, it's not terrible. What you're doing is basically scripting an import process, which is a fairly straight-forward imperative problem. Java maybe isn't the best tool for that job, but it's fine.

An experienced programmer might create an intermediary data structure to represent the data going into the database to help should that ever come from a different source than the file. They might abstract away the file or database so you can have different import/output targets. But that might also be over-engineering depending on your environment and needs.

Title: Creating a Java project without using any objects and just calling static methods on input?

Body:
I'm creating a program which takes a document, extracts it, and then moves this into a database. I've done most of this now and I've realised that I haven't made any instances of classes I've made (I have made instances of other thing such as buffered readers and arrays etc). </p>

<p>Is this bad? I seem to just have classes which are a collection of related methods which are called statically to manipulate my data (which is stored as a string) until it is then added to a database. How would an experienced programmer go about this if my technique is considered naive or bad form? </p>


答:
You can't make a Java program without objects. Everything you instantiate is an object. The static methods you call are called on instances of the Class object of their class.

But yes, it's generally a bad idea to use a single big class with just static methods. It gets terribly unwieldy really quickly.

Rather than avoid the issue of learning object orientation, making things worse for you in the future as your programs get bigger, make the effort now to wrap your head around it now that your creations are still small and easy to envision in your head.

Get some decent books, get someone to give you instruction preferably, don't think you can forever avoid the issue or solve it just by asking questions on some forum or watching youtube videos.


问:
Declaring 'chained' interface inheritance

I assume this is largely language-agnostic, but I'm working in C# if it's not

Let's say interface I3 inherits from I2, which in turn inherits from I1. I could write this:

```<code>interface I1 { ... }
interface I2 : I1 { ... }
interface I3 : I2 { ... }
</code>```

Or alternatively this:

```<code>interface I1 { ... }
interface I2 : I1 { ... }
interface I3 : I1, I2 { ... }
</code>```

The I1 in interface I3 is redundant - anything that implements I3 will still require anything declared in I2, which includes anything in I1.

To my mind the latter is more readable - I can see at a glance all the 'base' interfaces without having to dig down the inheritance tree - but I'm not sure if it's considered good practice. Is it? Are there any hidden traps here?

答:
You have to dig down the inheritance tree anyway - just to find out the set of interfaces all your inherited interfaces are inheriting from, and their children too. The difference is that you're making the developer do this when they develop the class instead of doing it when they need to know which interfaces their class extends, if they need to know at all.

Its probably a good thing though, making explicit the list of interfaces a class implements.


问:
Design pattern for different code behaviors according to different clients
At my company, we have a solution composed of a WinForm (multiple per client) and an API (one per client). This solution is deployed on different clients that require the solution to behave differently according to their desires. The same code base must support UI customizations (client logo, buttons visibility) and functionality customizations (calling the same WebMethod with different flags).

Currently we manage this flexibility on the WinForm side by having an Organization class that contains all these customizations (flags). The API is totally client-agnostic. Thus, the WinForm's methods look like this:

```<code>this.Logo = CurrentOrganization.LogoImage;

API.GetProducts(Organization.UsesPagination);
</code>```

In the past, we had conditional build directives scattered among the code:

```<code>#IF CLIENT_A
    API.GetProductsWithPagination();
#ELSE
    API.GetProducts();
#ENDIF
</code>```

Today, we have a single zone with those conditional build directives that, according to the build configuration, instantiates the required Organization class. Afterwards, there are no more IFs, parameter passing.

I'm a bit worried this is not the best design or the most maintainable solution. I studied the State pattern... I guess the Organization is my strategy object, since it tells other methods how they should behave through flags.

Is there a better way?

Storing configurations on a DB table? (requires more requests to the API, which costs time)

Storing configurations on a *.config files? (someone can easily change the app behavior by editing the file)

答:
I think you are almost there. You are getting the State and the Strategy. The way of selecting maybe would be a Factory or a Builder maybe reading a configuration file or a database just as you pointed.

At the end it will depend on your own requirements, but the strategy mixed with the Factory or a Builder Pattern to create the object which contains the right policy on creation will help you to get rid of the conditionals builds directives.


问:
Clean Abstract Syntax Tree
I'm writing a toy compiler for fun.

Basically, my problem is that I don't want to clutter the AST with stuff like debug information (symbol tokens, locations of tokens, etc) as well as data that the semantic analyzer computes.

For example, the semantic analyzer does some type inference and the result type is stored back into the Node type. It looks something like this:

```<code>/// A variable declaration in my language looks like this:
/// var x = 10
struct VarDec: Statement {
    var varKeyword: Keyword
    var varName: Id
    var assignment: Symbol
    var initializer: Expr
    var type: Optional<Type>
}
</code>```

The main problem here is that now the node type has a state, type inference has either been done or not. This makes it hard to reason about. The other thing is that the whole AST gets cluttered with those tokens that are only really needed for error messages.

It has been suggested that I could create another representation of the AST just for semantic analysis that links back to the AST but that seems like a lot of work and redundant code...

Does anybody have an idea how I can clean up this code without having to create multiple trees?

答:
My advise would be to keep tokens as tokens, and if anything, perform a type inference step where you wrap each node in another class or struct that does have state.

```<code>// Token type struct - immutable
struct VarDec: Statement {
    var varKeyword: Keyword
    var varName: Id
    var assignment: Symbol
    var initializer: Expr
}

// Type-checked token /w state
struct StatementTyped {
    var statement: Statement
    var type: Optional<Type>
}
</code>```

In this way, you get the best of both worlds.

Title: Clean Abstract Syntax Tree

Body:
My advise would be to keep tokens as tokens, and if anything, perform a type inference step where you wrap each node in another class or struct that does have state.

// Token type struct - immutable
struct VarDec: Statement {
    var varKeyword: Keyword
    var varName: Id
    var assignment: Symbol
    var initializer: Expr
}

// Type-checked token /w state
struct StatementTyped {
    var statement: Statement
    var type: Optional<Type>
}

In this way, you get the best of both worlds.


答:
First thing you should check is how many lines of code a typical Organization class implementation has, and how it is structured. If it has less than 100 lines of code, and the class consists mainly of properties providing some flags or data, do not worry. If it has more than 2000, and it contains a lot of business logic, you should consider to split it into smaller pieces, or to generalize some flags or properties. Nevertheless your Organization class can still be a facade to the configuration data.

Storing configurations on a DB table? Storing configurations on a *.config files?

Even if you use a DB table or a configuration file, you will still need an Organization object which loads the configuration from the DB table or configuration file into memory to provide those data to the rest of the program. This enables you or an admin or someone else to add new organizations, or to change features of existing organizations without actually changing the code. So use a DB table or a configuration file if you have that requirement - not because you want to achieve a better maintainability.

Title: Design pattern for different code behaviors according to different clients

Body:
At my company, we have a solution composed of a WinForm (multiple per client) and an API (one per client). This solution is deployed on different clients that require the solution to behave differently according to their desires. The same code base must support UI customizations (client logo, buttons visibility) and functionality customizations (calling the same WebMethod with different flags).

Currently we manage this flexibility on the WinForm side by having an Organization class that contains all these customizations (flags). The API is totally client-agnostic. Thus, the WinForm's methods look like this:

```<code>this.Logo = CurrentOrganization.LogoImage;

API.GetProducts(Organization.UsesPagination);
</code>```

In the past, we had conditional build directives scattered among the code:

```<code>#IF CLIENT_A
    API.GetProductsWithPagination();
#ELSE
    API.GetProducts();
#ENDIF
</code>```

Today, we have a single zone with those conditional build directives that, according to the build configuration, instantiates the required Organization class. Afterwards, there are no more IFs, parameter passing.

I'm a bit worried this is not the best design or the most maintainable solution. I studied the State pattern... I guess the Organization is my strategy object, since it tells other methods how they should behave through flags.

Is there a better way?

Storing configurations on a DB table? (requires more requests to the API, which costs time)

Storing configurations on a *.config files? (someone can easily change the app behavior by editing the file)