答:
I'd say that in the C# world, an enum would be one of the best options here.

With that you'd be forced to spell out what you're doing and any user would see whats happening. It's also safe for future extensions;

```<code>public enum WhatToInclude
{
    IncludeAll,
    ExcludeManagement
}

var ids = ReturnEmployeeIds(WhatToInclude.ExcludeManagement);
</code>```

So, in my opinion here:

enum > optional enum > optional bool

Edit:
Due to discussion with LeopardSkinPillBoxHat below regarding a [Flags] enum which in this specific case might be a good fit (since we specifically are talking about including/excluding things), I instead propose using ISet<WhatToInclude> as a parameter.

It's a more "modern" concept with several advantages, mostly stemming from the fact that it fits in the LINQ family of collections, but also that [Flags] has a maximum of 32 groups. The main downside of using ISet<WhatToInclude> is how badly sets are supported in C# syntax:

```<code>var ids = ReturnEmployeeIds(
    new HashSet<WhatToInclude>(new []{
        WhatToInclude.Cleaners,
        WhatToInclude.Managers});
</code>```

Some of it might be mitigated by helper functions, both for generating the set and for creating "shortcut sets" such as

```<code>var ids = ReturnEmployeeIds(WhatToIncludeHelper.IncludeAll)
</code>```

Title: Specify optional parameter names even though not required?

Body:
Consider the following method:

```<code>public List<Guid> ReturnEmployeeIds(bool includeManagement = false)
{

}
</code>```

And the following call:

```<code>var ids = ReturnEmployeeIds(true);
</code>```

For a developer new to the system, it'd be pretty difficult guessing what true did. First thing you'd do is hover over the method name or go to the definition (neither of which are big tasks in the slightest). But, for readability sake, does it make sense to write:

```<code>var ids = ReturnEmployeeIds(includeManagement: true);
</code>```

Is there anywhere that, formally, discusses whether or not to explicitly specify optional parameters when the compiler doesn't need you to?

The following article discusses certain coding conventions: https://msdn.microsoft.com/en-gb/library/ff926074.aspx

Something similar to the article above would be great.

Body:
I'd say that in the C# world, an enum would be one of the best options here.

With that you'd be forced to spell out what you're doing and any user would see whats happening. It's also safe for future extensions;

public enum WhatToInclude
{
    IncludeAll,
    ExcludeManagement
}

var ids = ReturnEmployeeIds(WhatToInclude.ExcludeManagement);

So, in my opinion here:

enum > optional enum > optional bool

Edit:
Due to discussion with LeopardSkinPillBoxHat below regarding a [Flags] enum which in this specific case might be a good fit (since we specifically are talking about including/excluding things), I instead propose using ISet<WhatToInclude> as a parameter.

It's a more "modern" concept with several advantages, mostly stemming from the fact that it fits in the LINQ family of collections, but also that [Flags] has a maximum of 32 groups. The main downside of using ISet<WhatToInclude> is how badly sets are supported in C# syntax:

var ids = ReturnEmployeeIds(
    new HashSet<WhatToInclude>(new []{
        WhatToInclude.Cleaners,
        WhatToInclude.Managers});

Some of it might be mitigated by helper functions, both for generating the set and for creating "shortcut sets" such as

var ids = ReturnEmployeeIds(WhatToIncludeHelper.IncludeAll)


问:
Specify optional parameter names even though not required?
Consider the following method:

```<code>public List<Guid> ReturnEmployeeIds(bool includeManagement = false)
{

}
</code>```

And the following call:

```<code>var ids = ReturnEmployeeIds(true);
</code>```

For a developer new to the system, it'd be pretty difficult guessing what true did. First thing you'd do is hover over the method name or go to the definition (neither of which are big tasks in the slightest). But, for readability sake, does it make sense to write:

```<code>var ids = ReturnEmployeeIds(includeManagement: true);
</code>```

Is there anywhere that, formally, discusses whether or not to explicitly specify optional parameters when the compiler doesn't need you to?

The following article discusses certain coding conventions: https://msdn.microsoft.com/en-gb/library/ff926074.aspx

Something similar to the article above would be great.

答:
does it make sense to write:

```<code> var ids=ReturnEmployeeIds(includeManagement: true);
</code>```

It is debatable if this is "good style", but IMHO this is as least not bad style, and useful, as long as the code line does not become "too long". Without named parameters, it is also a common style to introduce an explaining variable:

```<code> bool includeManagement=true;
 var ids=ReturnEmployeeIds(includeManagement);
</code>```

That style is probably more common among C# programmers than the named parameter variant, since named parameters were not part of the language before Version 4.0. The effect on readability is almost the same, it just needs an additional line of code.

So my recommendation: if you think using an enum or two functions with different names is "overkill", or you don't want to or cannot change the signature for a different reason, go ahead and use the named parameter.

ContentLicense: CC BY-SA 3.0

Body:
does it make sense to write:

 var ids=ReturnEmployeeIds(includeManagement: true);

It is debatable if this is "good style", but IMHO this is as least not bad style, and useful, as long as the code line does not become "too long". Without named parameters, it is also a common style to introduce an explaining variable:

 bool includeManagement=true;
 var ids=ReturnEmployeeIds(includeManagement);

That style is probably more common among C# programmers than the named parameter variant, since named parameters were not part of the language before Version 4.0. The effect on readability is almost the same, it just needs an additional line of code.

So my recommendation: if you think using an enum or two functions with different names is "overkill", or you don't want to or cannot change the signature for a different reason, go ahead and use the named parameter.


问:
Programming by dictation?
ie. you speak out the code, and someone else across the room types it in

Anyone tried this?

Obviously the person taking the dictation would need to be a coder too, so you didn't have to explain everything and go into tedious detail (not 'open bracket, new line...' but more like 'create a new class called myParser that takes three arguments, first one is...').

I thought of it because sometimes I'm too easily distracted at my computer. Surrounded by buttons, instant gratification a click away, the world at my fingertips. To get stuff done, I want to get away, write my code on paper. But that would mean losing access to necessary resources, and necessitate tedious typing-up later on.  The solution? Dictate.

Pros:

no chance to check reddit, stackexchange, gmail, etc.

code while you pace the room, lie down, play billiards, whatever

train your brain to think more abstractedly (have to visualize things if you can't just see the screen)

skip the tedious details (closing brackets etc.)

the typist gets to shadow a more experienced programmer and learn how they work

the typist can provide assistance/suggestions

external pressure of typist expecting instructions, urging you to stay focussed

Cons

might be too hard

might not work any better

rather inefficient use of assisting programmer

need to find/pay someone to do this

答:
The real issue seems to be I'm too easily distracted at my computer.

This is something you are going to have to learn to overcome as outside of the university course you won't have the liberty to dictate to a drone programmer.

There are ways of forcing this by blocking (eg in the hosts file) sites you find distracting, other ways of working such as the Pomodoro Technique which mandates times of no distraction interspersed with enforced 'rest' periods to do what you want.

Another thing to think about is if you find programing so arduous you would rather Reddit than do it... is this the right career for you? Maybe boat building would suit better?

ContentLicense: CC BY-SA 2.5

Title: Programming by dictation?


答:
If the parameter is obvious from the (fully qualified) name of the method and it's existence is natural to what the method is supposed to do, you should not use the named parameter syntax. For example, in ReturnEmployeeName(57) it's pretty damn obvious that 57 is the employee's ID, so it's redundant to annotate it with the named parameter syntax.

With ReturnEmployeeIds(true), like you said, unless you look at the function's declaration/documentation it's impossible to figure what true means - so you should use the named parameter syntax.

Now, consider this third case:

```<code>void PrintEmployeeNames(bool includeManagement) {
    foreach (id; ReturnEmployeeIds(includeManagement)) {
        Console.WriteLine(ReturnEmployeeName(id));
    }
}
</code>```

The named parameter syntax is not used here, but since we are passing a variable to ReturnEmployeeIds, and that variable has a name, and that name happens to mean the same thing as the parameter we are passing it to(this is often the case - but not always!) - we don't need the named parameter syntax to understand it's meaning from the code.

So, the rule is simple - if you can easily understand from just the method call what the parameter is supposed to mean, don't use the named parameter. If you can't - that's a deficiency in the code's readability, and you probably want to fix those(not at any price, of course, but you usually want the code to be readable). The fix doesn't have to be named parameters - you can also put the value in a variable first, or use the methods suggested in the other answers - as long as the end result makes it easy to understand what the parameter does.

Body:
If the parameter is obvious from the (fully qualified) name of the method and it's existence is natural to what the method is supposed to do, you should not use the named parameter syntax. For example, in ReturnEmployeeName(57) it's pretty damn obvious that 57 is the employee's ID, so it's redundant to annotate it with the named parameter syntax.

With ReturnEmployeeIds(true), like you said, unless you look at the function's declaration/documentation it's impossible to figure what true means - so you should use the named parameter syntax.

Now, consider this third case:

void PrintEmployeeNames(bool includeManagement) {
    foreach (id; ReturnEmployeeIds(includeManagement)) {
        Console.WriteLine(ReturnEmployeeName(id));
    }
}

The named parameter syntax is not used here, but since we are passing a variable to ReturnEmployeeIds, and that variable has a name, and that name happens to mean the same thing as the parameter we are passing it to(this is often the case - but not always!) - we don't need the named parameter syntax to understand it's meaning from the code.

So, the rule is simple - if you can easily understand from just the method call what the parameter is supposed to mean, don't use the named parameter. If you can't - that's a deficiency in the code's readability, and you probably want to fix those(not at any price, of course, but you usually want the code to be readable). The fix doesn't have to be named parameters - you can also put the value in a variable first, or use the methods suggested in the other answers - as long as the end result makes it easy to understand what the parameter does.


问:
Single Responsibility Principle - How Can I Avoid Code Fragmentation?
I'm working on a team where the team leader is a virulent advocate of SOLID development principles. However, he lacks a lot of experience in getting complex software out of the door.

We have a situation where he has applied SRP to what was already quite a complex code base, which has now become very highly fragmented and difficult to understand and debug.

We now have a problem not only with code fragmentation, but also encapsulation, as methods within a class that may have been private or protected have been judged to represent a 'reason to change' and have been extracted to public or internal classes and interfaces which is not in keeping with the encapsulation goals of the application.

We have some class constructors which take over 20 interface parameters, so our IoC registration and resolution is becoming a monster in its own right.

I want to know if there is any 'refactor away from SRP' approach we could use to help fix some of these issues. I have read that it doesn't violate SOLID if I create a number of empty coarser-grained classes that 'wrap' a number of closely related classes to provide a single-point of access to the sum of their functionality (i.e. mimicking a less overly SRP'd class implementation).

Apart from that, I cannot think of a solution which will allow us to pragmatically continue with our development efforts, while keeping everyone happy.

Any suggestions ?

答:
A lot of the answers here are really good but are focused on the technical side of this issue. I'll simply add that it sounds like the developer's attempts to follow the SRP actually violate the SRP.

You can see Bob's blog here on this situation, but he argues that if a responsibility is smeared across multiple classes then the SRP is violated because those classes change in parallel. I suspect your dev would really like the design at the top of Bob's blog, and might be a bit disappointed to see it ripped apart. In particular because it violates the "Common Closure Principle" - things that change together stay together.

Remember that the SRP refers to "reason for change" and not "do one thing", and that you don't need to concern yourself with that reason for change until a change actually occurs. The second guy pays for abstraction.

Now there's the second problem - the "virulent advocate of SOLID development." It sure doesn't sound like you have a great relationship with this developer, so any attempts to convince him/her of the problems in the codebase are stumped. You'll need to repair the relationship so you can have a real discussion of the issues. What I would recommend is beer.

No seriously - if you don't drink head to a coffee shop. Get out of the office and somewhere relaxed, where you can talk about this stuff informally. Rather than trying to win an argument at a meeting, which you won't, have a discussion somewhere fun. Try to recognize that this dev, who is driving you nuts, is an actual functioning human who is trying to get software "out the door" and doesn't want to ship crap. Since you likely share that common ground, you can start to discuss how to improve the design while still conforming to the SRP.

If you can both acknowledge that the SRP is a good thing, that you just interpret aspects differently, you can probably start to have productive conversations.

OwnerDisplayName: Dean Chalk

ContentLicense: CC BY-SA 4.0


问:
Does discoverability in HATEOAS require the information must be machine readable, or can it just be human readable?
I'm trying to understand the concepts of HATEOAS (Hypermedia As The Engine Of Application State) in REST.  The following have been very useful:

What does HATEOAS offer for discoverability and decoupling besides ability to change your URL structure more or less freely?

REST APIs must be hypertext-driven (from Roy Fielding himself)

From them I understand that HATEOAS isn't just about providing links to tell a client what the next valid actions are, it's also about providing information about the valid methods that can be applied to a resource, and the format of the data being passed in both directions between the client and the server.

It's the data format that I'm having trouble with.  Roy Fielding mentions defining new media types to describe the data formats.  If new media types have to be created for every API anyone creates there would be hundreds of thousands of single-use media types defined.

To get around this issue, someone suggested using the HAL (Hypertext Application Language) media type for RESTful APIs.  HAL includes the concept of CURIEs, prefixes for relation names that expand into URLs that point to documentation.

For example,

```<code>"_links": {
  "curies": [
    {
      "name": "doc",
      "href": "http://haltalk.herokuapp.com/docs/{rel}",
      "templated": true
    }
  ],

  "doc:latest-posts": {
    "href": "/posts/latest"
  }
}
</code>```

Here the relation name is doc:latest-posts where doc is a CURIE that expands to http://haltalk.herokuapp.com/docs/, and http://haltalk.herokuapp.com/docs/latest-posts will point to documentation about the latest-posts resource (note that the URL to the latest-posts resource itself, as opposed to the documentation about it, is /posts/latest)

This seems a good way for client-side developers to learn about each resource provided by the API.  But does having an automatic link to human readable documentation satisfy the discoverability requirements of HATEOAS?  Or must the information describing the data formats required for each resource be machine readable (eg a custom media type for the API)?

答:
As you pointed out, Roy Fielding wrote an interesting article on his blog. And this paragraph summarize pretty well "How to HATEOAS":

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]

