答:
There are two aspects of an API: The effort to implement the API, and the effort of all the clients to use the API correctly.

As the author of the client, I know that when I send a request to a web server, I may either get an error (never talked properly to the server), or a reply with a status code. I have to handle the errors. I have to handle a good response. I have to handle expected, documented, "bad" responses. I have to handle whatever else comes back.

Designing the API, you should look at what is the easiest for the client to process. If the client sends a well-formed request, and you can do what the request asks you to do, then you should give an answer in the 200 range (there are some cases where a number other than 200 in that range is appropriate).

If the client asks "give me all records like ...", and there are zero, then a 200 with success and an array of zero records is fully appropriate. The cases that you mention:

"Login failed" usually should be a 401. "Couldn't find file" should be a 404. "Missing parameter x" should be something around 500 (actually, a 400 if the server figures out that the request is bad, and 500 if the server is totally confused by my request and has no idea what's going on). Returning 200 in these cases is pointless. It just means as the author of a client, I cannot just look at the status code, I have to study the reply as well. I can't just say "status 200, great, here's the data".

Especially the "parameter missing" - that's not something that I would ever handle. It means my request is incorrect. If my request is incorrect, I don't have a fallback to fix that incorrect request - I would send a correct request to start with. Now I'm forced to handle it. I get a 200 and have to check whether there's a reply "parameter missing". That's awful.

In the end, there are a dozen or two status codes for handling many different situations, and you should use them.

Title: Should I use HTTP status codes to describe application level events

Body:
Several servers I have dealt with will return HTTP 200 for requests that the client ought to consider a failure, with something like 'success : false' in the body.

This does not seem like a proper implementation of HTTP codes to me, particularly in cases of failed authentication. I have read HTTP error codes pretty succinctly summed up as, '4xx' indicates that the request should not be made again until changed, while '5xx' indicates that the request may or may not be valid and can be retried, but was unsuccessful. In this case 200: login failed, or 200: couldn't find that file, or 200: missing parameter x, definitely seem wrong.

On the other hand, I could see the argument being made that '4xx' should only indicate a structural issue with the request. So that is proper to return 200: bad user/password rather than 401 unauthorized because the client is permitted to make the request, but it happens to be incorrect. This argument could be summarized as, if the server was able to process the request and make a determination at all, the response code ought to be 200, and it's up to the client to check the body for further information.

Basically, this seems to be a matter of preference. But that is unsatisfying, so if anyone has a reason why either one of these paradigms is more correct, I would like to know.


问:
Java Thread.sleep() considerations
I've been doing some testing in an app that I've been involved with for the past little while, and it appears as though some of the code we've written is causing a race condition.

What's happening is something like this:

```<code>//We make this call which resolves a task in a BPM service
//causing a process instance to flow to the next person/task
ServiceRemoteAPI.completeTask(taskId);

//We then make this call which depends on the complete resolution of the
//original call.
Tasks userTasks = ServiceRemoteAPI.tasksUserHasAvailable(nextUser);

//And we use those tasks to send an e-mail
for(Task task : userTasks){
    if(task == rightTask){
       sendEmail();
    }
}
</code>```

Problem is, it looks like in some cases the original remote API call isn't resolving completely before we're making the second one, and that's causing erratic behavior. So I was planning on doing something like this:

```<code>ServiceRemoteAPI.completeTask(taskId);

**Thread.sleep(5000);**

Tasks userTasks = ServiceRemoteAPI.tasksUserHasAvailable(nextUser);

for(Task task : userTasks){
    if(task == rightTask){
       sendEmail();
    }
}
</code>```

The question is, though, that I haven't done a lot of threading before, and based on my research this seems to be appropriate usage of Thread.sleep(), but I wonder if there's anything I'm missing, or if there is a more robust way to accomplish what I'd like to achieve here.

答:
Never sleep a thread for X time to give the API time to process something. This might seem to fix the problem, but it doesn't prevent race conditions, even though in all your testing you never see the race condition again. It's just not guaranteed.

In my experience, Thread.sleep() is a terribly useless function.

What you should do is pause the main thread (or whatever thread is making the 2nd call) until you get the response from the first thread (your first API call).

Google semaphore and read up a bit. Basically you don't give permission to the other thread to run until the current one is done doing it's critical section (any processing that needs to occur). You can think of current here to mean your first request to the API, and the other to be the thread that launches/waits for the 2nd API  call.

ContentLicense: CC BY-SA 3.0

Title: Java Thread.sleep() considerations


问:
Relational table design for data ownership
Setup

(schema simplified for clarity)

Suppose I have a table called resource:

```<code>+---------------+--------------+------+-----+
| Field         | Type         | Null | Key |
+---------------+--------------+------+-----+
| id            | int(11)      | NO   | PRI |
| name          | varchar(255) | NO   |     |
| owner_id      | int(11)      | NO   |     |
+---------------+--------------+------+-----+
</code>```

Each resource record is "owned" by a user defined in the user table:

```<code>+---------------+--------------+------+-----+
| Field         | Type         | Null | Key |
+---------------+--------------+------+-----+
| id            | int(11)      | NO   | PRI |
| name          | varchar(255) | NO   |     |
+---------------+--------------+------+-----+
</code>```

A resources ownership can be transferred to other users by two different methods:

a resource owner can request that another user takes ownership of the resource, and ownership is transferred as soon as that user accepts ownership.

A user can request ownership from the current owner of a resource, ownership is transferred as soon as the current owner accepts the request.

In both cases if the request is denied by the approver, than nothing is done.

My naive implementation of the tables required to implement these concepts.

```<code>transferOwnershipRequest
+------------------------+--------------+------+-----+
| Field                  | Type         | Null | Key |
+------------------------+--------------+------+-----+
| id                     | int(11)      | NO   | PRI |
| resource_id            | int(11)      | NO   |     |
| requested_by_owner_id  | int(11)      | NO   |     |
| approver_owner_id      | int(11)      | NO   |     |
| requested_new_owner_id | int(11)      | NO   |     |
| status_id              | int(11)      | NO   |     |
+------------------------+--------------+------+-----+

transferOwnershipRequestStatus
+---------------+--------------+------+-----+
| Field         | Type         | Null | Key |
+---------------+--------------+------+-----+
| id            | int(11)      | NO   | PRI |
| status        | varchar(10)  | NO   |     |
+---------------+--------------+------+-----+

// status example data
+----+----------+
| id | status   |
+----+----------+
| 1  | pending  |
| 2  | approved |
| 3  | denied   |
+----+----------+
</code>```

My business logic would update the transferOwnershipRequest.status_id as a request makes its way through the approval process.

Problem

I immediately see multiple issues with this implementation.

There is no way to track ownership changes over time.

Any timestamp fields in transferOwnershipRequest (like last_updated, request_time, approver_response_time etc) feel cumbersome

Any kind of fallback functionality (like reverting to a previous owner if the current owner is hit by a bus) would be difficult to implement.

Question

What are my options as far as relational database design patterns for this type of situation? Have you implemented something similar to this?

答: Why not capture events directly, ala Event Sourcing?  So, you'd have an Events table that would operate like an append only log file; rows would be immutable once written. Events have a time value so they can be ordered, and event name (request,approval,denial,etc..).  (You'd probably end up putting all the event types into one table using fat table.)  Ownership is considered transferred when approval event is logged.  If you need to, you can have a separate owner status, reflecting the current ownership without history.  (FYI, I've done some of this but not in SQL, though should work there, too.)</p>


问:
How does "repeat x = x:repeat x" return a list in Haskell?
This is supposed to return an infinite list of x's. However a list is created using an element, then the operator ':' and then a list.

The recursive definition of repeat' x = x:repeat' x seems to never get to the point where an actual list is created as it seams to continuously add singular elements (where?), doing something like x:x:x:x:...

答:
Expressed in pseudo-Java 8, this is how repeat works under the covers (and Haskell data types in general):

```<code>/**
 * A "thunk" is a structure that wraps around a Supplier,
 * computes its result when first requested, caches it and
 * then uses that cached value afterwards.
 *
 * The Haskell runtime generally passes thunks around between
 * object code routines and only computes the thunks's values when
 * they're really needed.  Exception: the compiler may optimize thunks
 * away in cases where it's safe to do so.
 */
abstract class Thunk<A> implements Supplier<A> {
    private Supplier<A> supplier;
    private A value = null;

    synchronized A get() {
        if (value == null) {
            value = supplier.get();
        }
        return value;
    }
}

/**
 * A single-linked list node, but the head and tail are
 * stored as thunks, not as values directly.
 */
class Node<A> {
    final Thunk<A> head;
    final Thunk<Optional<Node<A>>> tail;

    Node(Thunk<A> head, Thunk<Optional<Node<A>>> tail) {
        this.head = head;
        this.tail = tail;
    }
}

/**
 * The repeat function takes a thunk that produces an element value,
 * and gives you back a thunk that, as you chase it down, will gradually
 * produce an infinite list.
 *
 * The runtime structure for a Haskell-style list, in effect, is like
 * the return type of this function: a `Thunk<Optional<Node<A>>>`.
 */
static <A> Thunk<Optional<Node<A>>> repeat(Thunk<A> elem) {
    return new Thunk<>(() -> Optional.of(new Node<A>(elem, repeat elem)));
}
</code>```

Of course, in Haskell laziness and thunks are implicit, so you just write this:

```<code>repeat :: a -> [a]
repeat x = x : repeat x
</code>```

Body:
Expressed in pseudo-Java 8, this is how repeat works under the covers (and Haskell data types in general):

/**
 * A "thunk" is a structure that wraps around a Supplier,
 * computes its result when first requested, caches it and
 * then uses that cached value afterwards.
 *
 * The Haskell runtime generally passes thunks around between
 * object code routines and only computes the thunks's values when
 * they're really needed.  Exception: the compiler may optimize thunks
 * away in cases where it's safe to do so.
 */
abstract class Thunk<A> implements Supplier<A> {
    private Supplier<A> supplier;
    private A value = null;

    synchronized A get() {
        if (value == null) {
            value = supplier.get();
        }
        return value;
    }
}

/**
 * A single-linked list node, but the head and tail are
 * stored as thunks, not as values directly.
 */
class Node<A> {
    final Thunk<A> head;
    final Thunk<Optional<Node<A>>> tail;

    Node(Thunk<A> head, Thunk<Optional<Node<A>>> tail) {
        this.head = head;
        this.tail = tail;
    }
}

/**
 * The repeat function takes a thunk that produces an element value,
 * and gives you back a thunk that, as you chase it down, will gradually
 * produce an infinite list.
 *
 * The runtime structure for a Haskell-style list, in effect, is like
 * the return type of this function: a `Thunk<Optional<Node<A>>>`.
 */
static <A> Thunk<Optional<Node<A>>> repeat(Thunk<A> elem) {
    return new Thunk<>(() -> Optional.of(new Node<A>(elem, repeat elem)));
}

Of course, in Haskell laziness and thunks are implicit, so you just write this:

repeat :: a -> [a]
repeat x = x : repeat x


答:
As an alternative to @Chris' fine suggestion:  Queue the email requests.  That way they always go out in order.  For example, you send a "let's meet at 12:30" followed by "oops - meeting went late, meet at 1:00".

If the order is preserved, the recipient should understand.  If the order is indeterminate there's an excellent chance they will show up at the wrong time.

That's a trivial example, but, seriously, we had a highly complex multi-threaded multi-core application, and most every race-condition or out-of-order problem could be solved by adding another queue.

Title: Java Thread.sleep() considerations

Body:
I've been doing some testing in an app that I've been involved with for the past little while, and it appears as though some of the code we've written is causing a race condition.

What's happening is something like this:

```<code>//We make this call which resolves a task in a BPM service
//causing a process instance to flow to the next person/task
ServiceRemoteAPI.completeTask(taskId);

//We then make this call which depends on the complete resolution of the
//original call.
Tasks userTasks = ServiceRemoteAPI.tasksUserHasAvailable(nextUser);

//And we use those tasks to send an e-mail
for(Task task : userTasks){
    if(task == rightTask){
       sendEmail();
    }
}
</code>```

Problem is, it looks like in some cases the original remote API call isn't resolving completely before we're making the second one, and that's causing erratic behavior. So I was planning on doing something like this:

```<code>ServiceRemoteAPI.completeTask(taskId);

**Thread.sleep(5000);**

Tasks userTasks = ServiceRemoteAPI.tasksUserHasAvailable(nextUser);

for(Task task : userTasks){
    if(task == rightTask){
       sendEmail();
    }
}
</code>```

The question is, though, that I haven't done a lot of threading before, and based on my research this seems to be appropriate usage of Thread.sleep(), but I wonder if there's anything I'm missing, or if there is a more robust way to accomplish what I'd like to achieve here.


答:
It looks fine to me.  Add those timestamps to the request table and you have a permanent history - assuming all resources come into existence with a corresponding entry in the request table.  So if you want a full history, just search that table for the resource id, and that will show you the history of ownership going back to the resource creation which would be the first entry.

You might be able to cut down the number of columns in the request table by having a request type column and then a single id for the pending new owner. Since the resource id is already connected to the current owner there's no need to specify it.

Title: Relational table design for data ownership

Body:
Setup

(schema simplified for clarity)

Suppose I have a table called resource:

```<code>+---------------+--------------+------+-----+
| Field         | Type         | Null | Key |
+---------------+--------------+------+-----+
| id            | int(11)      | NO   | PRI |
| name          | varchar(255) | NO   |     |
| owner_id      | int(11)      | NO   |     |
+---------------+--------------+------+-----+
</code>```

Each resource record is "owned" by a user defined in the user table:

```<code>+---------------+--------------+------+-----+
| Field         | Type         | Null | Key |
+---------------+--------------+------+-----+
| id            | int(11)      | NO   | PRI |
| name          | varchar(255) | NO   |     |
+---------------+--------------+------+-----+
</code>```

A resources ownership can be transferred to other users by two different methods:

a resource owner can request that another user takes ownership of the resource, and ownership is transferred as soon as that user accepts ownership.

A user can request ownership from the current owner of a resource, ownership is transferred as soon as the current owner accepts the request.

In both cases if the request is denied by the approver, than nothing is done.

My naive implementation of the tables required to implement these concepts.

```<code>transferOwnershipRequest
+------------------------+--------------+------+-----+
| Field                  | Type         | Null | Key |
+------------------------+--------------+------+-----+
| id                     | int(11)      | NO   | PRI |
| resource_id            | int(11)      | NO   |     |
| requested_by_owner_id  | int(11)      | NO   |     |
| approver_owner_id      | int(11)      | NO   |     |
| requested_new_owner_id | int(11)      | NO   |     |
| status_id              | int(11)      | NO   |     |
+------------------------+--------------+------+-----+

transferOwnershipRequestStatus
+---------------+--------------+------+-----+
| Field         | Type         | Null | Key |
+---------------+--------------+------+-----+
| id            | int(11)      | NO   | PRI |
| status        | varchar(10)  | NO   |     |
+---------------+--------------+------+-----+

// status example data
+----+----------+
| id | status   |
+----+----------+
| 1  | pending  |
| 2  | approved |
| 3  | denied   |
+----+----------+
</code>```

My business logic would update the transferOwnershipRequest.status_id as a request makes its way through the approval process.

Problem

I immediately see multiple issues with this implementation.

There is no way to track ownership changes over time.

Any timestamp fields in transferOwnershipRequest (like last_updated, request_time, approver_response_time etc) feel cumbersome

Any kind of fallback functionality (like reverting to a previous owner if the current owner is hit by a bus) would be difficult to implement.

Question

What are my options as far as relational database design patterns for this type of situation? Have you implemented something similar to this?


答:
Your request table looks fine, keep it as it is, just add a general concept of "keeping track of historical records" to your other tables, this will solve all your three additional requirements.

Start by implementing the concept of ownership in a separate table "ownership":

```<code>+---------------+--------------+------+-----+
| Field         | Type         | Null | Key |
+---------------+--------------+------+-----+
| id            | int(11)      | NO   | PRI |
| resource_id   | int(11)      | NO   |     |
| owner_id      | int(11)      | NO   |     |
+---------------+--------------+------+-----+
</code>```

(and remove the owner_id from resource).

Now, extend this model by adding a "history functionality" to the ownership table. There are basically two standard ways to accomplish this: either you add a nullable timestamp field to this table and use the convention "timestamp=null" means "currently valid", "timestamp set" means "ownership in the past". Or, you create a shadow table "ownership_archive", with exactly the same attributes as the "ownership" table plus the timestamp field. Then you can move old ownership records which are not valid any more after approval of a request to that table.

If necessary, you can implement similar "history functionality" for your "resource" table and your "users" table, but that will be only necessary if you need to track the history of resources and users in detail as well.

You can find a broader discussion about storing historical data in a database in this older stackoverflow question.

Body:
Your request table looks fine, keep it as it is, just add a general concept of "keeping track of historical records" to your other tables, this will solve all your three additional requirements.

Start by implementing the concept of ownership in a separate table "ownership":

+---------------+--------------+------+-----+
| Field         | Type         | Null | Key |
+---------------+--------------+------+-----+
| id            | int(11)      | NO   | PRI |
| resource_id   | int(11)      | NO   |     |
| owner_id      | int(11)      | NO   |     |
+---------------+--------------+------+-----+

(and remove the owner_id from resource).

Now, extend this model by adding a "history functionality" to the ownership table. There are basically two standard ways to accomplish this: either you add a nullable timestamp field to this table and use the convention "timestamp=null" means "currently valid", "timestamp set" means "ownership in the past". Or, you create a shadow table "ownership_archive", with exactly the same attributes as the "ownership" table plus the timestamp field. Then you can move old ownership records which are not valid any more after approval of a request to that table.

If necessary, you can implement similar "history functionality" for your "resource" table and your "users" table, but that will be only necessary if you need to track the history of resources and users in detail as well.

You can find a broader discussion about storing historical data in a database in this older stackoverflow question.


问:
Can we add methods which is easier for assertion in test and which is only used in tests when TDD?
Here let me take a simple parking boy example.

A parking boy can manage several parking lots, and when a car comes, he will park the car into some parking lot and can also help to un-park the car.

So basically in my mind, there will be a ParkingBoy class like this:

```<code>class ParkingBoy {
    public ParkingBoy(List<ParkingLot> parkingLots) {}
    public Ticket park(Car car) {}
    public Car unpark(Ticket ticket) {}
}
</code>```

But in the practise of TDD, we design the api from the user's perspective, and won't presume what the actual class is and what methods it has. Let the tests drive them.

So I first split the requirement into several small tasks:

```<code>1. A parking boy can manage parking lots
2. A parking boy can park a car to any avaiable parking lot, and return a ticket
3. A parking boy can unpark the car for a ticket
</code>```

When doing the first task, my test is:

```<code>class ParkingBoySpec {
    @Test public void should_manage_parking_lots() {
        List<ParkingLot> parkingLots = list(parkingLot1, parkingLot2);
        ParkingBoy boy = new ParkingBoy(parkingLots);
        assertThat(boy.getParkingLots()).containsExactly(pakrkingLot1, parkingLot2);
    }
}
</code>```

But my friend has questions about the getParkingLots method.

In his opinion, this method is just used in the assertion of test, and will not be used in anywhere of the implementation, so we should not provide it. And even, we actually don't care the parking lots managed by the boy, what we care is he can park and unpark the car. So we should remove the first task and start from the task 2(park).

My opinion is:

Since we write tests before implementation in TDD, we actually don't know if the getParkingLots will be used in the later implementation.

Although the main purpose of the parking boy is to park and unpark a car, but I want to start from a simple task

The test is the "user" of the code, so when the test thinks if there is a getParkingLots, it's a good reason to provide a getParkingLots in ParkingBoy

How do you think this question?

答:
Congratulations.  You've just discovered White Box Testing.

As your friend has correctly stated, the general consensus around unit testing is that unit tests should only test the public API of a class, method or module.  It follows that, if you have internal methods, you test them indirectly, via the external methods.

In other words, unit testing is really Black Box Testing, according to the purists.

There's a problem with this, however: the API that you provide to the user of your class is not necessarily the same API that you want to test with.  Can you achieve better test coverage by unit-testing your internal methods directly?  Of course you can, that seems obvious.

The purists will say, however, that when you test internal methods, you're really testing what amounts to an implementation detail, not behavior.  It is the behavior of your external API that matters, not what goes on under the hood.  To which I would counter: integration tests are probably just as good, if not better, than unit tests for that purpose.

In addition, testing private methods can be a pain.  How does one test methods that don't expose a public interface?  There are several ways: you can use internal-accessor classes, reflection or (in C#) partial classes.  None of these ways are ideal.

So what to do?

Lately, I have been refactoring my internal methods into separate classes.  Sometimes these are collections of referentially-transparent utility methods in static classes.  These methods are highly testable and don't require mocks; all you do is hand them some parameter values and assert their returned result.  Sometimes they are simply helper classes which I compose into the main class.

I recognize that these techniques aren't the latest fashion, but they have the virtue of completely eliminating the "don't test your internal methods" problem, because none of the methods are private.  They are the only ways that I know of to get Uncle Bob's ideals without compromise: small, testable methods utilizing clean code in well-organized, small classes.


问:
How to convert a possibly ever-increasing number to a finite scale?
This is common in games, specially management games like Sim City, Civilization, etc: you have actions which provide additional integer bonuses to a metric, but the metric itself remains in a finite scale.

So, for example, suppose you have an Environment metric that's on a 0-10 scale. You can buy an item that adds +2 to the Environment, build a building that adds +20 etc. And yet the Environment metric will only display a value between 0 and 10 as a result. In the early stages of the game you might have amassed a total, "gross" amount of, say 200 environment points, and the Environment metric is 7. Later, the total environment points you gathered throughout the game might be in the tens of thousands, and still the Environment metric might read something like 7.5.

My question is, how can such a conversion be made? Can you provide some examples? I'm having a real hard time wrapping my head around this, thanks.

答:
If my old memories in mathematics are still intact, I think what you need is some function with a small enough order of growth.

I would give a try to the following:

1) x -> x ^ p, where p < 1 (e.g. for 1/2, we have the classic square root)

