答:
So if you wrote a unit test like this...

```<code>for (int i = 0; i < 100; i++) {
 assertTrue(i*i, square(i));
}
</code>```

you would be given 100 points.

I would give this person 0 points (even if the test were testing something actually relevant), because assertions within a loop make little sense and tests with multiple asserts (especially in a form of a loop or a map) are difficult to work with.

The problem is essentially to have a metric which cannot [easily] be cheated. A metric which is exclusively based on the number of asserts is exactly the same as paying developers per LOC written. As with pay-by-LOC which leads to huge and impossible to maintain code, your actual company policy leads to useless and possibly badly written tests.

If the number of asserts is irrelevant, the number of tests is irrelevant as well. This is also the case for many metrics (including combined ones) one could imagine for this sort of situations.

Ideally, you would be applying systemic approach. In practice, this can hardly work in most software development companies. So I can suggest a few other things:

Using pair reviews for tests and have something similar to the number of WTFs per minute metric.

Measure the impact of those tests over time on the number of bugs. This has several benefits:

Seems fair,

Can actually be measured if you collect enough data about bug reports and their fate,

Is actually worth it!

Use branch coverage, but combine it with other metrics (as well as a review). Branch coverage has its benefits, but testing CRUD code just to get a better grade is not the best way to spend developers' time.

Decide all together what are the metrics you want to enforce for the moment (such decisions may not be welcomed or even be possible in some companies and teams). Review and change the metrics often, picking the ones which become more relevant, and make sure everyone clearly understands what is measured and how.

Title: Unit Testing Competition

Body:
My employers runs a monthly unit testing day competition. One entire day is dedicated to writing unit tests -- obviously we do more testing throughout the month, but this is an entire day -- and the "winner" of the competition is given a prize.  However, we are finding it's hard to determine who the winner is.

We were assigning points for each test case.  So if you wrote a unit test like this...

```<code>for (int i = 0; i < 100; i++) {
  assertTrue(i*i, square(i));
}
</code>```

you would be given 100 points.  Obviously this is a simplistic example but it demonstrates the problems with assigning "points" to each test case.

We're primarily a Java & Javascript shop.  So I suggested counting number of code branches tested as a metric.  We can easily count the branches tested via a code coverage tool (such as EclEmma).  However, not sure how we would do this with our Selenium tests and getting a code coverage on the Javascript sources (any ideas?)

Does anyone have any suggestions on how we could better determine the winner of this competition?

Edit

I know how to write unit tests, I know how to write effective unit tests, I don't need help determining what to test.  I have no control over this competition -- the competition will go on.  So either I add some input to make it better or carry on gaming the tests (yeah, I game them.  Of course I game them.  There are prizes to be won)

Edit

This question here is obviously not a duplicate, though it contains useful information about how to find good test cases, it does not provide any useful metrics to evaluate the competition.

Body:
So if you wrote a unit test like this...

for (int i = 0; i < 100; i++) {
 assertTrue(i*i, square(i));
}

you would be given 100 points.

I would give this person 0 points (even if the test were testing something actually relevant), because assertions within a loop make little sense and tests with multiple asserts (especially in a form of a loop or a map) are difficult to work with.

The problem is essentially to have a metric which cannot [easily] be cheated. A metric which is exclusively based on the number of asserts is exactly the same as paying developers per LOC written. As with pay-by-LOC which leads to huge and impossible to maintain code, your actual company policy leads to useless and possibly badly written tests.

If the number of asserts is irrelevant, the number of tests is irrelevant as well. This is also the case for many metrics (including combined ones) one could imagine for this sort of situations.

Ideally, you would be applying systemic approach. In practice, this can hardly work in most software development companies. So I can suggest a few other things:

Using pair reviews for tests and have something similar to the number of WTFs per minute metric.

Measure the impact of those tests over time on the number of bugs. This has several benefits:

Seems fair,

Can actually be measured if you collect enough data about bug reports and their fate,

Is actually worth it!

Use branch coverage, but combine it with other metrics (as well as a review). Branch coverage has its benefits, but testing CRUD code just to get a better grade is not the best way to spend developers' time.

Decide all together what are the metrics you want to enforce for the moment (such decisions may not be welcomed or even be possible in some companies and teams). Review and change the metrics often, picking the ones which become more relevant, and make sure everyone clearly understands what is measured and how.


问:
Unit Testing Competition
My employers runs a monthly unit testing day competition. One entire day is dedicated to writing unit tests -- obviously we do more testing throughout the month, but this is an entire day -- and the "winner" of the competition is given a prize.  However, we are finding it's hard to determine who the winner is.

We were assigning points for each test case.  So if you wrote a unit test like this...

```<code>for (int i = 0; i < 100; i++) {
  assertTrue(i*i, square(i));
}
</code>```

you would be given 100 points.  Obviously this is a simplistic example but it demonstrates the problems with assigning "points" to each test case.

We're primarily a Java & Javascript shop.  So I suggested counting number of code branches tested as a metric.  We can easily count the branches tested via a code coverage tool (such as EclEmma).  However, not sure how we would do this with our Selenium tests and getting a code coverage on the Javascript sources (any ideas?)

Does anyone have any suggestions on how we could better determine the winner of this competition?

Edit

I know how to write unit tests, I know how to write effective unit tests, I don't need help determining what to test.  I have no control over this competition -- the competition will go on.  So either I add some input to make it better or carry on gaming the tests (yeah, I game them.  Of course I game them.  There are prizes to be won)

Edit

This question here is obviously not a duplicate, though it contains useful information about how to find good test cases, it does not provide any useful metrics to evaluate the competition.

答:
I suppose your employer organizes this unit testing day in order to give you people incentives to find bugs, to achieve greater code coverage, and also to end up having more tests, which are useful forever after.

So, I would think it would make sense that the winner should be the developer who finds the most bugs, or the developer whose tests achieve the greatest increase in code coverage.

A test would earn you a point if it causes a new entry to be opened in your issue / bug / defect tracking system.  If an entry is already open for that issue, it does not count.  Also, as suggested in the comments, bugs in your own code do not count; only bugs in other people's code should count.  Unfortunately, this approach does not deliver instant gratification because it may take a few days until all the failed tests are sifted through and the corresponding issues are opened.  Also, this may not always work; as your system matures, it may start becoming exceedingly rare to discover bugs by adding tests.

The increase in code coverage might provide a more objective measurement of the improvement represented by the new tests.  First, the total code coverage will have to be recorded the day prior to the competition. Then, each developer will need to somehow show the increase in code coverage which results from their tests alone, without taking into account the increase in code coverage resulting from tests written by other developers.  This means that you will probably need a referee who will go to each developer's machine and record the new code coverage before anyone's tests have been committed.

Incidentally, taking code coverage into consideration provides fair reward to people who write real tests, instead of doing silly things like the example that you provided in the question.

ContentLicense: CC BY-SA 3.0

Title: Unit Testing Competition


问:
Object Oriented Analysis and Design and DDD together
I fear this question seems to broad, so I'll try to explain what I mean with some detail. I couldn't, however, find a way to divide it into other questions. If that's really the case, I gladly accept suggestions on how to break this question down in more focused ones.

I work with object oriented programming and one of the first things I've heard about was the process of OOAD where starting with requirements, mainly in the form of use cases, we figure out the domain model classes we are going to need and the relationships between those classes.

On the other hand, on the last few weeks, I've been studying about Domain-Driven Design and there are many things that seems to help a lot with object oriented design. One of those is the division of the application with bounded contexts which solves the problem of confusions about the meaning of a certain term from the domain. Another things that seems to help a lot is the idea of entities, value objects, aggregates, repositories, factories, services and domain events.

Now, when programming, it's clear how we implement lots of those things with object orientation and classes. My doubt is: how we can join the process of OOAD and the use of DDD?

I mean, when planing, without coding anything, how do we join OOAD and DDD? OOAD puts enphasis on some work on paper before coding, like use cases, user stories, diagrams and so on. DDD doesn't seem to talk about this kind of things. How DDD enters this design phase of the project?

I imagine something like this: we first understand the domain, then divide it into subdomains, then for each subdomain we perform the process of OOAD, writing use cases and so on and when making the classes we keep in mind DDD ideas. Is it like that?

答:
I have been reflecting on Applying UML and Patterns by Craig Larman and Domain-Driven Design by Eric Evans and although both seem to tackle the same problem from a bird's eye view, they have different philosophies.

OOA/D is sort of 'waterfall-y' because you derive a model from the requirements using 'real-world objects' and translate it into a class diagram which you implement afterwards.

Evans on the other hand says that you should develop a Domain Model which helps you build a common language - the Ubiquitous Language - which everybody on the team speaks and understands. There is no analysis and design in the OOA/D-sense.

Starting from the Domain Model and the Ubiquitous Language the domain experts can write more precise use-cases and the developers can try to implement the domain model. If the implementation doesn't resemble the domain model it doesn't mean it's wrong but it means it doesn't work in your case so you have to refine it. If the domain experts can't phrase sensible use-cases again it doesn't mean it's wrong. It's just that something's missing and the domain model should be reviewed.

According to Evans this feedback loop is crucial when doing DDD.

This is probably more of a text book approach. Out 'in the wild' the two might not be so different.

As to how to integrate the two: Building a Domain Model and the Ubiquitous Language should be part of an early workshop. If there already are some use-cases you can validate those by talking about them. If there aren't, well, it's going to be much easier to write them now.


问:
Separate requests for static and dynamic page content on first page load?
I'm thinking of the following two requests:

Request 1:

Load all static HTML, JavaScript, images, etc. the website framework so to speak. Then fire a second request to get dynamic content (say news items, latest posts).

Request 2

Send new HTML, JavaScript, images, etc. as required by dynamic content.

I'm expecting the first request to be cached for subsequent times a user visits the website, and thus to be a non-issue for returning users. But for first-time users should I maybe build the entire content server-side and send it together in one request? Since in the approach above, both requests need to be responded to in order for the user to be able to use the website.

Can I just leave it as two requests (easier for me to program, since I'm building single page app that relies on Ajax requests)? Or is there an easy way to build everything server side and avoid two requests the for first time users?

... but wouldn't that break the caching mechanism, since the same URL would return partially different content each time?

Is this a known issue with a known solution?

答:
There are a couple things to consider here, at least when it comes to html content:

Method 1:
Loading a portion of the site that will remain static for the foreseeable future is good when the same users are expected to frequent the website and SEO is less of an issue*. You also have some more control over perceived performance; the 'static' content can prepare the user with a basic UI that will lazily load content. I would recommend this method for websites that are more 'app' than 'site', where content is not the main reason visitors use your site.

Method 2:
This is better for lots of one-time website visitors because there are less round trips to worry about. It is also better SEO because crawlers will see what the server generates*. It's also easier to maintain and update. I would recommend this for general-purpose sites that target a larger audience and contain a lot of mostly static content.

CSS and JS can be loaded and cached immediately. There are few reasons to load CSS or JS at any time other than when the website is first loaded.

*I don't have any sources handy, but I believe there has been some effort to make web crawlers capable of reading AJAX-generated content.


问:
What stops C from being compiled/interpreted/JIT'ed?
Java is often praised for its amazing portability, which I presume is because of  the JVM. My question is what stops C from being being compiled/interpreted/JIT'ed.., if so, C can also be write once and have it work on what ever device you have. but this is not a popular mechanism for processing a C program.

What are the disadvantages of processing C in this way, also what are the advantages of processing Java in this way and not compiling to machine code, other than the portability of course?

答:
You said:

Java is often praised for its amazing portability, which I presume is
  because of the JVM.

And there, within the first sentence, you are wrong. Java isn't portable because of the JVM. Java is portable, because the Java language is defined in a way that doesn't leave the implementor any leeway in how a program may behave.

As an example, Java has two types "int" (signed 32 bit integer) and "long" (signed 64 bit integer). C and C++ have "int" (signed at least 16 bit), "long" (signed at least 32 bit) and "long long" (signed at least 64 bit). That's because C is supposed to run on many different processors, and allows them to behave differently.

C could have defined fixed sizes for these types. If it had, then 36 bit processors couldn't have implemented the C language. And they can't indeed implement Java! So C allowed the language to work with a variety of different computers. It is unavoidable that this allows creation of code that is not portable. It's a matter of the language.


问:
As a tech team lead, how should I handle team members' coding mistakes and bad practices?
I'm a tech team leader on a team of about 5 developers. The team size is somewhat dynamic as team members periodically leave for other projects and others join the team from other projects.

Periodically I stumble upon my team members' code, either when making modifications to it, writing something nearby, or just reviewing their code. Sometimes (often enough to write this post, I guess) their code is poorly written, with either small mistakes (like converting two Date objects to strings in order to compare them) or larger ones (writing 2+ almost identical medium-to-large sized functions with only one line differences, instead of one function that can handle both cases.)

What's the best way to improve their skills and point out these mistakes to them? Sometimes I go over these segments of code with them, explaining why they should be written differently. But I don't want to be nitpicky and have them come over too often to review their code. Are code reviews the answer here? If so, how should they be organized? Should they include all team members or be individual? How often should they be held? Any other advice?

There is another question that reads similar, but it is actually different, because in addition to being curious about code reviews, I'd also like to know of other possible ways of improving my team members' coding skills. Also, deadlines don't play a role in my question because we can easily review and/or fix the code either before or after an upcoming version delivery.

答:
There are a few things you can do for this situation.  First, do what you can to have a rulebook to refer them to.  In other words, when things like this come up, it's best to say, "Have a look at page 6 of the style guide."  Or, "Here's a link to a website that will explain something I want you to know," and save that link for your library.  As a tech lead, its part of your job to avoid technical debt, so that's your obligation to them.

Secondly, rather than point to what they've done wrong, ask them questions about their own code.  For example, my mentor caught me copying arrays when I didn't need to, so he asked me, "What do you suppose this code here is really doing?"  We had a culture of mutual respect that made questions like that stimulating, rather than nit-picky.

If you govern from policy, maintain your role as the gatekeeper, and treat people respectfully, the good employees will love it and the bad ones will find another job.  Remember to praise publicly but criticize in private.  And feedback is a gift; the good coders will tell you how you're doing if you ask them.


答:
Here's my thoughts on code reviews.

Great idea in theory but you have to manage things carefully.  Programmers are creative, egotistical & can be extremely thin skinned.  An open team code review can all too easily turn into the Roman Colosseum.  Coders can pick each other's work to pieces viciously and unproductively.  Even if you do it one-on-one it can still turn into a negative experience.  Gavin's advice about criticising in private is great advice and something that's hard to maintain when there are open code reviews.

Gavin's (again) suggestion about writing a style guide or coding standards document is again great but you have to have the authority to enforce it.  I strongly suggest finding a good model online and adapting that otherwise there will be blood between factions of those who put the opening "{" on the same line and those who put it on its' own line etc.  I have seen (seriously) a command-line code formatting tool built into the check-in workflow to enforce the company style (good - I suppose) but then also saw renegade coders at the same company use the same tool with different style parameters to format the code "their way" on check-out (not so good).

On to the new content, buy a library of good books about programming e.g. "Clean Code", "Clean Coder", and "Code Complete" and try to start a culture of learning and improvement.

Title: As a tech team lead, how should I handle team members' coding mistakes and bad practices?

Body:
I'm a tech team leader on a team of about 5 developers. The team size is somewhat dynamic as team members periodically leave for other projects and others join the team from other projects.

Periodically I stumble upon my team members' code, either when making modifications to it, writing something nearby, or just reviewing their code. Sometimes (often enough to write this post, I guess) their code is poorly written, with either small mistakes (like converting two Date objects to strings in order to compare them) or larger ones (writing 2+ almost identical medium-to-large sized functions with only one line differences, instead of one function that can handle both cases.)

What's the best way to improve their skills and point out these mistakes to them? Sometimes I go over these segments of code with them, explaining why they should be written differently. But I don't want to be nitpicky and have them come over too often to review their code. Are code reviews the answer here? If so, how should they be organized? Should they include all team members or be individual? How often should they be held? Any other advice?

There is another question that reads similar, but it is actually different, because in addition to being curious about code reviews, I'd also like to know of other possible ways of improving my team members' coding skills. Also, deadlines don't play a role in my question because we can easily review and/or fix the code either before or after an upcoming version delivery.


答:
I'm not a team lead, so I haven't used that in practice.

 But, in my view a healthy contest is the way to go.

 Have your developers solve a challenge unrelated to work. Same challenge for all developers.

Make sure you explain beforehand what makes a good solution (short functions, meaningful names, efficiency etc.).

 When everybody is done, vote for the best implementation.

The fact that everyone is working on the same problem will allow deeper discussions, since everybody has thought about the solution.

The fact that it's not work related  will reduce anxiety of failure and make people more responsive to critique.

Making such contents a tradition will gradually improve coding skills of entire team without the need to go through code review process.


答:
Actually, this is done.  There are major compilers which support compilation to LLVM (I know clang does, and I believe gcc does as well).  That LLVM can be JIT'd just as Java code is compiled down to bytecode which is JIT'd.

However, what makes java "cross platform" as compared to C is that Java has a large runtime library which has been ported to many platforms.  C explicitly does not follow this paradigm.

Title: What stops C from being compiled/interpreted/JIT'ed?

Body:
Java is often praised for its amazing portability, which I presume is because of  the JVM. My question is what stops C from being being compiled/interpreted/JIT'ed.., if so, C can also be write once and have it work on what ever device you have. but this is not a popular mechanism for processing a C program.

What are the disadvantages of processing C in this way, also what are the advantages of processing Java in this way and not compiling to machine code, other than the portability of course?


问:
How do you go about understanding others' code?
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?

答:
How do I go about understanding others code?

Well, most I don't go about it at all. I only try to understand it if it doesn't work, and I'm trying to figure out if I did something wrong or "the other" did. And the tools I use for that is reading the code and using the debugger.

If that also doesn't help, I mail the author.

ContentLicense: CC BY-SA 2.5


问:
Testing strategy for wrapper class
In my Android project I decided to create wrapper around SharedPreferences(which is basically key-value storage) with following interface

```<code>interface Preferences{
    public void saveInt(int value, String key);
    public void saveString(String value, String key);
    public int readInt(String key);
    public String readString(String key);
}
</code>```

Implemetation uses Android SharedPreferences API, simplified version looks like that:

```<code>public class SharedPrefencesWrapper implements Preferences{
    private SharedPreferences mSharedPreferences;

    public SharedPreferencesStorage(Context context) {
        mSharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }
    public void saveInt(int value, String key){
        mSharedPreferences.edit().putInt(key, value).commit();
    }
    //The same for all other public methods
}
</code>```

Now I want to test SharedPreferencesWrapper class, every public method of Preferences class:

```<code>public class SharedPreferencesWrapperTest{
    @Test
    public void savesBoolean(){
       Preferences prefs = new SharedPreferencesWrapper(...);
       prefs.saveInt(3, "intKey");
       int savedValue = prefs.readInt("intKey");
       assertEquals(3, savedValue);
    }
}
</code>```

Now, can the test look like that? Or should I use SharedPreferences API to check saved values in tests? My concern is that to retrieve the value I will use methods of SharedPrefencesWrapper, something doesn't feel right here.

答:
In theory, you want to ensure the data has been stored using the SharedPreferences API, and so, in theory, you should check that the values stored using your wrapper are available when directly retrieved using the API.

In practice, especially if you intend that all your code should use your wrapper, you might as well only check it can retrieve what it stores, partly because one of the "normal" reasons for a wrapper is to allow for it to change the underlying storage mechanism, so in the future you might decide to store settings in a database, for example.

Title: Testing strategy for wrapper class


问:
Why don't Windows/Linux use relational Databases (RDBMS)?
Why don't Windows/Linux use relational databases (RDBMS)?

I know they use file systems to store all data but don't you think it is more efficient to use databases like we use in web sites/web apps?

Please elaborate on the use of a file system over a database for storage.

This is not a duplicate of When should use of database be preferred over parsing data from a text file? I am talking in terms of only operating system contexts, and that question is generalized.

答:
Today, most database management systems (e.g. PostGreSQL, MongoDB, etc...) internally keep their data inside OS files (in the past, some DBMSs used raw disk partitions directly).

On recent computers still using spinning hard disks, the disk is so slow - relative to the CPU or the RAM - that adding a few software layers is not relevant. SSD technology might change that a bit, and some file systems are optimized for SSDs.

Files are present in most OSes in general for historical and social reasons (in particular, C compilers and most tools - editors, linkers - want files, so there is a chicken and egg issue), and because there are a lot of very good file system implementations.

BTW, some essential system facilities can use databases. For example on Linux PAM can be configured to use information in databases (but this is rarely done in practice). Also, some mail servers may store some or most of their data in databases (e.g. Exim).

Files are slightly lower abstractions than databases, so they can be easier to implement (as the file systems & VFS layer in the Linux kernel) and faster to use. In particular, the operations on files are much more restricted than those on databases. In fact, you could see files or file systems as some very restricted databases!

You could design an operating system without any files, but with some other orthogonal persistence machinery (e.g. having every process be persistent, then you don't care much explicitly about storage, since the OS is managing persistent resources). This has been done in several academic operating systems(1) (and also in the Smalltalk and Lisp machines of the 1980s, somehow in the IBM System i, a.k.a. AS/400, and in some toy projects linked from osdev), but when you design your OS this way you cannot leverage on many existing tools (e.g. you also need to make your compiler and your user interface from scratch, and that is a lot of work).

Notice that microkernel operating systems might not need files provided by kernel layers since the file systems are just application servers (e.g. Hurd translators running in userland). Look also at the unikernel approach in today's MirageOS

Linux (and probably Windows, which got most of its inspiration from VMS & Unix) need files to work. At the very least, the init program (the first program started by the kernel) must be an executable stored in a file (often /sbin/init, but it could be systemd these days), and (nearly) all other programs are started with execve(2) syscall so must be stored in a file. However, FUSE enables you to give file-like semantics to non-file things.

Notice also that on Linux (and perhaps even Windows, which I don't know and never used) sqlite is a library managing some SQL database in a files and providing an API for that. It is widely known that Android (a Linux variant) uses a lot of sqlite files (but it still does have a POSIX-like file system).

Read also about application checkpointing (which, on many current OSes, is implemented to write the process state in files). Pushed to the extreme, that approach does not need to manually write application files (but only to persist the entire process state using the checkpointing machinery).

Actually, the interesting question is why do current operating systems still use files, and the answer is legacy, and economic and cultural reasons (sadly, most programming languages and libraries today still want files).

Note 1: persistent academic OSes include Lisaac & Grasshopper, but these academic projects seem to be inactive. Look also into http://tunes.org/ ; it is inactive, but has gotten lots of discussions around such topics.

Note 2: the notion of file has widely changed over time (look at this answer about my first programming experiences): the first MSDOS on 1980s IBM PCs (no directories!), the VMS -on 1978 Vaxen- (had both fixed-record files and sequential files, with a primitive versioning system), the 1970s mainframes (IBM/370 with OS/VS2 MVS) had a very different notion of files and file systems (in particular because at their time the ratio of hard disk access time to core memory access time was a few thousand - so at that time disk ran relatively faster than today, even if today's disks are absolutely faster than in the previous century, today the CPU / disk speed ratio is about a million; but we now have SSDs). Also, files are less (or even not) useful when the memory is persistent (as on CAB500 magnetic drum, 1960s; or future computers using MRAM)


问:
Best practice for allowing mutation of a Collection type field
Suppose I have a (DTO style) class with a field that is a list:

```<code>public class MyClass {
    private List<String> stuff = new LinkedList<>();
}
</code>```

There are a few choices to allow mutation of the field:

```<code>// provide only a setter that *replaces* the list with the contents of the parameter
public void setStuff(List<String> list) {
    stuff = new LinkedList<>(list); // safe copy, or clear() + addAll(), whatever
}

// provide only a getter, allowing direct mutation
public List<String> getStuff() {
    return stuff; // deliberately allowing getStuff().add("foo") etc
}

// provide delegating mutator methods for allowed mutations, eg
public void addStuff(String s) {
    stuff.add(s);
}
// and removeStuff(String), clearStuff(), etc as actual need arises
</code>```

Assuming the only callers are (trusted) same-project code, which is the "best" approach?

答:
The decision is between offering your own (proxy) methods, or returning an internal object to be mutated by the caller. Unless performance is the single most important goal of your architecture, the Law of Demeter would strongly suggest that you should rather implement proxy methods:

More correct: a proxy method is the ideal place to do validation that would otherwise have to be implicit and spread throughout the whole codebase. By not leaking a reference to internal state, you preclude the possibility of accidentally making that state invalid. setStuff and addStuff get this right, but getStuff doesn't.

Less coupled: the return- and argument  types of a method become part of the interface of that method. Therefore these types should be as narrow and general as possible. You sensibly try doing this by exposing the List interface, and not a specific class type.

In the context of DTOs – which are really just serialization containers – most of this discussion does not matter. There is no internal state to be protected, there is only a value. However, once constructed there is no reason to mutate a DTO. By this argument, an outgoing DTO only needs a constructor and serialization support, whereas an incoming DTO only needs serialization support and getter methods. Unless used by the serialization mechanism, this does not need mutators or setters, so that we can favour an immutable design.

In particular, we would have the equivalent of setStuff in the constructor, and a getStuff accessor. This accessor would typically enforce immutability, but since the lifetime of a DTO ends once the contained values have been read and the values are only read at one point for each DTO, it would be safe to freely use and mutate those values.


问:
Redis for caching
I've heard a lot of positive about Redis but have not used it myself. Now I want to add a cache layer for my web app to reduce the DB load, and I suppose Redis is fine for this.

But I don't clearly understand who should populate Redis with data and keep it in synch with the DB. If I need to create some service for this, then obviously it will contain some caching logic. If so, why can't this new service store the cache data itself? Then, if I add some access API to this new service, it will be able to process cache requests from clients itself. Why would I use Redis at all in this case?

答:
If your service is hosted on a single machine, chances are that in-memory caching will have a better performance and will be easier to implement.

On the other hand, there are three situations where local caching is not enough:

As soon as your service starts to be hosted on multiple servers, which is the case for most services hosted in production, you may need to implement either centralized¹ or distributed² caching in order for your services to share the same cache.

In this case, if your language/framework/infrastructure doesn't already have the feature (such as AppFabric in Microsoft community), Redis appears an excellent alternative.

Note that in the same way, you may have a system installed on a single machine, but written in multiple programming languages. If different parts of the system need to access the same cache entities, you may either create the caching service yourself, or do it the easy way and let Redis do the job.

Redis has much more features than ordinary cache systems. Have you seen the list of Redis commands? Instead, most caching systems are limited to three actions: add, get, remove, and to expiration options. For instance, what about DECRBY? Most caching libraries I've used don't even have the ability to increment/decrement values, which makes them a poor choice for counters, for example.

If you need those additional features, Redis is obviously a solution to your needs.

In large scale environments, system administrators may need to be able to properly configure the caching servers (as well as properly chose the hardware for the particular needs of caching). Having a common caching service such as Redis means that those system administrators may learn it well and focus on its configuration, given that it can then be used from services written in any programming language.

¹ In centralized caching, all clients access the same caching service (which, internally, can use failover as well) which handles all the data and its invalidation.

² In distributed caching, each client stores cached entities. When an entity is changed or removed, the action should be dispatched to all the nodes to ensure consistency.

Title: Redis for caching


问:
Partial Model Updates From View
I hope this is on-topic here since I'm a bit new to the whiteboard...

I'm currently developing an application using ASP.NET MVC 5 (and WebAPI 2).  One of my domain entities is huge, and is stored in a document database (MongoDb in this case).  The reason it's so large is that it resembles the fields on a paper form that used to be used for this process.  It logically makes sense for this entity to be as large as it currently is.  I'm currently brainstorming the best way to handle the updating of this entity.  I'm currently using a 1:1 model of this entity.

I'm going to explain what I'm in the process of implementing below, but nothing is set in stone at this point.

The View currently is split up into sections of this large model where a user can click on a section and then the section then appears as a form using some JavaScript magic for the end-user to update those fields (properties of the model).  This is where I'm not sure if I'm doing this properly:  The current implementation is sending the ENTIRE model to a WebAPI controller via $.ajax() to update the database with these changes, and if successful I update the View on the client side to display the current values.

I feel like I'm not really leveraging the ASP.NET MVC framework here though except for the initial display of the view, since I'm performing these updates on the client side.

Is this the proper way to do partial updates of a model (at least using ASP.NET MVC 5)?  I don't really want to have to refresh the entire page by requesting a new view after one of these partial submissions using the server-side processing of forms.  Should each of these sections be a partial view along with smaller models that can then update the larger entity?  In this case I believe that I can then utilize the server-side processing for forms since it can then send a new partial view?  (Am I even understanding how to use partial views here?!)

I'm a bit confused if you couldn't tell...

答: Splitting your model into smaller models makes sense. You can use Ajax.BeginForm to submit the data of your partial view. So you can use your controller's action methods to call the service layer (your WEB API). In the action method you can create an object of your Main entity and populate it with your smaller model's values and send it to the API. </p>

Title: Partial Model Updates From View


答:
Although this is opinion-based, I think it's just another historical artifact. Early OSes used a simple file system design for performance that was reasonably strongly tied to the characteristics of the hardware available at the time, and it's been the same way ever since. It's difficult to change the old file read/write APIs for more transactional query/insert APIs once they were established.

All current file systems have a requirement to be backward compatible with these old APIs.

Microsoft did think about replacing the file system with an RDBMS-based one, in the Longhorn development. That was too much of a change for them to pull off, but you do see their efforts continue in the form of Windows Search (where an RDBMS is used to store a copy of metadata) and features such as SQL Server's Filestream system (where a database table of file data is exposed to the OS as an ordinary directory allowing both Windows Explorer access to the data, and SQL queries of the same data).

Other OSs do have RDBMS filesystems. AS/400s used to have these, though I never learned enough about them; I remember how weird it appeared at the time). I think other mainframe systems have the same kind of approach.

Title: Why don't Windows/Linux use relational Databases (RDBMS)?

Body:
Why don't Windows/Linux use relational databases (RDBMS)?

I know they use file systems to store all data but don't you think it is more efficient to use databases like we use in web sites/web apps?

Please elaborate on the use of a file system over a database for storage.

This is not a duplicate of When should use of database be preferred over parsing data from a text file? I am talking in terms of only operating system contexts, and that question is generalized.


答:
Run the programm with a simple test case

Step through the code with the same test case

Use more difficult test cases

Title: How do you go about understanding others' code?

Body:
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?


问:
Highly scalable and dynamic "rule-based" applications?
For a large enterprise app, everyone knows that being able to adjust to change is one of the most important aspects of design. I use a rule-based approach a lot of the time to deal with changing business logic, with each rule being stored in a DB. This allows for easy changes to be made without diving into nasty details. Now since C# cannot Eval("foo(bar);") this is accomplished by using formatted strings stored in rows that are then processed in JavaScript at runtime. This works fine, however, it is less than elegant, and would not be the most enjoyable for anyone else to pick up on once it becomes legacy.

Is there a more elegant solution to this? When you get into thousands of rules that change fairly frequently it becomes a real bear, but this cannot be that uncommon of a problem that someone has not thought of a better way to do this. Any suggestions? Is this current method defensible? What are the alternatives?

Edit: Just to clarify, this is a large enterprise app, so no matter which solution works, there will be plenty of people constantly maintaining its rules and data (around 10).  Also, The data changes frequently enough to say that some sort of centralized server system is basically a must.

答:
If you are designing a highly scalable "rule-based" application where rules are subjected to frequent changes from business then consider market leading BRMS products such as:
1. IBM WODM
2. FICO BLAZE Advisor
3. Drools (open source)

I have been working on large commercial applications with a BRMS approach which make them highly scalable and easy to maintain and also make them very flexible with ZERO downtime to production. It makes business happy. :)


问:
Solving The Iceberg Problem
Joel Spolsky once wrote that 90% of a software project is not its visual parts:

If you show a nonprogrammer a screen which has a user interface which is 100% beautiful, they will think the program is almost done... And then when you spend the next year working "under the covers," so to speak, nobody will really see what you're doing and they'll think it's nothing.

Since many applications have the UI designed first, what are some effective ways that the development team can show progress when their work is essentially invisible?

答:
If there is no visualization for what you do, create one.

It doesn't matter if it's a time-series graph, a burndown chart, or any other quick-and-dirty visual. (In fact, quick and dirty is what you want, since you want to spend your time on programming and not on reporting.) Once you've demonstrated a series of slowly expanding deliverable measure to the people above, they will begin to understand that there is more to programming than mock-ups.

(Slowly begin to understand, to be sure, since they're people above and not engineers. But I've given up trying to convey to non-technical people exactly what the point of my work is, since the battle is not worth the effort.)

Title: Solving The Iceberg Problem


答:
technically it is fine to test one function with its inverse-function. Your low level integrationtest integrates your code with the underlying android-function. Since you cannot mock away the underlying android-function you cannot write a pure unit-test (test in in isolation).

But "...something doesn't feel right here." : I agree (at least with your example): does this abstraction and its test really make sense?

i usually do not write unittests for simple getters/setters/wrappers but have a more hight level integration-test that uses these. writing unittests for getters/setters/wrappers is too much work for too few benefit.

I donot see much benefit for the abstraction of SharedPreferences that still uses "magic numbers" like "intKey" or it-s corresponding constant.

In my opinion a more high-level abstration has more benefit. ie. for settings i would use

```<code>MySettingsViaSharedPreferences implements MySettings {
   boolean isDatabaseEnabled() {...}
   string getDatabaseUrl() {...}
</code>```

Title: Testing strategy for wrapper class

Body:
In my Android project I decided to create wrapper around SharedPreferences(which is basically key-value storage) with following interface

```<code>interface Preferences{
    public void saveInt(int value, String key);
    public void saveString(String value, String key);
    public int readInt(String key);
    public String readString(String key);
}
</code>```

Implemetation uses Android SharedPreferences API, simplified version looks like that:

```<code>public class SharedPrefencesWrapper implements Preferences{
    private SharedPreferences mSharedPreferences;

    public SharedPreferencesStorage(Context context) {
        mSharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }
    public void saveInt(int value, String key){
        mSharedPreferences.edit().putInt(key, value).commit();
    }
    //The same for all other public methods
}
</code>```

Now I want to test SharedPreferencesWrapper class, every public method of Preferences class:

```<code>public class SharedPreferencesWrapperTest{
    @Test
    public void savesBoolean(){
       Preferences prefs = new SharedPreferencesWrapper(...);
       prefs.saveInt(3, "intKey");
       int savedValue = prefs.readInt("intKey");
       assertEquals(3, savedValue);
    }
}
</code>```

Now, can the test look like that? Or should I use SharedPreferences API to check saved values in tests? My concern is that to retrieve the value I will use methods of SharedPrefencesWrapper, something doesn't feel right here.

Body:
technically it is fine to test one function with its inverse-function. Your low level integrationtest integrates your code with the underlying android-function. Since you cannot mock away the underlying android-function you cannot write a pure unit-test (test in in isolation).

But "...something doesn't feel right here." : I agree (at least with your example): does this abstraction and its test really make sense?

i usually do not write unittests for simple getters/setters/wrappers but have a more hight level integration-test that uses these. writing unittests for getters/setters/wrappers is too much work for too few benefit.

I donot see much benefit for the abstraction of SharedPreferences that still uses "magic numbers" like "intKey" or it-s corresponding constant.

In my opinion a more high-level abstration has more benefit. ie. for settings i would use

MySettingsViaSharedPreferences implements MySettings {
   boolean isDatabaseEnabled() {...}
   string getDatabaseUrl() {...}


答: I imagine how I'd write the code and look for similarities.</p>


答:
One trick is to keep a separate CSS for early demos.

Basic fonts and no fancy graphics and drab color scheme, all reinforce the idea that this is something under development.

The other trick (not really a trick -- you should be doing this anyway!) is agonize over the fine details of the background use cases ( most likely the actual business rules ) with your users so they get a feel for the complexity of the implementation (and hopefully improve your understanding of what they really want).

Title: Solving The Iceberg Problem

Body:
Joel Spolsky once wrote that 90% of a software project is not its visual parts:

If you show a nonprogrammer a screen which has a user interface which is 100% beautiful, they will think the program is almost done... And then when you spend the next year working "under the covers," so to speak, nobody will really see what you're doing and they'll think it's nothing.

Since many applications have the UI designed first, what are some effective ways that the development team can show progress when their work is essentially invisible?


问:
Database design for linking parent & child relationship
Currently i have requirement saying user from an UI creates there own forms which has types textbox,choicegroup etc..
Does anyone have a  any idea on how to architect the database to store all data?
If user want to link form1 to form2 etc..  how will these data links stored in database?

For example, parent1 has child1 & Child2, flow can be like this parent1->child1->child2.(In 1 single line how will parent child relationship need to be maintained in database tables)

答:
Parent-child relationships are usually implemented in databases by having a parent_id column.  So, each child has a direct reference to its parent, and all the children of parent A can be found by performing a SELECT ... WHERE parent_id = A.

This has the disadvantage of not encoding the order of the children in any way, so if the children need to be ordered, then an additional order field is needed, usually of type real.  Thus, inserting a child at a specific point along the list of children is done with new_child.order = (previous_child.order + next_child.order) / 2.

Other than that, it is unclear what you are asking.  You appear to have unnecessarily complicated your question by including things about your user interface in the narrative. Your user interface considerations seem to be completely unrelated to the question of how to represent parent-child relationships in databases.


问:
Is the application architecture of Facebook Flux a new idea?
Facebook announced that it's using the architecture they call Flux to develop their projects.

It consists of a single direction dataflow, and concepts like a Dispatcher, Stores and Actions (well described here).

This is their illustration of how the pieces glue together:

```<code>Views ---> (actions) ----> Dispatcher ---> (registered callback) ---> Stores -------+
Ʌ                                                                                |
|                                                                                V
+-- (Controller-Views "change" event handlers) ---- (Stores emit "change" events) --+
</code>```

My question is: Is that a new idea? Is it a application architecture used before? Is it a "best practice" borrowed from another language/framework?

The purpose of this question is to deepen the knowledge about the architecure which have been gaining lots of attention lately, and seem very different from the MV* pattern most developers I know have been working with.

答:
I believe that is an abstraction of CQRS (Command Query Responsibility Segregation)
http://www.codeproject.com/Articles/555855/Introduction-to-CQRS


问:
What can go wrong if the Liskov substitution principle is violated?
I was following this highly voted question on possible violation of Liskov Substitution principle. I know what the Liskov Substitution principle is, but what is still not clear in my mind is what might go wrong if I as a developer do not think about the principle while writing object-oriented code.</p>

答:
Example: You are working with a UI framework, and you create your own custom UI-control by subclassing the Control base class. The Control base class defines an method getSubControls() which should return a collection of nested controls (if any).
But you override the method to actually return a list of birthdates of presidents of the United States.

So what can go wrong with this? It is obvious that the rendering of the control will fail, since you don't return a list of controls as expected. Most likely the UI will crash. You are breaking the contract which subclasses of Control is expected to adhere to.


问:
Validating Server Response
I have written a REST API and a c# program.

how do i validate that the response is real, and from my server.

SCENARIO: i distribute a freeware to a certain community, which will then require them to register in order to continue.

currently upon logging in, the rest api reply with a JSON {status:"true" user_data: [...]}. (i added a login, so i could control who can use the said application)

at the back of my mind a person could setup a fake hostname, and forward traffic to a local webserver to intercept the data and reply the JSON. how do i prevent this?

答:
Short answer: you can't.

If it is on the client there is no way you can avoid this scenario if the 'attacker' is dedicated. There is simply no way you can 'force' your application to talk only to your server as the user can intercept and tamper with the communication, forcing it to other servers and returning canned responses.

You could make it harder for them by using a number of techniques to secure the communication between server and client: use SSL/TLS, encrypt communication between the applications with public/private key encryption, and so on.

But if your 'attacker' is dedicated, forget it. Just look at games such as Diablo III and SimCity. They required persistent connections and have very smart people writing loads of code, yet these games are often cracked within days of the release. And even if your communication is 100% foolproof, popping open the EXE with a hex editor and tampering with it works just as well.

Title: Validating Server Response


问:
What is the difference between a non-functional requirement and a quality attribute?
I'm trying to understand the difference between non-functional requirements and quality attributes. Are they the same thing?

You can find a set of quality attributes in the ISO 9126, now ISO/IEC 2500xx SQuaRE family of standards.

I know that each system is defined by a set of functional requirements and every of this requirements has associated one or more quality attributes. For example, suppose that you have the requirement that describes the login functionality of a system. You can associate to that requirement the attributes of security and performance.

If I say that the system can not take more than 1 second to respond, I'm talking about a constraint.

So, where the concept of non-functional requirements kicks in? Are they defined by the users? How can I identify them?

答:
Non-Functional requirements and Quality Attributes are one and the same

The idea behind the name change in recent times is that, these so called non-functional requirements are in fact system functionality (or a set of system functionality) that has a cross-cut impact in the system. Meaning, the transversal impact that this kind of "special functionality" has in a system makes it a Quality Attribute of that system. As an example:

A system with 5 components must process a request in 10ms. If one component has a defect taking 5ms to make its part in the processing it will affect the performance of the system as a whole.

Just as security is not only about a login and when it is affected it affects the whole system.

Summarizing, quality attributes (i.e. non-functional requirements) are all about functionality, how you implement something and how this implementation affects your systems. Typically, the difference to the "normal requirements" is in its impact, range and visibility.

Here is an interesting link on how to identify them in a structured way:

"Quality Attribute Workshop", SEI, 2003

And a book on how to document them and define them correctly:

"Architecting Software Intensive Systems: A Practitioners Guide", Anthony J. Lattanze, 2008

ContentLicense: CC BY-SA 4.0


问:
Composite Primary Key drawbacks
For website that I maintain (eCommerce) I now need to make a table that seems to require Composite Primary Key of 5 columns.
I never used 5 column as primary key before, only 2 and rarely 3.

I wonder whether there are any drawbacks to it, especially with regards to performance because this particular table is expected to have millions of records.

I haven't chosen a storage mechanism yet.

I am really rather interested in performance. How would for example "INSERT ... ON DUPLICATE KEY UPDATE" query work performance-wise in comparison to single column key? Are there any other performance drawbacks regarding to MySQL operations over this table?

答:
The biggest drawback is that you require 5 values to identify a row. If your application uses an O/RM (Object/Relation Mapping) layer, then you will have fits mapping these database rows to objects in a programming language. O/RM's are easiest to set up when every table has a single column primary key.

Once you get into web application frameworks, URLs in the browser often include some sort of identifier for data in the database and assume there is only one piece of data required to identify a resource, e.g. a single column primary key. This makes using modern web application frameworks more difficult (Ruby on Rails, Microsoft's ASP.NET MVC to name a few).

Programming aside, what if in the future you need to add a column that together with the other 5 should be unique? Now you are modifying your composite key. Just keep it simple. Use a single column primary key. If you need those 5 columns to be unique, consider adding a unique constraint or unique index to those columns instead.

The next drawback of composite keys in general, and especially composite keys requiring this many columns, is all of this data needs to be specified and copied to child tables in order to set up proper relationships between tables.

Business rule changes in the future might dictate that these values can be duplicated. How will you identify data then?

Values are duplicated between tables when you need foreign key references

O/RM's are harder to configure

Modern MVC web application frameworks are harder to configure routes to include the composite keys

Nothing but downsides to me.

The biggest headache I've run into with developers is they assume "uniqueness of data" equates "identifying a row in the database". This is rarely the case. I've found applications and databases to be much more maintainable and easy to build by defaulting to single column primary keys, and using composite keys as an exception to the rule, then enforcing data uniqueness by using unique constraints or indexes on those columns.

Title: Composite Primary Key drawbacks


问:
What would you consider best practice workflow tools for web application (PHP) development?
I'm really hoping somebody with more experience can edit the question as per my examples of answers:

using version control

test driven development

debugging code (xdebug for php)

use of UML diagrams

use of OOP for maintainable, reusable code

use of frameworks (like Zend Framework for php) for rapid application development

Anything else or an elaboration of what I mentioned above?

Basically, I'm in the middle of forming a team of developers (I'm a developer myself) and I'd like some advice on how professional programmers/designers etc should work together and what standards/paradigms they should use.

Also, if anybody has any books or links on the subject I'd welcome that!

I did find this which I guess satisfies what I'm looking for, or at least part thereof:

http://www.ibm.com/developerworks/websphere/library/techarticles/0306_perks/perks2.html

答:
I agree mostly with Click Upvote's post, however if you're working on a relatively large site I would definitely recommend using Symfony framework coupled with the Doctrine ORM.

If you're project is due next year, I would say take the time to invest in Symfony2 and Doctrine2.

Also, I can't stress enough the importance of developing on unix based system, Ubuntu is my preference and an all around great web server. I work primarily on windows but develop on Ubuntu running in a VMWare virtual machine on my desktop (or server when I'm at work).

As for IDE I highly recommend using NuSphere PHPEd or Storm PHP, sadly like all great things they are not free.


问:
Dictionary representation of an object
As python memory model is dictionaries of dictionaries, looks like any object in JavaScript has similar representation.

Below code,

```<code>>
foo = {}
</code>```

makes foo as an empty dictionary {}. fine.

If code says,

```<code>> foo["bar"] = function(){
     this.ack = 3;
  };
</code>```

then foo looks like a dictionary as shown below:

{"bar": function(){this.ack = 3}, "__proto__":Object}

Is my understanding correct?

Is yes, then any object in JavaScript can be accessed as object[expression], in my case object is foo.

mdn also says: JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name and a value.

If I drill down the details of foo, representation of foo from browser console, looks like dictionaries of dictionaries as shown below(in screenshot):

My question:

Can you write the dictionary form {} of foo for the above representation(shown in screenshot) as it looks like dictionaries of dictionaries ?

To support my claim that, objects are dictionaries in JavaScript, below is the data.

I observed that, anything is stored as dictionary element, in JavaScript:

```<code>var x = "hello";
window.x["length"]
   5
var number = 2
   undefined
number["toString"]
   toString()
number["toString"]();
   "2"
</code>```

I could write any code in JavaScript in terms of dictionary.

```<code>var foo = "hello";
var x = foo.length;  //5
x = foo.charAt(1);    // "e"
x = "avast".charAt(3);  //"s"
//like this
window["foo"] = "hello";
    "hello"
window["x"] = window["foo"].length;
    5
window["x"]
    5
window["x"] = window["foo"].charAt(1)
    "e"
window["x"] = "avast".charAt(3);
    "s"
</code>```

Note: key is always a string in Javascript. string is an immutable type

答:
As you can see in the console, you're looking at bar, a function with the body shown. Within that are a number of properties available on function objects. If you care about how foo is stored, check out this article on V8's isomorphism and structure optimization.

Looking at the MDN docs for function, you can see the same list of properties. arguments represents the arguments the function was called with, caller is the function that did the calling, length is the function's arity, and name is the functions proper name.

Since you're looking at the function object from outside -- as opposed to a stack trace while the function is being executed -- many of those fields are not filled in. There are no arguments or caller to a function object until it has been called, unsurprisingly.

There is no "dictionary" for this. Javascript has some types with their own properties, inherited or instance, that are not simple dictionaries. You can define your own types using new and a constructor function, which behave like dictionaries with prototypical inheritance, but aren't actually simple dictionaries. The dictionary representation in Javascript is largely an artifact of old runtimes that may have used maps to store objects, and has been retained so you can consistently treat different object types using the same associative-array syntax for access.

If you were to recursively walk enumerable keys for the object you've created, it would look like:

var foo = {
  bar: function() {
    this.ack = 3;
  }
};

function walkKeys(obj) {
  return Object.keys(obj).map(function(key) {
    return {
      key: key,
      children: walkKeys(obj[key])
    };
  });
}

var keys = walkKeys(foo);
document.getElementById('r').textContent = JSON.stringify(keys);
```

<pre class="lang-html prettyprint-override"><code><pre id=r>```
```

You don't get any keys for the function because it doesn't have any enumerable properties of its own. Those properties are all from the prototype or defined to be hidden and the function is not just a dictionary.

OwnerDisplayName: overexchange

Title: Dictionary representation of an object

Body:
As you can see in the console, you're looking at bar, a function with the body shown. Within that are a number of properties available on function objects. If you care about how foo is stored, check out this article on V8's isomorphism and structure optimization.

Looking at the MDN docs for function, you can see the same list of properties. arguments represents the arguments the function was called with, caller is the function that did the calling, length is the function's arity, and name is the functions proper name.

Since you're looking at the function object from outside -- as opposed to a stack trace while the function is being executed -- many of those fields are not filled in. There are no arguments or caller to a function object until it has been called, unsurprisingly.

There is no "dictionary" for this. Javascript has some types with their own properties, inherited or instance, that are not simple dictionaries. You can define your own types using new and a constructor function, which behave like dictionaries with prototypical inheritance, but aren't actually simple dictionaries. The dictionary representation in Javascript is largely an artifact of old runtimes that may have used maps to store objects, and has been retained so you can consistently treat different object types using the same associative-array syntax for access.

If you were to recursively walk enumerable keys for the object you've created, it would look like:

var foo = {
  bar: function() {
    this.ack = 3;
  }
};

function walkKeys(obj) {
  return Object.keys(obj).map(function(key) {
    return {
      key: key,
      children: walkKeys(obj[key])
    };
  });
}

var keys = walkKeys(foo);
document.getElementById('r').textContent = JSON.stringify(keys);

<pre id=r></pre>

You don't get any keys for the function because it doesn't have any enumerable properties of its own. Those properties are all from the prototype or defined to be hidden and the function is not just a dictionary.

OwnerDisplayName: ssube


问:
Designing a REST api by URI vs query string
Let's say I have three resources that are related like so:

```<code>Grandparent (collection) -> Parent (collection) -> and Child (collection)
</code>```

The above depicts the relationship among these resources like so: Each grandparent can map to one or several parents. Each parent can map to one or several children. I want the ability to support searching against the child resource but with the filter criteria:

If my clients pass me an id reference to a grandparent, I want to only search against children who are direct descendants of that grandparent.

If my clients pass me an id reference to a parent, I want to only search against children who are direct descendants of my parent.

I have thought of something like so:

```<code>GET /myservice/api/v1/grandparents/{grandparentID}/parents/children?search={text}
</code>```

and

```<code>GET /myservice/api/v1/parents/{parentID}/children?search={text}
</code>```

for the above requirements, respectively.

But I could also do something like this:

```<code>GET /myservice/api/v1/children?search={text}&grandparentID={id}&parentID=${id}
</code>```

In this design, I could allow my client to pass me one or the other in the query string: either grandparentID or parentID, but not both.

My questions are:

1) Which API design is more RESTful, and why? Semantically, they mean and behave the same way. The last resource in the URI is "children", effectively implying that the client is operating on the children resource.

2) What are the pros and cons to each in terms of understandability from a client's perspective, and maintainability from the designer's perspective.

3) What are query strings really used for, besides "filtering" on your resource? If you go with the first approach, the filter parameter is embedded in the URI itself as a path parameter instead of a query string parameter.

Thanks!

答:
First

As Per RFC 3986 §3.4 (Uniform Resource Identifiers § (Syntax Components)|Query

3.4 Query

The query component contains non-hierarchical data that, along with
data in the path component (Section 3.3), serves to identify a
resource within the scope of the URI's scheme and naming authority
(if any).

Query components are for retrieval of non-hierarchical data; there are few things more hierarchical in nature than a family tree!  Ergo - regardless of whether you think it is "REST-y" or not- in order to conform to the formats, protocols, and frameworks of and for developing systems on the internet, you must not use the query string to identify this information.

REST has nothing to do with this definition.

Before addressing your specific questions, your query parameter of "search" is poorly named.  Better would be to treat your query segment as a dictionary of key-value pairs.

Your query string could be more appropriately defined as

?first_name={firstName}&last_name={lastName}&birth_date={birthDate} etc.

To answer your specific questions

Which API design is more RESTful, and why? Semantically, they mean and behave the same way. The last resource in the URI is "children", effectively implying that the client is operating on the children resource.

I don't think this is as clear cut as you seem to believe.

None of these resource interfaces are RESTful.  The major precondition for the RESTful architectural style is that Application State transitions must be communicated from the server as hypermedia.  People have labored over the structure of URIs to make them somehow "RESTful URIs" but the formal literature regarding REST actually has very little to say about this. My personal opinion is that much of the meta-misinformation about REST was published with the intent of breaking old, bad habits. (Building a truly "RESTful" system is actually quite a bit of work. The industry glommed on to "REST" and back-filled some orthogonal concerns with nonsensical qualifications and restrictions. )

What the REST literature does say is that if you are going to use HTTP as your application protocol, you must adhere to the formal requirements of the protocol's specifications and you cannot "make http up as you go and still declare that you are using http"; if you are going to use URIs for identifying your resources, you must adhere to the formal requirements of the specifications regarding URI/URLs.

Your question is addressed directly by RFC3986 §3.4, which I have linked above.  The bottom line on this matter is that even though a conforming URI is insufficient to consider an API "RESTful", if you want your system to actually be "RESTful" and you are using HTTP and URIs, then you cannot identify hierarchical data through the query string because:

3.4 Query

The query component contains non-hierarchical data

...it's as simple as that.

What are the pros and cons to each in terms of understandability from a client's perspective, and maintainability from the designer's perspective.

The "pros" of the first two is that they are on the right path. The "cons" of the third one is that it appears to be flat out wrong.

As far as your understandability and maintainability concerns, those are definitely subjective and depend on the comprehension level of the client developer and the design chops of the designer.  The URI specification is the definitive answer as to how URIs are supposed to be formatted.  Hierarchical data is supposed to be represented on the path and with path parameters.  Non-hierarchical data is supposed to be represented in the query.  The fragment is more complicated, because its semantics depend specifically upon the media type of the representation being requested.  So to address the "understandability" component of your question, I will attempt to translate exactly what your first two URIs are actually saying. Then, I will attempt to represent what you say you are trying to accomplish with valid URIs.

Translation of your verbatim URIs to their semantic meaning
/myservice/api/v1/grandparents/{grandparentID}/parents/children?search={text}
This says for the parents of grandparents, find their child having search={text}
What you said with your URI is only coherent if searching for a grandparent's siblings.  With your "grandparents, parents, children" you found a "grandparent" went up a generation to their parents and then came back down to the "grandparent" generation by looking at the parents' children.

/myservice/api/v1/parents/{parentID}/children?search={text}
This says that for the parent identified by {parentID}, find their child having ?search={text} This is closer to correct to what you are wanting, and represents a parent->child relationship that can likely be used to model your entire API.  To model it this way, the burden is placed upon the client to recognize that if they have a "grandparentId", that there is a layer of indirection between the ID they have and the portion of the family graph they are wishing to see.  To find a "child" by "grandparentId", you can call your /parents/{parentID}/children service and then foreach child that is returned, search their children for your person identifier.

Implementation of your requirements as URIs
If you want to model a more extensible resource identifier that can walk the tree, I can think of several ways you can accomplish that.

1) The first one, I've already alluded to.  Represent the graph of "People" as a composite structure. Each person has a reference to the generation above it through its Parents path and to a generation below it through its Children path.

/Persons/Joe/Parents/Mother/Parents
would be a way to grab Joe's maternal grandparents.

/Persons/Joe/Parents/Parents
would be a way to grab all of Joe's grandparents.

/Persons/Joe/Parents/Parents?id={Joe.GrandparentID}
would grab Joe's grandparent having the identifier you have in hand.

and these would all make sense (note that there could be a performance penalty here depending on task by forcing a dfs on the server due to a lack of branch identification in the "Parents/Parents/Parents" pattern.)  You also benefit from having the ability to support any arbitrary number of generations.  If, for some reason, you desire to look up 8 generations, you could represent this as

/Persons/Joe/Parents/Parents/Parents/Parents/Parents/Parents/Parents/Parents?id={Joe.NotableAncestor}

but this leads into the second dominant option for representing this data: through a path parameter.

2) Use path parameters to "query the hierarchy"  You could develop the following structure to help ease the burden on consumers and still have an API that makes sense.

To look back 147 generations, representing this resource identifier with path parameters allows you to do

/Persons/Joe/Parents;generations=147?id={Joe.NotableAncestor}

To locate Joe from his Great Grandparent, you could look down the graph a known number of generations for Joe's Id.
/Persons/JoesGreatGrandparent/Children;generations=3?id={Joe.Id}

The major thing of note with these approaches is that without further information in the identifier and request, you should expect that the first URI is retrieving a Person 147 generations up from Joe with the identifier of Joe.NotableAncestor. You should expect the second one to retrieve Joe.  Assume that what you actually want is for your calling client to be able to retrieve the entire set of nodes and their relationships between the root Person and the final context of your URI.  You could do that with the same URI (with some additional decoration) and setting an Accept of text/vnd.graphviz on your request, which is the IANA registered media type for the .dot graph representation.  With that, change the URI to

/Persons/Joe/Parents;generations=147?id={Joe.NotableAncestor.Id}#directed

with an HTTP Request Header
Accept: text/vnd.graphviz
and you can have clients fairly clearly communicate that they want the directed graph of the generational hierarchy between Joe and 147 generations prior where that 147th ancestral generation contains a person identified as Joe's "Notable Ancestor."

I'm unsure if text/vnd.graphviz has any pre-defined semantics for its fragment;I could find none in a search for instruction.  If that media type actually does have pre-defined fragment information, then its semantics should be followed to create a conforming URI.  But, if those semantics are not pre-defined, the URI specification states that the semantics of the fragment identifier are unconstrained and instead defined by the server, making this usage valid.

What are query strings really used for, besides "filtering" on your resource? If you go with the first approach, the filter parameter is embedded in the URI itself as a path parameter instead of a query string parameter.

I believe I have already thoroughly beaten this to death, but query strings are not for "filtering" resources. They are for identifying your resource from non-hierarchical data. If you have drilled down your hierarchy with your path by going
/person/{id}/children/ and you are wishing to identify a specific child or a specific set of children, you would use some attribute that applies to the set you are identifying and include it inside the query.


问:
Architecture: Should I schema validate incoming reply messages?
A web service I consume uses XSD to describe its API. Recently, they added a field to a reply message where no xsd:any had been, so when our schema validator tried to validate against the previous xsd, it failed. We considered this a backwards incompatibility and opened a ticket.

Their architect replied that we should validate our outgoing messages (requests), but not bother to validate replies. We should pick and choose the fields we want in the replies and ignore the rest. He also said that we should set our schema validator to ignore "new" fields and validate the rest.

If such a setting exists for some schema validators, then maybe this architect is not wrong, but on the other hand if my application breaks because a field I don't need to care about changed (or got created) doesn't that indicate a violation of the interface segregation principle? Is it really acceptable for me to validate the individual fields of the object piecemeal instead of expecting it to be all-or-nothing correct?

I realize that not validating incoming data from an external service has security implications as well, but in this question I'm trying to learn about the architectural principles more than the security aspects.

答:
Their architect replied that we should validate our outgoing messages
  (requests)...

They are not practicing what they preach.  If they were, you'd be receiving messages valid to the XSD.

The problem is definitely on their side and they should fix it, but in the real world we often have to work around issues others create, so you may need to "not bother to validate replies" just to keep things going.

With Internet protocols in general, we try to generate standards compliant output while being tolerant of noncompliant input.  I'm trying to find the RFC about HTML or HTTP (or whatever it was) that put it this way, but not much luck at this time.  But the point is being tolerant on your side helps keep things going eventhough it feels dirty.


问:
One Enum vs Multiple Enums
I am developing an application where a user submits a mission and other users accept the mission.

Pretty simple.

I want to keep a track of the mission progress status and store it into a database.

Which would be more appropriately:

1.having the following enums in a database column:

```<code>PRICE_NEGOTIATION,
DEPOSIT_NEGOTIATION,
MISSION_STARTED,
DEMO_RECEIVED,
DEMO_APPROVED,
DEMO_UNAPPROVED,
PAYMENT_DONE,
PAYMENT_PENDING,

PRICE_NEGOTIATION_UNAPPROVED_BY_CREATOR,
PRICE_NEGOTIATION_UNAPPROVED_BY_ACCEPTOR,
DEPOSIT_NEGOTIATION_UNAPPROVED_BY_CREATOR,
DEPOSIT_NEGOTIATION_UNAPPROVED_BY_ACCEPTOR,
MISSION_CANCELED_AFTER_START_BY_CREATOR,
MISSION_CANCELED_AFTER_START_BY_ACCEPTOR,
MISSION_CANCELED_AFTER_DEMO_UNAPPROVEMENT,
</code>```

and so on..

having more than one column in the database where one of them gives a cancel reason, another one that holds who canceled the mission and another one about the payment status.

any better suggestions?

10x in advance and sorry if the question is too much opinion based.

答:
I can see the redundancy in your enum, this should be two separate columns, each of which can be an enum:

enum for col1:

```<code>PRICE_NEGOTIATION,
DEPOSIT_NEGOTIATION,
MISSION_CANCELED
</code>```

enum for col2:

```<code>UNAPPROVED_BY_CREATOR,
UNAPPROVED_BY_ACCEPTOR,
UNAPPROVED_BY_ACCEPTOR,
AFTER_START_BY_CREATOR,
AFTER_START_BY_ACCEPTOR,
AFTER_DEMO_UNAPPROVEMENT
</code>```

You can even add a check constraint to ensure sane values between the two enum columns (assuming you're using a RDBMS that supports check constraints - hello MySQL... you listening?)

```<code>alter table ... add constraint enum_sanity_chk check (
  case
    when col1='PRICE_NEGOTIATION' then
      col2 in (
        'UNAPPROVED_BY_CREATOR',
        'UNAPPROVED_BY_ACCEPTOR'
      )
    when col1='DEPOSIT_NEGOTIATION' then
      col2 in (
        'UNAPPROVED_BY_CREATOR',
        'UNAPPROVED_BY_ACCEPTOR'
      )
    when col1='MISSION_CANCELED' then
      col2 in (
        'AFTER_START_BY_CREATOR',
        'AFTER_START_BY_ACCEPTOR',
        'AFTER_DEMO_UNAPPROVEMENT'
      )
    ...
    else
      false -- col1 not matched to any expected enum
  end
);
</code>```

Let the database enforce all the rules between data.  With the rules well defined at the lowest level, the rest of the system gains this assurance.

Title: One Enum vs Multiple Enums

Body:
I can see the redundancy in your enum, this should be two separate columns, each of which can be an enum:

enum for col1:

PRICE_NEGOTIATION,
DEPOSIT_NEGOTIATION,
MISSION_CANCELED

enum for col2:

UNAPPROVED_BY_CREATOR,
UNAPPROVED_BY_ACCEPTOR,
UNAPPROVED_BY_ACCEPTOR,
AFTER_START_BY_CREATOR,
AFTER_START_BY_ACCEPTOR,
AFTER_DEMO_UNAPPROVEMENT

You can even add a check constraint to ensure sane values between the two enum columns (assuming you're using a RDBMS that supports check constraints - hello MySQL... you listening?)

alter table ... add constraint enum_sanity_chk check (
  case
    when col1='PRICE_NEGOTIATION' then
      col2 in (
        'UNAPPROVED_BY_CREATOR',
        'UNAPPROVED_BY_ACCEPTOR'
      )
    when col1='DEPOSIT_NEGOTIATION' then
      col2 in (
        'UNAPPROVED_BY_CREATOR',
        'UNAPPROVED_BY_ACCEPTOR'
      )
    when col1='MISSION_CANCELED' then
      col2 in (
        'AFTER_START_BY_CREATOR',
        'AFTER_START_BY_ACCEPTOR',
        'AFTER_DEMO_UNAPPROVEMENT'
      )
    ...
    else
      false -- col1 not matched to any expected enum
  end
);

Let the database enforce all the rules between data.  With the rules well defined at the lowest level, the rest of the system gains this assurance.


问:
Why don't Windows/Linux use relational Databases (RDBMS)?
Why don't Windows/Linux use relational databases (RDBMS)?

I know they use file systems to store all data but don't you think it is more efficient to use databases like we use in web sites/web apps?

Please elaborate on the use of a file system over a database for storage.

This is not a duplicate of When should use of database be preferred over parsing data from a text file? I am talking in terms of only operating system contexts, and that question is generalized.

答:
The real reason is a lack of need for it. Layering databases on top of files, rather than merging them, handles the vast majority of situations at least as well as a merged solution with substantially reduced complexity. In some situations others have mentioned, we've also layered parts of files on top of databases (such as permissions structures). In that case, the database managing those permissions is remarkably simpler than a commercial RDBMS.

There are advantages to merging them, but so far those have been few and far enough between that the movement is growing slowly. Consider how rare it is for people to say "Give me the 3rd column of every invoice I've received since 2010, and sum them together," or "don't let me delete this file until I've removed it from the Excel spreadsheet also."

File systems have a few advantages over relational databases that keep them going:

They are far simpler. This is a big deal when bootstrapping a computer. Even on Android, where they have an RDBMS for storage, they have plain old images for managing the initial bootloading process.

It is easier to define their limitations. In an unlimited machine, RDBMs provide quite a lot of power. However, in the file system world, there are a lot of limitations which stem from trying to be fast when directly layered on top of a spinning disk. It is harder to prove that an RDBMS query does not exceed those limitations than it is to provide the same guarantees for a file system.

They handle hierarchical structures better. In many cases, it is still natural for people to store files in a hierarchical form. In RDBMSes, that is a special case. File systems optimize for that special case, RDBMSes do not.

Reliability. It is much easier to prove that two layers work independently than to prove that one giant system works perfectly. RAID arrays, fail-safe journals in times of power failures, and other advanced features are easier to implement in a layer below the layer dealing with things like ACID or foreign key constraints.


问:
How do you judge if you're paid enough?
How do you evaluate how much you feel you ought to be paid as a junior programmer?</p>

答: Comparing it with my college/school friends working in other organizations. </p>

Title: How do you judge if you're paid enough?


答: If you're using the replies as input to your system, then you definitely should validate them. If you're just checking for success or failure, and possibly recording some returned IDs, then you probably don't need to validate, but I agree that you should make the web service guys fix their problem. They should have procedures in place to switch you to a new version of the service if they make a non-backwards-compatible change. And hopefully this will make them a little more careful about their schema design going forward!

Title: Architecture: Should I schema validate incoming reply messages?

Body:
A web service I consume uses XSD to describe its API. Recently, they added a field to a reply message where no xsd:any had been, so when our schema validator tried to validate against the previous xsd, it failed. We considered this a backwards incompatibility and opened a ticket.

Their architect replied that we should validate our outgoing messages (requests), but not bother to validate replies. We should pick and choose the fields we want in the replies and ignore the rest. He also said that we should set our schema validator to ignore "new" fields and validate the rest.

If such a setting exists for some schema validators, then maybe this architect is not wrong, but on the other hand if my application breaks because a field I don't need to care about changed (or got created) doesn't that indicate a violation of the interface segregation principle? Is it really acceptable for me to validate the individual fields of the object piecemeal instead of expecting it to be all-or-nothing correct?

I realize that not validating incoming data from an external service has security implications as well, but in this question I'm trying to learn about the architectural principles more than the security aspects.


问:
When should "should" be used in documentation?
I was just reading http://lasagne.readthedocs.org/en/latest/modules/layers.html and wondering about some documentation style questions. One of them was the use of the word "should".

For example:

This method should be overridden when implementing a new Layer class. By default it raises NotImplementedError.

Is that a place where "should" should be used? It seems to me that the following would be better:

This method has to be overridden when implementing a new Layer class. Otherwise, it raises NotImplementedError.

Is there a style guide about such language-independent documentation style questions? (e.g. should a documentation be written in passive voice or with "you" or "the developer" would be another question)

Please note that I'm not writing down requirements. This is a question about documentation of a library.

答:
The term "must" tends to be reserved for completely black and white situations where you really have no option but to do something in a specific way, or else failure is inescapable.

The person writing the documentation cannot write "must" if it is possible for someone, under some circumstances, no matter how artificial, to prove that technically, the issue being discussed is not an absolute necessity.

In other words, I suppose it must be fairly easy for someone to implement a new "Layer Class" without overriding the method that throws NotImplementedError, and then proceed to instantiate that class, invoke a few of its methods while making sure to not invoke the problematic method, and then go "voila! It was not necessary to override that method after all!"

Of course, this whole discussion may be an attempt to read too much into the written word of the documentation. Perhaps the person writing the documentation simply was not hell bent on using the most precise possible word of the English language, so they simply wrote "should" as a synonym for "must".


答:
Ever since I read RFC 2119, I began to put a reference to it in specifications - even code documentation. A comment like the following somewhere in the documentation helps set the standard for interpretation.

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED",  "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 (https://www.ietf.org/rfc/rfc2119.txt)

It's a pretty small and easy to understand RFC and you only need read it once.

Title: When should "should" be used in documentation?

Body:
I was just reading http://lasagne.readthedocs.org/en/latest/modules/layers.html and wondering about some documentation style questions. One of them was the use of the word "should".

For example:

This method should be overridden when implementing a new Layer class. By default it raises NotImplementedError.

Is that a place where "should" should be used? It seems to me that the following would be better:

This method has to be overridden when implementing a new Layer class. Otherwise, it raises NotImplementedError.

Is there a style guide about such language-independent documentation style questions? (e.g. should a documentation be written in passive voice or with "you" or "the developer" would be another question)

Please note that I'm not writing down requirements. This is a question about documentation of a library.


问:
XQL vs. XQuery vs.
I am studying some standards and tools for XML, but I confused with some terms and standards and their differences

What is XQL? It seems the same as XQuery and somehow even similar to XPath?

Are XQL and XQuery the same?
Are there other similar [even deprecated] standards?

答: The difference beween XQL and XQuery is that XQL is dead. It was pretty well stillborn. It influenced the design of XQuery but it was never significant in its own right.</p>

Title: XQL vs. XQuery vs.


问:
Generating New Media Content From Binary Patterns
At the most basic level, a digital media file (document, song, video, etc) is just a rather large pattern of 1's and 0's.

We can say that for any given piece of digital media, there corresponds a binary "fingerprint" unique to said media which defines it.

For example, an MP3 of a song will have a very specific binary pattern, that if altered, results in the file no longer being the same song.

Armed with this knowledge, it seems feasible to generate a binary pattern which results in a new (or copy of existing) media.

This leads one to conclude that all digital media already exists, but just has not been stored in format yet. All possible binary patterns must be discoverable or are already known.

Taking the thought experiment a little farther, it would seem possible to generate a pattern for content not yet produced, say an upcoming movie that's still in production.

Assuming every piece of media has a unique binary "fingerprint", how realistic is it to produce a binary pattern which is consumable in some media form?

答:
A favicon (the small 16x16 icon that your browser displays next to the address of a website) is 6144 bits long.  (Assuming 24-bit color.)  Encryption algorithms that are unbreakable by today's standards use only 512 bits, because it is considered impossible to enumerate all combinations of a sequence of 512 bits.

What this should tell you is that absolutely any random bit pattern that you can think of is virtually guaranteed to be nothing but noise.  The bit patterns that are meaningful to human beings are so few, and so very far apart from each other, that they are virtually non-existent, they are literally lost in the noise.

So, the chances of arbitrarily flipping bits and coming up with something even remotely meaningful are astronomically small.

And we have only touched 16-by-16-pixel favicons yet.


问:
Algorithm for comparing hundreds of similar, but not identical documents
I have seen similar questions about text comparison, but none on such a large scale.

I have a client with two sets of recordings of speeches, 250 and 550 recordings each. Each of the recordings in each set are unique, but about 200 out of the 250 are duplicated in the set of 550, and they need to weed out the doubles. The recordings were recorded on separate devices, so you can't just compare the file length and content.

They are willing to pay to have the first 15 seconds of each recording transcribed, and then they want me to devise some system of using those transcripts to identify the doubles.

First of all, I'm assuming that I should first remove any punctuation and capitalization, because those are things that might arbitrarily change based on the transcriptionist who happens to do that file.

My first idea was to simply calculate the Levenshtein distance for each combination of recordings, but I can't imagine doing that on such a large scale (250 x 550) would be efficient. Then I thought that instead of doing a Levenshtein distance, but using words as the unit instead of characters. But this still would involve running an algorithm 250X550 times, albeit a much faster algorithm each time.

Then I was thinking that maybe I should go through each document, and make a alphabetically sorted dictionary with a count of how many times each word appears in each document. Then I could just go through the dictionary associated with each document and subtract the number of appearances of each word from each other, to produce a total number of mismatched words. This looses taking into account the order of the words, but it should be much faster.

Which of these methods, or perhaps an entirely different method, should I use?

答: For one-shot reports like this, accuracy of results and ease of verifying your algorithm are way, way more important than efficiency.  Your brute force algorithm is only 137,500 combinations, comparing maybe a couple dozen words each.  That's a runtime on the order of a few seconds, assuming you read all the transcripts into memory first.  That's nothing compared to the hours spent doing the transcription and your own time.  Even if it took an hour to run, that would be better than a fast algorithm that you weren't sure would work.  Don't make this harder on yourself.


问:
How to define IntsWithoutZero type in f#
Recently I saw a great video of Scott Wlaschin about patterns in functional programming. He gives an example of dividing a numbers. In f# we'd use int option for the result to handle division by zero in a nice functional way.

As another possibility he mentions creating a type that would not allow 0 as a valid value.
Let's say IntsWithoutZero. How could we define this kind of type "functionally"?

I know how I'd do it with OO approach (e.g. write a IntsWithoutZero class and disallow 0 during construction).

答:
I know how I'd do it with OO approach (e.g. write a IntWihtoutZero class and disallow 0 during construction).

You do it the same way: hide the data constructor and only expose a function that checks if the integer is greater than 0.


答:
RFC2119 was mentioned. According to RFC2119, "SHOULD" means: There may possibly perhaps under some circumstances be reasons why you wouldn't follow the requirement, but you should really seriously think about it and consider all the consequences. </p>

<p>That seems to describe the situation quite well. </p>

Body:
RFC2119 was mentioned. According to RFC2119, "SHOULD" means: There may possibly perhaps under some circumstances be reasons why you wouldn't follow the requirement, but you should really seriously think about it and consider all the consequences.

That seems to describe the situation quite well.


问:
Should MVVM models contain complex objects
Let us say that I have a Book class, a book can have an object of another class like an Author or other complex objects like a list of Genres. My question is, in an MVVM model should I make the complex object a property or should I use a simple object like Integer which contains a reference to the complex object, like it's ID?</p>

答:
The Model is much more than a dumb data object. It can (and should) contain references to other objects, hold collections and so on.

In your case, you may have an Author, which has a collection of Book, which may have a collection of Genre. This really depends on your data structure, but you get the idea.

A good example would be Entity Framework, as it follows the pattern of having the foreign key (the ID), and the object itself. See here for more information.

There is nothing wrong with having references to other classes in your model.

OwnerDisplayName: Gaurav Joseph

OwnerDisplayName: Mike Eason