So, yes HATEOAS rely on providing links to clients to drive them on the application. A typical example is, as part of a banking application, a banking account where you have a link to withdraw and an other link to make a deposit. If your balance is negative, the withdraw link will disappear.
That's HATEOAS: you provide links to help the client.

But, wait a minute. In the quoted paragraph, Fielding talks about descriptive effort, media type and out-of-band information... interesting :-) !
In fact, HATEOAS is not just providing links, because it's not sufficient for a client to have only meaningless links. How the client is supposed to know the verbs to invoke when following on a link ? (GET/POST/PUT ?) ... How the client is supposed to know the data to pass as parameter when following a link ?
If the client don't know these informations, it's simple: your client rely on out-of-band information (and that's baaaaaad!)

Here comes the interesting part: how can the client get this information?
Answer: through self-descriptive message and the media-type used !
That's how you make HATEOAS: you fully (not just with providing links!) drive the client with links and self-descriptive message.

Depending on your application, you may have to define your own media type that will accurately describe your message.
Some other exist,s they are called "hypermedia format". HAL is one of them but has some limitations.
An outdated comparison can be found here: https://github.com/kevinswiber/siren/issues/15

Personally, I suggest you take a look at Hydra, that would probably be a W3C standard and has a lot of features. For example, you can define what operations are possible on a link (= which verbs to use, which data to pass as parameter, if it required or not, etc...).
Some nice presentations can be found there: http://www.hydra-cg.com/

To conclude: I would say that HATEOAS is related to machine readable. By self-describing the message you give the ability to any machine to understand your API. Because human readable could involve out of band knowledge and that's typically what is not RESTful (nor HATEOAS compliant).


问:
What is the value of checking in failing unit tests?
While there are ways of keeping unit tests from being executed, what is the value of checking in failing unit tests?

I will use a simple example: Case Sensitivity. The current code is case sensitive. A valid input into the method is "Cat" and it would return an enum of Animal.Cat. However, the desired functionality of the method should not be case sensitive. So if the method described was passed "cat" it could possibly return something like Animal.Null instead of Animal.Cat and the unit test would fail. Though a simple code change would make this work, a more complex issue may take weeks to fix, but identifying the bug with a unit test could be a less complex task.

The application currently being analyzed has 4 years of code that "works". However, recent discussions regarding unit tests have found flaws in the code. Some just need explicit implementation documentation (ex. case sensitive or not), or code that does not execute the bug based on how it is currently called. But unit tests can be created executing specific scenarios that will cause the bug to be seen and are valid inputs.

What is the value of checking in unit tests that exercise the bug until someone can get around to fixing the code?

Should this unit test be flagged with ignore, priority, category etc, to determine whether a build was successful based on tests executed? Eventually the unit test should be created to execute the code once someone fixes it.

On one hand it shows that identified bugs have not been fixed. On the other, there could be hundreds of failed unit tests showing up in the logs and weeding through the ones that should fail vs. failures due to a code check-in would be difficult to find.

答: How I see TDD done with implementing tests for an unfinished code is, write tests first with [ExpectedException] attribute or similar. This should pass initially as the incomplete code would not have any logic in it and write a throw new Exception() code in it. Though throughing exception is wrong, this would atleast make the tests pass initially and fit for checkin. We may forget an ignored test but may definitely tidy up or fill the incomplete code. When we do so, automatically the corresponding test that was expecting an excpetion would now start failing and alarm you to fix it. This may involve a slight alteration of test to get rid of ExpectException and instead do real asserts. CI, Dev, testers and customers all happy and a win-win situation?</p>


问:
How can you easily unit test deserialization to different versions of an object?
I am using the protobuf-net library for serialization/deserialization of messages.

Due to the distributed nature of the application some applications will have an older version of the object that is being used to serialize messages. The cases I'm concerned with are

adding new fields to the message object that some consumers(deserializers) won't have

removing fields in the message object that some consumers(deserializers) will still have.

Example an old app has this definition of Foo

```<code>class Foo
{
   public int Field1 {get; set;}
}
</code>```

A newer app has this definition of Foo

```<code>class Foo
{
   public int Field1 {get; set;}
   public int Field2 {get; set;}
}
</code>```

I want to have a test to verify that the library can deserialize an object with missing fields and fields that it isn't aware of in case I ever need to change my serialization library.

Is there an easy way to unit test this?  C# won't let the user change the fields availabe in an object.

Currently I have to build my reciever app and then change the object that is transported to add a new field and then build my sending app to test this.

Is there a better way?

答: Your deserialization test should take a String as its input, and try to produce a present-day object from it. Therefore, all you have to do is revert a copy of your project to an earlier state, save a serialized String, return to the head, and put that string into your test data. Unless I misunderstand your question, you never need to have different versions of the same class actually compiled in your code base.</p>


问:
What is the equivalent of The Little Lisper project in Haskell?
In the book The Little Lisper, you implement a minimal Scheme in 10 Chapters that is capable of interpreting any chapter in the book.

To me it seems you could do the same for a 'minimal subset of a typed language' to be self-bootstrapping. I'm trying to work out what is feasible.

To me the options are:

Simply Typed Lambda Calculus

System F

Miranda

Haskell subset

Assumptions:

Note that I'm ignoring the GHC runtime elements like spineless tagless graph-interpreter

My question is: What is the equivalent of the Little Lisper project in Haskell?

答:
There is a article "Typing Haskell With Haskell*". It presents the most problematic part of the question - making the type checker/inferrer for the Haskell language (all code included). As far as I can tell, this makes 1-rank polymorphic language.

For 2+-rank poly you could google for "Boxy Types" (however, there is no code like in THIH, but only hellish type math in form of "modus ponens").


问:
Best way to get push notifications to server from MS SQL Server
I partially found a solution to my question, but I'm not really satisfied with the result.

My application consists of ASP.NET MVC + MS SQL Server.

The case is as follows:

An external application saves data periodically to the SQL Database. In one tenth of a second, 20 to 100 records can be saved.

SQL should be polled from the back-end, or there should be push notifications after each save, in order to update (for example) a running total of saved items.

The back-end will push notifications to the UI (this will be done using SignalR)

I followed this tutorial http://venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/ to set it up.

SqlDependency with broker service is used to get push notifications from SQL firing the OnChange Event. The problem is that this solution is very slow. There is only one record saved every second for a small database, and the events fire with pretty big delays.

Is there another technology to get data changes from SQL? Or maybe the solution I'm using requires some kind of optimization?

答:
You're trying to fix a conceptual problem with a technological one, in that you need to know when the database has been written to in order to update your program, and you're depending on this SqlDependency to achieve that.  Don't get me wrong, SqlDependency is an excellent fit in some circumstances no doubt, but almost certainly in no such circumstance would it work well when mass inserts are being performed on the server.

Either the library has a feature that disables triggering the event after the first (or even better, after the last with some small delay), or you're going to have a solution that doesn't scale well.

I offer an alternative solution:  When your backend task begins writing, when it finishes writing, and for every second while writing, it updates a record indicating that the database has been written to by that task.

Your application polls the database for that value every so often (say every 5 seconds), and if it has the indicator that it has been written to, you perform an update and you reset the flag.  The next check performed happens only one second after the last in this case, and so in the case of database changes, it will update more frequently.

If you need to be more accurate with your checks, you may check more frequently as desired.  What is important is that your program only performs checks and updates only as fast as you need, and not for every single record added.  This means that when 100 records are added, you're not having to update your program data 100 times. If it indeed takes 0.1 seconds per 20-100 records, then you'll likely be updating 100 records at most 5 times.


问:
How do you deal with changing requirements?
In my current job it feels like we have a lot requirement changes. We are an "Agile" shop, so I get that we are supposed to adjust and what not, but sometime the change is large and nothing trivial.

My question is, how do you effectively communicate the cost of the change? Because of being agile, if a change is big enough something will get dropped from the current sprint, but it usually just get added next time around. Since our model is SaaS, the end customer is effectively the business itself, and they know they will get the cut feature n weeks later.

I guess what I am trying to get at is the removal of a feature really isn't anything to use for communication as it was only delayed by n weeks. What other ways do you have to get the business to understand what a change costs?

答:
This is a very common problem, no matter how fast a project is advancing on technical terms the client perceives it as going much much slower and feels free to change requirements as they like thinking that the developers must not be doing much anyway.

This flawed perception comes from three major development tasks that consume time and will never be accounted for properly by clients:

Code reviews / clean-up: Old code gets bloated and messed up and needs regular reviews and clean-ups, this takes a lot of time and the client will never believe it.

Security audit and fixes: Especially if you have junior team members you will have a lot of code related security problems and you will want to go regularly through all that new code that has been written and rewrite stuff that doesn't look good from a security perspective, the client will never know or account for this time.

Architecture related changes: A growing code base may (and most likely will) at multiple points require structural rethinking and refactoring this may involve:
A - Performance-related changes/optimizations (Algorithm changes, library replacements, cache engines, ... etc) or:
B - Productivity-related changes/optimizations (readability, code-reusability, ease of understanding, new coding conventions, a new framework, ... etc).

None of the above will ever be understood and properly accounted for by end clients.

Basically whatever has no "views" (GUI elements) has not been done.

Let's call this the projenix theorem, haha no just kidding :D


问:
Development workflow for a team: local to live (with GIT)
We're trying to put together a workflow for Wordpress development which turns out to be pretty complicated with lots of elements. Is there a way to streamline this or filling in the gaps?

We currently have 2 developers in the team - but essentially this can be however many, all working in the same way.

The problems

WP Stagecoach seems the only way to allow us to merge a database rather than just copying over one. Does anyone know any other methods?

We work on a lot of sites that need the live version to continue to run (and the data get updated)... whilst developing new features (therefore both versions are adding to the posts table in the database). This brings up the problem of losing data, copying over some etc etc.

The problem Wp Stagecoach has is that we can create a staging site, make the changes there, then merge back with the live site - that part works great. But we want to be able to work locally rather than on a staging site (which HAS to be on the Stagecoach servers).

So the real question is, how can we work on a site locally, and get it live without copying over live data (i.e merging with it)? Doing the files is straightforward, it's the database that causes the problem.

答:
I've never worked with wordpress, but I did work on several web applications that had a database, and the usual way to make the database play nice with source control is to use a Schema Migration Framework.

The idea is that each developer has a personal development database installed on their own machine(or on a personal server or however you want to work - but it's usually on their own machine because you don't need a powerful server for the personal development database). During development, instead of modifying the database schema(and the constant data) directly, you write migration scripts that perform these modifications. These scripts can be checked in to source control, and the migration framework takes care of running the needed scripts in the correct order.

For example, instead of adding a column to a table via the database's administration GUI, Rob with write a migration script that'll do that, and use the migration tool to run that script and add the column. Rob will commit that script into the codebase, and when Matt pulls Rob's changes, he'll also pull that script. Matt will then run the migration tool, which will recognize that the new script has not been yet run on Matt's personal development database - and run it.

When you want to deploy a new version, simply use the migration tool to run all the scripts added in these version on the database in stagecoach's staging area.


问:
Which events to store with event-sourcing?
I'm planning out the events that my application will be creating, but am running into problems with my design.  I believe I'm not applying the event-sourcing concepts correctly.

Take the bank account example.  My application receives a command to deposit cash, accepts it, and then creates the event CashDeposited.  Based on the business logic, the higher account balance triggers the interest rate to be increased, so I create the event InterestRateChanged.

Now if I record both of these events to my event store, upon restart, both events will be replayed.  But because the CashDeposited event triggers the InterestRateChanged event, won't the InterestRateChanged be replayed twice: once from the event store and once as a result of CashDeposited being replayed?

答:
My application receives a command to deposit cash, accepts it, and then creates the event CashDeposited. Based on the business logic, the higher account balance triggers the interest rate to be increased, so I create the event InterestRateChanged.

Now if I record both of these events to my event store, upon restart, both events will be replayed.

Good.  That's exactly what you want.

But because the CashDeposited event triggers the InterestRateChanged event, won't the InterestRateChanged be replayed twice: once from the event store and once as a result of CashDeposited being replayed?

Yeah, if you are having this problem, your business logic may be in the wrong place.

Very broadly: the event handler part of your entity is supposed to be simple; apply the state changes implied by the event, validate the business invariant, and nothing else.

The events themselves are typically created by running a command on your entity -- it's the command that has the business logic to say "increase the balance, and then if the trigger fires then change the interest rate".  In your specific example, that one command will generate two events (perfectly reasonable).

When you reload the entity, you are going to replay the events, but not the command(s) that produced them.  So the replay includes all the changes to state, but you don't replay the business logic.


问:
How to handle duplicate events when replaying event store?
If two aggregates are listening to the same event; then the event will be stored in an event store twice, once for each aggregate.

```<code>class ItemLoaded implements Event {
    LocationId location;
    VehicleId vehicle;
    Amount amount;
    Date loadDate;
}

class Location implements Aggregate {
    Amount itemAmount;

    void updateFrom(ItemLoaded event) {
        this.itemAmount.subtract(event.amount);
    }
}

class Vehicle implements Aggregate {
    Amount itemAmount;

    void updateFrom(ItemLoaded event) {
        this.itemAmount.add(event.amount);
    }
}
</code>```

For instance there will be entries of the ItemLoaded event in the store once for Location and once for Vehicle, in the above case.

This much is expected, as can be seen from the two toy examples below, which you might have already seen if you've been reading about event sourcing:

In one example:

```<code>_current = new Dictionary<Guid, List<EventDescriptor>>();
</code>```

In another example:

```<code>CREATE TABLE EventWrappers(
EventId uniqueidentifier NOT NULL,
StreamId nvarchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
Sequence bigint NOT NULL,
TimeStamp datetime NOT NULL,
EventType nvarchar(100) COLLATE Latin1_General_CI_AS NOT NULL,
Body nvarchar](max) COLLATE Latin1_General_CI_AS NOT NULL,
</code>```

Production systems aren't probably that different. In axon framework event are stored in a table like below, if you choose JPA or JDBC implementation of event store :

```<code>create table DomainEventEntry (
    -- .....
    primary key (aggregateIdentifier, sequenceNumber, type)
);
</code>```

type field above is a string used to differentiate different aggregate types.

Given that events apparently maybe persisted multiple times, if I want to recreate a view from scratch, or add a new view model, how would I replay the events.

If we return to the above example, consider a view model like this:

```<code>class ItemsLoadedByYearProjection {
    @Subscribe
    void update(ItemLoaded event) {
        ItemsLoadedByYear row = getRowForYear(event.loadDate.year);
        row.itemAmount.add(itemAmount);
    }
}

class ItemsLoadedByYear {
    int year;
    Amount itemAmount;
}
</code>```

Not only will the amounts will be counted twice now, if I replay the events naively; if I add a new aggregate in the future, some events will be counted twice, where others will be counted three times.

How do I prevent a projection/denormalizer from double counting the events that was saved to the event store multiple times?

答:
If two aggregates are listening to the same event; then the event will be stored in an event store twice, once for each aggregate.

I would spell that differently.  If two aggregates are listening to the same event, then representations of that event will appear in the history of each.

They won't be storing the same event, and the event that they store won't be the event that they are reacting to.

The aggregates will be storing events describing the changes to their own state, not the changes to state elsewhere in the domain that they are reacting to.

When you get that right, recreating the aggregates is easy - each aggregate loads its own history.  There's no "double counting" to worry about, because each event in the history represents a change to an aggregate, so they are all different things.


问:
How to design a complex REST API considering DB performance?
I've been following some tutorials on how to design REST APIs, but I still have some big questions marks. All these tutorials show resources with relatively simple hierarchies, and I would like to know how the principles used in those apply to a more complex one. Furthermore, they stay at a very high/architectural level. They barely show any relevant code, let alone the persistence layer. I'm specially concerned about database load/performance, as Gavin King said:

you will save yourself effort if you pay attention to the database at
  all stages of development

Let's say my application will provide training for Companies. Companies have Departments and Offices. Departments have Employees. Employees have Skills and Courses, and certain Level of certain skills are required to be able to sign for some courses. The hierarchy is as as follows, but with :

-Companies
  -Departments
    -Employees
      -PersonalInformation
        -Address
      -Skills (quasi-static data)
        -Levels (quasi-static data)
      -Courses
        -Address
  -Offices
    -Address
```

<p>Paths would be something as:</p>

<pre class="lang-none prettyprint-override"><code>companies/1/departments/1/employees/1/courses/1
companies/1/offices/1/employees/1/courses/1
</code>```

Fetching a resource

So ok, when returning a company, I obviously don't return the whole hierarchy companies/1/departments/1/employees/1/courses/1 + companies/1/offices/../. I might return a list of links to the departments or the expanded departments, and have to take the same decission at this level: do I return a list of links to the department's employees or the expanded employees? That will depend on the number of departments, employees, etc.

Question 1: Is my thinking correct, is "where to cut the hierarchy" a typical engineering decission I need to make?

Now let's say that when asked GET companies/id, I decide to return a list of links to the department collection, and the expanded office information. My companies don't have many offices, so joining with the tables Offices and Addresses shouldn't be a big deal. Example of response:

GET /companies/1

200 OK
{
  "_links":{
    "self" : {
      "href":"http://trainingprovider.com:8080/companies/1"
      },
      "offices": [
            { "href": "http://trainingprovider.com:8080/companies/1/offices/1"},
            { "href": "http://trainingprovider.com:8080/companies/1/offices/2"},
            { "href": "http://trainingprovider.com:8080/companies/1/offices/3"}
      ],
      "departments": [
            { "href": "http://trainingprovider.com:8080/companies/1/departments/1"},
            { "href": "http://trainingprovider.com:8080/companies/1/departments/2"},
            { "href": "http://trainingprovider.com:8080/companies/1/departments/3"}
      ]
  }
  "name":"Acme",
  "industry":"Manufacturing",
  "description":"Some text here",
  "offices": {
    "_meta":{
      "href":"http://trainingprovider.com:8080/companies/1/offices"
      // expanded offices information here
    }
  }
}
```

<p>At the code level, this implies that (using Hibernate, I'm not sure how it is with other providers, but I guess that's pretty much the same) I won't put a collection of <code>Department</code> as a field in my <code>Company</code> class, because:</p>

<ul>
<li>As said, I'm not loading it with <code>Company</code>, so I don't want to load it eagerly</li>
<li>And if I don't load it eagerly, I might as well remove it, because the persistence context will close after I load a Company and there is no point in trying to load it afterwards (<code>LazyInitializationException</code>).</li>
</ul>

<p>Then, I'll put a <code>Integer companyId</code> in the <code>Department</code> class, so that I can add a department to a company.</p>

<p>Also, I need to get the ids of all the departments. Another hit to the DB but not a heavy one, so should be ok. The code could look like:</p>

```@Service
@Path("/companies")
public class CompanyResource {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyParser companyParser;

    @Path("/{id}")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response findById(@PathParam("id") Integer id) {
        Optional<Company> company = companyService.findById(id);
        if (!company.isPresent()) {
            throw new CompanyNotFoundException();
        }
        CompanyResponse companyResponse = companyParser.parse(company.get());
        // Creates a DTO with a similar structure to Company, and recursivelly builds
        // sub-resource DTOs such as OfficeDTO
        Set<Integer> departmentIds = companyService.getDepartmentIds(id);
        // "SELECT id FROM departments WHERE companyId = id"
        // add list of links to the response
        return Response.ok(companyResponse).build();
    }
}
```

```@Entity
@Table(name = "companies")
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private String industry;

    @OneToMany(fetch = EAGER, cascade = {ALL}, orphanRemoval = true)
    @JoinColumn(name = "companyId_fk", referencedColumnName = "id", nullable = false)
    private Set<Office> offices = new HashSet<>();

    // getters and setters
}
```

```@Entity
@Table(name = "departments")
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private Integer companyId;

    @OneToMany(fetch = EAGER, cascade = {ALL}, orphanRemoval = true)
    @JoinColumn(name = "departmentId", referencedColumnName = "id", nullable = false)
    private Set<Employee> employees = new HashSet<>();

    // getters and setters
}
```

Updating a resource

For the update operation, I can expose an endpoint with PUT or POST. Since I want my PUT to be idempotent, I can't allow partial updates. But then, if I want to modify the company's description field, I need to send the whole resource representation. That seems too bloated. The same when updating an employee's PersonalInformation. I don't think it makes sense having to send all the Skills + Courses together with that.

Question 2: Is PUT just used for fine-grained resources?

I've seen in the logs that, when merging an entity, Hibernate executes a bunch of SELECT queries. I guess that's just to check if anything has changed and update whatever information needed. The upper the entity in the hierarchy, the heavier and more complex the queries. But some sources advise to use coarse grained resources. So again, I'll need to check how many tables are too much, and find a compromise between resource granularity and DB query complexity.

Question 3: Is this just another "know where to cut" engineering decission or am I missing something?

Question 4: Is this, or if not, what is the right "thinking process" when designing a REST service and searching for a compromise between resource granularity, query complexity and network chattiness?

答:
For your Q1 on where to cut the engineering decisions, how about picking up the unique Id of an entity that would other way give you the required details on the backend? For example, "companies/1/department/1" will have an unique Identifier on its own (or we can have one to represent the same) to give you the hierarchy, you can use that.

For your Q3 on PUT with full bloated information, you can flag the fields which were updated and send that additional metadata information to the server for you to introspect and update those fields alone.


问:
How to deal with Classes having the same name (different packages)
Me and my R&D team maintain a large codebase. We've divided our business logic into multiple packages. some of which have classes with identical names.

As you can guess, the names conflict when both classes are referenced in the same Java file.

For example:

```<code>com.myapp.model (package)
 - Device (class)
 - ...