2) x -> log[b] (x), where b is the base of the logarithm. E.g. log10(100) = 2, ,log(2)(1024) = 10

3) x -> arctan(x), this will surely limit the output even with your grow to infinity.

The first two functions diverge to infinity, as x grows to infinity, but it might be slow enough for you.

Of course, you should apply some factors to these functions (i.e. scaling) to obtain the best results.


答:
Simple: you start with f(x)=1/x, which goes down to zero when x goes to infinity. Now you want this approximate a constant c from below, utilize it this way:

```<code> f(x)= c - 1/x
</code>```

From your example I guess you want to allow x=0, and f(0)=0, so try:

```<code> f(x)= c*(1 - 1/(x+1))
</code>```

If the slope of that function does not suffer your needs, there are further ways to modify it like replacing x by x^k, where k might be a value between 0 and 1, or by replacing x by something like x/b, where b is a number like 1000, whatever your scoring range is, or both. I hope you get the idea.

Title: How to convert a possibly ever-increasing number to a finite scale?

Body:
This is common in games, specially management games like Sim City, Civilization, etc: you have actions which provide additional integer bonuses to a metric, but the metric itself remains in a finite scale.

So, for example, suppose you have an Environment metric that's on a 0-10 scale. You can buy an item that adds +2 to the Environment, build a building that adds +20 etc. And yet the Environment metric will only display a value between 0 and 10 as a result. In the early stages of the game you might have amassed a total, "gross" amount of, say 200 environment points, and the Environment metric is 7. Later, the total environment points you gathered throughout the game might be in the tens of thousands, and still the Environment metric might read something like 7.5.

