问:
How to flag a class as under development in Java
I'm working on a internship project, but I have to leave before I can finish up everything.

I have 1 class that is not stable enough for production use. I want to mark/flag this class so that other people will not accidentally use it in production. I have already put the notice in Javadoc, but that doesn't seem enough. Some compiler error or warning would be better.

The code is organized like this:

```<code>[Package] | company.foo.bar.myproject
          |-- Class1.java
          |-- Class2.java
          |-- Class3.java <--(not stable)
</code>```

If there was a single factory class that calls those classes in public methods, I could have set the method to class3 as private. However the API is NOT exposed that way. Users will directly use those class, e.g. new Class1();, but I can't make a top-level class private. What's the best practice to deal with this situation?

答:
Why is it there in the first place?

You've checked unstable code into the mainline?  Why?

Unstable code shouldn't be checked into trunk / main / master or whatever the main trunk name is.  This is considered to be high risk development and should instead have been sequestered off in its own branch that you worked on rather than checked into main.

I would strongly encourage you (and your team lead) to read Advanced SCM Branching Strategies. In particular, pay attention to the development role and what it says about what is considered to be high risk development:

In general, consider using separate branches for each high-risk project. High risk projects are characterized by large size, large numbers of people, unfamiliar subject matter, highly technical subject matter, very tight time lines, uncertain delivery dates, incomplete or volatile requirements, and geographically distributed project teams. Similarly, consider designating a single branch for low risk development in each release. Several sources including [WING98] recommend using the mainline for this purpose. Consider the factors discussed above for the mainline before committing to this course of action. Low risk development may have different policy from the mainline even if you have multiple members of a product family coordinating through the mainline.

Letting people check unstable (or unused) code into mainline means that you will confuse future development efforts about trying to maintain this code. Every branch and clone of the rep from now until the end of time will contain this until someone says "its dead codE" and deletes it.

There are some that say "well, if its in a branch it gets forgotten" and while that may be true, having forgotten dead (and unstable) code in mainline is many times worse as it confuses all future development until it is removed - and then it is even more forgotten.  A nicely named branch of "/fooProject/branches/WeisBigIdea" (or equivalent) is visible and easier to work with in the future - especially if it kind of works.

@Deprecated

The first thing is the @Deprecated annotation.  This goes beyond the javadoc and spits out compiler warnings. javac provides a -deprecation flag that is described as:

Show a description of each use or override of a deprecated member or class. Without -deprecation, javac shows a summary of the source files that use or override deprecated members or classes. -deprecation is shorthand for -Xlint:deprecation.

As noted, this goes above and beyond the standard compiler warnings.

In many IDEs, deprecated methods and values are shown with a strikethrough:

```<code>foo.<s>bar</s>();</code>```

And would produce output like:

$ javac -Xlint:all Foo.java Bar.java
Bar.java:2: warning: [deprecation] Foo in unnamed package has been deprecated
interface Bar extends Foo { }
                      ^
```

Depending on your build structure, you may have warnings break the build.  This would only break the build if one of your classes was used (not if it is just simply compiled in).

@CustomAnnotation

There are many approaches to this.  For example, the Lightweight javac @Warning annotation which provides an annotation processor that fires off a warning at compile time when something with that annotation is used (a netbeans tutorial on custom annotation processors so you can get an idea of what is going on behind the scenes).

Oracle even describes an example of using custom annotations for an @Unfinished annotation in Making the Most of Java's Metadata, Part 2: Custom Annotations.

With the AnnotationProcessor, you can run arbitrary code at compile time.  Its really up to you to decide what you want it to do. Warn, break the build when something is used. There are numerous tutorials out there on the web for how to write this sort of code. Whether you want to generate an error when its compiled (this will be annoying and lead to it getting deleted) or if its used (quite a bit more complex to write).

Note that all of this implies changing the builds to actually use the annotation processor.

Body:
Why is it there in the first place?

You've checked unstable code into the mainline?  Why?

Unstable code shouldn't be checked into trunk / main / master or whatever the main trunk name is.  This is considered to be high risk development and should instead have been sequestered off in its own branch that you worked on rather than checked into main.

I would strongly encourage you (and your team lead) to read Advanced SCM Branching Strategies. In particular, pay attention to the development role and what it says about what is considered to be high risk development:

In general, consider using separate branches for each high-risk project. High risk projects are characterized by large size, large numbers of people, unfamiliar subject matter, highly technical subject matter, very tight time lines, uncertain delivery dates, incomplete or volatile requirements, and geographically distributed project teams. Similarly, consider designating a single branch for low risk development in each release. Several sources including [WING98] recommend using the mainline for this purpose. Consider the factors discussed above for the mainline before committing to this course of action. Low risk development may have different policy from the mainline even if you have multiple members of a product family coordinating through the mainline.

Letting people check unstable (or unused) code into mainline means that you will confuse future development efforts about trying to maintain this code. Every branch and clone of the rep from now until the end of time will contain this until someone says "its dead codE" and deletes it.

There are some that say "well, if its in a branch it gets forgotten" and while that may be true, having forgotten dead (and unstable) code in mainline is many times worse as it confuses all future development until it is removed - and then it is even more forgotten.  A nicely named branch of "/fooProject/branches/WeisBigIdea" (or equivalent) is visible and easier to work with in the future - especially if it kind of works.

@Deprecated

The first thing is the @Deprecated annotation.  This goes beyond the javadoc and spits out compiler warnings. javac provides a -deprecation flag that is described as:

Show a description of each use or override of a deprecated member or class. Without -deprecation, javac shows a summary of the source files that use or override deprecated members or classes. -deprecation is shorthand for -Xlint:deprecation.

As noted, this goes above and beyond the standard compiler warnings.

In many IDEs, deprecated methods and values are shown with a strikethrough:

foo.<s>bar</s>();

And would produce output like:

$ javac -Xlint:all Foo.java Bar.java
Bar.java:2: warning: [deprecation] Foo in unnamed package has been deprecated
interface Bar extends Foo { }
                      ^

Depending on your build structure, you may have warnings break the build.  This would only break the build if one of your classes was used (not if it is just simply compiled in).

@CustomAnnotation

There are many approaches to this.  For example, the Lightweight javac @Warning annotation which provides an annotation processor that fires off a warning at compile time when something with that annotation is used (a netbeans tutorial on custom annotation processors so you can get an idea of what is going on behind the scenes).

Oracle even describes an example of using custom annotations for an @Unfinished annotation in Making the Most of Java's Metadata, Part 2: Custom Annotations.

With the AnnotationProcessor, you can run arbitrary code at compile time.  Its really up to you to decide what you want it to do. Warn, break the build when something is used. There are numerous tutorials out there on the web for how to write this sort of code. Whether you want to generate an error when its compiled (this will be annoying and lead to it getting deleted) or if its used (quite a bit more complex to write).

Note that all of this implies changing the builds to actually use the annotation processor.


问:
What are R-value references used for?
I'm trying to dig deep into C++ and really learn the nuances of the language but one thing I've found to be really confusing is the R-Value reference. The whole double ampersand thing to be clear (in case I'm getting the terminology wrong). It's not a big deal as it doesn't seem to come up often but it seems like it could occasionally be useful to know.</p>

答:
I found this very hard to understand at first too. If you think about r-values as temporary, unnamed instances it helps. For example

functionCall( SomeObject{ 0 } );

In this case

SomeObject{ 0 }

is a constructor call creating a temporary, unnamed instance of the SomeObject class. If you make the signature of

functionCall( SomeObject&& x )

then it will only accept temporary unnamed objects.

Now, once you understand this, then you need to realize that a named, non-temporary object can be converted into an R-value either automatically by the compiler, or explicitly by the programmer ( std::move ).

If you move a named object std::move( x ) then x can no longer be used because it's "guts" (memory) have been moved.

The primary use for r-values as a language feature is to move objects into and out of functions without copying.

ContentLicense: CC BY-SA 3.0

Title: What are R-value references used for?


问:
What is a readable algorithm for selecting a random buyer based on what they purchased?
I am working on a giveaway algorithm to select a customer based on what they purchased:

If they purchase item 1, they gain 1 point.

If they purchase item 2, they gain 2 points.

If they purchase item 3, they gain 3 points.

Each purchase in the database has an item_id, which I can use to figure out which item they have purchased.

I'm trying to make the minimum number of queries to the database to prevent memory usage from going up (e.g. I can't retrieve all records and calculate points all in memory), and I'm trying to put the minimum weight on MySQL. Here is what I've come up with:

Step 1: Get Total Points

I make three count queries to the database, multiply the count by the score multiplier for each item, add the multiplied scores together, and put the results in an array. For example, if there are 10 purchases for item 1, 10 for item 2, and 10 for item 3, the results array would look like this:

```<code>[
    1 => 10,
    2 => 30,
    3 => 60
];
</code>```

As you can probably tell, the first item is just itself (10), the second item is (10 * 2) + 10 (10 * 2 is the count of purchases multiplied by the score multiplier, and then added up to the previous item). Likewise, the third item in the array is (10 * 3) + 30.

Step 2: Select a random number

At this stage, I simply choose a random number between 1 and 60 (1 and the value of the last item in the array).

Step 3: Retrieving the Winner

At this stage, I do almost the reverse of step 1. Imagine that the random number is 33. I find out what value is less than this random number (it is the item at index 2), then I deduct the value of that index from my random number (33 - 30 = 3), then I divide the remainder by the score multiplier for index + 1. In this case, the score multiplier for 2 + 1 (item number 3) is 3, so I divide 3 by 3, which gives me 1. Then I retrieve the very first purchase for item 3.

It's complicated!

It took me a lot of time just to write this here. Now imagine someone being faced with a piece of code that adds and multiplies and subtracts and divides all the time! Is there a way to make this simpler?

I don't mind some performance loss if it gains me better readability; I prefer my code to be as readable as possible, rather than performing well but being hard to understand.

答:
Generally, the solution which has the RDBMS do everything for you usually ends up being the most lightweight on the database, because you end up hitting the database only once, instead of multiple times.  This is also, by definition, the solution which taxes the web server the least, as it only brings to the server the final results, nothing more.

So, you need to do the whole thing using a single select statement, ideally only with joins, but with nested sub-selects if need be.  Then, you can try to find more optimal ways by breaking it down into pieces, but I would be willing to bet that you will not find anything that performs better.

So:

(Edit: the following is not correct, see scriptin's comments and scriptin's answer.)

Select customers.

Left join items purchased.

Left join that with the table that lists points per item.

Use SUM() to calculate total points per customer. I do not remember the exact details, but you will need to also look up the SQL reference for GROUP BY and possibly also for HAVING.

Use ORDER BY with DESCENDING on the sum of points to get the top-scoring customers first.

Use LIMIT 60 if you want to select someone among the top 60.

Nest the above in a new query which adds a column containing a random number. (See https://stackoverflow.com/questions/14798640/creating-a-random-number-using-mysql)

Add ORDER BY on the random column.

Take LIMIT 1 of that if you want only one winner.

Do all of the above in a single query, nesting as much as necessary. Indent nicely, but keep in mind that no matter how nicely you indent, in the end it will be an ugly looking monster. However, SQL is a relatively simple language, so anyone who has enough experience with SQL should be able to understand what it does and how it does it after giving it enough diligent study.  A major benefit of doing it all in a single SQL query is that it is all in one place for someone to read and understand.  (Besides the fact that it will most probably be the best performing way to obtain a random customer among the top scorers.)

Hint: in order to test this, you need to use the RAND(N) syntax of MySQL, so as to obtain the exact same sequence of random numbers each time you run the query.  If you also want to have control over the exact values of the "random" numbers, then create a separate table with customer ids and random numbers and LEFT JOIN it when testing your algorithm in order to make sure it works.  Then, replace that with RAND().


问:
How to design a UML class diagram for two sub systems?
Currently I am working on a project which has two sub system: a web application and a web API (consumed by android app) and both being developed as separate project since the API system need to deploy on different server but will access same database. After gathering requirements and producing Use cases, I have designed all the system functionalities as a single system (as a single use case diagram and I have not explicitly designed separate diagrams e.g. communication diagram, state diagram etc. for web application and API). So, my problem lies here. For instance, while producing the class diagram, I found the functions getProductDetails() (a function called from android/web api) and addNewProduct() (function called from web application) belongs to same class Product. In this case, how would I transform class diagram into coding considering the fact that function will implemented in two distinct sub-system?

Do I have to produce the same class in both system? In this case, addNewProduct() function for API system would be useless and vice versa.

Or do I have to design separate design for both system?

Any ideas on designing the class diagram would be very appreciated.
PS. I am newbie in system design, so I am eager to have any good guidance from you guys.

答:
In a system-level design, drawing classes is too much detail. The system design should contain only the sub-systems and possibly the components that are present in the system and how they are connected.

In your case, the system design would describe the two sub-systems and that they only communicate through the shared database.

When designing the sub-systems, you describe the classes that each sub-system has and which methods each class has. With two sub-systems, you would also create two sub-system designs.


答:
You need to use the running total to perform the same summation you described, but in SQL.

Assuming you have tables like this:

```<code>CREATE TABLE items(
  id int(10) auto_increment,
  score int(10),
  PRIMARY KEY(id)
);