com.myapp.data (package)
 - Device (class)
 - ...
</code>```

We had a debate on what's the best practice to treat these cases and the following options came up:

1st Option

Renaming the class, adding a prefix

```<code>ModelDevice
DataDevice
</code>```

2nd Option

Using the full package+class name when both are referenced

```<code>com.myapp.model.Device
com.myapp.data.Device
</code>```

What's more correct in terms of code management and scalability?

we are currently mixing both approaches and starting to have inconsistency

答:
As of now you have one ModelDevice class (Device in the model package). What if you have another such ModelDevice for a different classification? The problem may still persist and the overheads will also continue to increase.

Though for the time being you may find that renaming classes be of some good help, for a long run the suggested alternate is to go by prefixing the package names, which is what the Industry Standard.


问:
Big O of loop of 0...n with nested loop doing k iterations
My coworkers and I are discussing this code and need a third party to settle our discussion :)

```<code>Random randNum = new Random();
int[] A = Enumerable.Repeat(0, 1000).Select(i => randNum.Next(0, 100)).ToArray();
int k = randNum.Next(0, A.Length);
int[] B = new int[A.Length - k];

for (int i = 0; i < B.Length; i++)
{
    int min = A[i];

    for (int j = i + 1; j <= i + k; j++)
    {
        min = Math.Min(A[j], min);
    }

    B[i] = min;
}
</code>```

What would this be considered in big O notation?

答:
Let's assume that you want Big-O in terms of the size of the array A (ie n = A.Length).

The size of B is A.Length-k, and k is some random number between 0 and the size of A.

Big-O is all about worst-case scenarios. I'll leave it as an exercise to the reader to prove the worst-case here is when k = A.Length / 2 = n / 2. In such a case, B.Length = A.Length - k = n / 2.

Then we have both loops doing n / 2 work, for a final answer of O(n^2)


答:
Question 1: Is my thinking correct, is "where to cut the hierarchy" a typical engineering decission I need to make?

Maybe - I'd be worried that you are going about it backwards, though.

So ok, when returning a company, I obviously don't return the whole hierarchy

I don't think that's obvious at all.  You should be returning representation(s) of company appropriate for the use cases you are supporting.  Why wouldn't you?  Does it really make sense that the api depends on the persistence component?  Isn't part of the point that the clients don't need to be exposed to that choice in the implementation?  Are you going to preserve a compromised api when you swap out one persistence component for another?

That said, if your use cases don't need the whole hierarchy, there's no need to return it.  In an ideal world, the api would produce representations of company that are perfectly suited to the immediate needs of the client.

Question 2: Is PUT just used for fine-grained resources?

Pretty much - communicating the idempotent nature of a change by implementing as a put is nice, but the HTTP specification allows agents to make assumptions about what is really happening.

Note this comment from RFC 7231

A PUT request applied to the target resource can have side effects on
other resources.

In other words, you can PUT a message (a "fine-grained resource") that describes a side effect to be executed on your primary resource (entity).  You need to take some care to ensure your implementation is idempotent.

Question 3: Is this just another "know where to cut" engineering decission or am I missing something?

Maybe.  It might be trying to tell you that your entities are not scoped correctly.

Question 4: Is this, or if not, what is the right "thinking process" when designing a REST service and searching for a compromise between resource granularity, query complexity and network chattiness?

This doesn't feel right to me, insofar as it seems you are trying to tightly couple your resource scheme to your entities, and are letting your choice of persistence drive your design, rather than the other way around.

HTTP is fundamentally a document application; if the entities in your domain are documents, then great - but the entities aren't documents, then you need to think.  See Jim Webber's talk: REST in Practice, particularly starting from 36m40s.

That's your "fine grained" resource approach.

Title: How to design a complex REST API considering DB performance?

Body:
I've been following some tutorials on how to design REST APIs, but I still have some big questions marks. All these tutorials show resources with relatively simple hierarchies, and I would like to know how the principles used in those apply to a more complex one. Furthermore, they stay at a very high/architectural level. They barely show any relevant code, let alone the persistence layer. I'm specially concerned about database load/performance, as Gavin King said:

you will save yourself effort if you pay attention to the database at
  all stages of development

Let's say my application will provide training for Companies. Companies have Departments and Offices. Departments have Employees. Employees have Skills and Courses, and certain Level of certain skills are required to be able to sign for some courses. The hierarchy is as as follows, but with :

-Companies
  -Departments
    -Employees
      -PersonalInformation
        -Address
      -Skills (quasi-static data)
        -Levels (quasi-static data)
      -Courses
        -Address
  -Offices
    -Address
```

