问:
Why not annotate function parameters?
To make this question answerable, let's assume that the cost of ambiguity in the mind of a programmer is much more expensive then a few extra keystrokes.

Given that, why would I allow my teammates to get away with not annotating their function parameters? Take the following code as an example of what could be a far more complex piece of code:

```<code>let foo x y = x + y
</code>```

Now, a quick examination of the tooltip will show you that F# has determined you meant for x and y to be ints. If that's what you intended, then all is well. But I don't know if that's what you intended. What if you had created this code to concatenate two strings together? Or what if I think you probably meant to add doubles? Or what if I just don't want to have to hover the mouse over every single function parameter to determine its type?

Now take this as an example:

```<code>let foo x y = "result: " + x + y
</code>```

F# now assumes you've probably intended to concatenate strings, so x and y are defined as strings. However, as the poor schmuck who's maintaining your code, I might look at this and wonder if perhaps you had intended to add x and y (ints) together and then append the result to a string for UI purposes.

Certainly for such simple examples one could let it go, but why not enforce a policy of explicit type annotation?

```<code>let foo (x:string) (y:string) = "result: " + x + y
</code>```

What harm is there in being unambiguous? Sure, a programmer could choose the wrong types for what they are trying to do, but at least I know they intended it, that it wasn't just an oversight.

This is a serious question... I am still very new to F# and am blazing the trail for my company. The standards I adopt will likely be the basis for all future F# coding, embedded in the endless copy-pasting that I am sure will permeate the culture for years to come.

So... is there something special about F#'s type inference that makes it a valuable feature to hold onto, annotating only when necessary? Or do expert F#-ers make a habit of annotating their parameters for non-trivial applications?

答:
I don’t use F#, but in Haskell it is considered good form to annotate (at least) top-level definitions, and sometimes local definitions, even though the language has pervasive type inference. This is for a few reasons:

Reading

When you want to know how to use a function, it’s incredibly useful to have the type signature available. You can simply read it, rather than trying to infer it yourself or relying on tools to do it for you.

Refactoring

When you want to alter a function, having an explicit signature gives you some assurance that your transformations preserve the intent of the original code. In a type-inferred language, you may find that highly polymorphic code will typecheck but not do what you intended. The type signature is a “barrier” that concretises type information at an interface.

Performance

In Haskell, the inferred type of a function may be overloaded (by way of typeclasses), which may imply a runtime dispatch. For numeric types, the default type is an arbitrary-precision integer. If you don’t need the full generality of these features, then you can improve performance by specialising the function to the specific type you need.

For local definitions, let-bound variables, and formal parameters to lambdas, I find that type signatures usually cost more in code than the value they would add. So in code review, I would suggest you insist on signatures for top-level definitions and merely ask for judicious annotations elsewhere.

Title: Why not annotate function parameters?


答:
Jon gave a reasonable answer which I won't repeat here. I will however show you an option that might satisfy your needs and in the process you will see a different type of answer other than a yes/no.

Lately I have been working with parsing using parser combinators. If you know parsing then you know you typically use a lexer in the first phase and a parser in the second phase. The lexer converts text to tokens and the parser converts tokens into an AST. Now with F# being a functional language and combinators being designed to be combined, parser combinators are designed to make use of the same functions in both the lexer and the parser yet if you set the type for the parser combinator functions you can only use them to lex or to parse and not both.

For example:

```<code>/// Parser that requires a specific item.

// a (tok : 'a) : ('a list -> 'a * 'a list)                     // generic
// a (tok : string) : (string list -> string * string list)     // string
// a (tok : token)  : (token list  -> token  * token list)      // token
</code>```

or

```<code>/// Parses iterated left-associated binary operator.

// leftbin (prs : 'a -> 'b * 'c) (sep : 'c -> 'd * 'a) (cons : 'd -> 'b -> 'b -> 'b) (err : string) : ('a -> 'b * 'c)                                                                                // generic
// leftbin (prs : string list -> string * string list) (sep : string list -> string * string list) (cons : string -> string -> string -> string) (err : string) : (string list -> string * string list)  // string
// leftbin (prs : token list  -> token  * token list)  (sep : token list  -> token  * token list)  (cons : token  -> token  -> token  -> token)  (err : string) : (token list  -> token  * token list)   // token
</code>```

Since the code is copyright I won't include it here but it is available at Github. Do not copy it here.

For the functions to work they must be left with the generic parameters, but I include comments that show the inferred types depending upon the functions use. This makes it easy to understand the function for maintenance while leaving the function generic for use.

ContentLicense: CC BY-SA 3.0

Title: Why not annotate function parameters?

Body:
To make this question answerable, let's assume that the cost of ambiguity in the mind of a programmer is much more expensive then a few extra keystrokes.

Given that, why would I allow my teammates to get away with not annotating their function parameters? Take the following code as an example of what could be a far more complex piece of code:

```<code>let foo x y = x + y
</code>```

Now, a quick examination of the tooltip will show you that F# has determined you meant for x and y to be ints. If that's what you intended, then all is well. But I don't know if that's what you intended. What if you had created this code to concatenate two strings together? Or what if I think you probably meant to add doubles? Or what if I just don't want to have to hover the mouse over every single function parameter to determine its type?

Now take this as an example:

```<code>let foo x y = "result: " + x + y
</code>```

F# now assumes you've probably intended to concatenate strings, so x and y are defined as strings. However, as the poor schmuck who's maintaining your code, I might look at this and wonder if perhaps you had intended to add x and y (ints) together and then append the result to a string for UI purposes.

Certainly for such simple examples one could let it go, but why not enforce a policy of explicit type annotation?

```<code>let foo (x:string) (y:string) = "result: " + x + y
</code>```

What harm is there in being unambiguous? Sure, a programmer could choose the wrong types for what they are trying to do, but at least I know they intended it, that it wasn't just an oversight.

This is a serious question... I am still very new to F# and am blazing the trail for my company. The standards I adopt will likely be the basis for all future F# coding, embedded in the endless copy-pasting that I am sure will permeate the culture for years to come.

So... is there something special about F#'s type inference that makes it a valuable feature to hold onto, annotating only when necessary? Or do expert F#-ers make a habit of annotating their parameters for non-trivial applications?

Body:
Jon gave a reasonable answer which I won't repeat here. I will however show you an option that might satisfy your needs and in the process you will see a different type of answer other than a yes/no.

Lately I have been working with parsing using parser combinators. If you know parsing then you know you typically use a lexer in the first phase and a parser in the second phase. The lexer converts text to tokens and the parser converts tokens into an AST. Now with F# being a functional language and combinators being designed to be combined, parser combinators are designed to make use of the same functions in both the lexer and the parser yet if you set the type for the parser combinator functions you can only use them to lex or to parse and not both.

For example:

/// Parser that requires a specific item.

// a (tok : 'a) : ('a list -> 'a * 'a list)                     // generic
// a (tok : string) : (string list -> string * string list)     // string
// a (tok : token)  : (token list  -> token  * token list)      // token

or

/// Parses iterated left-associated binary operator.

// leftbin (prs : 'a -> 'b * 'c) (sep : 'c -> 'd * 'a) (cons : 'd -> 'b -> 'b -> 'b) (err : string) : ('a -> 'b * 'c)                                                                                // generic
// leftbin (prs : string list -> string * string list) (sep : string list -> string * string list) (cons : string -> string -> string -> string) (err : string) : (string list -> string * string list)  // string
// leftbin (prs : token list  -> token  * token list)  (sep : token list  -> token  * token list)  (cons : token  -> token  -> token  -> token)  (err : string) : (token list  -> token  * token list)   // token

Since the code is copyright I won't include it here but it is available at Github. Do not copy it here.

For the functions to work they must be left with the generic parameters, but I include comments that show the inferred types depending upon the functions use. This makes it easy to understand the function for maintenance while leaving the function generic for use.


答:
The number of bugs is directly proportional to the number of characters in a program!

This is usually stated as the number of bugs being proportional to lines of code. But having less lines with the same amount of code gives the same amount of bugs.

So while it's nice to be explicit, any extra parameters you type can lead to bugs.

Title: Why not annotate function parameters?


问:
observer class as instance
Sometimes I read in observer-pattern descriptions, to make the constructor of a observer base class protected so the class will be abstract. but by making the constructor public (if even one is neccessary), I could use the observer as an instance and not only as base-class.

Is there any disadvantage of doing so i'm not mentioned yet?

答:
Assuming you did make the Observer class just another standard class and created a new instance, what would you intend to do with it then? An observer without any behavior is a rather useless object.

Any logic specific to what you are observing would end up in a subclass anyways (i.e. MyEventObserver) and anything that would be generic enough to be used by all observers would be best served in a base class such as an abstract Observer class.

Title: observer class as instance


问:
How do we pass data between two Amazon instances?
I'm trying to create a website where the user enters a few numbers, these numbers are fed into some equations, and the output of these equations is emailed to the user. I'm using Python 2.7 for everything. I'm using a cheap Amazon instance (m1.small, Ubuntu 12.04) to host the frontend, but I only want to launch a backend instance when needed (the computations are heavy and require a powerful - and expensive - instance). I can use boto to programmatically launch a backend instance, but after that how do I feed the user input into the backend? Everything is simple enough when I'm doing things manually, with SFTP and SSH, but what's the programmatic way to do it? Should I simply execute SFTP and SSH from my Python script (using, say, 'os.system')? Somehow that feels wrong; how do people actually do it?