CREATE TABLE purchases(
  id int(10) auto_increment,
  item_id int(10),
  PRIMARY KEY(id),
  FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE CASCADE
);
</code>```

The query you're looking for is something like this:

```<code>SELECT a.id, SUM(i.score) as running_total
FROM purchases a,
     purchases b JOIN items i ON i.id = b.item_id
WHERE b.id <= a.id
GROUP BY a.id
HAVING SUM(i.score) >= (SELECT ROUND(RAND() * (SELECT SUM(i.score) from purchases a JOIN items i ON i.id = a.item_id)))
ORDER BY a.id
LIMIT 1;
</code>```

I create the running total by joining the table on itself, using ID for ordering. b.id <= a.id makes sure that running total only takes previous purchases.

Then I apply a filter SUM(i.score) >= (SELECT ROUND(RAND() * (SELECT SUM(i.score) from purchases a JOIN items i ON i.id = a.item_id))) and LIMIT 1 to get just one result.

See SQLFiddle for step-by-step explanation.

The only concern is performance, you have to try it on your actual data. If it's bad, I believe there is a way to optimize this. Replacing HAVING with another WHERE condition is probably a good way to start.

Related article: NoSQL? No, SQL! – How to Calculate Running Totals

Title: What is a readable algorithm for selecting a random buyer based on what they purchased?

Body:
I am working on a giveaway algorithm to select a customer based on what they purchased:

If they purchase item 1, they gain 1 point.

If they purchase item 2, they gain 2 points.

If they purchase item 3, they gain 3 points.

Each purchase in the database has an item_id, which I can use to figure out which item they have purchased.

I'm trying to make the minimum number of queries to the database to prevent memory usage from going up (e.g. I can't retrieve all records and calculate points all in memory), and I'm trying to put the minimum weight on MySQL. Here is what I've come up with:

Step 1: Get Total Points

I make three count queries to the database, multiply the count by the score multiplier for each item, add the multiplied scores together, and put the results in an array. For example, if there are 10 purchases for item 1, 10 for item 2, and 10 for item 3, the results array would look like this:

```<code>[
    1 => 10,
    2 => 30,
    3 => 60
];
</code>```

As you can probably tell, the first item is just itself (10), the second item is (10 * 2) + 10 (10 * 2 is the count of purchases multiplied by the score multiplier, and then added up to the previous item). Likewise, the third item in the array is (10 * 3) + 30.

Step 2: Select a random number

At this stage, I simply choose a random number between 1 and 60 (1 and the value of the last item in the array).

Step 3: Retrieving the Winner

At this stage, I do almost the reverse of step 1. Imagine that the random number is 33. I find out what value is less than this random number (it is the item at index 2), then I deduct the value of that index from my random number (33 - 30 = 3), then I divide the remainder by the score multiplier for index + 1. In this case, the score multiplier for 2 + 1 (item number 3) is 3, so I divide 3 by 3, which gives me 1. Then I retrieve the very first purchase for item 3.

It's complicated!

It took me a lot of time just to write this here. Now imagine someone being faced with a piece of code that adds and multiplies and subtracts and divides all the time! Is there a way to make this simpler?

I don't mind some performance loss if it gains me better readability; I prefer my code to be as readable as possible, rather than performing well but being hard to understand.

Body:
You need to use the running total to perform the same summation you described, but in SQL.

Assuming you have tables like this:

CREATE TABLE items(
  id int(10) auto_increment,
  score int(10),
  PRIMARY KEY(id)
);

CREATE TABLE purchases(
  id int(10) auto_increment,
  item_id int(10),
  PRIMARY KEY(id),
  FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE CASCADE
);

The query you're looking for is something like this:

SELECT a.id, SUM(i.score) as running_total
FROM purchases a,
     purchases b JOIN items i ON i.id = b.item_id
WHERE b.id <= a.id
GROUP BY a.id
HAVING SUM(i.score) >= (SELECT ROUND(RAND() * (SELECT SUM(i.score) from purchases a JOIN items i ON i.id = a.item_id)))
ORDER BY a.id
LIMIT 1;

I create the running total by joining the table on itself, using ID for ordering. b.id <= a.id makes sure that running total only takes previous purchases.

Then I apply a filter SUM(i.score) >= (SELECT ROUND(RAND() * (SELECT SUM(i.score) from purchases a JOIN items i ON i.id = a.item_id))) and LIMIT 1 to get just one result.

See SQLFiddle for step-by-step explanation.

The only concern is performance, you have to try it on your actual data. If it's bad, I believe there is a way to optimize this. Replacing HAVING with another WHERE condition is probably a good way to start.

Related article: NoSQL? No, SQL! – How to Calculate Running Totals


答: I like SysML (a profile for UML) better than UML for doing this sort of "System of Systems" design.  The block layout is a little more intuitive. Also, the SysML working group has put a lot of effort into creating nice modeling constructs for interfaces. </p>

Title: How to design a UML class diagram for two sub systems?

Body:
Currently I am working on a project which has two sub system: a web application and a web API (consumed by android app) and both being developed as separate project since the API system need to deploy on different server but will access same database. After gathering requirements and producing Use cases, I have designed all the system functionalities as a single system (as a single use case diagram and I have not explicitly designed separate diagrams e.g. communication diagram, state diagram etc. for web application and API). So, my problem lies here. For instance, while producing the class diagram, I found the functions getProductDetails() (a function called from android/web api) and addNewProduct() (function called from web application) belongs to same class Product. In this case, how would I transform class diagram into coding considering the fact that function will implemented in two distinct sub-system?

Do I have to produce the same class in both system? In this case, addNewProduct() function for API system would be useless and vice versa.

Or do I have to design separate design for both system?

Any ideas on designing the class diagram would be very appreciated.
PS. I am newbie in system design, so I am eager to have any good guidance from you guys.


答:
There are several possibilities to visualise the two subsystems.

Considerations beforehand

But the fact that it is difficult to model the two interwoven systems in UML may indicate that there some problems with your solution.  Therefore, you should first ask yourself the question whether it really are two systems.  There are several possible alternative answers:

your two systems are a single system that has two interfaces*;

one of your two systems is built on top of the other;

your two systems are in fact three systems with the two systems you recognised using common functionality of a third system;

the two systems are a number of cooperating micro services (i.e. systems in their own right); or,

it really are two (interwoven) systems.

A second question you can ask yourself is "if a class C has completely different responsibilities in system S1 compared to system S2, is it the same class or should it be two distinct classes**.

To answer the question.

To visualise two interwoven systems you can use colour.

I've used greyed classes to indicate things like "existing classes in an other system that this system uses" and "possibilities for future extension that exist but that we will not implement at first".  You could, for example, colour classes or methods blue for system S1, yellow for system S, and green for shared between both systems.  With some explanation human readers will understand it and can see the big picture and how the systems relate; automated tools on the other hand will not be able to understand the semantics you attach to colour.

Or, you can use UML packages

Each system can refer to the other sysem as a package.  You can make a diagram for each system.  Include the other system as a package in the current system's diagram.  And draw classes from the other system, that are relevant for the current system, inside the other system's package.

UML tools do understand packages.  The circular dependency may cause a problem.  And when using packages you really have to decide to with system a class belongs.  You cannot represent a class with some method in system *S1 and some methods in system S2 with UML packages.

[*]: Perhaps with one or both of the system's interfaces not providing access the full functionality of the system.

[**]: Perhaps the two classes can share the same name but be in different packages (in UML terms) and in different namespaces in your implementation language.


问:
Web applications: is there such a thing as "semi-stateful"?
I'm a bit of an amateur when it comes to web development, but I need to do something a little more sophisticated than usual at work and I'm not sure how best to proceed.

The setup is as follows.  I have a web server set up which takes some input from the user, gathers a reasonably large amount of data from various web APIs, does some processing, and sends some processed data back to the user.  In particular, the server is stateless.

What I want to do next is allow the user to inspect the output and dynamically request additional information about the unprocessed data.  I can think of two potentially sensible ways to do this:

Give the user all of the data and let him or her sort it out.

Store the unprocessed data in a database and retrieve it when asked.

I can rule out option 1 because some of the unprocessed data is proprietary - I am only allowed to distribute summary statistics.  And I would rather not do option 2 because it seems like an ordeal and there is no need to keep the data around once the user is finished making requests.  What I want is a third option which allows me to keep the data in the first request around for subsequent requests (until, say, the user is inactive for 5 minutes or something).  Does this sort of system exist?  Or is there a reason why it is a bad idea?

答:
There's nothing particularly wrong with having a stateful communication rather than stateless. But it is harder to implement from both the client and server perspective.

In your case I think the answer will be determined by whether you are able to make the second 'additional' request without first making the first 'processing' request and how you handle this process.

I'm guessing that 'processing' is a computationally expensive process, which you don't want to repeat, so caching the result seems like a good idea in any case. What if the client sends the same process request twice for example? you would want to just return the result.

Once you have these intermediate results floating around, you could offer a list of possible 'additional' requests via a third 'list intermediate data' request. this would allow you to keep the service strictly speaking stateless, as you can make this 'list' request at any point and then follow up on one of its options without having to have made the first 'process' request.

The length of time you keep the intermediate data is a tricky one. But perhaps you can instead offer a 'delete intermediate data' service to the client, so they can tell you when they have finished.


问:
Enforcing aggregate rules in purchase management domain
I'm having problems defining the aggregate boundaries (and maybe even the aggregate root) to enforce the transactional consistency rule. Let me first describe the problem domain.

In our domain we have a project that contains a budgeted plan, which in turn contains hundreds of purchase items that need to be purchased. Some of these items are selected to form a purchase task. When this occurs, the item should be moved from the budgeted plan to the purchase task. The flow of the item is of importance (needs to be audited for later review), so the item must be an entity and have an identifier.

My current design would have the purchase task as the aggregate root and it would know all its items. I'm inclined to leave the budgeted plan outside of this aggregate as it contains lots of items. But then I began to doubt myself.

Vaughn Vernon describes that a well designed aggregate should be "based on true business rules that require specific data to be up-to-date at the end of a successful database transaction". In my scenario the purchase item that is moved from the budgeted plan to a designated purchase task should be removed from the list of items in the budgeted plan. Now if my aggregate would not include the budgeted plan and all the hundreds of items there, I cannot enforce this rule. If I do include it, the aggregate grows large and will have to load the all the budgeted plans items (hundreds, maybe thousands) for validation to succeed.

As the purchase item is also an entity that needs to be trackable and modifiable I think that should be it's own aggregate root. Then the item should be referenced only by its ID from both the budgeted plan and the purchase task. Is this correct?

The main question is: How should I define my aggregate boundaries and roots to be able to enforce the transactional consistency rule in this domain?

答:
When this occurs, the item should be moved from the budgeted plan to the purchase task.

Are you sure?  That language sounds really strange.

I would expect a budget plan to act like a shopping list.  You plan what you are going to buy, and then when you get to the store you start checking things off the list.  Note that this is different from removing the items from the list, which would involve what? tearing the list into pieces so you can take the item at the end and throw it away.

Note that because the list persists, you arrive at checkout and have the ability to compare the contents of your cart to the list.

As the purchase item is also an entity that needs to be trackable and modifiable I think that should be it's own aggregate root.

Which invariants does the purchase item entity need to enforce for itself in this domain?


问:
Designing around shallow constness with inheritance

Background

I'm writing an image handling class. For this question two requirements of the class are of interest:

Must have "deep" const correctness.

Must allow sub-image aliases, a.k.a. sections or slicing without performing deep copies of image data.

By deep constness I mean the following. Consider this example class:

```<code>class Image{
public:
    ...
    Image(const Image&);

    Image alias(int x0, int y0, int x1, int y1) const;
private:
    Buffer image_data;
};
</code>```

And assume you have a function that is passed a const reference to a image, like so:

```<code>void foo(const Image& im){
    Image alias = im.alias(0,0, 10, 10);
    // Hold on, the mutable alias can modify the data in the const argument!
}
</code>```

The above alias function call defeats the constness of the argument because the contents of the argument image can be modified through the non-const alias. I can't return a const Image from alias because well that makes no sense really and the copy constructor of Image will happily construct a mutable instance anyway.

My solution (and I've seen it used often so I don't claim originality here) is to introduce two classes (interfaces really, but for the simplicity they are classes in this example and return by value is okay, in reality alias(...) returns a shared_ptr to interface):

```<code>class ConstImage{
public:
    ConstImage alias(...) const;
};