<p>Paths would be something as:</p>

<pre class="lang-none prettyprint-override"><code>companies/1/departments/1/employees/1/courses/1
companies/1/offices/1/employees/1/courses/1
</code>```

Fetching a resource

So ok, when returning a company, I obviously don't return the whole hierarchy companies/1/departments/1/employees/1/courses/1 + companies/1/offices/../. I might return a list of links to the departments or the expanded departments, and have to take the same decission at this level: do I return a list of links to the department's employees or the expanded employees? That will depend on the number of departments, employees, etc.

Question 1: Is my thinking correct, is "where to cut the hierarchy" a typical engineering decission I need to make?

Now let's say that when asked GET companies/id, I decide to return a list of links to the department collection, and the expanded office information. My companies don't have many offices, so joining with the tables Offices and Addresses shouldn't be a big deal. Example of response:

GET /companies/1

200 OK
{
  "_links":{
    "self" : {
      "href":"http://trainingprovider.com:8080/companies/1"
      },
      "offices": [
            { "href": "http://trainingprovider.com:8080/companies/1/offices/1"},
            { "href": "http://trainingprovider.com:8080/companies/1/offices/2"},
            { "href": "http://trainingprovider.com:8080/companies/1/offices/3"}
      ],
      "departments": [
            { "href": "http://trainingprovider.com:8080/companies/1/departments/1"},
            { "href": "http://trainingprovider.com:8080/companies/1/departments/2"},
            { "href": "http://trainingprovider.com:8080/companies/1/departments/3"}
      ]
  }
  "name":"Acme",
  "industry":"Manufacturing",
  "description":"Some text here",
  "offices": {
    "_meta":{
      "href":"http://trainingprovider.com:8080/companies/1/offices"
      // expanded offices information here
    }
  }
}
```