My question is, how can such a conversion be made? Can you provide some examples? I'm having a real hard time wrapping my head around this, thanks.

Body:
Simple: you start with f(x)=1/x, which goes down to zero when x goes to infinity. Now you want this approximate a constant c from below, utilize it this way:

 f(x)= c - 1/x

From your example I guess you want to allow x=0, and f(0)=0, so try:

 f(x)= c*(1 - 1/(x+1))

If the slope of that function does not suffer your needs, there are further ways to modify it like replacing x by x^k, where k might be a value between 0 and 1, or by replacing x by something like x/b, where b is a number like 1000, whatever your scoring range is, or both. I hope you get the idea.


答:
The most common operation to limit a range of numbers to a finite scale is the MOD
operation.</p>


答:
This is more gamedev.stackexchange.com answer.

Other way to do this is to have opposite "Required Environment" variable, that will increase with different buildings. Then, you can just divide those two, to get "ratio" how "Environment" variable is satisfied.

Ok, for example lets take "Sanitation" in some city building game, because "Environment" doesn't make so much sense. Every house or factory increases "Required Sanitation" value. This value represents how much Sanitation you need for perfectly cover the need for Sanitation. Each water treatment plant or garbage dump increases "Provided Sanitation" value. Now, you could display it as Provided/Required, but you can also display it as percentage value (lets call it Satisfaction) by simply dividing (Provided/Required * 100)%. You should also max it out at 100%, because it doesn't make sense to have more than 100% satisfaction. This value will always be between 0-100%.

So, the Sanitation Satisfaction drops as you build more houses and factories, and it raises as you build more garbage dumps. So even if you have thousand more "Provided Sanitation" numbers than at the beginning your game the "Satisfaction" rating can be same, because you require much more of it. This also simulates the "dimishing return" feel, because adding 10 sanitation to 70% at beginning of game is completely different to adding 10 sanitation to 70% at end of the game.

Of course, the "Required" value might be invisible to player.


答:
A parking boy can manage several parking lots, and when a car comes, he will park the car into some parking lot and can also help to un-park the car. [...]

So I first split the requirement into several small tasks:

A parking boy can manage parking lots

A parking boy can park a car to any avaiable parking lot, and return a ticket

A parking boy can unpark the car for a ticket

In my opinion, the root cause of the problem is the way that you split up the requirement is smaller tasks.

For example, what does it mean that a parking boy "manages" parking lots? Most likely it means that the parking boy knows about multiple parking lots to be able to park/unpark cars, but does it also mean that he can provide you information about those lots?

When decomposing the requirement about the parking boy into smaller tasks, you should try to keep those tasks closely related to the tasks that the final software will likely want to do with the parking boy.

If the end product only cares about the ability to park/unpark cars, then a breakdown like this would be more suitable:

A parking boy can park a car to any available parking lot that the boy knows about, and return a ticket

A parking boy will refuse to park a car if there are no available lots to the boy's knowledge

A parking boy can unpark the car when presented with a ticket

The biggest leap that you need to make here is that the first task/test requires two interfaces to be made: One to tell the parking boy about parking lots (could be the constructor) and another to park a car. If that bothers you, you can build up the test in multiple stages: First verify, by having compilation failures, that you must provide a list of parking lots and after that add the call to park a car to the same test.

Title: Can we add methods which is easier for assertion in test and which is only used in tests when TDD?

Body:
Here let me take a simple parking boy example.

A parking boy can manage several parking lots, and when a car comes, he will park the car into some parking lot and can also help to un-park the car.

So basically in my mind, there will be a ParkingBoy class like this:

```<code>class ParkingBoy {
    public ParkingBoy(List<ParkingLot> parkingLots) {}
    public Ticket park(Car car) {}
    public Car unpark(Ticket ticket) {}
}
</code>```

But in the practise of TDD, we design the api from the user's perspective, and won't presume what the actual class is and what methods it has. Let the tests drive them.

So I first split the requirement into several small tasks:

```<code>1. A parking boy can manage parking lots
2. A parking boy can park a car to any avaiable parking lot, and return a ticket
3. A parking boy can unpark the car for a ticket
</code>```

When doing the first task, my test is:

```<code>class ParkingBoySpec {
    @Test public void should_manage_parking_lots() {
        List<ParkingLot> parkingLots = list(parkingLot1, parkingLot2);
        ParkingBoy boy = new ParkingBoy(parkingLots);
        assertThat(boy.getParkingLots()).containsExactly(pakrkingLot1, parkingLot2);
    }
}
</code>```

But my friend has questions about the getParkingLots method.

In his opinion, this method is just used in the assertion of test, and will not be used in anywhere of the implementation, so we should not provide it. And even, we actually don't care the parking lots managed by the boy, what we care is he can park and unpark the car. So we should remove the first task and start from the task 2(park).

My opinion is:

Since we write tests before implementation in TDD, we actually don't know if the getParkingLots will be used in the later implementation.

Although the main purpose of the parking boy is to park and unpark a car, but I want to start from a simple task

The test is the "user" of the code, so when the test thinks if there is a getParkingLots, it's a good reason to provide a getParkingLots in ParkingBoy

How do you think this question?


答:
A parking boy can manage parking lots

Wrong. The very fact there is "manage" in that sentence should be huge red flag. This sentence says absolutely nothing about behavior of parking boy. If there is no interesting behavior, then there is no need to implement a test for this. Having this requirements can actually be dangerous, because different people imagine different things when reading this sentence. Actually, this kind of sentence would be high-level user story, that gets divided into specific tasks, like what happens if all lots are full or if customer looses a ticket.

Although the main purpose of the parking boy is to park and unpark a car, but I want to start from a simple task

Then you start with "Parking boy can park a car to a parking lot and return a ticket." This would mean from the start, Parking Boy only know about single parking lot. Only after you get requirement like "Parking boy can park multiple cars" should you realize he needs a list of Parking lots.


答:
What you should ask yourself is whether the simple fact that a ParkingBoy is managing a set of ParkingLots is something that you should be testing. What you probably should be testing is what effect does the fact that a ParkingBoy has a set of ParkingLots have on the behaviour of your class?