class Image{
public:
    Image alias(...);
};
</code>```

Now the following code:

```<code>void foo(const Image& im){
    // compile error, cannot convert ConstImage to Image, perfect!
    Image alias = im.alias(...);
}
</code>```

And of course you would change the signature to void foo(const ConstImage& im) so that you can accept invocations like foo(const_im.alias(...)) or other ConstImage objects.

Now of course we want foo(const ConstImage& im) to be callable (1) with a mutable Image too and here is where the question comes in.

Question

Using inheritance: class Image : public ConstImage will make all Image types usable through ConstImage references and pointers. It will also facilitate code-reuse between the const and non-const implementations which by necessity are very similar.

This solves the above mentioned problem (1). However if you look at the inheritance relation as an "is a" statement then "a mutable image IS AN immutable image" makes no sense. Which speaks against using inheritance here.

My question is, is this kind of (ab)use of inheritance widely acceptable? Is there some other better solution that I have overlooked? Note that the Image class is more of an interface so naive value conversion from Image to ConstImage isn't possible. Although one could probably come up with something crazy to allow it.

答:
Looks like I'm a little late to the party, but hopefully the OP sees this answer. The best solution to your problem is not to use inheritance at all, but rather leave the Image class as is. Instead, what you need are two Alias classes: Alias, and ConstAlias. Then, change all of your functions that don't really need the Image itself, but an alias to take Alias or ConstAlias as appropriate. The alias method has a const and non-const version, which return ConstAlias and Alias types respectively.

Does this sound familiar from somewhere? Replace Image with vector, and Alias with iterator, and you've got... well, half the STL.

It's better to distinguish explicitly between Images and Aliases using the type system, the former is an owner, and the latter is not. Most functionality just requires a view (possibly mutable) of the data, it doesn't need to actually mess with the ownership at all. This makes you think harder about whether your function should take an Image or just an alias. It also allows you to avoid using shared_ptr at all and stick with a much simpler and clearer (and possibly more performant) model of ownership.


问:
RESTful service layer with MVC
I need a advice on creating an architecture where I want API layer in between UI layer and business layer. UI layer should only consume REST services for displaying data.

Reason for doing this is that we need to expose same service for others clients like iPad, Android etc.

Now my questions are:

Do we need dependency injection in this case? (I don't think so because we are not going to use any reference at UI layer. The only thing is, we are manipulating the JSON returned by service.)

Will it hurt performance?

Is this the right approach?

答:
Do we need dependency injection in this case?

It depends on what you try to accomplish. Dependency injection is needed in order to easily replace the underlying implementation. Common examples are:

To replace actual implementation by stubs/mocks in a context of unit testing.

To easily swap between several data access layers (for instance to deal with several database systems).

In your case, you would probably want to test your presentation layer without having to do the actual calls to the API, in which case DI would be useful.

Will it hurt performance?

Any additional abstraction or layer hurts performance.

What you should ask yourself is:

Do you actually have performance issues?

If yes, what profiling reveals about the source of the slowness?

Don't guess. Measure.

Is this the right approach?

Having a common API which is then used at once by desktop applications, mobile applications and web applications is a common practice and makes it possible to reduce code duplication and simplify the porting of a system to the different types of devices.

Title: RESTful service layer with MVC


问:
Should a class go inside the package which pertains to it?
```<code><?= $vars['title'] ?>
</code>```

For example, if we were writing a library from scratch, and we had File, FileHandle, DirHandle, and FileSystem classes, would each of these go inside a package/namespace called file? Or one named filesystem? Or os or fs? And if one of the former two, would it be a problem that we had file::File? I know that in Python at least, there are packages structured this way. But it seems a little ugly to have the class name inside the package with the same name.

An alternative would be to put the class at the same level of hierarchy as the package, so you might have:

```<code>class File {
    getFileSystem () : FileSystem
    getGroupId () : int
    getSize () : int
    ...
}