<p>At the code level, this implies that (using Hibernate, I'm not sure how it is with other providers, but I guess that's pretty much the same) I won't put a collection of <code>Department</code> as a field in my <code>Company</code> class, because:</p>

<ul>
<li>As said, I'm not loading it with <code>Company</code>, so I don't want to load it eagerly</li>
<li>And if I don't load it eagerly, I might as well remove it, because the persistence context will close after I load a Company and there is no point in trying to load it afterwards (<code>LazyInitializationException</code>).</li>
</ul>

<p>Then, I'll put a <code>Integer companyId</code> in the <code>Department</code> class, so that I can add a department to a company.</p>

<p>Also, I need to get the ids of all the departments. Another hit to the DB but not a heavy one, so should be ok. The code could look like:</p>

```@Service
@Path("/companies")
public class CompanyResource {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyParser companyParser;

    @Path("/{id}")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response findById(@PathParam("id") Integer id) {
        Optional<Company> company = companyService.findById(id);
        if (!company.isPresent()) {
            throw new CompanyNotFoundException();
        }
        CompanyResponse companyResponse = companyParser.parse(company.get());
        // Creates a DTO with a similar structure to Company, and recursivelly builds
        // sub-resource DTOs such as OfficeDTO
        Set<Integer> departmentIds = companyService.getDepartmentIds(id);
        // "SELECT id FROM departments WHERE companyId = id"
        // add list of links to the response
        return Response.ok(companyResponse).build();
    }
}
```

```@Entity
@Table(name = "companies")
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private String industry;

    @OneToMany(fetch = EAGER, cascade = {ALL}, orphanRemoval = true)
    @JoinColumn(name = "companyId_fk", referencedColumnName = "id", nullable = false)
    private Set<Office> offices = new HashSet<>();

    // getters and setters
}
```

```@Entity
@Table(name = "departments")
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private Integer companyId;

    @OneToMany(fetch = EAGER, cascade = {ALL}, orphanRemoval = true)
    @JoinColumn(name = "departmentId", referencedColumnName = "id", nullable = false)
    private Set<Employee> employees = new HashSet<>();

    // getters and setters
}
```

Updating a resource

For the update operation, I can expose an endpoint with PUT or POST. Since I want my PUT to be idempotent, I can't allow partial updates. But then, if I want to modify the company's description field, I need to send the whole resource representation. That seems too bloated. The same when updating an employee's PersonalInformation. I don't think it makes sense having to send all the Skills + Courses together with that.

Question 2: Is PUT just used for fine-grained resources?

I've seen in the logs that, when merging an entity, Hibernate executes a bunch of SELECT queries. I guess that's just to check if anything has changed and update whatever information needed. The upper the entity in the hierarchy, the heavier and more complex the queries. But some sources advise to use coarse grained resources. So again, I'll need to check how many tables are too much, and find a compromise between resource granularity and DB query complexity.

Question 3: Is this just another "know where to cut" engineering decission or am I missing something?

Question 4: Is this, or if not, what is the right "thinking process" when designing a REST service and searching for a compromise between resource granularity, query complexity and network chattiness?


问:
How can I store incomplete records but enforce data correctness?
I'm in the planning/design stages of a new project, and I'm having trouble coming up with a good way to handle one of the requirements:

Users must be able to create a new record and save it as "Incomplete" without filling out all required fields.

This is a requirement that will apply to almost all user-editable record types in the application.

Records have a number of potential states, and in any state other than "Incomplete" they must have all required fields filled out.

It's straightforward enough, but I'm having trouble figuring out how to store it in a way that won't sacrifice the ability to enforce data correctness on "completed" records.

The simplest way to handle this requirement would be to make all the fields of the business object and its database table nullable, and then have strict validation checks run against records any time they are moved from the Incomplete state.  However, I dislike the idea of enforcing most of the data correctness requirements purely in application-level code rather than in the design of the database, so I'm trying to come up with some other option.

Maintaining a separate schema for incomplete records is an idea that's been discussed, but there's concerns that it will add too much overhead, since we now have a separate schema to extend every time something changes and we'll need to manage moving records from one to the other as they're completed.

Is there a best practice for this sort of problem?  Should we just bite the bullet and make all the fields nullable?