Here are a few approaches that I often consider (none perfect), which may give you the ability to test your class without requiring test-accessors (but with other trade-offs).

1. Test the effects on your collaborators' state.

Instead of testing whether parkingBoy is managing parkingLots directly, you could test the effect of parking a car has on the state of parkingBoy's parkingLots:

```<code>public void mustParkCarInManagedParkingLot() {
    ParkingBoy parkingBoy = new ParkingBoy(parkingLot1, parkingLot2);
    parkingBoy.park(car);
    assertThat(parkingLot1.isOccupied(car), equalTo(true));
    assertThat(parkingLot2.isOccupied(car), equalTo(false));
}
</code>```

Of course, this assumes that ParkingBay has methods that allows you to query its state. If not, then you are probably just passing the buck.

2. Test the effects on your collaborators interface

There is another popular type of unit testing approach where you don't test the effect of behaviour on the state of the class, but you actually test the interaction of your class with its collaborators. This is called "Behavioural Testing" if I recall correctly.

This approach is most practical when used with a mocking framework (I use Mockito as it is relatively simple):

```<code>@Mock ParkingLot parkingLot1;
@Mock ParkingLot parkingLot2;

public void parkingCarMustOccupyManagedParkingLot() {

    ParkingBoy parkingBoy = new ParkingBoy(parkingLot1, parkingLot2);
    parkingBoy.park(car);
    verify(parkingLot1).add(car);
    verify(parkingLot2, never()).add(car);
}
</code>```

What you are doing here is testing whether the park method has an effect on the ParkingLot collaborator via a behavioural method call rather than inspecting state (which requires accessors). The nice thing with the mocking framework is that your test class is not dependent on implementation details of ParkingLot itself - it simply requires thet the .add() method be invoked at the correct time. So to some extend you are protecting your unit test of ParkingBoy against changes in ParkingLot.

Neither of these approaches are perfect. The first still requires that you access some state, if indirectly. The second ties your test code to some private implementation details - the interaction with the collaborators, but at least this only relies on the public API of those collaborators, which I usually feel I can live with.

Body:
What you should ask yourself is whether the simple fact that a ParkingBoy is managing a set of ParkingLots is something that you should be testing. What you probably should be testing is what effect does the fact that a ParkingBoy has a set of ParkingLots have on the behaviour of your class?

Here are a few approaches that I often consider (none perfect), which may give you the ability to test your class without requiring test-accessors (but with other trade-offs).

1. Test the effects on your collaborators' state.

Instead of testing whether parkingBoy is managing parkingLots directly, you could test the effect of parking a car has on the state of parkingBoy's parkingLots:

public void mustParkCarInManagedParkingLot() {
    ParkingBoy parkingBoy = new ParkingBoy(parkingLot1, parkingLot2);
    parkingBoy.park(car);
    assertThat(parkingLot1.isOccupied(car), equalTo(true));
    assertThat(parkingLot2.isOccupied(car), equalTo(false));
}

Of course, this assumes that ParkingBay has methods that allows you to query its state. If not, then you are probably just passing the buck.

2. Test the effects on your collaborators interface

There is another popular type of unit testing approach where you don't test the effect of behaviour on the state of the class, but you actually test the interaction of your class with its collaborators. This is called "Behavioural Testing" if I recall correctly.

This approach is most practical when used with a mocking framework (I use Mockito as it is relatively simple):

@Mock ParkingLot parkingLot1;
@Mock ParkingLot parkingLot2;

public void parkingCarMustOccupyManagedParkingLot() {

    ParkingBoy parkingBoy = new ParkingBoy(parkingLot1, parkingLot2);
    parkingBoy.park(car);
    verify(parkingLot1).add(car);
    verify(parkingLot2, never()).add(car);
}

What you are doing here is testing whether the park method has an effect on the ParkingLot collaborator via a behavioural method call rather than inspecting state (which requires accessors). The nice thing with the mocking framework is that your test class is not dependent on implementation details of ParkingLot itself - it simply requires thet the .add() method be invoked at the correct time. So to some extend you are protecting your unit test of ParkingBoy against changes in ParkingLot.

Neither of these approaches are perfect. The first still requires that you access some state, if indirectly. The second ties your test code to some private implementation details - the interaction with the collaborators, but at least this only relies on the public API of those collaborators, which I usually feel I can live with.


问:
How to synchronize segments in polylines?
My input are two polylines -- I had one polyline and I computed offset of it, similarly to polygons. Here is the useful post: https://stackoverflow.com/questions/1109536/an-algorithm-for-inflating-deflating-offsetting-buffering-polygons

So I have to correct polylines, however the number of vertices (and segments) can vary, consider such polyline:

```<code>A\    /D
  \__/
  B  C
</code>```

After offsetting it up ("inside") I could get

```<code>A'\  /C'
   \/
   B'
</code>```

The horizontal segment is gone.

My task is to add in source or target polyline empty segments (i.e. duplicate vertices) in such way that the number of vertices is the same, and that I could iterate over one polyline and can get its counterpart in the other polyline just by index (no computation during "get").