// functions which don't need to know the internals of the File class
file::putContents
file::getContents
file::readLine
file::truncate
</code>```

But then you have the question of... do you put something like FileHandle at the same level as File, or do you put it within the file package? And if the latter, do you use file::FileHandle or simply file::Handle? What about directories? Would you do file::DirHandle? Or should all of this be in an os package?

I guess I'm trying to reconcile the idea of grouping related concepts together into hierarchical packages vs. keeping the names sensible, descriptive, and not redundant.

One potential answer to this that I've considered is that packages should only be used where everything that might go in the package could conceivably have the name of the package in its name. For example, putting a Directory class in the file package wouldn't be right, since you wouldn't say DirectoryFile (or at least, not usually). I contrast, for something like Google Maps, it would make sense to put stuff about Google Maps markers and maps into a package called google::maps::. Likewise, a package named mysql would make sense.

So are packages really only perfect for companies and products, not concepts? Or is it that I'm trying to group concepts at too fine a level? Are there any style guides for this sort of thing?

答:
Packages are tools.  If you find yourself sweating the details, just ask yourself what you're really accomplishing when you subdivide or group your classes.

Some languages e.g. java have special scoping rules and access control for classes residing in the same package.  In these cases, don't fight or amend the language's native concept of what a package is for.  If you want those access rights between two classes, put them in the same package.  If you don't have any reason to suspect that two classes will need these privileges, separate them.

Some languages give you an ergonomic benefit when some classes tend to be included together if they are in the same package.  Again, don't fight the language.  Use the tool the way it's intended to be used.  If class A must logically be imported every time you import class B, put them in the same package.  If they don't, separate them to avoid future clashes.

If you're in a significant sized codebase and there is no very compelling reason to change, be consistent with the existing organization.

Otherwise we're talking about aesthetics and human readability.  Ask a coworker which package he or she would look in first for your class and that's where it should go.  Subdivide to the point that you can scan a package's classes visually, stop subdividing before  your coworkers can't immediately guess (correctly) where they are.

If you're still not sure, get it to the point where if it's wrong, you can fix it quickly, then move on.


问:
HTML 4, XHTML and CSS 2 - How long until these are obsolete?
I got into the game of programming, exactly a year ago. Now i am posing as an HTML, CSS and Javascript Guru.

html5 and css3 are the new things out there but in my opinion they are still experimental, (some new websites remind me of the blink tag). I know HTML 4.x and xhtml were out there for a very long time and eventually became standards. But i wasn't around to see that transition from experimental to strict standards. So my question is how long will it take for us to get there with these new versions of html, css and javascript.

Most of the code I see around is accommodating older browsers, and i can fairly say that it is easier to write javascript code that work in ie5-8 than to write one that works with i9 and ie5 (let's take localStorage for this example).

So when are we going to get to this level where if you want to  make sure code works almost universally you have to make sure it's at least HTML5 and CSS3 compliant.

答:
Never - at least for HTML4 and CSS2.

HTML5 is basically a backwards-compatible superset of HTML4, and CSS3 is a superset of CSS2. This means a browser supporting HTML5 will also support HTML4, while the reverse is not true. Same with CSS. So HTML4/CSS2 will always be more widely supported than the more recent versions, and they will never be obsolete.

The exception is some obscure features from HTML4 which is declared obsolete in HTML5 - but there were never widely supported or used in the first place.


问:
Why can't I return an implementation of an interface for a method that requests the interface?
I am implementing an interface I on a class A.
Class A implements I.

I have an Iterator T that is supposed to return an object which implements I everytime I call next.

My iterator goes as follows (of course omitting other stuff):

```<code>public class T<I> implements Iterator<I> {
    @Override
    public I next() {
        return new A();
    }
}
</code>```

However, I get this error: Required I, found A (for the return new A() line)....

I don't know what is happening. Can someone help me?

答:
Your class definition introduces I as a type variable, meaning that it does not refer to the interface you expect it to. Change your class definition to

```<code>public class T implements Iterator <I>
</code>```

and everything should work fine.

Body:
Your class definition introduces I as a type variable, meaning that it does not refer to the interface you expect it to. Change your class definition to

public class T implements Iterator <I>

and everything should work fine.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答: and, obviously, get_shutdown_functions() and unregister_shutdown_function(). Currently there is no way to acces that. And more generally, some abstract support for callback stacking - something to unify spl_autoloads, shutdown functions, error handlers (currently not stackable, but maybe...) etc. Kind of register_callback($callback, $stack) and so on , with some predefined stacks ('autoload', 'shutdown', 'error' ...) called by php or by user itself.</p>

ContentLicense: CC BY-SA 2.5


问:
How to retrieve the third-party library licenses
I am looking for a way to automatically collect all the third-party library licences that my project is using. Currently I am collecting by hand the licences on github.

So far , I don't have a clear idea how to get a 3rd party library licence automatically.
What is the most reliable way to get the 3rd party licence ?

Small ideas :

Most Github projects contain a licence text. ex : https://github.com/square/dagger . But can you map a dependency
'com.squareup.dagger:dagger:1.2.2' with its github url ?

most JVM artifacts are found on mvnrepository . I don't know if mvnrepository.com list the licence.

the .jar files may contain licence text . How to extract it ?

Related :
What is the best practice for arranging third-party library licenses "paperwork"?

答:
One possible way to automate part of this is the following algorithm:

```<code>Add the project GAV to queue
For each GAV in queue
  Add all dependencies from GAV to queue // optional after first run?
  Download jar
  Extract/unzip jar and search root directory of jar for file containing "license" // see Java zip classes
  Parse root pom.xml for license information
  if neither work
     output that license information could NOT be found
  else
     save license information for GAV