In case it matters, this is not for a commercial website. I'm in grad school and I want my committee members to be able to replicate and tweak my research, which is stats-heavy. Also, I have no security concerns - it's just academic research, I'm not storing any kind of personal info or anything.

答:
Perhaps SQS (Amazon Simple Queue Service) could help you. The principle idea is that the frontend would publish a message on the queue and promptly forget about it. The backend service, upon waking up would consume messages from the queue until there is no more work to do, and then go to sleep. There are good apis for many languages, and it is generally pretty cheap at low volume.

If time is not critical you could even start and stop the backend processor as a scheduled task.

With this method you could even start up multiple instances of the back end processor, and not worry that they are duplicating work.


问:
Am I right to be skeptical of ASP.NET MVC "Html Helpers"?
ASP.NET WebForms seemed really great until that moment of realization the abstraction you'd welcomed was producing HTML that was worlds away from what you needed. Wrestling with that framework to generate HTML that matched a designers or used external libraries became a big nightmare for me and one I'd rather not have again.

When approaching a simple Bootstrap form in ASP.NET MVC I copied over the basic HTML and then started the process of adding @Html.BeginForm(), @Html.EditorFor() until it hit me that I was going down the same path. Sure, you add an attribute here, define an alternate helper there, but how long until you are fighting the framework to get back to what you could have just pasted in from any Bootstrap example on the web?

Is anyone else feeling that, or is it possible that the Helpers introduce enough "sugar" to make using them worth the effort?

答:
You are certainly right to be skeptical of them, but I think they are different enough from Web Forms to alleviate your concerns. The biggest problem with Web Forms is that it pretended the Web didn't exist. It tried to make everything feel like a Windows application, which caused a lot of weird HTML output on pages to keep track of sessions, ViewState, etc.

ASP.NET MVC doesn't have that same fundamental abstraction. It's a web framework for the web. Although I still hand-code a lot of HTML, one of the nice things about the HTML helpers is that you can define what the actual HTML output is--so, for instance, you can have all decimals display as currency and keep that code in one place. I like, most of all, being able to pick and choose when I want the raw code and when I want to make my life a little easier and just use the Helper. I've personally replaced all of the HTML helpers for DisplayFor() and EditorFor() to use formatting that I prefer in my projects. It cuts down on copy-and-paste for me a lot.


问:
What to do if my own opensource code greatly resembles another project's code?
I'm writing a Java class, part of an opensource game development framework under the Apache 2.0 license.

There is another framework, under the same license, that happens to also have a Java class that addresses the same subject as mine. I recently checked it out, and my implementation is extremely similar to that. Heck, even the local variables. The differences are minimal.

Since both classes are opensource, I guess it doesn't matter. However, since the codes are so similar, anyone may come to the conclusion that I just modified theirs a bit, and eventually quote the license:

You must give any other recipients of the Work or Derivative Works a
  copy of this License;

You must cause any modified files to carry
  prominent notices stating that You changed the files;

Since I wrote my class, there's no need to put their copyright notice in my code. However, it cannot be proven that I didn't just copy their code and modified a bit.

What is one supposed to do in this scenario?

答:
You developed the code in isolation of the other code, the code is not a derivative work of the other.  Do nothing that would claim that yours is a derivative of the other.

Writing code that does similar things will often be implemented the same way.  An anecdote of this is I was working on some software to handle arbitrary precision decimals (money).  The code had a long and an integer and some methods.  Later I found another developer had previous implemented some code to handle decimal fractional quantities (it was a big project) - it had a long and an integer and some methods.  Our internals were identical with very similar access methods.  We were solving the same problem and had the same ideas about how to implement it - there are only so many ways to do it.  If these were different software projects, mine still wouldn't be a derivative of his.

If you and I were both to implement an abstract factory for accessing files via a web server and we both chose to do it with annotations and had very similar base types... it doesn't make one a derivative of the other unless you were basing your code design off of mine.

Copyright covers the actual implementation.  If you reworded it.  Changed the variables.  Modified the other to something in yours. Those are a derivative work, which would be covered by copyright law.  But copyright law doesn't cover ideas - that is the domain of patent law.  That you and the other both hand an idea and implemented the idea in the same way, that's just convergent coding.

Now, it wouldn't be a fun lawsuit to fight if it ever came down to it.  Lawsuits are never fun to fight.  But saying that yours is a derivative work can cause you more headaches down the road if you should ever decide to dual license or pursue someone else for copyright infringement of the work (because only the copyright holder can pursue the infringement, and you would be saying you're not the holder of that copyright).


问:
How are I/O port addresses and data sent?
First of all, I'd like to say this is a hardware-level question, which is very closely related to the "in" and "out" command in x86 assembly.

I have searched for quite some time, but I still haven't found how they send the addresses and the data. Does the 8086 first send the address, then the data? If so, how does the receiver know if the 8086 is sending a 16-bit address or an 8-bit address?

Aside from that, I'd also like to learn how the 8255 works, and how it accepts specific ports such as "port 60H".

Thanks for reading! :D

答:
As you mentioned 8086 processor i'm explaining with reference to 8086:

8086 is 16-bit processor(16-bit Data Bus means: no.of Physical lines to carry-out or carry-in are 16 lines some time ALU size also)
and 20-bit Address Bus(20-bit Address Bus means : no.of Physical lines to carry-out the address are 20) these lines are nothing but 8086-pins.

To save No.of 8086 pins 16-data bus lines and 16- Address lines are multiplexed(during first part of Machine cycle  16-lines acts as Address bus later they acts as DATA Bus line)
so pin count will be reduced.

Now your main Question Answer:
Case:1(8086 wants to access a Byte in a Memory)
8086 can address 2^20(Address Bus size) Locations, each location holds a Byte(8-bits of data) that implies (2^10 x 2^10 =1024(1K) x1024(1K)=>1M) finally it  ought to be 1MByte

Memory: Like USB Drive(2GB, 4GB,etc.) Each memory location has an Address and Location holds a byte(8-bits) suppose 1MB memory Chip will have 1024K Memory locations and each location has 8-bits data unit capacity

If 8086 Processor wants access a byte at an address first it'll send Address to to 1MB memory chip let say(0x20002) Location, this 1MB memory chip is connected to the 8086 Address bus and data bus. it's like below

8086 address on address bus to 1MB Memory Chip

1MB memory Chip will receive address on its address Bus(0x20002)

8086 waits for awhile to sync with memory waiting time(memory may slower than Processor )

1MB Memory Chip will send out requested byte on the data bus lines
to 8086

8086 reads in the receiving byte

There is another case if the memory is stack of memory chips like two 512KB chips of total 1MB(512KB + 512KB)
In this case each memory chip has 19 address lines(512K = 512 x 1024 =>2^9 x 2^10) and one Important line called CHIP SELECT which enables the memory Chip
Both Memory chip address line  are connected to 8086 address bus
But 8086 has 20 address lines so one line is used to connect Chip Select line of 512K Memory Chip which Enables the 512KB chip
Here 1 address line has two states:0 or 1

0:is used to select one memory Chip-A-521KB + 19 Address line

1:is used to select second memory Chip-B-521KB + 19 Address line

Another case if memory size of 256 Bytes capacity(2^8), It has 8-ADDRESS LINES and a Chip Select Line

In the above case just 8 address line of 8086 are connected to the 256 Bytes Memory Chip but reaming are connected to the Chip select line of memory chip it maybe  NOR gate whose output is one if all the inputs are zero

here let say 20 address lines(A19-A0) of 8086

Address Lines A7-A0 are connected to the 256 bytes Memory Chip

Reaming Address lines i.e A19 to A8 are connected to the Chip Select Line of  memory Chip Through 14-Input NOR gate Whose out put is One if All the inputs are Zero i.e.(A19-A8=0x0 00)

Above Procedure is called Address Decoding
4. The Address Range for 256 Bytes memory Chip is(A7-A0=>0x00 to 0xFF) But 8086 has 20-Address Lines So Reaming lines are connected to Chip select of 256 Bytes memory Chip through NOR gate So final Address range is 0x000 00 to 0x000 FF in this way 256 Bytes Memory Chip is addressed

In this way Processor access data from Memory Chip with the help of address and Data Bus

Case:2(some device may wants send data to 8086)
It's very complex to explain here but soon i'll add to this question

finally about 8255 please refer this intel 8255 Wiki Page


问:
Best books on the theory and practice of software architecture?
I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can.

Feel free to include general books, and also books that relate to a specific technology.

答:
The commonly cited/referenced book on software architectures, and the book used when I took the Software Architecture course at my university is Software Architecture in Practice (2nd Edition) by Len Bass, Paul Clements, and Rick Kazman.

At least one professor who teaches the course has switched the textbook to Software Systems Architecture by Nick Rozanski and Eoin Woods, but I can't vouch for the quality or content of that book. According to Sergio Acosta (in the comments), Rozanski's book is newer, based on the work of Bass, and he considers it easier to read. I'm rarely disappointed by books used in the software engineering program.

ContentLicense: CC BY-SA 2.5


答:
Why not contact the other project and offer to pool your resources?