(The technology stack we're using is ASP.NET WebAPI on top of SQL Server 2014, but it seems pretty applicable to any stack backed by a relational database)

答:
You could have a separate table for works in progress. You would use more or less the same table scheme, just with each field set as nullable.

When a record is initially created, it goes into the incomplete records table (you could have a check to put first time completed records directly into your completed records table, of course). Once a record has been completed, you would copy it to your completed table and delete it from incomplete.

Of course, this would force you to join tables in the case that you did want to run queries over complete and incomplete records, but that's hardly the end of the world [Citation Needed]


问:
Should a client ever test server response at runtime?
I'm writing a client application that receives a JSON response from a server. In the past I've run into situations where a developer on the server side changes the JSON response in a way that causes the client application to crash. An example of this is when the client expects that a JSON field or subobject will always be present, but a change on the server side causes the JSON to deviate from what is expected possibly returning a null value when null should never be a possible response.

It seem like the server side could always have unit tests that ensure that the JSON response fulfills the contract, but that's susceptible to human error if a developer decides to rewrite a test or simply makes a mistake in testing or misunderstands a requirement. The client side can check that the JSON response is valid, but this would need to occur at runtime and if the server is writing proper tests, the double-checking of the server response by the client would be unnecessary.

Is there a recommended process to ensure that the contract (JSON response format) between the client and server doesn't get broken?

答:
Why on Earth wouldn't you? A good rule of thumb is to assume that all input is evil until proven otherwise. Blindly assuming that your input will be valid is a good way to wake up to empty databases and overflowing error logs. Just because that input is coming from a (presumably proficient) coworker's server doesn't mean it should get a free pass from you.

At the very least, you want a different error to be logged for Client and Server issues. If the owner of the server changes the response without notice, you want to be able to determine as quickly as possible the source of the error. Aside from covering yourself towards management, it helps to be able to tell at a glance the general area of a problem when your application stops working.


答:
Yes, you should validate what you get, but you also need to be a Tolerant Reader:

http://martinfowler.com/bliki/TolerantReader.html

Martin Fowler states that:

My recommendation is to be as tolerant as possible when reading data from a service. If you're consuming an XML file, then only take the elements you need, ignore anything you don't. Furthermore make the minimum assumptions about the structure of the XML you're consuming.

Which, to my experience is a good way to be resilient (tolerant) to changes. Also, if the change is too big to be tolerant, you should consider some strategy to versioning your API:

https://blog.pivotal.io/labs/labs/api-versioning

http://www.mashery.com/blog/ultimate-solution-versioning-rest-apis-content-negotiation

From a more practical point of view, you can also write some test/contracts to your API so that you can continuously check the contracts:

https://github.com/realestate-com-au/pact (see the links at the end of page)

https://github.com/thoughtworks/pacto

Title: Should a client ever test server response at runtime?

Body:
I'm writing a client application that receives a JSON response from a server. In the past I've run into situations where a developer on the server side changes the JSON response in a way that causes the client application to crash. An example of this is when the client expects that a JSON field or subobject will always be present, but a change on the server side causes the JSON to deviate from what is expected possibly returning a null value when null should never be a possible response.

It seem like the server side could always have unit tests that ensure that the JSON response fulfills the contract, but that's susceptible to human error if a developer decides to rewrite a test or simply makes a mistake in testing or misunderstands a requirement. The client side can check that the JSON response is valid, but this would need to occur at runtime and if the server is writing proper tests, the double-checking of the server response by the client would be unnecessary.

Is there a recommended process to ensure that the contract (JSON response format) between the client and server doesn't get broken?


问:
Specify optional parameter names even though not required?
Consider the following method:

```<code>public List<Guid> ReturnEmployeeIds(bool includeManagement = false)
{

}
</code>```

And the following call:

```<code>var ids = ReturnEmployeeIds(true);
</code>```

For a developer new to the system, it'd be pretty difficult guessing what true did. First thing you'd do is hover over the method name or go to the definition (neither of which are big tasks in the slightest). But, for readability sake, does it make sense to write:

```<code>var ids = ReturnEmployeeIds(includeManagement: true);
</code>```

Is there anywhere that, formally, discusses whether or not to explicitly specify optional parameters when the compiler doesn't need you to?

The following article discusses certain coding conventions: https://msdn.microsoft.com/en-gb/library/ff926074.aspx

Something similar to the article above would be great.

答:
Yes, I think it's good style.

This makes most sense for Boolean and integer constants.

If you're passing in a variable, the variable name should make the meaning clear. If it doesn't, you should give the variable a better name.

If you're passing in a string, the meaning is often clear. Like if I see a call to GetFooData("Oregon"), I think a reader can pretty much guess that the parameter is a state name.

Not all strings are obvious, of course. If I see GetFooData("M") then unless I know the function I have no idea what "M" means. If it's some kind of code, like M="management-level employees", then we probably should have an enum rather than a literal, and the enum name should be clear.

And I suppose a string could be misleading. Maybe "Oregon" in my example above refers, not to the state, but to a product or a client or whatever.

But GetFooData(true) or GetFooData(42) ... that could mean anything. Named parameters are a wonderful way to make it self-documenting. I've used them for exactly that purpose on a number of occasions.


答:
The requirement is self-contradictory: the required fields must all be optional. But okay, let's laugh at the person who wrote the spec and then move on.

I think creating two tables is a very bad idea. This would mean that all the field definitions must be duplicated. It's likely that many queries would have to be duplicated -- your basic insert at a minimum. So any time there's a change to the schema, you have to be careful to make it in both places. Sooner or later somebody's going to forget, or you'll have a programmer working on it who doesn't know about the two tables, and then if you're lucky it blows up in testing and not in production. If you have processes that apply to both complete and incomplete records, now you have to do UNIONs, which if the query is simple may not be a big deal but if the query is complex would add another layer of complexity and create potential for error. You may have to worry about duplicates between the complete table and the incomplete table. Etc. All around, sounds like a giant pain.

If the validation for a complete record is simply "not null", then okay, doing it in one table forces you to write some extra code. This doesn't sound like all that big a deal to me. You could easily throw in an add/update trigger that says that if complete=true and (name is null or foo is null or bar is null), throw an error.

I'd think you need this validation in the code anyway. You likely have some sort of data entry screen where the user has to type all this in. I'd think you'd want to give an error message like "Error: Last name cannot be blank" or something of that sort. You don't just rely on a SQL exception to tell you that data is invalid, do you? Sure, when a field is really required, I'll put a not-null constraint in the DB as an extra guarantee against bad data. But the code should be checking it before writing a record anyway, so if the field is really only conditionally required, I put that test in code.

Title: How can I store incomplete records but enforce data correctness?

Body:
I'm in the planning/design stages of a new project, and I'm having trouble coming up with a good way to handle one of the requirements:

Users must be able to create a new record and save it as "Incomplete" without filling out all required fields.

This is a requirement that will apply to almost all user-editable record types in the application.

Records have a number of potential states, and in any state other than "Incomplete" they must have all required fields filled out.

It's straightforward enough, but I'm having trouble figuring out how to store it in a way that won't sacrifice the ability to enforce data correctness on "completed" records.

The simplest way to handle this requirement would be to make all the fields of the business object and its database table nullable, and then have strict validation checks run against records any time they are moved from the Incomplete state.  However, I dislike the idea of enforcing most of the data correctness requirements purely in application-level code rather than in the design of the database, so I'm trying to come up with some other option.

Maintaining a separate schema for incomplete records is an idea that's been discussed, but there's concerns that it will add too much overhead, since we now have a separate schema to extend every time something changes and we'll need to manage moving records from one to the other as they're completed.

Is there a best practice for this sort of problem?  Should we just bite the bullet and make all the fields nullable?

(The technology stack we're using is ASP.NET WebAPI on top of SQL Server 2014, but it seems pretty applicable to any stack backed by a relational database)


问:
How can you catch all index out of range errors in python?
Our program does these kinds of operations hundreds of times for many different variables and lists, then uses them throughout the program:

```<code>variable = values[5]
</code>```

The list values are coming from the command line, often as words, paragraphs, rows of a table or other (it's not important). Our issue is that our program, which is designed to run in a continuous loop, stops when there is an index out of range error. Since this comes from the command line, we can expect these fairly often, but cannot accept our program stopping.

Thus, the question is: How can I catch all index out of range errors in python so that my program does not stop. Do I have to use try/except statements everywhere I make the above type statements (which is a lot of extra work for 40k lines of code) or can I do a catch all somehow? How the error is handled is important (I expect 99% of the time we can set it to NULL, ERROR or 0), but keeping the loop running is even more important.

答:
There is no global solution that just sets the problem variable to NULL and continuous on with normal program flow. This appears to be the only way:

```<code>try:
   variable=values[5]
except:
   variable='error'
</code>```

You'll have to change the original one liner to a 4 liner everywhere you use a list variable. It is the most appropriate way since it allows specific response for different variables, but it is a shame that your 10,000 line program is probably going to end up being 30,000 lines just to deal with an index out of range error. Furthermore, you cannot really use referenced lists in equations do to the lack of global error handling in python, which will bulk it up even more. For example:

```<code>string_var = "first name: " + values[5] + "last name: " + values[6]
</code>```

Will not work for your program since you are not 110% certain what your lists will contain (only 99% certain). You'll have to rewrite this using multiple discrete exception handling for each list item, or one exception that has if statements for each discrete list item.

Body:
There is no global solution that just sets the problem variable to NULL and continuous on with normal program flow. This appears to be the only way:

try:
   variable=values[5]
except:
   variable='error'

You'll have to change the original one liner to a 4 liner everywhere you use a list variable. It is the most appropriate way since it allows specific response for different variables, but it is a shame that your 10,000 line program is probably going to end up being 30,000 lines just to deal with an index out of range error. Furthermore, you cannot really use referenced lists in equations do to the lack of global error handling in python, which will bulk it up even more. For example:

string_var = "first name: " + values[5] + "last name: " + values[6]

Will not work for your program since you are not 110% certain what your lists will contain (only 99% certain). You'll have to rewrite this using multiple discrete exception handling for each list item, or one exception that has if statements for each discrete list item.


问:
A way to update a list an Android application displays
I just started working on an Android app that should display posts from my site and then a three-column list of some products. The three columns on the list contain the product names, a short description, and then some pricing information. The pricing info should always be up to date.

I am not experienced, but I am thinking of two approaches:

Allowing the app to interact with an online database in order to get the most current data. However, this approach means I will also need another web app to manage the database, which seems complicated to me.

Hosting an up-to date CSV or XML file in a certain URL. Then, each time the app synchronizes, it gets the file and process it. However, this seems to be a waste of bandwidth.

My questions are:

Of the two options, which one is viable/appropriate? And why.

Is there any other efficient way to handle this?

答:
I have the same problem, and i realize that. When we create adapter and set it to listview, listview will point to object somewhere in memory which adapter hold, data in this object will show in listview.

```<code>adapter = new CustomAdapter(data);
listview.setadapter(adapter);
</code>```

if we create an object for adapter with another data again and   notifydatasetchanged():

```<code>adapter = new CustomAdapter(anotherdata);
adapter.notifyDataSetChanged();
</code>```

this will do not affect to data in listview because the list is pointing to different object, this object does not know anything about new object in adapter, and notifyDataSetChanged() affect nothing. So we should change data in object and avoid to create a new object again for adapter

Body:
I have the same problem, and i realize that. When we create adapter and set it to listview, listview will point to object somewhere in memory which adapter hold, data in this object will show in listview.

adapter = new CustomAdapter(data);
listview.setadapter(adapter);

if we create an object for adapter with another data again and   notifydatasetchanged():

adapter = new CustomAdapter(anotherdata);
adapter.notifyDataSetChanged();

this will do not affect to data in listview because the list is pointing to different object, this object does not know anything about new object in adapter, and notifyDataSetChanged() affect nothing. So we should change data in object and avoid to create a new object again for adapter


问:
If a number is too big does it spill over to the next memory location?
I've been reviewing C programming and there are just a couple things bothering me.

Let's take this code for example:

```<code>int myArray[5] = {1, 2, 2147483648, 4, 5};
int* ptr = myArray;
int i;
for(i=0; i<5; i++, ptr++)
    printf("\n Element %d holds %d at address %p", i, myArray[i], ptr);
</code>```

I know that an int can hold a maximum value of positive 2,147,483,647. So by going one over that, does it "spill over" to the next memory address which causes element 2 to appear as "-2147483648" at that address? But then that doesn't really make sense because in the output it still says that the next address holds the value 4, then 5. If the number had spilled over to the next address then wouldn't that change the value stored at that address?

I vaguely remember from programming in MIPS Assembly and watching the addresses change values during the program step by step that values assigned to those addresses would change.

Unless I am remembering incorrectly then here is another question: If the number assigned to a specific address is bigger than the type (like in myArray[2]) then does it not affect the values stored at the subsequent address?

Example: We have int myNum = 4 billion at address 0x10010000. Of course myNum can't store 4 billion so it appears as some negative number at that address. Despite not being able to store this large number, it has no effect on the value stored at the subsequent address of 0x10010004. Correct?

The memory addresses just have enough space to hold certain sizes of numbers/characters, and if the size goes over the limit then it will be represented differently (like trying to store 4 billion into the int but it will appear as a negative number) and so it has no effect on the numbers/characters stored at the next address.

Sorry if I went overboard. I've been having a major brain fart all day from this.

答:
No, it does not.  In C, variables have a fixed set of memory addresses to work with.  If you are working on a system with 4-byte ints, and you set an int variable to 2,147,483,647 and then add 1, the variable will usually contain -2147483648.  (On most systems.  The behavior is actually undefined.)  No other memory locations will be modified.

In essence, the compiler will not let you assign a value that is too big for the type.  This will generate a compiler error.  If you force it to with a case, the value will be truncated.

Looked at in a bitwise way, if the type can only store 8 bits, and you try to force the value 1010101010101 into it with a case, you will end up with the bottom 8 bits, or 01010101.

In your example, regardless of what you do to myArray[2], myArray[3] will contain '4'.  There is no "spill over".  You are trying to put something that is more than 4-bytes it will just lop off everything on the high end, leaving the bottom 4 bytes.  On most systems, this will result in -2147483648.

From a practical standpoint, you want to just make sure this never, ever happens.  These sorts of overflows often result in hard-to-solve defects.  In other words, if you think there is any chance at all your values will be in the billions, don't use int.


问:
Can sequence alignment algorithms be used for search implementation?
Hi I want to implement a search on a website which includes imperfect search results. Meaning, if the search term is misspelled or slightly different from a 100% match, the function should still return results which are sorted by similarity in terms of the search keyword.

I already have implemented algorithms like Smith-Waterman and Needleman-Wunsch which also can be used for database searching. So my idea was to run those algorithms against every keyword in the database and sort them by the score of each result.

Is this a good idea? I am using ASP.NET in C#. Are there any tools or tricks which can accomplish this for me without using my own methods? My biggest concern is performance, after all those algorithms create at least one two dimensional matrix, calculate its values and perform a traceback.

Any suggestions?

答: You could do that. But as mentioned by Robert in the comments you could avoid a lot of trouble by using a library, such as Lucene. In your case (.NET) you should pick the Lucene.net port.</p>


问:
Foundations of computation, and relation to modern computers
I want to understand how the theoretical foundations of computation relate to real-world computers. As far as my knowledge goes, Turing machines, recursive functions, finite state machines, lambda calculus, combinatoric logic, and other models are all theoretically equivalent in how they represent computation. To me, these models seem to underlie what computation really is, at the most basic level.

Thus, my primary question is, how do these purely theoretical models of computation relate to real-world computer architecture? How do we go from these theoretical models to a real-world tool, which makes use of electrical engineering and physics, aspects which are not taken into account in the models of computation? For example, is the real-world computer an advanced physical embodiment of the Turing machine, or is this completely off the mark?

EDIT: My question is different than simply asking how computers work. I am specifically asking about the relationship between practical, real-life computers and models of computation.

答:
how do these purely theoretical models of computation relate to real-world computer architecture?

They don't.

Both λ-calculus and Turing Machines were designed to model the way a human computes. They weren't designed to model computing machines.

This is most obvious in the Turing Machine, which was heavily modeled after the way a "computer" (which during Alan Turing's time was a job description for a human!) worked: by keeping a limited amount of information in his head and writing down the rest on a sheet of paper. Turing made the amount of information arbitrarily large (but finite), and allowed for infinite amounts of paper (and he cut the sheets in stripes and glued them together to get a simplified one-dimensional tape), however, even allowing for inhuman amounts of information and physically impossible infinite tapes, he could prove that there are certain things that cannot be computed.

λ-calculus similarly developed out of a desire to formalize what computation means, in this case instead of starting from the very physical act of how a human writes down computations on paper, it is more based on an intuition of how one would evaluate a function in one's head.

Turing proved that a Universal Turing Machine can exist, i.e. a Turing Machine which can read the description of an arbitrary Turing Machine from tape and perform that Turing Machine's operations. This can be considered to be the very first interpreter, and the very first stored-program computer.

However, people who were actually involved in developing the first digital computers claim that the work of the logicians on models of computation had little influence on the work of the electrical engineers and applied mathematicians building the first digital computers, despite the striking resemblance.

There are models of computation that are much closer to what current mainstream computers look like. The Random Access Machine, for example, is a cost model for algorithm analysis that more closely models how memory is accessed in a typical computer, namely with constant-time random access, as opposed to a Turing Machine, where access time is linear in the distance from your current memory location to the one you want to access (you have to move the head across the tape one cell at a time).

Note that you use the term "real-world computer architecture" as if there was only one. There are in fact many different architectures. For example, the Reduceron is a graph-reduction CPU specifically designed for Haskell-like languages, it works very differently from, say, a typical x86 CPU. There are architectures which explicitly model the communication costs on the chip, such as the FLEET architecture. The Harvard Architecture strictly separates code and data as opposed to the von Neumann Architecture, which doesn't distinguish between them. And so on.


答:
One possibility, not yet mentioned, is that you don't stick an incomplete record in the database at all - you just hold it as a blob (serialized by some means) somewhere (could be in the database, could be elsewhere).

It rather depends on what, if anything, is done with incomplete records (this is about workflow and related). Specifically if 90% of the code loads data with variations of '''WHERE NOT status = incomplete''' then basically incomplete records are just noise. If, on the other hand, value starts to accrue even though the record is incomplete then this is not necessarily a good solution.

Either way simply asking the question may aid better understanding


问:
Functional programming, and pushing item to array
I'm studying functional programming and I'm having some question concerning array population.

Actually, I'm trying to rebuild the Array.prototype.map function, and here's what I've got:

```<code>Array.prototype.map = function(callback) {
  let newArray = [];
  for (let item of this) {
    newArray.push(callback(item));
  }
  return newArray;
};
</code>```

It's working, bug I'm having some trouble with the fact that I'm allocation memory on each iteration, meaning that I'm breaking functional principles (no references, only new things).

Is that true when dealing with arrays?
I mean there, is it correct to loop and assign in to a new array?

答:
The code you have there is about as far from functional as could possibly be. The entire function is built around a side-effecting loop which mutates a value.

Here's the trivial functional implementation of a map operation:

```<code>Array.prototype.map = function (fn) {
  const [first, ...rest] = this;
  return this.length === 0 ? [] : [fn(first)].concat(rest.map(fn));
};
</code>```

This will, however, blow the stack for a sufficiently large array. To avoid that, we need to make the function tail-recursive. In the version above, the tail-call is to the concat method. That call will be optimized away, but that doesn't help us much: we want the recursive call to map to be the tail-call, so that it gets optimized away.

The standard trick to make a function tail-recursive is to introduce an accumulator that gets passed along and then reverse the result.

```<code>Array.prototype.map = function (fn) {
  const mapTailrec = (ary, acc) =>
    ary.length === 0 ?
      acc :
      mapTailrec(ary.slice(0, -1), acc.concat([fn(ary[ary.length-1])]));
  return mapTailrec(this, []).reverse();
};
</code>```

[Note: I'm actually cheating here, because Array.prototype.reverse is unfortunately not referentially transparent. It is however, pretty simple to write a tail-recursive referentially-transparent reverse, so I'll let that slide.]

As it turns out, fold is a general method of iteration: everything that can be done with loops can be done with folds, and so every collection operation is actually just a special case of fold:

```<code>Array.prototype.map = function (fn) {
  return this.reduce([], (acc, el) => acc.concat([fn(el)]));
};
</code>```

Body:
The code you have there is about as far from functional as could possibly be. The entire function is built around a side-effecting loop which mutates a value.

Here's the trivial functional implementation of a map operation:

Array.prototype.map = function (fn) {
  const [first, ...rest] = this;
  return this.length === 0 ? [] : [fn(first)].concat(rest.map(fn));
};

This will, however, blow the stack for a sufficiently large array. To avoid that, we need to make the function tail-recursive. In the version above, the tail-call is to the concat method. That call will be optimized away, but that doesn't help us much: we want the recursive call to map to be the tail-call, so that it gets optimized away.

The standard trick to make a function tail-recursive is to introduce an accumulator that gets passed along and then reverse the result.

Array.prototype.map = function (fn) {
  const mapTailrec = (ary, acc) =>
    ary.length === 0 ?
      acc :
      mapTailrec(ary.slice(0, -1), acc.concat([fn(ary[ary.length-1])]));
  return mapTailrec(this, []).reverse();
};

[Note: I'm actually cheating here, because Array.prototype.reverse is unfortunately not referentially transparent. It is however, pretty simple to write a tail-recursive referentially-transparent reverse, so I'll let that slide.]

As it turns out, fold is a general method of iteration: everything that can be done with loops can be done with folds, and so every collection operation is actually just a special case of fold:

Array.prototype.map = function (fn) {
  return this.reduce([], (acc, el) => acc.concat([fn(el)]));
};


问:
Javascript Closures to Separate Class
PROBLEM: In Javascript I use closures to encapsulated methods inside a class. It helps building hierarchy inside and minimize amount of methods at root, but they become lengthy.

RESEARCH: Applied to library classes or GUI frameworks classes (prototype-based inside).

QUESTION: Should I consider refactoring each root method into a separate class or keep them all thematically composed? Is the same applicable to other languages (Java)?

答:
It sounds like you've discovered that you can use javascript closures to create classes.  Doing this you can treat javascript as an object oriented language.  But is this wise?

Look at java 8.  Java is desperately trying to be more functional.  It was originally intended to be an object oriented language.

Which you should lean towards, OO or functional, depends on how you expect your application to change.  OO reacts well to the addition of new data types, that is new classes.  It doesn't do so well when you wish to add new methods.  Functional programming is the opposite.  Adding new methods is easy, but adding new data types/structures can be very hard.

Javascript is powerful enough to let you develop either way.  If you choose to go completely OO using closures you're predicting that most change will be about new data types.

Title: Javascript Closures to Separate Class


答:
Signed integer overflow is undefined behavior.  If this happens your program is invalid.  The compiler is not required to check this for you, so it may generate an executable that appears to do something reasonable, but there is no guarantee that it will.

However, unsigned integer overflow is well-defined.  It will wrap modulo UINT_MAX+1.  The memory not occupied by your variable will not be affected.

See also https://stackoverflow.com/q/18195715/951890

Title: If a number is too big does it spill over to the next memory location?

Body:
I've been reviewing C programming and there are just a couple things bothering me.

Let's take this code for example:

```<code>int myArray[5] = {1, 2, 2147483648, 4, 5};
int* ptr = myArray;
int i;
for(i=0; i<5; i++, ptr++)
    printf("\n Element %d holds %d at address %p", i, myArray[i], ptr);
</code>```

I know that an int can hold a maximum value of positive 2,147,483,647. So by going one over that, does it "spill over" to the next memory address which causes element 2 to appear as "-2147483648" at that address? But then that doesn't really make sense because in the output it still says that the next address holds the value 4, then 5. If the number had spilled over to the next address then wouldn't that change the value stored at that address?

I vaguely remember from programming in MIPS Assembly and watching the addresses change values during the program step by step that values assigned to those addresses would change.

Unless I am remembering incorrectly then here is another question: If the number assigned to a specific address is bigger than the type (like in myArray[2]) then does it not affect the values stored at the subsequent address?

Example: We have int myNum = 4 billion at address 0x10010000. Of course myNum can't store 4 billion so it appears as some negative number at that address. Despite not being able to store this large number, it has no effect on the value stored at the subsequent address of 0x10010004. Correct?

The memory addresses just have enough space to hold certain sizes of numbers/characters, and if the size goes over the limit then it will be represented differently (like trying to store 4 billion into the int but it will appear as a negative number) and so it has no effect on the numbers/characters stored at the next address.

Sorry if I went overboard. I've been having a major brain fart all day from this.


问:
What are the differences between operating systems and computer systems?
Wikipedia's definition of a "computer system" is:

Computer system is define as the combination of hardware software user and data with referring to communication and procedure involved in between them.

Which doesn't make much sense to me. Whereas the definition of an operating system is:

An operating system (OS) is system software that manages computer hardware and software resources and provides common services for computer programs.

Both those definitions seem to refer to the same thing: a system that manages hardware and software for controlling programs.

A list of topics doesn't help me much, either. For example, MIT's computer systems course lists the topics as:

virtual memory

threads

networks

atomicity

coordination of parallel activities

recovery and reliability

privacy, security, and encryption

While MIT's operating systems course lists the topics as:

virtual memory

threads

context switches

kernels

interprocess communication

interrupts

system calls

coordination

interaction between software and hardware*

*According to the only answer to this question, this is a computer systems topic?

It seems like OS is slightly more related to software and to individual computers, whereas computer systems might involve multiple computers?

答: An operating system is software, whereas a computer system is a combination of software and hardware.</p>


问:
Difficult design with multiple associations between two entities
I'm trying to design the data schema and the restful api for a specific case.

In my system I have several users and several books. Every book can have several users as authors and at the same time every user can be an authors of several books.

Now the hard part, users are interested to have a list of their books and to let the system know they are the authors, but it's important that they can also keep this association private. So a user can be the author of a book but doesn't want to make this information public.

Now a first solution can be to replicate the books information for every author and set them as private or public but this is not what I want. My idea was to use two associations in the user entity (books, public_books) where the second one is a subset of the first one.

But another problem comes with the restful api. I'm not sure what is a good way to expose this kind of data.

Something like this maybe?

```<code>/users/:id/books
</code>```

that returns a list of books made with an additional boolean property ispublic?

Is there a better idea to handle this situation in your opinion?

EDIT:
The REST API needs to return all the books linked to the user and offer a way to distinguish between public and private books. A user can obviously see all his books, but only the public books of the other users.

Another necessary thing is the possibility for a user to change the status of one of his books. A private book can become public and viceversa.

答:
Every book can have several users as authors and at the same time every user can be an authors of several books.

So you have an n:m relationship. No problem, that justmeans you'll need a link table that references both entities.

they can also keep this association private

Even less of a problem: you add visibility as another attribute to the linking table.

In which format you expose this information via REST is really a different question,
 and impossible to decide without knowing your requirements better.


答:
To further @StevenBurnap's answer, the reason this happens is because of how computers work at machine-level.

Your array is stored in memory (e.g. in RAM).
When an arithmetic operation is performed, the value in memory is copied into the input registers of the circuit that performs the arithmetic (the ALU: Arithmetic Logic Unit), the operation is then carried out on the data in the input registers, producing a result in the output register. This result is then copied back into memory at the correct address in memory, leaving other areas of memory untouched.


问:
Why use XML in Android?
From what I understand, isn't XML used for layouts and to setup how an activity looks?

My book says that XML files are converted into Java code but then, why not just write everything in Java?

答:
Because Android designers decided to implement it that way :)

In principle, everything could be written in Java. Microsoft did it for WinForms: the form description is saved as the auto-generated *.designer.cs file (or a generated region in early version of .NET framework).

Each method has its pros and cons. By storing the UI as XML, it may be easier to parse so the designer can be simpler to implement. However, it is another language for developer to learn: a totally new Domain Specific Language (UI), not just XML. By storing the UI as the target language (Java, C#...), the designer's implementation may be more complex but the code for creating UI is already familiar to the developers. Another advantage is that the existing code refactor tools can work without any changes.

Title: Why use XML in Android?