// end for loop
</code>```

You could create a maven plugin that does this and outputs the file to the root directory of your project (instead of a build directory) so that you notice when the file changes. Otherwise, a perl/python script might be easier (but also more of a hack.. :) ).

Given that it's easy to use transitive dependencies in your code without knowing it, you should also look at using the the Ban Transitive Dependencies enforcer rule.

If you do not do that, then I would definitely make sure to scan all transitive dependencies for their licenses (always use the 3rd line of the algorithm).

Body:
One possible way to automate part of this is the following algorithm:

Add the project GAV to queue
For each GAV in queue
  Add all dependencies from GAV to queue // optional after first run?
  Download jar
  Extract/unzip jar and search root directory of jar for file containing "license" // see Java zip classes
  Parse root pom.xml for license information
  if neither work
     output that license information could NOT be found
  else
     save license information for GAV
// end for loop

You could create a maven plugin that does this and outputs the file to the root directory of your project (instead of a build directory) so that you notice when the file changes. Otherwise, a perl/python script might be easier (but also more of a hack.. :) ).

Given that it's easy to use transitive dependencies in your code without knowing it, you should also look at using the the Ban Transitive Dependencies enforcer rule.

If you do not do that, then I would definitely make sure to scan all transitive dependencies for their licenses (always use the 3rd line of the algorithm).


问:
Do software patches ever modify an existing file or do they replace the whole thing?
Imagine a modern PC game for example. I'm using this example because typically the executable file is fairly large, and especially in modern games the resource files are also pretty big.

Patching a resource file is fairly simple because depending on the file format it could just be a case of replacing one contiguously stored resource with another. But what about if you wanted to change one line of code in a bulky executable?

When the code is compiled, it's optimised and rearranged to allow for structures not present in lower level languages, and so generally the resulting code file is very rarely a line-by-line translation of the high level code. So with this in mind if you wanted to change one particular line to fix a bug, would the update then contain a new version of the entire executable, or can it work like some sort of difference-spotting technique like a source control system?

答:
Yes and no, both mechanisms work.

The easiest way to patch a product is by replacing a component (eg a dll) with a new version of it. This usually requires the program to be stopped, so it's useful for a game or other program that is run occasionally but not so good for OS components.

So various techniques have been developed to directly patch a running executable (or dll). Microsoft does this by creating all dlls with a space before each function so it can be overwritten by a "jump to a new location" patch, the new function can be shipped and the location changed so all running programs will start to use the new code once patched. (Technical details here) This occurs at runtime, so stopping the patched program will require the patch to be re-applied (this either occurs automatically or the component is upgraded once the program is stopped - i.e. on a reboot, the new dll replaces the old one so the runtime patching is no longer required).

ContentLicense: CC BY-SA 4.0


问:
Microservices REST or AMQP, which case
I've read many articles concerning microservices architecture and I was wondering when to use AMQP or REST.

I've read that loose coupling between services is a good thing and AMQP seems to be a good choice in that case. But if we use AMQP, this means that we do not need REST endpoints anymore (but it means that we lose the HATEOAS concept).

But is REST really a good way to build my services? Cause I won't use any endpoints... In which case one is better than the other one?

When should I use one or the other?

答:
REST is a standard technology that particularly is suited for interoperability between components - this is the key part, its great for making a web service that someone else can consume. However, it suffers from the usual problems of such interoperability in that it is less efficient than a custom protocol.

If you're writing a back-end architecture where the services are only consumed by yourself, then you can use whatever protocol you like - you're no longer constrained by using one that is so interoperable. You can use a MQ or something more tightly coupled and performant. Which one you use depends on your use-case, a message bus is very good for distributed set of services that process data where the client doesn't care who gets the messages it sends out.

Title: Microservices REST or AMQP, which case


答:
Use both.

REST style JSON web services are great for interoperablity with javascript, ios etc

AMQP is great for long running processes, events and orchestration of microservices.

But both are just communication wrappers for the actual service, you can expose the same service in multiple ways and probably should.

AMPQ can work well exposed over Websockets, which can look pretty much like a REST endpoint if you squint at it.

Title: Microservices REST or AMQP, which case

Body:
I've read many articles concerning microservices architecture and I was wondering when to use AMQP or REST.

I've read that loose coupling between services is a good thing and AMQP seems to be a good choice in that case. But if we use AMQP, this means that we do not need REST endpoints anymore (but it means that we lose the HATEOAS concept).

But is REST really a good way to build my services? Cause I won't use any endpoints... In which case one is better than the other one?

When should I use one or the other?


问:
How to properly store messages in a webservice?
We are building a multitenant webservice with PHP and MongoDB. There is a need for communication between service employees and clients, communication can be established in many different ways. Some of them are: SMS, MMS, Email and, possibly, an internal chat system.

The question is, how to properly implement the database structure for it?

My boss insists, that there should be one collection - messages, where we would store the sender, type, receiver, message body, timestamp and arguments it that way, that we would have a route which points to users/1235/messages, where the chat history can be retrieved.

I, however, disagree on it and argument it in such a way, that every message type has its own properties and settings. For example, it would not be right to store the whole body of SMS message inside just one instance - one SMS can consist of up to 6 parts, which are delivered independently (they have their own tracking ID). This way, it is easy to track, which parts have been delivered, thus allowing to send missing parts instead of the whole message. Emails also have their own properties such as address, reply-to and other stuff.

Probably I think about constistency too much, since I've been using MySQL for a long time. But, in my opinion, storing all messages just in one collection would give a huge property diversity in the object. Storing each message system separately, however, would give flexible options, allowing to track each message's status and other details. All the messages normalized and joined into one data collection later. (Concat SMS to build the whole body, etc)

So, what kind of solution would you see here?

答:
This sounds to me like the same problem you would have storing sub classes in a relational database.

ie. you have an abstract Message class with some common fields, Id, SenderId etc and then subclasses such as SMSMessage, EmailMessage with extra fields.

My approach here is to have one table Message with the common columns plus 'Type' and 'TypeId' then a table per type with the extra type specific data

This creates an odd relationship, but does allow you to do simple, 'get all messages regardless of type' queries, plus more complicated, 'get sms messages where some parts have failed to send'

Translating to a NoSql approach does raise some interesting questions about how many object types you want to have a single collection. However, I believe the c# MongoDb client will allow you to put the sub classes in the same collection and correctly deserialise them from BSON (assuming you have set the mappings up) Which suggest this is the approach they expect you to take.

If you did split this objects into multiple collections, how would you enforce the relationship integrity? It seems like a RDB style approach to me, which would give you additional problems.


答:
When the executable is changed, it's often easier to replace the entire executable, rather than modify it. This makes it possible to patch the executable no matter which version it's at (unlike binary difference patchers). The vast majority of modern games do it like this.

In modern games, the size of the executable pales in comparison to the resource files, so there is little to gain by modifying the executable.

Title: Do software patches ever modify an existing file or do they replace the whole thing?

Body:
Imagine a modern PC game for example. I'm using this example because typically the executable file is fairly large, and especially in modern games the resource files are also pretty big.

Patching a resource file is fairly simple because depending on the file format it could just be a case of replacing one contiguously stored resource with another. But what about if you wanted to change one line of code in a bulky executable?

When the code is compiled, it's optimised and rearranged to allow for structures not present in lower level languages, and so generally the resulting code file is very rarely a line-by-line translation of the high level code. So with this in mind if you wanted to change one particular line to fix a bug, would the update then contain a new version of the entire executable, or can it work like some sort of difference-spotting technique like a source control system?


答:
I suppose that with Mongo putting everything onto one polymorphic collection is not unreasonable.

For every message you can pack whatever details pertain to its type, because you're not limited by a relational schema. Your processing / display code should be pretty flexible, though, ready to discover extra details in a record, and ready to handle absence of certain details. In time, the data format will inevitably slightly change.

That said, you'll have to have some strictly required fields, like and ID and a timestamp, which you will index for fast access.

Title: How to properly store messages in a webservice?

Body:
We are building a multitenant webservice with PHP and MongoDB. There is a need for communication between service employees and clients, communication can be established in many different ways. Some of them are: SMS, MMS, Email and, possibly, an internal chat system.

The question is, how to properly implement the database structure for it?

My boss insists, that there should be one collection - messages, where we would store the sender, type, receiver, message body, timestamp and arguments it that way, that we would have a route which points to users/1235/messages, where the chat history can be retrieved.

I, however, disagree on it and argument it in such a way, that every message type has its own properties and settings. For example, it would not be right to store the whole body of SMS message inside just one instance - one SMS can consist of up to 6 parts, which are delivered independently (they have their own tracking ID). This way, it is easy to track, which parts have been delivered, thus allowing to send missing parts instead of the whole message. Emails also have their own properties such as address, reply-to and other stuff.

Probably I think about constistency too much, since I've been using MySQL for a long time. But, in my opinion, storing all messages just in one collection would give a huge property diversity in the object. Storing each message system separately, however, would give flexible options, allowing to track each message's status and other details. All the messages normalized and joined into one data collection later. (Concat SMS to build the whole body, etc)

So, what kind of solution would you see here?


问:
Is it better to document functions in the header file or the source file?
In languages that distinguish between a "source" and "header" file (mainly C and C++), is it better to document functions in the header file:

(pilfered from CCAN)

```<code>/**
 * time_now - return the current time
 *
 * Example:
 *  printf("Now is %lu seconds since epoch\n", (long)time_now().tv_sec);
 */