Such "project merges" are reasonably common for open source projects.

Title: What to do if my own opensource code greatly resembles another project's code?

Body:
I'm writing a Java class, part of an opensource game development framework under the Apache 2.0 license.

There is another framework, under the same license, that happens to also have a Java class that addresses the same subject as mine. I recently checked it out, and my implementation is extremely similar to that. Heck, even the local variables. The differences are minimal.

Since both classes are opensource, I guess it doesn't matter. However, since the codes are so similar, anyone may come to the conclusion that I just modified theirs a bit, and eventually quote the license:

You must give any other recipients of the Work or Derivative Works a
  copy of this License;

You must cause any modified files to carry
  prominent notices stating that You changed the files;

Since I wrote my class, there's no need to put their copyright notice in my code. However, it cannot be proven that I didn't just copy their code and modified a bit.

What is one supposed to do in this scenario?


问:
What kind of transform is this?
I have a function that linearly "remaps" a value from a given interval to an other interval?

The function remaps a value from a given interval [oldMin, oldMax] to another interval [newMin, newMax] using this formula:

```<code>newVal = newMin + (newMax - newMin) * (oldVal - oldMin) / (oldMax - oldMin)
</code>```

If it helps identify what type of transform it is, the above formula is just a reformulation of the following equation.  All I did was re-arrange the terms to express newVal on the left hand side of the equation so it is a function of all the other parameters:

Is there a standard name for the remapping transformation?

答:
This is known as Linear Interpolation.

Very common and powerful, in game development it's shorthand is "Lerp"

It is used to map one value (in a range) to another value (in a range).  For example one might map health to color (for tinting the health bar) or time to rotation (for animation).

Title: What kind of transform is this?


答: Mathematically, it's an affine transformation -- a linear transformation composed with a translation (from oldMin to newMin).</p>

Title: What kind of transform is this?

Body:
I have a function that linearly "remaps" a value from a given interval to an other interval?

The function remaps a value from a given interval [oldMin, oldMax] to another interval [newMin, newMax] using this formula:

```<code>newVal = newMin + (newMax - newMin) * (oldVal - oldMin) / (oldMax - oldMin)
</code>```

If it helps identify what type of transform it is, the above formula is just a reformulation of the following equation.  All I did was re-arrange the terms to express newVal on the left hand side of the equation so it is a function of all the other parameters:

Is there a standard name for the remapping transformation?


问:
Is there a standard for encoding recurring patterns of dates?
I'm trying to re-write a backend interface doohickey for a calendar, a todo list and another sort of calendar and found that they all were programmed to have subtly different formats for patterns of dates that could be used to configure certain properties in them.

I have three screens that have different ways of essentially doing the same thing:

and they essentially have the same information.  I've got objects for all these, but what I'd like to do is serialize the objects, not to bytecode, but to a semi-human readable format that could be transferred between not only these three screens, but stored as one field in a database and XML.

答: Probably the closest thing to a standard would be the recurrence rules of the iCalendar format, specified in RFC 2445.  Nearly every reputable calendar-related program can import and export iCal format, although they vary a lot in how thoroughly they support recurrence rules.  You should be able to find an open source project with a parser.  Whether you consider it "abbreviated" or not is a matter of perspective, I suppose.  It could certainly be shorter, but it beats listing the dates individually.</p>


问:
Entity Framework Entities - Some Data From Web Service - Best Architecture?
We are currently using Entity Framework as an ORM across a few web applications, and until now, it has suited us well as all our data is stored in a single database. We are using the repository pattern, and have services (the domain layer) which use these, and return the EF entities directly to the ASP.NET MVC controllers.

However, a requirement has come up to utilise a 3rd party API (through a web service) which will give us extra information that relates to the user in our database. In our local User database, we will store an external ID which we can provide the to API to get additional information. There is quite a bit of information available, but for the sake of simplicity, one of them relates to the user's company (name, manager, room, job title, location etc). This information will be used in various places throughout our web apps - as opposed to being used in a single place.

So my question is, where is the best place to populate and access this information? As it is used in various places, it's not really sensible to fetch it on an ad-hoc basis wherever we use in the web application - so it makes sense to return this additional data from the domain layer.

My initial thought was just to create a wrapper model class which would contain the EF entity (EFUser), and a new 'ApiUser' class containing the new information - and when we get a user, we get the EFUser, and then get the additional info from the API, and populate the ApiUser object. However, whilst this would be fine for getting single users, it falls over when getting multiple users. We can't hit the API when getting a list of users.

My second thought was just to add a singleton method to the EFUser entity which returns the ApiUser, and just populate it when needed. This solves the above problem as we only access it when we need it.

Or the final thought was to keep a local copy of the data in our database, and synchronise it with the API when the user logs in. This is minimal work as it's just a synchronisation process - and we don't have the overhead of hitting the DB and API every time we want to get user information. However, these means storing the data in two places, and also means the data is out of date for any user that hasn't logged in for a while.

Does anyone have any advice or suggestions on how best to handle this kind of scenario?

答:
Your case

In your case all three options are viable. I think that the best option is probably to sync your data sources someplace the asp.net application is not even aware of. That is, avoid the two fetches in the foreground every time, sync the API with the db silently). So if that's a viable option in your case - I say do it.

A solution where you make the fetch 'once' like the other answer suggests doesn't seem very viable since it doesn't persist the response anywhere and ASP.NET MVC will just make the fetch for every request over and over.

I'd avoid the singleton, I don't think it's a good idea at all for plenty of the usual reasons.

If the third option is not viable - one option is to lazy load it . That is, have a class extend the entity, and have it hit the API on a need to basis. That's a very dangerous abstraction though since it's even more magic and non-obvious state.

I guess it really boils down to several questions:

How often does the API call data change? Not often? Third option. Often? Suddenly the third option is not too viable. I'm not sure I'm as against ad-hoc calls as you.

How expensive is an API call? Do you pay per call? Are they fast? Free? If they're fast, making a call each time might work, if they're slow you need to have some sort of prediction in place and make the calls. If they cost money - that's a big incentive for caching.

How fast does the response time have to be? Obviously faster is better, but sacrificing speed for simplicity might be worth it in some cases, especially if it's not directly facing a user.

How different is the API data from your data? Are they two conceptually different things? If so, it might be even better to just expose the API outside rather than return the API result with the result directly and let the other side make the second call and handle managing it.

A word or two about separation of concerns

Allow me to argue against what Bobson is saying about separation of concerns here. At the end of the day - putting that logic in the entities like that violates separation of concerns just as bad.

Having such a repository violates separation of concerns just as bad by putting presentation centric logic in the business logic layer. Your repository is now suddenly aware of the  presentation related things like how you display the user in your asp.net mvc controllers.

In this related question I've asked about accessing entities directly from a controller. Allow me to quote one of the answers there:

"Welcome to BigPizza, the custom Pizza shop, may I take your order?" "Well, I'd like to have a Pizza with olives, but tomato sauce on top and cheese at the bottom and bake it in the oven for 90 minutes until it's black and hard like a flat rock of granite." "OK, Sir, custom Pizzas are our profession, we'll make it."

The cashier goes to the kitchen. "There is a psycho at the counter, he wants to have a Pizza with... it's a rock of granite with ... wait ... we need to have a name first", he tells the cook.

"No!", the cook screams, "not again! You know we tried that already." He takes a stack of paper with 400 pages, "here we have rock of granite from 2005, but... it didn't have olives, but paprica instead... or here is top tomato ... but the customer wanted it baked only half a minute." "Maybe we should call it TopTomatoGraniteRockSpecial?" "But it doesn't take the cheese at the bottom into account..." The cashier: "That's what Special is supposed to express." "But having the Pizza rock formed like a pyramid would be special as well", the cook replies. "Hmmm ... it is difficult...", the desparate cashier says.

"IS MY PIZZA ALREADY IN THE OVEN?", suddenly it shouts through the kitchen door. "Let's stop this discussion, just tell me how to make this Pizza, we are not going to have such a Pizza a second time", the cook decides. "OK, it's a Pizza with olives, but tomato sauce on top and cheese at the bottom and bake it in the oven for 90 minutes until it's black and hard like a flat rock of granite."