In the case above I should get two polylines -- A, B, C, D (no change here) and A', B', B', C' (B' is duplicated).

I hope my question is clear. Now -- how to add "missing" vertices?

答:
You need to construct a mapping of the vertices from polyline one to polyline two, where duplicates are allowed. Once you have this, the mapping of the segments follows trivially from that.

You said you know the offset (a positive real value x) and the point coordinates.  So for each segment A -> B in the first polygon, search the second polygon for a parallel segment A' -> B' of distance x. If you find exactly one, you are done for A and B. If you find none, look if there is a "zero length" segment like A' -> A' (in other words a single point) in the second polygon with distance x from A->B. When there is exactly one, you are done for A and B as well, they both map to A'.

If you do not find any parallel segment in the given distance, the polylines cannot be mapped, so stop.

The tricky part is to deal with the situation where you find more two or more parallel segments from A->B. For this case, put "A->B" back into the "bag of unprocessed segments" and continue with the next segment, lets assume it is "B->C". Maybe you are lucky and this one has exactly one parallel counterpart "B' -> C'", so now you know where to map B. After you processed all segments, start from the beginning with all unprocessed segments again. When processing A->B, there are still two possible counterparts in the second polyline, but now you know where B must be mapped, which reduces the number of possibilities to the parallel segments of distance x where B maps to the found B'.

Continue that algorithm until you either cannot process any segment from the "unprocessed bag" any more, or the bag becomes empty.


问:
Dependency Inversion Principle and Hollywood analogy
Often DIP is known as the Hollywood principle: "Don't call us, we'll call you.".

But doesn't always higher level module calls lower level module, whether there is dependency inversion or not?

Then why is DIP called the Hollywood principle?

Am I missing something? Thanks!

答:
Dependency inversion principle is a fancy name for "coding to abstraction, rather than concrete implementation".

In procedural programming, the Holywood principle is not applicable. The flow of the application goes (mostly) from the top to bottom with possible loops, containing switches and conditionals, which decide what is the next action.

This means, the user has no control over the procedure execution, because it is predetermined by the software programmer.

DIP means, you do not know what exactly is going to be executed until the caller, usually the user of you application, wants to use (for example) some service.

Consider the following example:

```<code>interface FancyStuff
{
    int GiveMeNumber();
    bool ProcessNumber(int number);
}
</code>```

You have an interface which institutes a contract that by calling the GiveMeNumber() method you will have an int to work with and also allowing you to use the ProcessNumber() method returning boolean and taking in an int as a parameter.

Somewhere in your app, perhaps the service layer, you can have a class depending on this interface.

```<code>class FancyStuffService
{
    private FancyStuff fancyStuff;

    public FancyStuffService(FancyStuff fancyStuff)
    {
        this.fancyStuff = fancyStuff;
    }

    public bool FancyOperation()
    {
        var number = this.fancyStuff.GiveMeNumber();
        ++number;
        return this.fancyStuff.ProcessNumber(number);
    }
}
</code>```

Notice, how you are using some methods, but you do not have any implementation. The class FancyStuffService has no idea, what the implementations for the methods GiveMeNumber() and ProcessNumber() look like, but it knows, which return values it may expect and what to pass to them.

Naturally, without an implementation, the interface is pretty useless, so you implement two versions of the FancyStuff interface to provide the logic.

```<code>class FancyStuffImplOne : FancyStuff
{
    int GiveMeNumber()
    {
        return 5;
    }

    bool ProcessNumber(int number)
    {
        return number != 0;
    }
}

class FancyStuffImplTwo : FancyStuff
{
    int GiveMeNumber()
    {
        return 42;
    }

    bool ProcessNumber(int number)
    {
        return number < 15;
    }
}
</code>```

You have an implementation of your FancyStuff interface, you have a FancyStuffService which uses the interface, and you have to wire it all together. But how?

In your factory pile, of course. That is where all the new operators in your application are, meaning it is a place where the objects are constructed.

```<code>class FancyStuffServiceFactory
{
    private FancyStuff ObtainFancyStuffImplementation(int id)
    {
        switch (id)
        {
            case 1:
                return new FancyStuffImplOne();
            case 2:
                return new FancyStuffImplTwo();
            default:
                throw new RuntimException("Undefined fancy stuff ID.");
        }
    }

    public FancyStuffService BuildFancyStuffService(int fancyStuffId)
    {
        var fancyStuff = this.ObtainFancyStuffImplementation(fancyStuffId);
        return new FancyStuffService(fancyStuff);
    }
}
</code>```

And the variable fancyStuffId is exactly what you want. The integer could be populated during the runtime with an input from the user, perhaps via a selectbox, or any other method.

Only after a user inserts or selects some number, the factory is called, passing the user's input into the factory, which in return creates a FancyStuffService for the user to use. Once that is done, there can be an event mapped to call the FancyOperation() method of the FancyStuffService class.

Also notice, how you do not know which implementation of the FancyStuff will be chosen until you really need it. That is the holywood principle at work.

Note, that DIP is directly tied to dependency injection and cannot work without it. Which is good, considering dependency injection prevents global states and static methods and leads to code which is testable.

Body:
Dependency inversion principle is a fancy name for "coding to abstraction, rather than concrete implementation".

In procedural programming, the Holywood principle is not applicable. The flow of the application goes (mostly) from the top to bottom with possible loops, containing switches and conditionals, which decide what is the next action.

This means, the user has no control over the procedure execution, because it is predetermined by the software programmer.

DIP means, you do not know what exactly is going to be executed until the caller, usually the user of you application, wants to use (for example) some service.

Consider the following example:

interface FancyStuff
{
    int GiveMeNumber();
    bool ProcessNumber(int number);
}

You have an interface which institutes a contract that by calling the GiveMeNumber() method you will have an int to work with and also allowing you to use the ProcessNumber() method returning boolean and taking in an int as a parameter.

Somewhere in your app, perhaps the service layer, you can have a class depending on this interface.

class FancyStuffService
{
    private FancyStuff fancyStuff;

    public FancyStuffService(FancyStuff fancyStuff)
    {
        this.fancyStuff = fancyStuff;
    }

    public bool FancyOperation()
    {
        var number = this.fancyStuff.GiveMeNumber();
        ++number;
        return this.fancyStuff.ProcessNumber(number);
    }
}

Notice, how you are using some methods, but you do not have any implementation. The class FancyStuffService has no idea, what the implementations for the methods GiveMeNumber() and ProcessNumber() look like, but it knows, which return values it may expect and what to pass to them.

Naturally, without an implementation, the interface is pretty useless, so you implement two versions of the FancyStuff interface to provide the logic.

class FancyStuffImplOne : FancyStuff
{
    int GiveMeNumber()
    {
        return 5;
    }

    bool ProcessNumber(int number)
    {
        return number != 0;
    }
}

class FancyStuffImplTwo : FancyStuff
{
    int GiveMeNumber()
    {
        return 42;
    }

    bool ProcessNumber(int number)
    {
        return number < 15;
    }
}

You have an implementation of your FancyStuff interface, you have a FancyStuffService which uses the interface, and you have to wire it all together. But how?

In your factory pile, of course. That is where all the new operators in your application are, meaning it is a place where the objects are constructed.

class FancyStuffServiceFactory
{
    private FancyStuff ObtainFancyStuffImplementation(int id)
    {
        switch (id)
        {
            case 1:
                return new FancyStuffImplOne();
            case 2:
                return new FancyStuffImplTwo();
            default:
                throw new RuntimException("Undefined fancy stuff ID.");
        }
    }

    public FancyStuffService BuildFancyStuffService(int fancyStuffId)
    {
        var fancyStuff = this.ObtainFancyStuffImplementation(fancyStuffId);
        return new FancyStuffService(fancyStuff);
    }
}

And the variable fancyStuffId is exactly what you want. The integer could be populated during the runtime with an input from the user, perhaps via a selectbox, or any other method.

Only after a user inserts or selects some number, the factory is called, passing the user's input into the factory, which in return creates a FancyStuffService for the user to use. Once that is done, there can be an event mapped to call the FancyOperation() method of the FancyStuffService class.

Also notice, how you do not know which implementation of the FancyStuff will be chosen until you really need it. That is the holywood principle at work.

Note, that DIP is directly tied to dependency injection and cannot work without it. Which is good, considering dependency injection prevents global states and static methods and leads to code which is testable.


问:
Should I use HTTP status codes to describe application level events
Several servers I have dealt with will return HTTP 200 for requests that the client ought to consider a failure, with something like 'success : false' in the body.

This does not seem like a proper implementation of HTTP codes to me, particularly in cases of failed authentication. I have read HTTP error codes pretty succinctly summed up as, '4xx' indicates that the request should not be made again until changed, while '5xx' indicates that the request may or may not be valid and can be retried, but was unsuccessful. In this case 200: login failed, or 200: couldn't find that file, or 200: missing parameter x, definitely seem wrong.

On the other hand, I could see the argument being made that '4xx' should only indicate a structural issue with the request. So that is proper to return 200: bad user/password rather than 401 unauthorized because the client is permitted to make the request, but it happens to be incorrect. This argument could be summarized as, if the server was able to process the request and make a determination at all, the response code ought to be 200, and it's up to the client to check the body for further information.

Basically, this seems to be a matter of preference. But that is unsatisfying, so if anyone has a reason why either one of these paradigms is more correct, I would like to know.

答:
Interesting question.

Basically, we can reduce this down to the right way to classify things in terms analogous to OSI layers. HTTP is commonly defined as an Application Level protocol, and HTTP is indeed a generic Client/Server protocol.

However, in practice, the server is almost always a relaying device, and the client is a web browser, responsible for interpreting and rendering content: The server just passes things on to an arbitrary application, and that applications sends back arbitrary scripts which the browser is responsible for executing. The HTTP interaction itself--the request/response forms, status codes, and so on--is mostly an affair of how to request, serve, and render arbitrary content as efficiently as possible, without getting in the way. Many of the status codes and headers are indeed designed for these purposes.

The problem with trying to piggyback the HTTP protocol for handling application-specific flows, is that you're left with one of two options: 1) You must make your request/response logic a subset of the HTTP rules; or 2) You must reuse certain rules, and then the separation of concerns tends to get fuzzy. This can look nice and clean at first, but I think it's one of those design decisions you end up regretting as your project evolves.

Therefore, I would say it is better to be explicit about the separation of protocols. Let the HTTP server and the web browser do their own thing, and let the app do its own thing. The app needs to be able to make requests, and it needs the responses--and its logic as to how to request, how to interpret the responses, can be more (or less) complex than the HTTP perspective.

The other benefit of this approach, which is worth mentioning, is that applications should, generally speaking, not be dependent upon an underlying transport protocol (from a logical point of view). HTTP itself has changed in the past, and now we have HTTP 2 kicking in, following SPDY. If you view your app as no more than an HTTP functionality plugin, you might get stuck there when new infrastructures take over.


问:
Is it safe to only use intval to sanitize user input for a database select?
Is it safe to only use intval to sanitize the user input for a database select, as in the following example?</p>

```<code>$id = intval($_GET['id']);

$query = "SELECT * FROM table WHERE id='$id'";
</code>```

答:
intval is guaranteed to produce an integer (it returns 0 if it "fails"), and an integer is a safe thing to use in a MySQL query. This answer https://stackoverflow.com/a/3208089/458614 on SO agrees:

Yes, intval() is safe. There is absolutely no way to perform an SQL injection when the parameter is converted to integer, because (obviously) the format of an integer does not allow putting SQL keywords (or quotes, or whatever) in it.

I suspect the same goes for uses other than SQL.


答:
A common way of writing OO code is to to have code such as:

```<code>void SomeMethod()
{
    SomeClass x = new SomeClass(params...);
    ...
}
</code>```

or code such as:

```<code>void SomeMethod()
{
    SomeClass x = SomeStaticLocator.GetSomeClass();
    ...
}
</code>```

In both cases, the code is obtaining other parts of the system by "asking" for them.

With dependency injection/dependency inversion, the opposite (inverse) approach is taken:

```<code>void SomeMethod(SomeClass x)
{
    ...
}
</code>```

Rather than the method asking for its dependencies, it is told what they are. This helps to reduce coupling within the system and makes testing a lot simpler. Further improvements are to then design to interfaces, rather than concrete types to further decouple parts of the system:

```<code>void SomeMethod(ISomeClass x)
{
    ...
}
</code>```

Because the method/class is being supplied its dependencies, rather than it needing to request them itself, the terms "tell; don't ask" and "don't call us, we'll call you" are often used to sum up the behaviour of DI.

Title: Dependency Inversion Principle and Hollywood analogy

Body:
Often DIP is known as the Hollywood principle: "Don't call us, we'll call you.".

But doesn't always higher level module calls lower level module, whether there is dependency inversion or not?

Then why is DIP called the Hollywood principle?

Am I missing something? Thanks!

Body:
A common way of writing OO code is to to have code such as:

void SomeMethod()
{
    SomeClass x = new SomeClass(params...);
    ...
}

or code such as:

void SomeMethod()
{
    SomeClass x = SomeStaticLocator.GetSomeClass();
    ...
}

In both cases, the code is obtaining other parts of the system by "asking" for them.

With dependency injection/dependency inversion, the opposite (inverse) approach is taken:

void SomeMethod(SomeClass x)
{
    ...
}

Rather than the method asking for its dependencies, it is told what they are. This helps to reduce coupling within the system and makes testing a lot simpler. Further improvements are to then design to interfaces, rather than concrete types to further decouple parts of the system:

void SomeMethod(ISomeClass x)
{
    ...
}

Because the method/class is being supplied its dependencies, rather than it needing to request them itself, the terms "tell; don't ask" and "don't call us, we'll call you" are often used to sum up the behaviour of DI.


问:
Best practices in exposing interface
Let's assume I have a class that downloads data from API, cleans it and saves to database. What methods should I expose?

```<code>class ApiConnector1
{
    public string GetDataFromApi()
    {
        // ...
    }

    /// <summary>
    /// removes unnecessary records
    /// </summary>
    public string CleanApiData(string apiData)
    {
        // ...
    }

    public bool SaveToDb(string processedData)
    {
        // ...
    }
}

class ApiConnector2
{
    public string GetDataFromApi()
    {
        // ...
    }

    public bool SaveData(string processedData)
    {
        SaveToDb(CleanApiData(processedData));
    }

    /// <summary>
    /// removes unnecessary records
    /// </summary>
    private string CleanApiData(string apiData)
    {
        // ...
    }

    private bool SaveToDb(string processedData)
    {
        // ...
    }
}

class ApiConnector3
{
    public bool GetDataToDb()
    {
        SaveToDb(CleanApiData(GetDataFromApi()));
    }

    private string GetDataFromApi()
    {
    }
    private string CleanApiData(string apiData)
    {
    }
    private bool SaveToDb(string processedData)
    {
    }
}
</code>```

and usage

```<code>// ApiConnector1 usage
var apiConnector = new ApiConnector1();
var apiData = apiConnector.GetDataFromApi();
// show information that data was successfull downloaded
var cleanData = apiConnector.CleanApiData(apiData);
apiConnector.SaveToDb(cleanData);

// ApiConnector2 usage
var apiConnector2 = new ApiConnector2();
var apiData2 = apiConnector2.GetDataFromApi();
// show information that data was successfull downloaded
apiConnector2.SaveData(apiData2);

// ApiConnector3 usage
var apiConnector3 = new ApiConnector3();
apiConnector3.GetDataToDb();
</code>```

My thoughts:
In Approach 1 when somebody want to use class he have to call method in proper order, which can create bugs if he not. On the other hand in approach 3 is easy to use but introduces little magic (he doesn't know what will happen), and is hard to unit test.

答:
Case #1 and #2 are not easy to unit test, they are in fact more difficult to properly unit test. They have lots of invalid call sequences that you have to specify the behavior of.

Case #3 is simplest to both use and test; this is generally true because tests should mirror usage. Greater complexity of usage is almost always going to mean greater complexity of testing. #1 or #2 should only be used if there is a use case where the individual steps are necessary (e.g load data but don't save to db).

Even then you can probably do better by setting up a fluent api so that invalid call sequences are inherently impossible, something like:

```<code>api.loadDataSet().clean().saveToDatabase();
</code>```

Title: Best practices in exposing interface

Body:
Case #1 and #2 are not easy to unit test, they are in fact more difficult to properly unit test. They have lots of invalid call sequences that you have to specify the behavior of.

Case #3 is simplest to both use and test; this is generally true because tests should mirror usage. Greater complexity of usage is almost always going to mean greater complexity of testing. #1 or #2 should only be used if there is a use case where the individual steps are necessary (e.g load data but don't save to db).

Even then you can probably do better by setting up a fluent api so that invalid call sequences are inherently impossible, something like:

api.loadDataSet().clean().saveToDatabase();


答:
Unless is makes sense to call these operations separately then option 3 should be used.

If these operations should only be called in a specific order then they should be grouped into a single cohesive interface.

I would only look at splitting these up if they were useful individually or perhaps option 3 resulted in many hidden side effects.

Title: Best practices in exposing interface

Body:
Let's assume I have a class that downloads data from API, cleans it and saves to database. What methods should I expose?

```<code>class ApiConnector1
{
    public string GetDataFromApi()
    {
        // ...
    }

    /// <summary>
    /// removes unnecessary records
    /// </summary>
    public string CleanApiData(string apiData)
    {
        // ...
    }

    public bool SaveToDb(string processedData)
    {
        // ...
    }
}

class ApiConnector2
{
    public string GetDataFromApi()
    {
        // ...
    }

    public bool SaveData(string processedData)
    {
        SaveToDb(CleanApiData(processedData));
    }

    /// <summary>
    /// removes unnecessary records
    /// </summary>
    private string CleanApiData(string apiData)
    {
        // ...
    }

    private bool SaveToDb(string processedData)
    {
        // ...
    }
}

class ApiConnector3
{
    public bool GetDataToDb()
    {
        SaveToDb(CleanApiData(GetDataFromApi()));
    }

    private string GetDataFromApi()
    {
    }
    private string CleanApiData(string apiData)
    {
    }
    private bool SaveToDb(string processedData)
    {
    }
}
</code>```

and usage

```<code>// ApiConnector1 usage
var apiConnector = new ApiConnector1();
var apiData = apiConnector.GetDataFromApi();
// show information that data was successfull downloaded
var cleanData = apiConnector.CleanApiData(apiData);
apiConnector.SaveToDb(cleanData);

// ApiConnector2 usage
var apiConnector2 = new ApiConnector2();
var apiData2 = apiConnector2.GetDataFromApi();
// show information that data was successfull downloaded
apiConnector2.SaveData(apiData2);

// ApiConnector3 usage
var apiConnector3 = new ApiConnector3();
apiConnector3.GetDataToDb();
</code>```

My thoughts:
In Approach 1 when somebody want to use class he have to call method in proper order, which can create bugs if he not. On the other hand in approach 3 is easy to use but introduces little magic (he doesn't know what will happen), and is hard to unit test.


问:
Is agile a good fit when bidding against other vendors?
We're looking into agile increasingly at my company but I think it works better for some projects than others.

We have one product that is all ours and we control the roadmap. This is obviously perfect for agile.

However, a lot of our work involves putting in a proposal or bid against other vendors for custom development. Clients typically expect documentation on what they can expect and they want to know the budget up front. Is this really a good fit for an agile process? Contract negotiations and documentation are on the wrong side of the agile manifesto but they are also part and parcel of trying to win new business.

Of course you and I know that the specs can never accurately refelct what the users really want. At best it will be 80% right and then there will be requests for change at the end. We also know that the estimates will be difficult to get right but when you're dealing with big corps they always want a fix cost and for the small vendor to take the risk if it goes over budget. Of course in the end they have to pay for changes so it's not really a fixed budget but how do you convince a client of this when other vendors are promising they can deliver?

So on the one hand an agile process would give a better end product but on the other if you don't produce documentation and a fixed budget it's going to be difficult to win the business.

Are there examples of agile working in this environment?

答:
Estimating and bidding is one thing, making the contract is the business of managers, sales persons and attorneys, but how you develop the software after you got the contract is a separated issue. And the (initially) written down requirements in the contract as well as the price should IMHO not depend on the development methodology. Your contract might be partially different because when you plan for agile development, you want to commit the client to participation, but that's not directly related to the other points.

Lets assume you negotiated a price worth of 4 months of development effort, you made a very detailed contract and start developing waterfall-like. You stick exactly to the words of the contract, and after three months of development you deliver the first release. Now it is the first time the customer sees what he will get, he notices the errors/different possible interpretations of the contract, and it turns out half of the product must be thrown away or redesigned in full to turn the product into something usable - much more work than one month. In the best case you both agree about the misunderstandings, and set up a new contract, in the worst case the customer tries to blame you for all the misunderstandings and tries to get all the changes for the original price.

Now compare this to a more "agile" approach: you start with a contract as well, maybe not so detailed, maybe exactly as detailed as before, but also worth four months of development effort. After two weeks of development, you deliver the first release and the customer gives you early feedback how good you matched the requirements. So you can compare the feedback very early to the contract. If necessary, you can re-negotiate with the customer if he has brought new requirements on the table. There will probably other requirements of the customer which turn out "not-so-important-as-written-in-the-contract". They can get a very low priority, and you do not develop them with every bit and detail, and the customer will probably agree to this.

So in both cases you make an initial bidding and estimation, and in both cases you give the customer a documentation "what he can expect to get" beforehand. The difference in  "Agile" is it gives you much more opportunity to react early to the customers wishes, match your estimated effort better, and adapt the contract or the documentation (in consensus with the customer), if necessary.

Note, in both cases, it can turn out you wrote too many requirements into the contract for the estimated working hours, that is a always a risk - quoting Nils Bohr, "Prediction is very difficult, especially if it's about the future". Agile development, however, will (hopefully) help you not to waste too many extra hours for developing the completely wrong product.


答:
You should not open any business logic method to outer class. </p>

```<code>class ApiConnector
{
    private string GetDataFromApi()
    {
        //Logic
    }
    private void CleanApiData(string apiData)
    {
        //Logic
    }
    private void SaveToDb(string processedData)
    {
        //Logic
    }

    public GetDataAndSeaveToDB()
    {
       var appdata=null;

       appdata = GetDataFromApi();

       //validateData received data

       CleanApiData(appdata);
       SaveToDb(appdata);
    }
}

var apiConnectorObj = new ApiConnector();
apiConnectorObj.GetDataAndSeaveToDB();
</code>```

Title: Best practices in exposing interface

Body:
You should not open any business logic method to outer class.

class ApiConnector
{
    private string GetDataFromApi()
    {
        //Logic
    }
    private void CleanApiData(string apiData)
    {
        //Logic
    }
    private void SaveToDb(string processedData)
    {
        //Logic
    }

    public GetDataAndSeaveToDB()
    {
       var appdata=null;

       appdata = GetDataFromApi();

       //validateData received data

       CleanApiData(appdata);
       SaveToDb(appdata);
    }
}

var apiConnectorObj = new ApiConnector();
apiConnectorObj.GetDataAndSeaveToDB();


答:
Normally, you should not add methods which only purpose is to violate incapsulation by exposing internal state of the objects. The need of them is a good sign of issues with the design and it's better to review it and find missing entities and operations.

In your example this is exactly the case: in real world there's usually some area identified as parking and split into multiple lots. First question the driver/parking boy wants to ask is "Can I park on this parking?" Sometimes there's even a screen with a number of available parking lots, which is not a property of any specific lot, but an interface to the parking as a whole.
This means, that you need to add one more entity: Parking

In this entity you will certainly need operations to query total space and number of available lots (to be able to answer questions like "can I park" and "what is the revenue"), as well as operation to get the next available lot.

```<code>interface Parking {
    int getAvailableSpace() { ... }
    int getSize() { ... }
    /** returns DTO with number and directions to the taken parking lot */
    Route takeNextFreeLot() { ... }
    void release(int lot) { ... }
}
</code>```

This interface can then be extended to allow parking lots with electric chargers, dedicated lots for people with disabilities, lots for trucks etc.
The tests for it will look very straightforward:

```<code>Parking parking = new ParkingBuilding(15);
assert(15, parking.getSize());
assert(15, parking.getAvailableSpace());
int number = parking.takeNextFreeLot().getNumber();
assert(14, parking.getAvailableSpace());
parking.release(number);
assert(15, parking.getAvailableSpace());
</code>```

Parking boys then will work with the parking and record lot numbers in tickets, but will not operate with ParkingLot objects which will become the internal state of the Parking. Tests for ParkingBoy will look like following:

```<code>@Mock Parking parking;

public void parkingCarMustOccupyParkingLot() {
    when(parking.takeNextFreeLot()).thenReturn(new Route(1));
    ParkingBoy parkingBoy = new ParkingBoy(parking);
    Ticket ticket = parkingBoy.park(car);
    verify(parking).takeNextFreeLot();
    parkingBoy.getCar(ticket);
    verify(parking).release(1);
}
</code>```

Body:
Normally, you should not add methods which only purpose is to violate incapsulation by exposing internal state of the objects. The need of them is a good sign of issues with the design and it's better to review it and find missing entities and operations.

In your example this is exactly the case: in real world there's usually some area identified as parking and split into multiple lots. First question the driver/parking boy wants to ask is "Can I park on this parking?" Sometimes there's even a screen with a number of available parking lots, which is not a property of any specific lot, but an interface to the parking as a whole.
This means, that you need to add one more entity: Parking

In this entity you will certainly need operations to query total space and number of available lots (to be able to answer questions like "can I park" and "what is the revenue"), as well as operation to get the next available lot.

interface Parking {
    int getAvailableSpace() { ... }
    int getSize() { ... }
    /** returns DTO with number and directions to the taken parking lot */
    Route takeNextFreeLot() { ... }
    void release(int lot) { ... }
}

This interface can then be extended to allow parking lots with electric chargers, dedicated lots for people with disabilities, lots for trucks etc.
The tests for it will look very straightforward:

Parking parking = new ParkingBuilding(15);
assert(15, parking.getSize());
assert(15, parking.getAvailableSpace());
int number = parking.takeNextFreeLot().getNumber();
assert(14, parking.getAvailableSpace());
parking.release(number);
assert(15, parking.getAvailableSpace());

Parking boys then will work with the parking and record lot numbers in tickets, but will not operate with ParkingLot objects which will become the internal state of the Parking. Tests for ParkingBoy will look like following:

@Mock Parking parking;

public void parkingCarMustOccupyParkingLot() {
    when(parking.takeNextFreeLot()).thenReturn(new Route(1));
    ParkingBoy parkingBoy = new ParkingBoy(parking);
    Ticket ticket = parkingBoy.park(car);
    verify(parking).takeNextFreeLot();
    parkingBoy.getCar(ticket);
    verify(parking).release(1);
}


问:
How to document a Ubiquitous Language?
Our company is in the process of converting a lot of manual business processes (and the associated institutional knowledge) into new enterprise software.  The project is going really well, but as we proceed it is clear that there is a lot of confusion concerning terms and definitions on both the business and development sides.

I've been aware of Evan's arguments for forming a ubiquitous language for a while, but this is the first time I've needed to formally document them.  As I look around and try to think about where/how to document our UL terms, I'm kind of lost.

How do other companies document ubiquitous language?  Is this just a wiki-style dictionary?  Is there some tool intended for this purpose?

答:
You can treat "ubiquitious language documentation" as a software customization project: you need to take some software for documentation management and adapt it to your specific need. In software projects you normally start with gathering user needs, then you build information architecture and design solution and then you proceed to implementation. Below is the example of this process.

What are the user needs for it? In some organization people with different functions from different domains want to use common language dialect for describing their problems and solutions. This dialect will be defined solely by its vocabulary (words and figures of speech), since pronunciation is probably not important here and grammar will be based on literature form of the language. To document the dialect, you need to design a documentation structure that will be best suitable for managing a vocabulary (glossary of terms).

People may want to use this documentation for learning the meaning of the word or acronym, to find correct word by its synonym or definition or to learn all the words that compose the domain.

For these user needs, wiki is indeed a good choice. How does it fit?
In good wiki system like Confluence or MediaWiki it is possible to:

Create an article for each term.

Define common structure of the articles in some template, so that they will contain some common sections, that can be used for aggregation.

Easily add links to term definitions in other wiki articles.

Build aggregate tables with term definitions and embed them in other documentation.

Currently I'm using Confluence for documenting information architecture and ubiquitous language definitions are part of it. Highest level of this documentation are domain articles. In every application there are multiple domains, e.g. security, payments etc. These domains are defined by a number of interactions of user with the system, which can be described via ubiquitous language, so I put definitions of these interactions in separate subpages, and definitions of terms introduced by these interactions in the subpages of interaction pages. I put aggregate tables on parent pages so it's possible to see, for example, of which scenarios consists the domain and which terms are defined in it.

When this documentation structure is done and I go to more detailed system specifications, I can simply refer to the IA and UL definitions of the scenarios e.g. "component A implements integration with system B to support interaction C (IA scenario link) by passing information about Z (UL link)".

Title: How to document a Ubiquitous Language?


问:
Confusion about the meaning of the word aggregate in domain driven design
In a discussion about domain driven design I have learned the different people seem to think of different things when using the word aggregate. The main difficulty is that some people use the word aggregate for what other people call aggregate type.

It is quite difficult to have a discussion if people assume different meaning for the same words. For this reason I set out trying to clarify on what most people and the literature agrees too. If you give an answer to this question I would be very happy if you could provide a reference to literature.

For one person an aggregate is the boundary that groups a collection of entities. It is more a conceptional clustering boundary.

For another person an aggregate is a collection of entities transfered from a database repository (having transitional consistency). So an aggregate is something real and not just a concept. If I for example load two users from a database then I have loaded two aggregates of the same aggregate type.

Another person that also thinks that a collection of entities that are transactional consent but thinks that if you load data of a given aggregate type you can also load it partially (with some data just null for example) and still call the whole thing one aggregate while others would see this as two aggregates (with eventual consistency, meaning the consistency is given after both aggregates are saved).

To find the true meaning of the word aggregate myself I have had a look at the definition of Martin Fowler. Here an aggregate is something real and there can be two aggregates of the same aggregate type. But when reading something like this article from Vaughn Vernon I get the impression that he calls aggregate what according to the 'Martin Folwer like interpreted understanding' should be called aggregate type.

答:
There is no "database" or "transaction" in DDD. DDD is completely agnostic to databases, transactions or "eventual consistency". So any definition that includes those is not valid for DDD. That basically leaves only your first definition, which I feel is the correct one.  Also, I don't see how you can feel Martin Fowler's description fits anything other than the first definition.

But I can see how confusion can creep in when you think about "practical DDD". That means DDD + infrastructure build on top of it. For example, it might not make sense to materialize whole aggregate from database if you are working with just part of it. But then, I would question if the aggregate is really properly designed. Maybe it should be split in multiple aggregates.

Either way, if you start bringing infrastructure into it, it stops being a concept of DDD and becomes a different concept. The only thing you can do is to realize this and make sure everyone on team agrees what "aggregate" means and what properties it has. Remember, names are primarily for efficient communication, and communication with your team has priority against communication with the outside world.

ContentLicense: CC BY-SA 4.0


问:
Can't I use an enum at application level if I have a NxN relationship?
After reading the answers to this question, and this and this related questions, I'm now confused about how/if to work with an enum having an NxN relationship.

Let's say I have an entity Hotel, an my hotels can offer some services: sauna, gym, wifi, etc. Following

You should decide whether your Platform is an entity or not. If it's
  an entity, it can't be an enum

From here, and

The set of valid values is data, not code

From here, and if I understood it all correctly, my approach to modelling this with the enum in DB is to have a hotels table, a services table, and a junction table hotels_services. The services table would have two columns (id, service) or just one (service). When saving hotel information, the validity of the services would be enforced not by the application but by the DB. My Service class would then have two (Long id, String service) or just one (String service/value) fields. My Hotel class would have a List<Service> services.

So far, kind of good. But if my application's logic depends somehow on the type of service, I would like to have the enum's type safety. That looks hard, because then I would have to convert them to a ServiceEnum enum, which sounds just wrong: somewhere I would need to do the convertion, and there I would need to hardcode the possible values, so duplicity. Then, I have this extra class ServiceEnum that is confusing.

Is this how it's supposed to be? Just give up on using an enum in this case? I can live with it, but I'd like to hear that I need to, or what is it that people do in these cases.

答:
You're confusing two ideas.  The relationship between Hotel's and Service's is going to either be one-to-many or many-to-many according to whether Hotel objects have ownership over a Service or if Service's will be commonly shared amongst all Hotel's.  You can do it in either way, since they both have pluses and minuses, but the important thing to note is that you could have a potentially unlimited amount of Service's associated with a Hotel.

Today, you have "Room service", "Pool", and "Laundry service" to choose from and tomorrow you'll have "Room service", "Pool", "Laundry service", and "Parking".  While you could represent this with enum, it is likely best that you do not.  Keep in mind that entries in the Service table now only have a name, but you may later want to add other fields.  Service is just as much an entity as Hotel is, so it should be treated thusly.

In other words, you should have a Service class, and not an enum to handle Service instances.  Representing Service as a class not only represents that database table better, but it will make future maintenance much easier.  Adding say, localizations for each service is only a matter of adding a child table.  If you were handling it as an enum, you'd have to keep a static resource bundle that expands to represent new possible ServiceEnum values as you add them to your program, and though you wouldn't realize it, you'd essentially be trying to emulate ServiceEnum in your program as if it were a Service entity anyway.

It all boils down to properly representing this object in your program, and the best way to do that in this case is to treat it like any other entity.


问:
How do I create my own Objective-C to Swift converter？
I'm really interested in writing my own converter.
I know C++/Python/Objective-C/Swift and a little Haskell.

There are website like objectivec2swift and iswift.org, which can convert OC to Swift online.

I have a strong interest in making my own parser and compiler, but I don't know what should I do to get start with this converter task. It seems like making an Source to Source Compile

I really want to try doing this and I hope to get help. Thanks.

答:
This is a pretty big task.  But then again, so are most things worth doing in programming.  We start by breaking it down into smaller and smaller tasks until we get them down to the level of a problem we know how to solve.

You're right in that your overall task is a source-to-source compiler, and that you need to start with a parser.  Unfortunately, C (and by extension any superset of the language, such as Objective-C) is difficult to parse.  From the vocabulary you're using, you may already know a few things about parsing theory and the Chomsky hierarchy.  If not, read up on it.  It defines four levels of language complexity from 0 (very difficult to parse) to 3 (very easy to parse.)  Most modern programming languages are level 2, context-free languages, because it's difficult to create a useful language without a recursive grammar, which is what differentiates level 2 from level 3.  C and Objective-C are level 1, context-sensitive languages, because of the way typedefs work: the same string of code can parse in two different ways, with two different meanings, depending on whether or not the symbol it's reading is a type.  This makes creating a proper parser for them much more difficult.  Until you've got a lot of experience with compiler work, you'd be better off finding an existing parser than trying to build your own.

Once you have a parser, a lot of the hard work is done, but there's still plenty of interesting challenge ahead for you.  You can run your parser over Objective-C code and get an Abstract Syntax Tree (AST) out.  Hopefully you have a strong grasp of trees and recursion, because compiler work uses them everywhere.  I'm not kidding.

Once you have your AST, the next step is semantic analysis.  This is a formal way of saying "take this AST and figure out what its meaning is."  Exactly how you perform semantic analysis depends a lot on the specifics of how your AST works and what you're trying to do.  In this specific case, what you're trying to determine is the proper semantics for the code in question to be mappable to to Swift semantics.  (This will, of course, require a deep knowledge of how both Swift and Objective-C work.)  Your semantic analysis should either produce a new AST or annotate the AST from the parser in some way, and when you're done, you have a semantic tree.

The final phase is code generation.  This is where you walk the semantic tree, inspect the semantics of the tree, and produce code in the target language.

On the Swift side, there's some good news and some bad news.  The good news is, Apple has open-sourced the Swift language, so you can borrow their official AST, including a class called ASTPrinter that appears to take a swift AST and generate Swift code from it.  (This means that your semantic analysis phase can be turning your Objective-C AST into an equivalent Swift AST, and your code generation phase is already taken care of.)  The bad news, if you want to go this route, is that Apple's code is in C++, which is a really horrible language to work in.  But at the very least, you can use their AST code for inspiration.

Anyway, that's a very high-level overview of how to write a source-to-source compiler.  I didn't go into too many details, because details differ a lot depending on the specifics of what you're doing, but I hope it's helpful, at least for giving you an idea of what you need to do.


问:
Is it advisable to create a single API to access the database?
Got an organization that its core work is acquiring various sources of data, validating it and integrating it to existing mostly financial data sets and then availing that data to many different types of customers through various web, mobile, USSD and API applications it has developed internally and others which have been outsourced.

Some of the challenges they are having and will continue to have is enforcing application authentication to access the database, managing DB sessions and importantly, ensuring that the various developers from different countries and organizations return the same result as other applications.

We want to enhance security by encrypting the DB -Postgresql DB- and want to be able to manage access to it. There is also more development work for new applications but all new applications will now be fully outsourced.

Since data is the core asset of this company, is it advisable that the company provides one API that all other applications call when they want data from the company? Will this be a bottleneck to manage and maintain or its actually the best way to go about in such an environment? By such an environment I mean the core job is data aggregation, securing the data and then giving access to business partners who are building web apps, USSD applications, SMS applications etc making hundreds of thousands of calls a day.

答:
If you do heavily custom things like your own layer of authentication and encryption, it's a good idea to have a canonical, well-supported API. It's easier to maintain one API than several.

I'd try to have a single low-level API, something like a layer that can pass through clients' SQL while handling auth and encryption transparently. Higher-level interfaces can be built on top of it, by your team and other teams alike.

With some luck and consideration, the low-level interface can be built in such a way that standard tools will access it as is. E.g. providing a JDBC and/or Python DBI interface on top of your custom layer would greatly simplify further development.


问:
Anemic domain models and domain services injection
The anemic domain model is described as an anti-pattern in domain driven design by Martin Fowler. To have business logic on the domain models often domain services are used. But injecting domain services into domain models is considered harmful by Vaughn Vernon (see "Implementing Domain-Driven Design, Page 387).

In my opinion those opinions are contradictory, is this true? How can both points be considered?

Is it really rich domain model with domain services injected vs. anemic domain model and normal domain services?

答:
An anemic model is simply a data container. It doesn't contain behavior. (This might actually be considered a good thing in the functional paradigm.) The opposite of an anemic model is not a model injected full of domain services. You're describing two extremes -- both are bad.

If you have an anemic model, you're not fully embracing what OOP offers. If you start injecting services into those models, you're likely injecting concerns that don't belong there. Either that or your model is more anemic than you think. Why else would you need the service other than it provides something that's required but missing? (Missing might mean anemic.)

Avoiding both "tells" leads to stronger design. Do you have something in a service that a model needs? Maybe it should be moved to the model. If not, maybe you should reconsider your concerns. A model's behavior should work inside the model. It should mainly (if not only) concern itself with members. But remember, there will still be things that work on or with the model. For example, models shouldn't be opening TCP connections or listening for UI events, even if they're somehow involved. That's someone else's responsibility and that someone never belongs inside the model.


问:
AutoIncrement Integer Column,Guid or PGuid, which to choose?
Guid has been a Global Unique Identification. Why does "PGuid" (Global Unique Identification) appear?

1) Is Guid NOT PERMENT for unique? (I sometimes wonder whether Guid is REALLY PERMENT generator in .NET or Java)

2) Is "PGuid" just for "easy to read with namespace"? In what kinds of situations can we choose "Pguid" instead of "Guid" (Please offer some MOST DIFFERENCES examples).

3) Since we can use integer column in SQL or in most of db as a unique identifier, why Guid or Pguid? Are there any reasonable things for them?

It would be very nice if you can list each item and explain it in detailled sitations.

Reguards!

PS: I wanna add "Guid" or "Pguid" as a tag for my question, however I didn't find it. Anyone helps to apply it onto my question?

答:
If you only have 1 database, usually an auto incrementing number is fine as they are easy to implement and maintain.  The index on the primary key will not fragment over time because the numbers are nice and sequential.  So, there is very little index maintenance needed.  Additionally, storing a number should be smaller than a GUID as usually an INT in SQL Server only takes 4 bytes of storage.

However, GUIDs can be used when you have to replicate records from several databases into a master database.  The number "10" may be unique for that 1 database, but across several databases, that scheme will not work as those databases may also have a record "10".  So, GUIDs are used.  Then each record is unique.  With GUIDs the storage size is greater and you will have maintain the index (rebuild, etc.) with greater frequency then using a straight up integer.  There are ways to make "sequential" GUIDs to make the maintenance easier.


问:
Is there a standardized practice for ordering attributes in HTML tags?
I am working on an AngularJS project and the attributes are numerous in many of my HTML elements:

```<code>  <button type="submit"
          ng-click="Page.UI.DetailView.ExecuteFunction()"
          ng-disabled="step5.$invalid"
          class="btn btn-success pull-right">
      Submit this Product
  </button>
</code>```

Is there a standardized convention for the order of these attributes?  Alphabetical? Grouped by meaning (e.g. all angular attributes together)?  Standard HTML attributes ("type" for example) first?

答:
There is no standard. Optimize for ease of understanding, and try to be consistent.

Personally I think it's also good to always put the id attribute first, so that it's easier for testers to find it.


问:
How to refer to ByRef and ByVal in a dropdown label?
The MSDN page on ByRef and ByVal keywords isn't very helpful; unless I somehow skipped it, they're simply being referred to as "keywords" everywhere.

One of the main contributors of the Rubberduck project is working on a very cool Encapsulate Field refactoring, and the UI is coming along pretty nicely.. except I have a problem with the label above the dropdown for ByRef/ByVal, which says "Accessibility":

I don't like "Accessibility" because I'm using it elsewhere for Public/Private/Friend access modifiers where it feels more accurate.

I don't want to use "Modifier" because IMO it's just a short for "access modifier".

I'd like that label to be accurate, but my vocabulary is apparently lacking and I don't know what to call these keywords.

What should this label say, to be accurate? What's the word I'm looking for? What "family of keywords" do ByRef/ByVal belong to?

答: "Pass By Semantics" is probably closest to what you are looking for.</p>


答:
I would use either of these 3 terms to label a dropdown selecting that:

Semantics

Pass by

Parameter modifier

Title: How to refer to ByRef and ByVal in a dropdown label?

Body:
The MSDN page on ByRef and ByVal keywords isn't very helpful; unless I somehow skipped it, they're simply being referred to as "keywords" everywhere.

One of the main contributors of the Rubberduck project is working on a very cool Encapsulate Field refactoring, and the UI is coming along pretty nicely.. except I have a problem with the label above the dropdown for ByRef/ByVal, which says "Accessibility":

I don't like "Accessibility" because I'm using it elsewhere for Public/Private/Friend access modifiers where it feels more accurate.

I don't want to use "Modifier" because IMO it's just a short for "access modifier".

I'd like that label to be accurate, but my vocabulary is apparently lacking and I don't know what to call these keywords.

What should this label say, to be accurate? What's the word I'm looking for? What "family of keywords" do ByRef/ByVal belong to?


答:
In this case, I would use "Pass As" (or "Pass").

You have a flow that perfectly matches this usage.

Variable name: foo

Pass as: ByVal   / Pass: ByRef

This fits your workflow perfectly and incidentally is exactly what the article you reference indicates.

As you read through your options, it reads perfectly when using 'Pass As' as you can simply read through the heading and select the text appropriately - "'Variable name' foo, 'Pass As' value."

If you wanted to make it slightly read better you could make your list options "Value" and "Reference" depending on if your target audience is VBA programmers or non-VBA programmers who may be slightly less familiar with ByVal and ByRef keywords.

Or alternatively, change it to "Pass:" and make it "By Reference (ByRef)" and "By Value (ByVal)" in the dropdown. It looks like your dropdown has the space to show all this text. Or just the ByRef/ByVal keywords.


答:
I'd call it an "[argument] category".

The argument has a name, a type and a category.