struct timeval time_now(void);
</code>```

or in the source file?

(pilfered from PostgreSQL)

```<code>/*
 * Convert a UTF-8 character to a Unicode code point.
 * This is a one-character version of pg_utf2wchar_with_len.
 *
 * No error checks here, c must point to a long-enough string.
 */
pg_wchar
utf8_to_unicode(const unsigned char *c)
{
...
</code>```

Note that some things are defined in the header only, such as structs, macros, and static inline functions.  I'm only talking about things that are declared in a header file and defined in a source file.

Here are some arguments I can think of.  I am leaning toward documenting in the source file, so my "Pro-header" arguments may be somewhat weak.

Pro-header:

The user doesn't need the source code to see the documentation.

The source may be inconvenient, or even impossible, to acquire.

This keeps interface and implementation further apart.

Pro-source:

It makes the header a lot shorter, giving the reader a birds-eye view of the module as a whole.

It pairs the documentation of a function with its implementation, making it easier to see that a function does what it says it does.

When answering, please be wary of arguments based on what tools and "modern IDEs" can do.  Examples:

Pro-header: Code folding can help make commented headers more navigable by hiding the comments.

Pro-source: cscope's Find this global definition feature takes you to the source file (where the definition is) rather than the header file (where the declaration is).

I'm not saying don't make such arguments, but bear in mind that not everyone is as comfortable with the tools you use as you are.

答:
Assuming this is code within a larger project (where developers will be moving between source and headers often), and
providing this isn't a library/middle-ware, where others may not have access to the source, I've found this works best...

Headers:
Terse 1-2 line comments, only if they're needed.
Sometimes
comments above a group of related functions is helpful too.

Source:
Documentation on API directly above the function (plain-text or doxygen if you prefer).

Keep implementation details, only relevant to a developer modifying the code in the body of the function.

The main reason for this is to keep the comments close to the code, I've noticed docs in headers tend to get out of sync with changes to the code more often (of course they shouldn't, but they did in our project at least).
Also developers may add documentation at the top of functions when they make some change, even when there are docs in the header,
causing double-ups or useful info only to be in one of the doc-strings.

Of course you can pick a convention and ensure all devs follow, I just found the convention above the most natural-fit and causes least trouble to maintain.

Last of all, for large projects - there is an inclination not to make small corrections in a header when you know its going to cause potentially 100's or 1000's of files to re-compile when others update version control - slowing down bisecting errors too.


问:
ID properties on Domain objects in DDD
In my domain I have an Account object.

e.g.

class Account
{
    public string Number;
    public string SortCode;
}
```

Within the context of DDD, should this account object have an ID property? The ID would be a primary key, basically a database artefact.

答:
Most of the time, the ID field you are talking about would be generated by the database, e.g. as a RDBMS sequence or a NoSQL unique identifier. It is therefore tied to the corresponding database backend used.

According to the Persistence Ignorance / Polyglot Persistence principle, you should better hide this ID from your domain aggregates as much as possible.

In practice, your domain Aggregates may already have an unique identifier. For instance, a serial number, a client code, a logon name, an account number, an invoice reference or an ISBN for a book.

If there is no such "natural" identifier in your model, it may be one role of the domain logic to generate such genuine identifiers, e.g. following a pattern defined by regulation, or human-friendly notions, following your company best practice (it is common to include the year and the month in invoice numbers, or an alphanumeric identifier of the department in charge of the process for instance).

Within the Infrastructure Layer, you would probably let an ID field appear, especially if you need to construct joined SQL queries among several RBDMS tables. Or, if you use an ORM, you may not persist directly the DDD aggregate objects as ORM objects, but use an "agnostic" translation layer. This is for instance what our DDD framework proposes, by adding an automated translation layer between the DDD plain objects and the ORM objects, which have their own ID... some kind of "square ORM": on DDD mapper over an ORM mapper.

DDD is mainly about isolation: don't pollute your domain with database consideration! Naming an aggregate object field as ID does definitively smell: there is probably another naming, compatible with the Ubiquitous Language of your bounded context, which may be used instead of a plain ID.

Title: ID properties on Domain objects in DDD


问:
How do I use decision tables to prioritize between objects - or should I do something different?
I have a case similar to this one: Multivariable decisions

The difference is, that it's not a single decision I need to make but more like I have a pool of (let's say 10 object) where each object has 4 attributes with 3-4 different states for each. I now need to select the ONE single most relevant of the objects based on comparing these attributes for each object.

What techniques can I use to implement this behaviour?

An example could be: you are in a theme park and you need to choose what roller coaster to try for a last ride before going home. There are 10 roller coasters in the park. Variables going into consideration are:

How far away is the roller coster (can you reach it before the park closes)

How wild is it (the wilder the better)

Have you tried it before (you wanna try something new)