(Read the rest of the answer, it's really nice imo).

It's naive to ignore the fact there is a database - there is a database, and no matter how hard you want to abstract that, it's not going anywhere. Your application will be aware of the data source. You won't be able to 'hot swap it'. ORMs are useful but they leak because of how complicated the problem they solve is and for plenty of performance reasons (Like Select n+1 for example).


问:
Is functional programming actually used to create applications?

Possible Duplicate:

  What are some well known applications written in F#?

I see a lot of people talking about how cool functional programming is, how awesome Lisp and Haskell and F# are, etc, but what I don't see is them actually being used.  Just about every program on my computer is written in either something in the C family, Delphi, or Python.  I see tutorials talking about how easy it is to use functional languages to do complicated math problems, but no one talking about using them to do things most people actually care about using computers for, like business applications and games.

Does anyone have any examples of actual programs that people have heard of and are using, written in a functional language?  The only one I can think of off the top of my head is Abuse, from almost 15 years ago.  (Things like Emacs, where the core program is written in C with a functional language scripting layer on top, don't count.)

答:
Ever used a modern website, lots of Javascript, tons of people using jQuery?

Well that's effectively a functional language, closures, functions as first-class objects, etc.

Everywhere, millions of users day by day.


问:
Where should libraries be placed, in windows?
I have just moved from Linux to Windows, and I have to use the Zend Framework library. Where should the library be placed?

Directly on C drive

Create a lib folder like C:/lib/

Create a lib folder in my user folder

I am wondering if there is a classic folder where these kind of libraries are placed.

Update:I am asking about the location on my own standpoint. The Zend Framework library is a PHP framework.

答:
Depending on the use of the machine then i would give the following advice:-

For server machines
if you are using the windows machine as a server machine then i would advice you to save the zend library files in a locations you can easy access. like C://zendLibs. Then include the zendLibs path to the include path of your php.ini. advantage is any application that will be deployed to the server will by default use the libraries eliminating the need for copying the libraries in every project.

for development machines
if you are using the zend library files on a developers machine, i would suggest copying the files in the application. this is to avoid the "its working on my machine" clause when the application is deployed. this will definitely make the application bulky and many of its libraries will not be used.
the other thing about coping the code on the developer machine is thhe support for auto completion with some IDE, only used netbeans though, and it works perfectly(auto complete).

either way you can copy your library any place on the  machine as long as its accessible to the application.


问:
Benefits of using config files over making many small classes?
My friend and I are building a mobile game and ran into the following design problem:

We will have many different types of units all with different stats and abilities. However, all unit types should have a few commonalities (for example, they would all have a totalhealth attribute).

We were trying to decide what the best way of representing these units would be.

My friend suggested simply making a new class for each unit type.

I feel that having hundreds of different classes feels wrong, but can't quite figure out what's so bad about it.

My alternative is to put the unit type information into either configuration files or a database (which will also solve the issue of enforcing every unit type to have a few common attributes with a schema). And then have a master unit class to instantiate types of units from the db.

What is the proper way of architecturing this?

答:
Indeed, hundreds of classes feels wrong. It seems like your colleague wants to create a separate class, where in fact, you have separate instances of the same class. For example:

```<code>Animal
    Cat
        Black cat
        Brown cat
    Dog
        ...
</code>```

is a wrong class hierarchy. One should instead limit himself to:

```<code>Animal
    Cat
    Dog
</code>```

with Cat having a property FurColor.

In your context, this means that different stats and abilities would be presented as properties, while either all units sharing the same class, or having a few specific classes.

Now, where to put the information about the units? You have the following choice:

Hard code it,

Use configuration files,

Use database.

The first one has a major drawback: you have to rebuild¹ the application each time you want to change one aspect of a unit. This makes tweaking and customization practically impossible.

The second and the third one are the same thing, since configuration files are a database too. What should concern you is to pick a right level of strictness for your database. A relational database would probably be a bad choice, unless you're absolutely sure you won't change the schema over time. If the choice is between a NoSQL and, say, a bunch of XML files, see what's easy and more flexible for you; also, don't reinvent the wheel.

¹ Build ≠ compile. If you use a dynamically typed language, you still have to run tests at build a stable version on every change you make.

Body:
Indeed, hundreds of classes feels wrong. It seems like your colleague wants to create a separate class, where in fact, you have separate instances of the same class. For example:

Animal
    Cat
        Black cat
        Brown cat
    Dog
        ...

is a wrong class hierarchy. One should instead limit himself to:

Animal
    Cat
    Dog

with Cat having a property FurColor.

In your context, this means that different stats and abilities would be presented as properties, while either all units sharing the same class, or having a few specific classes.

Now, where to put the information about the units? You have the following choice:

Hard code it,

Use configuration files,

Use database.

The first one has a major drawback: you have to rebuild¹ the application each time you want to change one aspect of a unit. This makes tweaking and customization practically impossible.

The second and the third one are the same thing, since configuration files are a database too. What should concern you is to pick a right level of strictness for your database. A relational database would probably be a bad choice, unless you're absolutely sure you won't change the schema over time. If the choice is between a NoSQL and, say, a bunch of XML files, see what's easy and more flexible for you; also, don't reinvent the wheel.

¹ Build ≠ compile. If you use a dynamically typed language, you still have to run tests at build a stable version on every change you make.


答:
The proper way depends on many factors, but a big one among them is how these units differ from each other.

If the units only differ from each other in the (initial) values that they have for their attributes (which all are common to all the units), then your idea of using configuration data is a good way to easily create many different units.

On the other hand, if the different units need to respond differently to interactions with other entities in your game (where different response means writing different code), then your best bet is to use different classes for the different units, that all derive from a common base class that defines the common attributes and method interfaces.

As a third possibility, you might have a mixture of the two options. In that case, you should also use a mixture of the designs: different classes for the groups of units that show different behaviour, with configuration data to make up the different units within each group.

Title: Benefits of using config files over making many small classes?

Body:
My friend and I are building a mobile game and ran into the following design problem:

We will have many different types of units all with different stats and abilities. However, all unit types should have a few commonalities (for example, they would all have a totalhealth attribute).

We were trying to decide what the best way of representing these units would be.

My friend suggested simply making a new class for each unit type.

I feel that having hundreds of different classes feels wrong, but can't quite figure out what's so bad about it.

My alternative is to put the unit type information into either configuration files or a database (which will also solve the issue of enforcing every unit type to have a few common attributes with a schema). And then have a master unit class to instantiate types of units from the db.

What is the proper way of architecturing this?


答:
Hundreds of classes are a problem simply because you will be forced to create an intricate inheritance hierarchy. The main principle that speaks against this is the Composition over Inheritance principle. Inheritance at such a large scale has large drawbacks, apart from simply having to know about hundreds of classes.

I also suggest that you create an interface for a Unit and shift your mental focus: think less about individual unit's stats and abilities, but more about general unit behavior.

For example, a unit may be able to move. In this case, you can add an orthogonal interface (i.e., it need not be inheriting from the Unit interface even) for Movable things, which allows you to query how far they may move, whether moving to x/y is valid, or to actually perform the move operation. Similarly, do not think about "this unit has x health", but think about units being damageable with the possible consequence of dying.

For the actual configuration of units you do of course need to provide these stats and abilities in some form of configuration (along with images/animations/etc.). For the retrieval, however, I suggest you take a close look at the Factory pattern.

Finally, you proposed a "master unit class", which reminds me to make you aware of the God object anti-pattern. Do not fall into this other extreme. There are many more choices than hundreds of classes versus one class. The whole spectrum in-between these is feasible as well, and certainly much more preferable than the extremes.


问:
PHP common uses for the Command Line
I started with PHP a little while ago. I've been doing a lot of tutorials, practice sites, etc. and it's going great.

One thing I like about PHP is how easy it is to get started (downloading WAMP and voila). However, up until I learned about PEAR and MVC frameworks,  I haven't put much thought in using a command line Interface for PHP development...

I've not really used the command line that much and it will take me some getting used to, so a couple of questions I have are:

What are the most common uses of the Command Line when developing websites and web applications with PHP?

Can you run MVC frameworks such as Zend, CakePHP, etc without ever using it?

Besides PEAR, are there any other PHP repositories that use the command line to work?

(It seems if you want to avoid using PEAR there are countless other PHP Classes/libraries on the internet that one could download and then simply copy and paste files into your site.)

答:
What are the most common uses of the Command Line when developing websites and web applications with PHP?

Some. When you want to develop a web service that doesn't necessarily need an interface, like an auto response system to sms/emails, I would recommend writing an application that runs on the console. These are background processes generally.

Can you run MVC frameworks such as Zend, CakePHP, etc without ever using it? From a Zend perspective: you can run the Zend framework without the console. The console only makes work a little easier, reduces repetition.

Title: PHP common uses for the Command Line


问:
Licensing libraries (which do code generation, etc) and GPL boundaries
I want to really opensource a project that did start as a personal hobby, but I'm an ignorant of licensing details.

This project, provides some libraries for a given $language, and some wrapper command line utilities for those libraries.

Those libraries, across many things, do generate more code in the same language, code which can be reused by the caller.

On my drafts, I always used a MIT style license for the sake of brevity, but it's unreleased copies I'm reviewing right now to merge on a finally released version.

I would like to use GPL style policies for usage/contribution of my code (lets call it a framework).

But.

Could choosing GPLv2 (3?) for my project, limit the things that a given user can do with the code generated or managed by my libraries/utilities? (i.e. commercial profit of such generated code without release her improvements/changes to my code)

Is there something to consider (in a plain language) when licensing code that generates code ?

Update:

To try to answer some comments:

What do you wish to accomplish with your license?

The best goals for the project health (from the view point of a community-based opensource project).

Who do you want to use your code?

Anybody

What do you want to happen to changes?

To be back-ported to the project as much as possible.

What do you want to happen to generated code?

To don't be affected by my licensing choice. It belongs to the user who generated it.

What about money - if the user makes money do you want that to affect the licensing?

If the user makes money from the generated code, great. If the user makes money modifying my code, I would like to force to publish the changes.

I did a group-therapy with those answers. Now, choosing GPL (2? 3?) I could be ok or not?

Update2

So they have to bundle/compile your library in with theirs when they deploy it, in order for it to run?

yes, the library needs to be installed previously, or bundled with the result (there is an option for this).

答:
The main thing to consider when choosing the license for a code generator is how much of the code generator itself will wind up in its output. With most (all?) compilers, this is such a small portion that the compiler's license is not considered to apply to the compiler's output. This makes it possible to use GPL-licensed compilers to write closed-source software, because the end-product is not considered to be derived from the compiler's source.

On the other hand, there are also tools like Bison, where a significant portion of the tool makes it into the output. As Bison is licensed with the GPL, this would normally mean that and software you generate with Bison would also be covered by the GPL, were it not that the Bison license has a special clause to allow its output to be used in (a limited set of) closed source projects.

As you do not wish to restrict the uses of the generated code, but you do want modifications to the generator and libraries to be made public, your best choice seems to to use LGPL or a permissive license for the libraries (provided they can be linked dynamically to the user's project) and GPL (optionally with a Bison-like exception) or a permissive license for the code generator.


问:
If we only know that a video is 720P, 480P or 240P can that unambiguously tell us of the resolution?
The main issue I have here is are the 720P, 480P, 240P... classes for defining video quality or do they unambiguously define the resolution of the video?

For example, the wikipedia article about 240P refers to a family of resolutions.

答:
720P

720 means 720 lines to paint, the image on the screen has this amont
of lines.

P means full pictures, so every line is painted, to create
a image on the screen.

If you have a 100Hz device, the device paints 100 full pictures in 1 second. All 720 lines are painted each turn.

You can not find out the resolution by this information.


问:
Why do some compilers generate direct machine code?
I was taking this course - CMU 18-447, Computer Architecture at Carnegie Mellon to brush my knowledge and concepts.

They say that most of the machine level details and implementations are taken care of at the Instruction Set Architecture(ISA) level and is abstracted at that level.

Some Intel processors even have hardware level translation layers that take the front level ISA that is exposed to the programmer and translate them further closer to the machine.

Given such power is provided by the ISA/Processor itself, why do compilers generate direct machine code, or is it just a black box and internally it uses assemblers to convert them into direct machine code?

I hear that JVM takes byte code and translate them directly to machine code(exe).Is this true or is my understanding wrong here?

答:
I find this definition pretty clear:

The Instruction Set Architecture (ISA) is the part of the processor that is visible to the programmer or compiler writer. The ISA serves as the boundary between software and hardware.

The ISA provides an abstraction of the actual microarchitecture, which is the implementation of the instruction set by the processor.

So when your compiler is said to produce machine code, it produces instructions for the configured instruction set, not the actual processor, so any processor implementing that instruction set can run that machine code.

A virtual machine such as the JVM or CLR runs code that has been compiled to bytecode specific to that virtual machine's architecture, Java bytecode and CIL in this case.

The runtime of such a virtual machine, which in turn is built for and runs on a specific processor architecture and OS, translates the bytecode to the machine code and API calls for the platform it runs on, and usually does so just-in-time.


问:
Why do dynamic languages make it more difficult to maintain large codebases?
Large codebases are more difficult to maintain when they are written in dynamic languages. At least that's what Yevgeniy Brikman, lead developer bringing the Play Framework to LinkedIn says in a video presentation recorded at JaxConf 2013 (minute 44).

Why does he say this? What are the reasons?

答:
Because they deliberately abandon some of the tools that programming languages offer to assert things you know about the code.

The best-known and most obvious example of this is strict/strong/mandatory/explicit typing (note that the terminology is very much disputed, but most people agree that some languages are stricter than others). When used well, it acts as a permanent assertion about the kind of values you're expecting to occur in a particular place, which can make reasoning about the possible behaviour of a line, routine or module easier, simply because there are fewer possible cases. If you're only ever going to treat someone's name as a string, many coders are therefore willing to type a declaration, to not make exceptions to this rule, and to accept the occasional compilation error when they have made a slip of the finger (forgot quotes) or of the brain (forgot that this rating is not supposed to allow fractions).

Others think that this restricts their creative expressivity, slows down development and introduces work that the compiler should do (e.g. via type inference) or that isn't necessary at all(they'll just remember to stick to strings). One problem with this is that people are quite bad at predicting what kind of errors they will make: almost everybody overestimates their own ability, often grossly. More insidiously, the problem becomes gradually worse the larger your code base - most people can, in fact, remember that the customer name is a string, but add 78 other entities to the mix, all with IDs, some with names and some with serial 'numbers', some of which really are numeric (require computation to be done them) but others of which require letters to be stored, and after a while it can become pretty hard to remember whether the field you're reading is actually guaranteed to evaluate to an int or not.

Therefore, many decisions that suit a quick prototype project well work much less well in a huge production project - often without anyone noticing the tipping point. This is why there is no one-size-fits-all language, paradigm or framework (and why arguing which language is better are silly).


问:
Modeling an extensible Domain Driven Design project
Say that we are developing an application with modules (Sales, Accounting, Purchasing, etc).

An example case here is :

Sales module is the basic / primary module available, and Accounting module is a complementary module.

```<code>SalesModule
-. Product
</code>```

And

```<code>AccountingModule
-. Account
-. Journal
</code>```

If we were to say that :

If the Accounting Module were installed, then it will provide a direct
  integration with the Product class from the Sales Module, such as : a Product now has a List of Account which if a transaction is applied to the Product, a Journal will be posted according to the Account.

In my mind, I would picture that Product would have a property of List<Account>, but that would be impossible without adding that property directly in the Product class, making Product now dependent on Accounting Module when SalesModule should be able to run without it.

Another solution came up to mind is to add SalesIntegrations classes (ProductAccount, etc) to complement the previously described Product, making it independent. But this solution doesn't sound as 'natural' as saying that a Product has a list of Accounts.

From what I understand, doing DDD means to know beforehand the whole concept of business rules.

What if a requirement come along to add a new project to complement the previous DDD project with only having it's DLL (no access to source code)?

答:
Many MVC frameworks make use of Inversion of Control to inject dependencies and make them more flexible. Not sure how tight your integration should be, and even further how decoupled these modules should work. eg. are they all standalone applications?

You may want to have at look at some patterns that inject dependencies, it's a way of having loosely coupled modules. You can also create interfaces to formalize and create 'contracts' among modules. eg. AccountAwareInterface, with something like    setListAccount and getListAccount.

If the Product module should work irrespective of other modules, I would extend affected Product classes and integrate there. But how you make use of one or other class, certainly it has to be configured properly.

Not sure if it helps a bit.


问:
Managing false positives in TDD or BDD
I'm relatively new to TDD and have been thinking a lot about how to manage the perpetually growing pool of tests that comes with it.

One of my biggest concerns is about false positives.

In my experience, it's not uncommon at all for a feature to undergo fairly massive changes over time.  To implement a change we would first write a test (or many tests) for the new behaviour and then code the change.  Ideally, all the tests would pass once the feature change has been correctly implemented.

But what about the tests that covered the first incarnation of the feature?  There is no guarantee that:

they are still relevant;

they still pass;

their pass/fail status is even correct.

Reviewing/updating/deleting these tests in a relatively small pool of tests may be manageable, but what about when you have thousands or tens of thousands of tests?  It seems to me that there is a big risk that your collection of tests will eventually contain many false positives.  And, considering that these tests are a form of system documentation, this is pretty bad!

Question: How do you mitigate the risk of accumulating False Positive tests when applying TDD or BDD (or anything that eventually leads to having a massive collection of tests)?

答:
The key is to have all your tests clearly refer to the precise bit of functionality they are supposed to test.

It can be via very expressive test names and strict one-assert-per-test discipline, or really clever subdirectory structure in your test suite, or references from test suite to source code, or whatever. The point is that you can quickly identify which tests will become obsolete.

Then you delete them.

That sounds foolhardy, but every major change deletes some functionality and replaces it with new, different functionality. If you're using TDD, you're going to write new tests for every bit of that anyway, and fixing old tests instead of forging ahead with new tests and production code is just a waste of time. And this is why questions of organization, coupling, coherence etc. etc. are just as important in test code as in production code!

Title: Managing false positives in TDD or BDD


答:
Why don't you ask the author of that presentation? It's his claim, after all, he should back it up.

There are plenty of very large, very complex, very successful projects developed in dynamic languages. And there are plenty of spectacular failures of projects written in statically typed languages (e.g. the FBI Virtual Case File).

It is probably true that projects written in dynamic languages tend to be smaller than projects written in statically typed languages, but that is a red herring: most projects written in statically typed languages tend to be written in languages like Java or C, which are not very expressive. Whereas most projects written in dynamic languages tend to be written in very expressive languages like Scheme, CommonLisp, Clojure, Smalltalk, Ruby, Python.

So, the reason why those projects are smaller is not because you can't write large projects in dynamic languages, it's because you don't need to write large projects in expressive languages … it simply takes much fewer lines of code, much less complexity to do the same thing in a more expressive language.

Projects written in Haskell, for example, also tend to be pretty small. Not because you can't write large systems in Haskell, but simply because you don't have to.

But let's at least take a look at what a static type system has to offer for writing large systems: a type system prevents you from writing certain programs. That's its job. You write a program, present it to the type checker, and the type checker says: "No, you can't write that, sorry." And in particular, type systems are designed in such a way that the type checker prevents you from writing "bad" programs. Programs that have errors. So, in that sense, yes, a static type system helps in developing large systems.

However, there is a problem: we have the Halting Problem, Rice's Theorem and many other Incompleteness Theorems which basically tell us one thing: it is impossible to write a type checker which can always determine whether a program is type-safe or not. There will always be an infinite number of programs for which the type checker can't decide whether they are type-safe or not. And there is only one sane thing to do for the type checker: reject these programs as not type-safe. And an infinite number of those programs will, in fact, not be type-safe. However, also an infinite number of those programs will be type-safe! And some of those will even be useful! So, the type checker has just prevented us from writing a useful, type-safe program, just because it cannot prove its type-safety.

IOW: the purpose of a type system is to limit expressiveness.

But, what if one of those rejected programs actually solves our problem in an elegant, easy to maintain manner? Then we cannot write that program.

I'd say it's basically a give-and-take: statically typed languages restrict you from writing bad programs at the expense of occasionally also preventing you from writing good programs. Dynamic languages don't prevent you from writing good programs at the expense of also not preventing you from writing bad programs.

The more important aspect for maintainability of large systems is expressiveness, simply because you don't need to create as large and complex a system in the first place.

Title: Why do dynamic languages make it more difficult to maintain large codebases?

Body:
Large codebases are more difficult to maintain when they are written in dynamic languages. At least that's what Yevgeniy Brikman, lead developer bringing the Play Framework to LinkedIn says in a video presentation recorded at JaxConf 2013 (minute 44).

Why does he say this? What are the reasons?


答:
240P, 480P, 720P, etc. give you vertical resolution. However "P" does not stand for "pixels" but for "progressive". 720p means that all 720 lines are drawn in each frame. It is the opposite to Interlaced (denoted as "i") where just half of the lines is drawn each frame.

So the numbers give you vertical resolutions. Horizontal resolution depends on a given aspect ratio.

Title: If we only know that a video is 720P, 480P or 240P can that unambiguously tell us of the resolution?

Body:
The main issue I have here is are the 720P, 480P, 240P... classes for defining video quality or do they unambiguously define the resolution of the video?

For example, the wikipedia article about 240P refers to a family of resolutions.


答:
In Eric Evans book the problem you are experiencing is somewhat touched when dealing with Bounded Contexts, which are contexts that are born separated (legacy, different teams, etc.) and need to interact.

It all depends on the investment and resources, but if as you said you only have access to the DLLs, you cannot use any approach that involves refactoring commonalities out of the other module, so you will have to live with it in a fashion similar to dealing with legacy code.

The approaches you have are described in the Context Mapping strategies. In my opinion, given the inability to work on the existing code, a defensive approach like an "Anti-Corruption layer" could be the case.

Title: Modeling an extensible Domain Driven Design project

Body:
Say that we are developing an application with modules (Sales, Accounting, Purchasing, etc).

An example case here is :

Sales module is the basic / primary module available, and Accounting module is a complementary module.

```<code>SalesModule
-. Product
</code>```

And

```<code>AccountingModule
-. Account
-. Journal
</code>```

If we were to say that :

If the Accounting Module were installed, then it will provide a direct
  integration with the Product class from the Sales Module, such as : a Product now has a List of Account which if a transaction is applied to the Product, a Journal will be posted according to the Account.

In my mind, I would picture that Product would have a property of List<Account>, but that would be impossible without adding that property directly in the Product class, making Product now dependent on Accounting Module when SalesModule should be able to run without it.

Another solution came up to mind is to add SalesIntegrations classes (ProductAccount, etc) to complement the previously described Product, making it independent. But this solution doesn't sound as 'natural' as saying that a Product has a list of Accounts.

From what I understand, doing DDD means to know beforehand the whole concept of business rules.

What if a requirement come along to add a new project to complement the previous DDD project with only having it's DLL (no access to source code)?


答: Explicit static types are a universally-understood and guaranteed correct form of documentation which is not available in dynamic languages. If this is not compensated for, your dynamic code will simply be harder to read and understand.</p>


答:
This needs clarifying.  Clime is correct in this answer. The P in 1080p 720p refers to 'progressive'.  It means that the image is intended to be render its lines to screen one line at a time, sequentially.

This comes from the old days where TV was a cathode-ray tube device that needed to render images in an interlaced manner to improve the temporal appearance to the viewer -- start at the top, then emit the even lines first then return to the top then the odd lines odd lines. The set of lines that is half a picture it called a 'field' and a full image is made up of two interlaced fields.  We refer to these formats as 1080i, 720i.

To get the spatial resolution you must look beyond the name of the format because, as you've found, they are as best ambiguous.  The info you need is in the file's header as metadata.


问:
Testing: deterministic or non-deterministic?
Is it better to have either a

Deterministic test suite, that results in the same tests succeeding

Non-deterministic test suite, which potentially possibly covers more cases

?

Example:
You write a test suite to test controller functionality in an MVC application. The controller requires application data from a database as input during the test. There are two options to do this:

You hardcode which row(s) from the test database are selected as input (e.g. the 10th and 412th row)

You use a random number generator to pseudorandomly pick the data from the database (two rows selected by a random number generator)

The first is deterministic: every run of the test for the same revision of code should yield the same result. The second is non-deterministic: every run of the test suite has the possibility to yield a different result. The randomly picked data might however be a better representation of data edge cases. It might simulate a user feeding our controllers with unpredictable data better?

What are reasons to choose one over the other?

答:
When every run of the test suite gives you the possibility to yield a different result, the test is almost completely worthless - when the suite shows you a bug, you have a high chance that you cannot reproduce it, and when you try to fix the bug, you cannot verify whether your fix works (or not).

So when you think you need to use some kind of random number generator for generating of your test data, either make sure you always initialize the generator with the same seed, or persist your random test data in a file before feeding it into your test, so you can re-run the test again with exact the same data from the run before. This way, you can transform any non-deterministic test into a deterministic one.

EDIT: Using a random number generator to pick some test data is IMHO sometimes a sign for being too lazy about picking good test data. Instead of throwing 100,000 randomly choosen test values and hope that this will be enough to discover all serious bugs by chance, better use your brain, pick 10 to 20 "interesting" cases, and use them for the test suite. This will not only result in a better quality of your tests, but also in a much higher performance of the suite.

ContentLicense: CC BY-SA 4.0


答:
Consider a large codebase including database bindings and a rich
testsuite and let me highlight a few advantages of static languages
over dynamic languages. (Some examples may be idiosyncratic and not
apply to any static or dynamic language.)

The general idea—as others pointed that out—is that the type system is
a “dimension” of your program which exposes some information to
automated tools processing your program (compiler, code analysis
tools, etc.).  With a dynamic language, this information is basically
stripped and therefore not available.  With a static language, this
information can be used to help writing correct programs.

When you fix a bug, you start with a program that looks good to your
compiler but has faulty logic. When you fix the bug, you make an edit
fixing locally the logic of your program (e.g. within a class) but
breaking this logic at other places (e.g. classes collaborating with
the previous one).  Since a program written in a static language
exposes much more information to the compiler¹ than a program written
in a dynamic language, the compiler will help you to locate the other
places where the logic breaks more than a compiler for a dynamic
language will do.  This is because a local modification will break the
type correctness of the program at other places, thus forcing you to
fix the type correctness globally before having a chance to run the
program again.

A static language enforce type-correctness of a program, and you can
assume that all type errors you encounter when working on the program
would correspond to a runtime failure in an hypothetical translation of
the program in a dynamic language, thus the former has less bugs than
the latter.  As a consequence, it requires less coverage tests, less
unit tests and less bugfixes, in one word, it is easier to
maintain.

Of course, there is a tradeoff: while it is possible to expose a lot
of information in the type system and thus taking the chance to write
reliable programs, it might be difficult to combine this with a
flexible~API.

Here is a few examples of information that one can encode in the type
system:

— Const correctness the compiler can guarantee that a value is
  passed “read-only” to a procedure.²

— Database schema the compiler can guarantee that code binding the
  program to a database corresponds to the database definition.  This
  is very useful when this definition changes. (Maintainance!)

— System resources the compiler can guarantee that code using a
  system resourcce only does it when the resource is in the correct
  state.  For instance, it is possible to encode the attribute close
  or open of a file in the type system.

¹ It is not useful to distinguish between a compiler and an
  interpreter here, if such a difference exists.


答:
Some Intel processors even have hardware level translation layers that take the front level ISA that is exposed to the programmer and translate them further closer to the machine.

That concept is called microprogramming and has been around in theory since Charles Babbage and in implementation since the 1960s.  Some processors aren't microprogrammed at all and use hardware to execute the instructions, others are entirely microprogrammed and some take a hybrid approach depending on what instruction is being executed.

Given such power is provided by the ISA/Processor itself...

That power exists in the processor but isn't provided.  The API for a processor is its instruction set.  The microprogramming, if there is any, is an implementation detail that you're not supposed to know or care about.

... why do compilers generate direct machine code, or is it just a black box and internally it uses assemblers to convert them into direct machine code?

I'm sure there are a few compilers that directly generate object code, but most generate assembly and then assemble it behind the scenes.  Assembly is just a human-readable longhand for the corresponding object code that's a lot easier to generate and use for debugging or just understanding what the compiler produces.  Odds are very good that if you're writing a compiler for a target, you'll already have a perfectly serviceable assembler (or cross-assembler) that's preferable to use over re-inventing that wheel yourself.

I hear that JVM takes byte code and translate them directly to machine code(exe).Is this true or is my understanding wrong here?

Early versions of the JVM were, essentially, emulators that would examine each bytecode instruction and carry out the operations needed.  This is very similar to what microcode does, just implemented in software on a general-purpose computer.  Early JVMs were also very slow, which led to the use of things like just-in-time compilation of bytecode to native instructions.

None of this matters, though, because the lingua franca for Java is Java bytecode.  This is no different than the instruction set on a real CPU in that you don't care how it's implemented under the covers.  There are, in fact, a number of CPUs called "Java processors" that can run Java bytecode directly, a variant of the ARM9 being one of them.  Java software won't know or care if it's being run on a Java Processor or JVM.

Title: Why do some compilers generate direct machine code?

Body:
I was taking this course - CMU 18-447, Computer Architecture at Carnegie Mellon to brush my knowledge and concepts.

They say that most of the machine level details and implementations are taken care of at the Instruction Set Architecture(ISA) level and is abstracted at that level.

Some Intel processors even have hardware level translation layers that take the front level ISA that is exposed to the programmer and translate them further closer to the machine.

Given such power is provided by the ISA/Processor itself, why do compilers generate direct machine code, or is it just a black box and internally it uses assemblers to convert them into direct machine code?

I hear that JVM takes byte code and translate them directly to machine code(exe).Is this true or is my understanding wrong here?


问:
Should I return Collection or ImmutableCollection from a method?
When writing an API in Java, returning an immutable collection of some sort, I've got the option of returning Collection (or List, Map, etc) from the method, or guava's ImmutableCollection (or ImmutableList, ImmutableMap, etc):

```<code>private final ImmutableMap<> _immutableMap = ...

public Collection<T> getValues() {
    return _immutableMap.values();
}
</code>```

or

```<code>public ImmutableCollection<T> getValues() {
    return _immutableMap.values();
}
</code>```

Which is better?

Setting the return value as ImmutableCollection constrains me to use that exact type forever more, so that I can't swap out _immutableMap for my own immutable type later on that returns, say, an immutable view of the values that isnt an ImmutableCollection (constructing one requires copying the values, and I can't subclass it to provide an immutable view of a mutable collection).

But there is benefit to people calling the method to see the return value is actually immutable, and have the add and remove methods marked as deprecated, rather than trying to add or remove items and have it fail at runtime.

Generally, I like to return the most-specific interface type from a method, so that I can change the underlying implementation later on if necessary without breaking contract. But there is benefit to callers returning an ImmutableCollection, at the cost of constraining future development of the method and causing future possible performance problems due to copying all the values into an ImmutableCollection rather than providing an immutable view.

答:
Generally, I like to return the most-specific interface type from a method

You probably mean the least-specific type, because that's what allows you to exchange the concrete result type by something more specific.

In general, if you want to remain open like this you have to look for the best suited common ancestor of the types you have in mind, then walk all the way up to the root until you think it is no longer suited for your method's return type.

Let's make this example concrete with your two classes:

ImmutableCollection extends Collection extends Iterable extends Object

and

List extends Collection extends Iterable extends Object

Clearly, your common ancestor is Collection, so you must ask yourself the following question:

Would it be ok, if my callers got a Collection back instead of ImmutableCollection?

I guess it would be fine, as they are already assuming a collection anyways. So let's say you write it with Collection<T> as return type. It is easy to see, that you can now simply switch the implementation to an non-modifable java.util.List, without any client code needing a change.

You do indeed lose some information as you pointed out by not knowing from the type, whether your Collection can be modified or not. But, this is a kind of red herring really, because if you open up the Javadoc f.ex. of the add method you can easily read:

Throws:

UnsupportedOperationException - if the add operation is not supported
  by this collection

Therefore, while one can no longer see from the type itself, that the collection is immutable, you also do not have a type that clearly says it is mutable. In other words, Collection can be read as handle with care either way.


问:
Event-driven vs. 'reference'-driven programming (i.e. in JavaScript)
I haven't been able to find the appropriate terminology to search for content on the web related to what I'm asking, so I'm hoping someone on here can at least point me in the right direction.

I'm a fairly senior JavaScript developer, but I have a secret -- I don't like event-driven programming (aside from user-triggered event binding I mean). Something about it has never sat well with me, it's the feeling of a "disconnect" in the logic flow.

In the simple example of some module invoking arbitrary numbers of views, an event-driven friend would create event listeners for elements those views could have and keep any reference to the parent module out of the view code.

I, on the other hand, would pass reference to the parent module in to the views so that I could directly trigger the module's methods.

I go for the second approach because I know exactly what is going to happen and what method I'm triggering at all points in the code. In the event-driven case I'm separating the assignment of an event response from the element that would trigger it, putting things in to the 'listening ether'.

I know responsible event-driven programming should avoid any risks like double-binding, etc., but even when that care is taken I still see it all as a bit of a black-box ripe for debugging nightmares. While passing references may be a bit more cumbersome in the code, at least it's clear what things are going to happen and when.

Can anyone identify the pros and cons of these two methods, and in particular why JS seems to be pushing in general toward the event-driven stuff?

答:
Not sure what you mean with reference driven programming. From what I gather, you're wondering what the advantages of event-driven programming are as opposed to writing code, and then using a bunch of branches to determine when to call a given method.

Before I set off, allow me to be pedantic and point out that: a module can't listen for any event, nor can a button have a reference to a module. The button is part of the DOM, the module is JS. Both live in separate universes, and never the twain shall meet.

You can have the event loop pick up on certain events, and then invoke a given function object (either stand-alone, anonymous, or a function object that is part of a module) to handle that event, or you can mix JS into your markup, using certain html attributes (onclick="" and the like).

The latter method is generally said to be outdated, messy, and therefore bad practice. In this day and age, where OOP-buzzwords have found there way into the daily vocab of the average middle-manager, mixing JS in with markup isn't what I'd call separation of concern...

I see it like this:

JavaScript was originally intended to run client side. It's not been considered a valid server-side language for that long. It's small, light and portable, and was meant to make it easy to "liven up" your website. Making the UI responsive, move stuff around and, most importantly, load content dynamically using AJAX.

When talking about AJAX, I think you'll agree, event-driven programming is the better option: you request content, based on user input (clicks links, scrolls the page down etc...), and as you probably know: an ajax response is dealt with using an event handler (xhr.onreadystatechange = function).

Since then, we've come a long way, but some things have remained the same: JS is, in essence, a functional language, which implies closures, lambda's and callback functions to be used all over the place. The easiest way to make functional code work is to set all the functions up, and then let a change in the state (aka event) call one or more of these functions. Basically: functional languages feel at home in an event driven universe.

The expressive power of these constructs is huge, and so it stands to reason that with every new trick, technology or feature that gets added, the people developing the JS engines will tend to implement events to better support these new bells and whistles. Couple that to the fact that the main libs/toolkits will probably provide an API that requires you to pass around functions, and you end up with a bunch of developers who, when confronted with a problem, will look at it as a series of events, that they can tap into to respond accordingly.

So, I guess you might say that JS was designed to be event-driven to a rather large extent, and that the people who use it are "trained" if you will to think accordingly.

Another thing to consider is: how the engines work. V8, for example, is great at idling. If you run node.js, you'll see that it's perfectly happy, consuming very little resources, just sitting there, doing nothing. Once it receives a request (which is an event in a way), it'll wake up and set to work.

Event driven code does reflect this:

```<code>http.createServer(function(){}).listen();
</code>```

This script doesn't do anything, until the server "has to be there", then the function passed to createServer is invoked, and, you could say, becomes the server.

Back to the client-side:

You say you see the point of event binding with DOM elements, and responding to the user's actions. Well, that's what client-side JS does. Its main purpouse was (and is) to augment the user experience. Whatever code gets executed client side, should be triggered by an event.

The event could be the load event, or a click or change event... it doesn't matter. If the user isn't doing anything, JS shouldn't be busy. Some browsers kill a script if it's busy for too long anyway.

You ought to realize that picking up on changes, without using the event loop JS already has to offer, leaves you no real alternative than to write a busy loop: JS isn't meant to be a system language, so you could end up with: for(;;) or while(1) loops. If you then were to have a single event handler, owing to JS being single threaded, that handler can't ever get called, because the JS thread is always busy, claiming the CPU like there's no tomorrow.

I can't see how else you could set about your business, to be honest. Worker's? No, because they communicate only through events. setTimout and setInterval? Not really: it's a right hasstle to sort out the scope, it's error prone and expensive. Besides, an event probably translates to an interrupt at some lower level, as does an interval, or a timeout. What those do is, essentially the same thing as events, only: they're obtrusive, because they weren't initiated by the user, and they could block the UI.

The only "alternative" I can think of, and reading your question and comments again is what you're actually thinking of, is something along the following lines. The first is the reference driven example, the second is a quick translation of the same basic concept to event-driven programming:

```<code>var btnMod = (function(w)
{
    var nextOn = false,
    stopEvent = function(e)
    {
        e.returnValue = false;
        e.cancelBubble = true;
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        return false;
    },
    module = {};
    module.switch = function(e,elem)
    {
        e = e || w.event;
        //do stuff
        nextOn = !nextOn;//toggle bool
    };
    module.next = function(e,elem)
    {
        e = e || w.event;
        //do stuff
        if (nextOn) location.href = 'next-url';//for example
        else return stopEvent(e);
    };
    return module;
}(window));
</code>```

then either have markup like below, or bind the module methods to certain elements

```<code><li onclick="module.switch(event, this)">on/off</li>
<li onclick="module.next(event,this)">next</li>
</code>```

As opposed to doing something like

```<code>var btnMod = (function(w)
{
    var stopEvent = function(e)
    {
        e.returnValue = false;
        e.cancelBubble = true;
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        return false;
    },
    module = {};
    module.switch = function(e,elem)
    {
        e = e || w.event;
        w.removeEventListener('click', module.switch, false);
        w.addEventListener('click', module.next, false);
    };
    module.next = function(e,elem)
    {
        e = e || w.event;
        w.removeEventListener('click', module.next, false);//unbind to disable
        //do stuff
    };
    if (!nextOn) w.addEventListener('click', module.switch,false);
    else w.addEventListener('click', module.next, false);
}(window));
</code>```

Well, quite apart from the fact that event-driven code is lighter (only one listener is bound at a time), and less error prone (if the module.next listener is bound, the switch listener isn't), it also doesn't require JS to mixed in with JS. Given some more effort, it can also be written a lot shorter than the snippets I've posted here, and it's not littered with tons of if's and else's. it uses functions, which is what you do in a functional language

Bottom line:

The advantages of event-driven JS are simple, IMO: JS was intended to be used on the web, client-side. It was meant to enhance the user experience by making static pages responsive, and fetching content on-the-fly. All through events. Coupled with the functional paradigm, that makes for a rather expressive little language. To use it in any other way means using it in a way it wasn't designed to be used (excel).

If you don't use a hammer to fasten a screw if you have a screwdriver lying right next to it.

Likewise: you don't work around events, if there is an event readily available.

In the end, though, what's in a name?. If ever you write a standalone program in C, using the GTK+ lib, you'll use "events", too. C# is popular nowadays, guess what, it wont take many tutorials before you see the word "event" crop up. You want to react on some changes in state or user input? That's what we happen to call an event. Lastly: as svidgen pointed out: JS engines already have an event system written out. Good programmers are lazy: they don't go and write their own systems, if they can find an existing one that allows them to do what they need to do. Sure, sometimes you may find the existing systems lacking in some respect, and curse the people making it for not seeing that there might be a need for whatever you happen to need at that time, but that's life.

Personally, I'd say: if you don't like event-driven programming, you don't really like JS(?)

Body:
Not sure what you mean with reference driven programming. From what I gather, you're wondering what the advantages of event-driven programming are as opposed to writing code, and then using a bunch of branches to determine when to call a given method.

Before I set off, allow me to be pedantic and point out that: a module can't listen for any event, nor can a button have a reference to a module. The button is part of the DOM, the module is JS. Both live in separate universes, and never the twain shall meet.

You can have the event loop pick up on certain events, and then invoke a given function object (either stand-alone, anonymous, or a function object that is part of a module) to handle that event, or you can mix JS into your markup, using certain html attributes (onclick="" and the like).

The latter method is generally said to be outdated, messy, and therefore bad practice. In this day and age, where OOP-buzzwords have found there way into the daily vocab of the average middle-manager, mixing JS in with markup isn't what I'd call separation of concern...

I see it like this:

JavaScript was originally intended to run client side. It's not been considered a valid server-side language for that long. It's small, light and portable, and was meant to make it easy to "liven up" your website. Making the UI responsive, move stuff around and, most importantly, load content dynamically using AJAX.

When talking about AJAX, I think you'll agree, event-driven programming is the better option: you request content, based on user input (clicks links, scrolls the page down etc...), and as you probably know: an ajax response is dealt with using an event handler (xhr.onreadystatechange = function).

Since then, we've come a long way, but some things have remained the same: JS is, in essence, a functional language, which implies closures, lambda's and callback functions to be used all over the place. The easiest way to make functional code work is to set all the functions up, and then let a change in the state (aka event) call one or more of these functions. Basically: functional languages feel at home in an event driven universe.

The expressive power of these constructs is huge, and so it stands to reason that with every new trick, technology or feature that gets added, the people developing the JS engines will tend to implement events to better support these new bells and whistles. Couple that to the fact that the main libs/toolkits will probably provide an API that requires you to pass around functions, and you end up with a bunch of developers who, when confronted with a problem, will look at it as a series of events, that they can tap into to respond accordingly.

So, I guess you might say that JS was designed to be event-driven to a rather large extent, and that the people who use it are "trained" if you will to think accordingly.

Another thing to consider is: how the engines work. V8, for example, is great at idling. If you run node.js, you'll see that it's perfectly happy, consuming very little resources, just sitting there, doing nothing. Once it receives a request (which is an event in a way), it'll wake up and set to work.

Event driven code does reflect this:

http.createServer(function(){}).listen();

This script doesn't do anything, until the server "has to be there", then the function passed to createServer is invoked, and, you could say, becomes the server.

Back to the client-side:

You say you see the point of event binding with DOM elements, and responding to the user's actions. Well, that's what client-side JS does. Its main purpouse was (and is) to augment the user experience. Whatever code gets executed client side, should be triggered by an event.

The event could be the load event, or a click or change event... it doesn't matter. If the user isn't doing anything, JS shouldn't be busy. Some browsers kill a script if it's busy for too long anyway.

You ought to realize that picking up on changes, without using the event loop JS already has to offer, leaves you no real alternative than to write a busy loop: JS isn't meant to be a system language, so you could end up with: for(;;) or while(1) loops. If you then were to have a single event handler, owing to JS being single threaded, that handler can't ever get called, because the JS thread is always busy, claiming the CPU like there's no tomorrow.

I can't see how else you could set about your business, to be honest. Worker's? No, because they communicate only through events. setTimout and setInterval? Not really: it's a right hasstle to sort out the scope, it's error prone and expensive. Besides, an event probably translates to an interrupt at some lower level, as does an interval, or a timeout. What those do is, essentially the same thing as events, only: they're obtrusive, because they weren't initiated by the user, and they could block the UI.

The only "alternative" I can think of, and reading your question and comments again is what you're actually thinking of, is something along the following lines. The first is the reference driven example, the second is a quick translation of the same basic concept to event-driven programming:

var btnMod = (function(w)
{
    var nextOn = false,
    stopEvent = function(e)
    {
        e.returnValue = false;
        e.cancelBubble = true;
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        return false;
    },
    module = {};
    module.switch = function(e,elem)
    {
        e = e || w.event;
        //do stuff
        nextOn = !nextOn;//toggle bool
    };
    module.next = function(e,elem)
    {
        e = e || w.event;
        //do stuff
        if (nextOn) location.href = 'next-url';//for example
        else return stopEvent(e);
    };
    return module;
}(window));

then either have markup like below, or bind the module methods to certain elements

<li onclick="module.switch(event, this)">on/off</li>
<li onclick="module.next(event,this)">next</li>

As opposed to doing something like

var btnMod = (function(w)
{
    var stopEvent = function(e)
    {
        e.returnValue = false;
        e.cancelBubble = true;
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        return false;
    },
    module = {};
    module.switch = function(e,elem)
    {
        e = e || w.event;
        w.removeEventListener('click', module.switch, false);
        w.addEventListener('click', module.next, false);
    };
    module.next = function(e,elem)
    {
        e = e || w.event;
        w.removeEventListener('click', module.next, false);//unbind to disable
        //do stuff
    };
    if (!nextOn) w.addEventListener('click', module.switch,false);
    else w.addEventListener('click', module.next, false);
}(window));

Well, quite apart from the fact that event-driven code is lighter (only one listener is bound at a time), and less error prone (if the module.next listener is bound, the switch listener isn't), it also doesn't require JS to mixed in with JS. Given some more effort, it can also be written a lot shorter than the snippets I've posted here, and it's not littered with tons of if's and else's. it uses functions, which is what you do in a functional language

Bottom line:

The advantages of event-driven JS are simple, IMO: JS was intended to be used on the web, client-side. It was meant to enhance the user experience by making static pages responsive, and fetching content on-the-fly. All through events. Coupled with the functional paradigm, that makes for a rather expressive little language. To use it in any other way means using it in a way it wasn't designed to be used (excel).

If you don't use a hammer to fasten a screw if you have a screwdriver lying right next to it.

Likewise: you don't work around events, if there is an event readily available.

In the end, though, what's in a name?. If ever you write a standalone program in C, using the GTK+ lib, you'll use "events", too. C# is popular nowadays, guess what, it wont take many tutorials before you see the word "event" crop up. You want to react on some changes in state or user input? That's what we happen to call an event. Lastly: as svidgen pointed out: JS engines already have an event system written out. Good programmers are lazy: they don't go and write their own systems, if they can find an existing one that allows them to do what they need to do. Sure, sometimes you may find the existing systems lacking in some respect, and curse the people making it for not seeing that there might be a need for whatever you happen to need at that time, but that's life.

Personally, I'd say: if you don't like event-driven programming, you don't really like JS(?)