How long time does the ride last (you don't wanner get locked up inside the park - or maybe you do actually :-)

答:
I will assume you are looking for a programming pattern to implement such decision making, not a concrete algorithm implementation.

So, I guess you need to assign weights to your objects based on attribute testing. For this you could have an abstract AbstractWeightCalculator class which has an abstract calculateWeight(MyObject obj) method.

Now you create various attribute testers:

DistanceWeightCalculator: How far away is the roller coster

WildnessWeightCalculator: How wild is it

etc.

Now, you grab all your weight testers, apply them one by one to each object and get a sum of all weights of the objects. And then just sort the list you got by the weight.

Does that suit your needs?


问:
Are Windows 10 app services only useful in enterprise environments?
I have been following one of the capabilities Microsoft introduced for the Universal Windows Platform (UWP), namely app services. An app can now provide a service in the form of a background task that can be called by other apps to perform some task. It's something like a webservice on device.

Let's say a developer creates an application which provides an app service with the goal to provide that service to other apps, either their own or from other developers. Since there is no way to guarantee that an app will be present on the system at any given time, what can a developer do when they need to use the app service?

Implementing the service functionality for every app defeats the purpose and building apps that will not work when other apps are not installed sounds like a bad decision. So are app services intended only for controlled enterprise environments and not for the general public?

答:
In the Linux world, where most users install software using package managers(except those who build it manually, and they are used to follow instructions form READMEs), this problem is solved by making the package format support dependencies. Each package declares what other packages it depends on(and what versions), so package manager make can sure these dependencies are installed.

Windows 10 introduces a package manager, and it supports dependencies(https://msdn.microsoft.com/en-us/library/windows/apps/dn934744.aspx), so if an app requires an app service to run, the app's package will add the app service's package as a dependency, and the package manager will install it. If another app requires the same app service and adds it as a dependency, the package manager will recognize that it is already installed and won't re-install it(unless a newer version is required)


问:
Does a pattern for "houskeeping" a NoSQL DB with eventual consistency exist?
I'm working with a NoSQL DB with eventual consistency. My software is not only inserting Java Objects in JSON but also creating secondary indices for cross-referencing and similar things. Due to the fact that my software has to create all references on it's own, there is no real mechanism to ensure complete consistency throughout the whole DB.

That's why I want to program something like a housekeeping routine, that can be called during runtime to test for inconsistencies.

Now I'm wondering if there are any advisable software patterns that serve these specific purposes:

A scheme (not quite sure what the format will be; probably XML or sth similar) should be used as input that describes the relations between DB entries. This scheme will probably be the documentation itself.

The routine should be able to identify keys that were never accessed during checking the relations mentioned above.

It must be capable of checking aggregated values, de-/incrementation and JSON.

The first item on the list is the most important, so that the routine identifies flaws in the code as well as in the documentation/requirements. Any hints towards helpful literature or probable issues, I should consider, are much appreciated.

答:
First of all, eventual consistency should be pretty safe, and such a "data housekeeping" process may not be mandatory. It may be indeed a feature to have several states of the data in the database. In BigData process, it is pretty usual - Google for instance may have several states of the same data in its servers.

IMHO your question may have answers at two levels, following the DDD architecture.

1. At Infrastructure Layer

You may write some code specific to the NoSQL engine you are using.

It would be optimized e.g. for fast process using KVP, perhaps with the following patterns:

Using memory as cache as much as possible, to avoid unnecessary requests on the NoSQL;

Run the operation in a separated process, to reduce impact on the main process;

Let this separated process use a map/reduce pattern, then injecting the modifications as batches;

Use some kind of CQRS pattern, and several databases: one KVP database for your direct writes, then dedicated secondary read-only databases, containing some "polished" data (also filled with map/reduce), ready to be consumed by your Domain Services.

Your idea of identifying "dead" keys is interesting. It could be implemented within the infrastructure layer, as part of the storage process, e.g. by maintaining an in-memory list of just written entries, then deleting then garbage-collect them using a generational-like algorithm, marking keys with a generation number, ready to remove the unused one.

2. At Domain Level

In DDD we try to be as uncoupled from the database as possible. As a result, doing some data cleaning process at infrastructure layer sounds somewhat weird.

Such data cleaning may be part of the domain, in a dedicated Bounded Context. The infrastructure layer, when apply the map/reduce algorithm, may use some logic defined in the domain, using domain objects, to validate your data, and fix any synchronization problem.

Last but not least, if your data seems eventually incoherent, it may smell like a domain problem. Your aggregates may be wrongly defined. What you should persist are Aggregates Roots, which scope has been defined by a given execution context. Typically, Aggregates are persisted in your database, and guarantee the consistency of changes by isolating their members from external objects (i.e. you can link to an aggregate via its ID, but you can not directly access to its internal objects). The eventual consistency of the KVP should be enough to ensure consistent data. If you encounter consistency issues, you may consider fixing your domain, which may have some problems about the Aggregate Roots scope.


问:
Do we need servant pattern? What about implementing in parent class?
From wikipedia:

Servant is used for providing some behavior to a group of classes.
  Instead of defining that behavior in each class - or when we cannot
  factor out this behavior in the common parent class - it is defined
  once in the Servant.

Please take a look at MoveServant and Movable example in the wiki page. What can be the reason so that I will not want to put moveBy and moveTo in the parent class for all shapes? In other words why parent class implementing the functionality is worse compared with servant implementing the functionality.

BTW in this sentence "Servant is used for providing some behavior to a group of classes." group of classes means classes that belong the the same type (class hierarchy)?

答:
I also can't see any advantages from provided simple example. But consider next possibilities
1. Possibility to change/switch behavior in runtime by providing other Servant.
2. Encapsulation. If you don't want to expose new method in your class hierarchy.
3. There is no common parent class or you don't want to implement the method for all children? This is debatable case. Because you should cast your object to interface so it's not a good idea to have such design. </p>


问:
Array vs Object for View in Laravel
First, yes This question is very similar to Arrays vs Objects in view template but my question sort of expands on this...

When deciding on whether to use an object or array to pass data to your view.  Which would be a better approach when you're looking for a view that you can re-use for both....

Data passed through as an Eloquent object

Data that is manually created in your controller that does NOT originate from an Eloquent or any other object...

For example let's say I have a piece of code in my view that is simply...

```<code>{!! $foo->bar !!}
</code>```

I have my Foo Model..

```<code>class Foo extends Model
{
    protected $fillable =[
      'bar',
    ];
</code>```

and MyController controller...

```<code>class MyController extends Controller
{
    public function fromDB()
    {
        $foo = Foo:all();
    }

    public function manually()
    {
        $foo = array(
            'bar' => 'Hello World',
        );
    }
</code>```

To re-use my view, should I.

Convert my foo Eloquent object to an array?

Convert my foo array to an object?

Other

If using option 2, should the object be the Foo model? Or another Foo class?

答: This is one of the reasons why view models were created. Define a class that holds the necessary data for the view and this question becomes moot. The source of the data could be an Eloquent object or array, but since the view is rendering its own model the original source and format of the data is irrelevant.</p>

Title: Array vs Object for View in Laravel


答:
I would decide based on my UI design.

If I have separate UI for each type of messages - SMS, Email, etc. and a single simple call is all I need to get the required data for each type, then I'll separate out each type of message.

But, if the UI is designed in a way that requires you to display all types of messages on the same screen, then I will club them all together.

The intention is to hit the DB as less as I can. At the same time, trying to keep the query as simple and efficient as possible.


问:
Is it a good idea to modify the array keys in foreach
Some times I need to modify an array key for example something like:

$temp = array();
foreach($arrayIWantToModify as $key => $value) {
    if($value % 2) == 0) {
        $temp['odd_' . $key] = $value;
    } else {
        $temp[$key] = $value;
    }
}
```

<p>I always use a temp array to achieve that, but I had a memory problem when working on a project that had some big arrays. Of course the best solution is to increase the memory but, but i was just wondering is it so bad to just do it like:</p>

<pre class="lang-php prettyprint-override"><code>foreach($arrayIWantToModify as $key => $value) {
    if(($value % 2) == 0) {
        $arrayIWantToModify['odd_' . $key] = $value;
        unset($arrayIWantToModify[$key]);
    }
}
</code>```

It seems to work but I always saw it as a bad practice because you are changing an array you are iterating.

答:
Let's use a slightly different take on the problem. You describe what you do as:

Some times I need to modify an array key

When we look at it like this, we have the problem of doing everything in the same loop. Can we look at it differently? Maybe say:

Some times I need to find a set of keys, and then I need to modify those keys in the array

Now we can see two separate tasks to complete, which means we can break them apart. The code to accomplish this might look something like:

```<code>$oddKeys = array();

// Task 1: Find a set of keys
foreach($arrayIWantToModify as $key => $value) {
    if($value % 2 == 0) {
        $oddKeys[] = $key;
    }
}

// Task 2: Modify those keys
foreach($oddKeys as $key) {
    $arrayIWantToModify['odd_' . $key] = $arrayIWantToModify[$key];
    unset($arrayIWantToModify[$key]);
}
</code>```

We have less memory usage* than the temporary array as we are only storing the keys that need to change, not an entire duplicate array. The code is also clearer than the alternative as there is no question about the behavior here. Since we've broken the behavior apart, we can now even extract it and reuse it elsewhere (for example by extracting a function that returns an array of keys where the values meet certain criteria).

* If the number of keys that need to change is the same or nearly the same as the total number of keys, the memory usage gains may not be as large. You would need to test whether you are still running into memory limitations, and possibly come up with a different strategy (say, swap all the keys, then reverse the action on the reverse condition).

Body:
Let's use a slightly different take on the problem. You describe what you do as:

Some times I need to modify an array key

When we look at it like this, we have the problem of doing everything in the same loop. Can we look at it differently? Maybe say:

Some times I need to find a set of keys, and then I need to modify those keys in the array

Now we can see two separate tasks to complete, which means we can break them apart. The code to accomplish this might look something like:

$oddKeys = array();

// Task 1: Find a set of keys
foreach($arrayIWantToModify as $key => $value) {
    if($value % 2 == 0) {
        $oddKeys[] = $key;
    }
}

// Task 2: Modify those keys
foreach($oddKeys as $key) {
    $arrayIWantToModify['odd_' . $key] = $arrayIWantToModify[$key];
    unset($arrayIWantToModify[$key]);
}

We have less memory usage* than the temporary array as we are only storing the keys that need to change, not an entire duplicate array. The code is also clearer than the alternative as there is no question about the behavior here. Since we've broken the behavior apart, we can now even extract it and reuse it elsewhere (for example by extracting a function that returns an array of keys where the values meet certain criteria).

* If the number of keys that need to change is the same or nearly the same as the total number of keys, the memory usage gains may not be as large. You would need to test whether you are still running into memory limitations, and possibly come up with a different strategy (say, swap all the keys, then reverse the action on the reverse condition).


问:
Beginner need help on learning Qt programming
Thought of learning Qt. Need help from experienced ones out here. How should I begin. Some good books to refer. Some good tutorials to learn...

Edit: Also which is the good IDE available out there for Qt programming. One that gives inline help, auto completion,indentation... I am using Debian Lenny

答:
C++ GUI Programming with Qt 4  passed at one time through my hands. From what few days I had it, it seemed like a nice book; it's style of writing (explaining things) suited me very much. Your mileage may vary, but worth checking out nevertheless.

Also, two more advanced ones as suggested by Martin Beckett and Jestin Joy.

Advanced Qt Programming: Creating Great Software with C++ and Qt 4 (Prentice Hall Open Source Software Development Series)

and The Book of Qt 4: The Art of Building Qt Applications


问:
Does algorithm design belong to software engineering?
In academic meaning, it seems to me that

algorithm design is studied in a high/abstract level of computation (computability, complexity), although software engineering is also studied in high/abstract level in academia.

software engineering is about the process of creating a software program for solving a problem. That seems to make algorithm design part of the process.

But from the limited references on software engineering that I have taken a glanced at, algorithm design isn't discussed (but I may miss something).
Instead, pattern design (or is it called design pattern instead?) is discussed in software engineering.

My questions are:

Does algorithm design belong to software engineering? Is algorithm design a step in the process of software engineering?

what are the differences and relations between algorithm design, pattern design, program design, and system design? These words can be heard often from industry as buzzwords.  Can you share the definitions of these various kinds of designs?

答:
Yes and no.

The study of algorithms (and data structures - the two go hand-in-hand) as they relate to computation tends to fall into the category of computer science. Some algorithms, however, may be developed by those in a particular domain. For example, the algorithms needed to implement some kind of automatic control in a hardware/software system may be developed by someone who specializes in controls engineering. Likewise, signal processing filters may require knowledge of physics and electrical engineering. However, the people who develop these algorithms may not have the knowledge and expertise to turn a mathematical representation of an algorithm into something that can be used by software. In order to turn that algorithm into something that can be used by software, you would also need some of the knowledge that falls into the scope of software engineering.

Algorithm design must fit into software engineering. Your requirements and constraints will likely drive the choices of algorithms. Then, you must design for the use of algorithms, either how you will go about implementing the algorithm or the use of a library or existing module that implements the algorithm. You'll also need to consider the algorithm testability and maintainability - both things that software engineers are concerned with.

Although I wouldn't consider algorithm design to be part of software engineering, I would consider it something that a software engineer must be minimally aware of. The environment and domain in which the software engineer is working will determine the amount of involvement in algorithm design.


问:
What business value does a semantic platform offer that a graph database doesn't
We hear a lot about graph databases such as Neo4J and a little less about semantic platforms such as OWLIM and similar triple (or quad) stores.

I understand the latter is associated with embedded OWL support but what does that mean in value terms? What is the unique value of an RDF triple/quad store with OWL tooling that is not offered by a simpler graph database without "semantic" features?

I am looking for the business outcomes that might be achievable with semantic tech only.

答:
A semantic platform can answer questions whose answers are not directly captured by the facts, by reasoning over the facts using rules, some of which are built in and some added by a domain expert.

In a semantic platform, you can describe a property as being transitive, meaning the if there is a relationship R between A and B and there is a relationship R between B and C, it can infer that there is a relationship R between A and C.

That alone is somewhat sophisticated and hard to code within a single complex query in a graph db or non-semantic platform.  One could hard code an example, sure, but transitivity could have any number of hops (which some graph db's can indeed support).  Further however, using a semantic platform, we don't have to code the hops, loops or recursion, rather we merely tell the platform that some property or relationships is transitive, and it infers the rest.

We can also describe one entity as being a subclass of another entity, where being a subclass means that members, properties, or qualities of the base apply to subclasses.

Further, these rules and/or descriptions can be combined and interact.  The semantic platform can reason thru multiple rules connecting multiple entities and relationships to give answers.

So using those rules, for example, we can logically describe a traditional system of classes and instances with members(, properties, or qualities).  If class A's instances have a member (or quality) M, and class B is a subclass of A, and class C is subclass of B, then the reasoning system will realize that (1) C is a subclass of A, and (2) M is applicable to C's instances.

This kind of thing would be relatively difficult to code in one non-semantic graph db query (even using views), that is, without the application resorting to multiple queries and being driven by its own external logic (which goes to what @Robert said of layering semantics on top of the graph db).

Semantic platforms typically have dozens and dozens of rules, e.g.
Transitive Axiom: http://www.w3.org/TR/owl2-syntax/#Transitive_Object_Properties

There are also varied levels of logic, which are progressively more powerful.  Semantic platforms usually employ Description Logic (https://en.wikipedia.org/wiki/Description_logic), which is specifically limited so as to have certain qualities of computability (aka decidability).  First Order Logic systems (https://en.wikipedia.org/wiki/First-order_logic) have higher expressiveness, through their use of variables and quantifiers.  Thus, they can solve problems DL's can't.  There are also more complex logic systems beyond FOL...


答: Algorithm's are not unique to software engineering. These days your more likely to see the term used along with software engineering/development but its not a exclusive term. Now in terms of Algorithm's belonging to software engineering as compared to? software development? That depends on who is in charge of the programmers. You can either come up with the solution and ask the programmers to implement it, or you can explain the problem and have them solve it as well. It's more of a who do you work for issue. I work for a company that explains the problem and its my problem to solve it (come up with the algorithm) I have worked for other companies that the entire solution is already mapped out for you and all you do is translate the algorithm they provide to the computer. who designs the algorithm is really dependent on how software development takes place at a specific organization. Are algorithms exclusive to Software engineering? No. </p>

Body:
In academic meaning, it seems to me that

algorithm design is studied in a high/abstract level of computation (computability, complexity), although software engineering is also studied in high/abstract level in academia.

software engineering is about the process of creating a software program for solving a problem. That seems to make algorithm design part of the process.

But from the limited references on software engineering that I have taken a glanced at, algorithm design isn't discussed (but I may miss something).
Instead, pattern design (or is it called design pattern instead?) is discussed in software engineering.

My questions are:

Does algorithm design belong to software engineering? Is algorithm design a step in the process of software engineering?

what are the differences and relations between algorithm design, pattern design, program design, and system design? These words can be heard often from industry as buzzwords.  Can you share the definitions of these various kinds of designs?


问:
How can I best test a multithreaded C producer-consumer program?
How does one best write tests for a multi-threaded producer-consumer C program?

I know GDB can be used to debug threads, but I believe GDB also stops the thread currently being debugged while other threads continue running.

I want to test proper mutex lucking/unlocking and blocking by my threads. I've looked around a lot but haven't been able to find any good resources.

I have unit tests for all the non-concurrent functionality, but want to make sure my concurrency is correct. How can tests for multithreaded programs best be achieved?

答:
The only way that I know of for testing software that utilizes concurrency of the locking kind is by stress-testing them.

You can write unit tests that cover some or even all of the operations that involve concurrency, but you have still not really tested your software, because the problems with concurrency come from unexpected interactions between threads which are highly dependent on timing, and therefore non-deterministic.

So, you need to write one test which runs your system for hours on end, hoping that if there is a problem, it will manifest itself.

Of course, your software may contain a defect which manifests itself only once in a million lock operations, in which case, from a statistical point of view, you stand virtually no chance of detecting it during in-house testing, so you ship your product, and thousands upon thousands of users start using it day in, day out, around the clock, and the defect starts manifesting every so often, which is a nightmare.

That's why the industry has been moving away from concurrency of the locking kind, and uses other approaches instead, like share-nothing systems where the threads only communicate with each other via message queues, through which they pass only immutable data, so that the only place in the entire system which involves locking is a few instructions in just one class, the message queue class. The great benefit of these systems is that they are testable, whereas concurrent systems of the locking kind are not really testable.

They are more like "stress-test and pray."


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
Code complete

The Pragmatic Programmer

Body:
Code complete

The Pragmatic Programmer