问:
Javascript and web application data
I am pretty new to Web Application programming and so to OOP Javascript and the new Client-Server interactions.
I am encountering some trouble wondering about how much AJAX I should use or how much data I have to save "locally" .
Explainig it better: at the moment , to manage the data that I obtain from AJAX request , I push them in Data Structure like Array's and then I handle them helping myself rendering html through template.
Now, was I wondering : is all this necessary? Do I really need to store all this data in Data Structures or I can make AJAX call for every action users do on my application?
I apologize for the explanation but it's a difficult concept for me to explain in English.
Thanks in advance

答:
Going out to separate pages for simple small pieces data is much MUCH slower than referencing it locally. On the other hand, storing too much locally can start causing major issues as well.

If all you want to do is store a few user specific variables, then do it locally. If you want to access and parse entire data dumps with hundreds of rows with tens of columns, do that server-side with AJAX.

It's all about balance. Think of it this way:

I store all my pens at my desk in a cup. I just use them to write and take notes, I have black, blue, red, and a pencil. This works well anything more would just be a hassle.

But say I was a professional artist who needed hundreds or thousands of different pens and pencils of different types, storing all of this on my desk in cups would be a mess and inefficient. I would need to store them in boxes something where I could easily move around and find what I needed, even if I used them constantly this method would still be much more efficient than if I was to just put them all in cups on my desk.

Hope that makes sense.

Title: Javascript and web application data


答:
It is not cut and dry but it should be a simple rule of thumb.  If the page "needs" the data then embed it in the page.  Needs would mean that no matter what action the user does the data is needed to perform that action.

For example the page is a grid that has a list of orders, the order data is needed to populate the grid which is the only item on the screen.  It would make sense to embed the data. Now if the user clicks a row and a popup appears with more data that should probably be done with an ajax request cause the user may or may not see the popup.

The only situation where I wouldn't embed the page when it is need would be if the data takes a very long time to generate.  No user would tolerate a url request that takes 5+ seconds to come back.  A quick response and a loading mask would be more acceptable.

ContentLicense: CC BY-SA 3.0

Title: Javascript and web application data

Body:
I am pretty new to Web Application programming and so to OOP Javascript and the new Client-Server interactions.
I am encountering some trouble wondering about how much AJAX I should use or how much data I have to save "locally" .
Explainig it better: at the moment , to manage the data that I obtain from AJAX request , I push them in Data Structure like Array's and then I handle them helping myself rendering html through template.
Now, was I wondering : is all this necessary? Do I really need to store all this data in Data Structures or I can make AJAX call for every action users do on my application?
I apologize for the explanation but it's a difficult concept for me to explain in English.
Thanks in advance


问:
Introducing Fowler's Table Data Gateway to refactor poorly designed systems
I am developing an application, which currently has about 150,000 lines of code.  The previous developer didn't really use any discipline when writing code. Application is in production but is continually developed.

I have read Martin Fowler's book (Patterns of Enterprise Application Architecture) and it talks about 'Transaction Scipt' and 'Data Access Objects'.  These are the patterns used i.e. there is a class called Person, which contains everything Person related and a class called Order with everything Order related.  The functions are not reusable because they contain everything i.e. data access logic, business logic etc.  For example, Person.GetPerson will connect to the database find the person, check the age of the person, get all the orders linked to the person etc.

I am thinking about introducing what Martin Fowler terms a Table Data Gateway.  I am seeing this as a longer term refactor project.  The problem is that this will mean inconsistency to begin with i.e. data access logic will be contained in the new Gateway, but also in the Transaction Script classes (where the other developer put it)? Is it a bad idea to go against the original developers style of coding?

答:
According to Patterns of Enterprise Application Architecture, you can use a Table Data Gateway with the Transaction Script pattern (see the "When To Use It" section of the Table Data Gateway pattern).  So your approach seems like a pretty conservative way to move towards better code without radically changing the original style all at once - which is a good thing.

The refactoring should be pretty straightforward as well - you are just going to pull the database logic in the Person class into a PersonGateway class.  Admittedly you can't simultaneously refactor all the Transaction Script classes, but that's unavoidable.  You probably won't even have to break their API, so I wouldn't worry too much about the fact that for a while some scripts will use gateway classes and some won't.

I think making that change is a better approach than not making it.


问:
Does anyone prefer proportional fonts?
I was reading the wikipedia article on programming style and noticed something in an argument against vertically aligned code:

Reliance on mono-spaced font; tabular
  formatting assumes that the editor
  uses a fixed-width font. Most modern
  code editors support proportional
  fonts, and the programmer may prefer
  to use a proportional font for
  readability.

To be honest, I don't think I've ever met a programmer who preferred a proportional font.  Nor can I think of any really good reasons for using them.  Why would someone prefer a proportional font?

答:
Common points against proportional fonts, commented.

You cannot precisely align code vertically with proportional fonts. I mean, you could precisely align code vertically with proportional fonts, if everybody was using elastic tabstops, but alas...

Some proportional fonts make it hard to distinguish some characters groups. (e.g., mrnm). Not all programming fonts are perfect either, however: Courier New has identical 'O' and '0' and identical '1' and 'l'.

Some IDEs have poor support for non-fixed-width fonts (like aforementioned Visual Studio or Python's IDLE). In some contexts, also, you just can't use one. (e.g., terminals.)

Choosing a proportional font for coding will get you in endless holy wars. Here, however, the problem exists between the keyboard and the chair.

Points in favour of proportional fonts

Some characters are just wider than others. Having to cram an m in the same space of an n or an i makes it truly challenging to design a good, readable monospace font.

Improved spacing between letters just right. Compare rnW and Ill in this Proggy Clear screenshot for an example of font spacing done wrong.

Most programmer fonts lack italic or bold. This makes it hard to use effective syntax highlighting.

Vertical alignment is a can of worms anyway. Tabs or spaces or tabs and spaces?

Personally, I've been using both the 'Ubuntu' font and WenQuanYi Zen Hei Mono with pleasure and find myself unable to prefer one to the other. :)

Ubuntu 10 and WenQuanYi Zen Hei Mono 9, compared. There's no clear winner here, if you ask me.

That said, fonts are like food. Some like them well rounded, some like them hot and spicy --  there's no one right font, or all of us would be using it right now. Yay for choice!

ContentLicense: CC BY-SA 2.5

Title: Does anyone prefer proportional fonts?


问:
Extracting domain logic from the forms to which they are coupled?
Many applications do nothing to separate the interface from domain logic.  I’ve been programming for a couple decades and have worked at more than a dozen shops and none of them have taken any measure of separating the interface from the domain logic.  That is, they're all using the Autonomous View pattern.   This runs counter to all the wisdom I’ve read about separating concerns.  When the user needs to choose an item from a set of items, that selection is directly tied to a combo box rather than an abstraction.

A huge drawback with all this coupling is that it makes it impossible to write unit tests.  To run any unit tests the application in its entirety must first be loaded.  In my mind, the use case should be encapsulated within an abstraction that can later have a database and an interface attached to it.  This kind of separation would make implementing unit tests trivial by comparison.

Given that the average shop has its interface and domain logic tightly coupled, how to we refactor to separation?  That is, a complete rewrite is off the table. What I’m talking about is taking a proposal to management about how to go about creating domain objects (whatever these happen to look like) that live in isolation from the database and the interface. In other words, it would be useful to be able to explain how this concept of presenting the user with a choice (something that is now represented by combos on forms) and to see how some methodology/framework/pattern represents that in an abstract sense and how that abstraction is then tied to the interface.  This would make replacing combos with listboxes nothing more than a slight detail.

What are some good ways for extracting abstractions (domain use cases) from forms?  Any good online resources?  My current shop is on .NET, though I am interested in ideas from any development platform.  Ultimately, what I need to provide is a concrete example (code) of how this might be accomplished.

答:
There are a variety of presentation patterns whose exact role is to split out the interface from the behaviour.

Since you specifically mention a Microsoft environment, I would recommend you look up MVVM (which is promoted with particular reference to WPF) and MVC (which is promoted re ASP.NET). Microsoft's MVC approach is a physical framework based closely on the generic MVC pattern - it breaks a few abstractions but auto-produces code for you.

A further approach, also promoted by Microsoft until they jumped on the WPF bandwagon, is the MVP pattern.

In theory all three of these patterns, being patterns, are applicable arcoss any platform. But MVVM was definitely developed with WPF in mind, and as I say Microsoft's implementation of MVC deviates from the "pure" a little.

There are more, but as I say they're all broadly aimed at pulling logic out of the UI layer. Martin Fowler's web site is a decent reference here.


问:
Are there any industry standards that define code quality?
Our specific situation is that we are creating an agreement between ourselves and another team for shared control or use of a PHP based web application that we have been building.    We have a set of standards and conventions documented in our technical specs.  However, I have been asked to define them in terms of an industry standard.

I am aware of different terminology for coding conventions. Hungarian notation, CamelCase, for example. And some defined standards for very specific things, PSR-0 for example covers namespaces in PHP.

It seems the point is to try to give us stronger ground in the agreement, by pointing to industry standards rather than an arbitrary standard we set forth.  They're looking for things like the PSR-0 or an ISO#### or IEEE#### that we can point to.

My personal concern is that I've spent the time working with the team to show them the standards we have and to get buy in on the bigger parts of it. So I'm worried we'll either end up having to conform to some standard that doesn't match how we like to program, or the better case will be picking and choosing pieces of standards if they exist, to fit our current conventions.

Anyway, the core of the question is, Are there any industry standards regarding code quality, coding processes, or other areas that would help us keep their programmers from making disruptive or difficult to maintain code?  I realize we can't prevent it, but if we can point to the agreement, at least we have recourse other than refactoring or recoding it ourselves.

Any other thoughts or suggestions would be helpful.

答:
Industry standards are subjective.  The field is so full of competing ideas that you can always find someone who will prefer another approach over even those that are recommended in some manifesto.  What matters is consistency within the organization.  That trumps industry standards.

The reason being is that sometimes organizations have good cause to take a less favored approach.  For example, I have worked on a lot of government contracts.  The government has a tough time attracting and keeping top-tier developers.  As such it tries to code in a very general, entry-level developer kind of manner.  They want it to be easy to bring in new developers.  They also want it to be easy for developers to move between projects.  Thus, they try to keep the coding style across projects homogeneous and explicit.  By explicit I mean they favor coding things outs vs. having things magically happen (look at an ActiveRecord definition in Rails and you'll know exactly what I mean by "magic").

No two organizations have the exact same priorities.  As such, there may be good reasons for their standards to vary.  Consistency is what matters.


问:
Naming functions that retrieve a value
I have this personal rule to start all function/method names with a verb. My verb of choice for functions or methods that get a value based on some data structure or object is get. I'm wondering if that's a good idea.

The good thing about get is that it doesn't really say anything about how that value is being retrieved, just get it. Something like calculate (apart from being awfully long) may be too much information.

This applies to both functions and methods, i.e.:

```<code>float get_magnitude(Vector2d vector)
{
    return sqrt(pow(vector.x, 2), pow(vector.y, 2));
}
</code>```

or

```<code>float Vector2d::get_magnitude() const
{
    return sqrt(pow(x, 2), pow(y, 2));
}
</code>```

On the other hand, I sometimes end up with getter methods for read-only properties. It may make sense to use a more meaningful verb for anything that doesn't just return some property, and may not run in linear time.

Is there a case to be made for either approach or is it just a matter of taste?

答:
This is such a great question, i am dealing with similar issues right now! At this point i am trying to learn clean code techniques for naming - methods should be named well enough to make comments unnecessary.

However there is more then one great way to name something. So now i am looking at a working application with a bunch of classes and clear names. But they aren't completely consistent and that would make the app more clear.

I've been using get alot recently. For me its only 3 letters, it looks good in camel case, and it makes it crystal clear what is happening. there is no ambiguity with getProductBy($id). Also for me with get - there is an important hint that we might not get the result back. There might be an error with the database, etc etc etc.

So getProductBy($id) also issues a warning to the application flow - we are going to try and get a Product by id, AND it might fail so there has to be error control for whatever happens next.

Title: Naming functions that retrieve a value


问:
Why is 0 false?
This question may sound dumb, but why does 0 evaluates to false and any other [integer] value to true is most of programming languages?

String comparison

Since the question seems a little bit too simple, I will explain myself a little bit more: first of all, it may seem evident to any programmer, but why wouldn't there be a programming language - there may actually be, but not any I used - where 0 evaluates to true and all the other [integer] values to false? That one remark may seem random, but I have a few examples where it may have been a good idea. First of all, let's take the example of strings three-way comparison, I will take C's strcmp as example: any programmer trying C as his first language may be tempted to write the following code:

if (strcmp(str1, str2)) { // Do something... }
```

<p>Since <code>strcmp</code> returns <code>0</code> which evaluates to <code>false</code> when the strings are equal, what the beginning programmer tried to do fails miserably and he generally does not understand why at first. Had <code>0</code> evaluated to <code>true</code> instead, this function could have been used in its most simple expression - the one above - when comparing for equality, and the proper checks for <code>-1</code> and <code>1</code> would have been done only when needed. We would have considered the return type as <code>bool</code> (in our minds I mean) most of the time.</p>

<p>Moreover, let's introduce a new type, <code>sign</code>, that just takes values <code>-1</code>, <code>0</code> and <code>1</code>. That can be pretty handy. Imagine there is a spaceship operator in C++ and we want it for <code>std::string</code> (well, there already is the <code>compare</code> function, but spaceship operator is more fun). The declaration would currently be the following one:</p>

<pre class="lang-cpp prettyprint-override"><code>sign operator<=>(const std::string& lhs, const std::string& rhs);
</code>```

Had 0 been evaluated to true, the spaceship operator wouldn't even exist, and we could have declared operator== that way:

sign operator==(const std::string& lhs, const std::string& rhs);
```

<p>This <code>operator==</code> would have handled three-way comparison at once, and could still be used to perform the following check while still being able to check which string is lexicographically superior to the other when needed:</p>

<pre class="lang-cpp prettyprint-override"><code>if (str1 == str2) { // Do something... }
</code>```

Old errors handling

We now have exceptions, so this part only applies to the old languages where no such thing exist (C for example). If we look at C's standard library (and POSIX one too), we can see for sure that maaaaany functions return 0 when successful and any integer otherwise. I have sadly seen some people do this kind of things:

#define TRUE 0
// ...
if (some_function() == TRUE)
{
    // Here, TRUE would mean success...
    // Do something
}
```

<p>If we think about how we think in programming, we often have the following reasoning pattern:</p>

<pre class="lang-none prettyprint-override"><code>Do something
Did it work?
Yes ->
    That's ok, one case to handle
No ->
    Why? Many cases to handle
</code>```

If we think about it again, it would have made sense to put the only neutral value, 0, to yes (and that's how C's functions work), while all the other values can be there to solve the many cases of the no. However, in all the programming languages I know (except maybe some experimental esotheric languages), that yes evaluates to false in an if condition, while all the no cases evaluate to true. There are many situations when "it works" represents one case while "it does not work" represents many probable causes. If we think about it that way, having 0 evaluate to true and the rest to false would have made much more sense.

Conclusion

My conclusion is essentially my original question: why did we design languages where 0 is false and the other values are true, taking in account my few examples above and maybe some more I did not think of?

Follow-up: It's nice to see there are many answers with many ideas and as many possible reasons for it to be like that. I love how passionate you seem to be about it. I originaly asked this question out of boredom, but since you seem so passionate, I decided to go a little further and ask about the rationale behind the Boolean choice for 0 and 1 on Math.SE :)

答:
Ultimately, you are talking about breaking the core language because some APIs are crappy. Crappy APIs are not new, and you can't fix them by breaking the language. It is a mathematical fact that 0 is false and 1 is true, and any language which does not respect this is fundamentally broken. The three-way comparison is niche and has no business having it's result implicitly convert to bool since it returns three possible results. The old C APIs simply have terrible error handling, and are also hamstrung because C does not have the necessary language features to not have terrible interfaces.

Note that I am not saying that for languages which do not have implicit integer->boolean conversion.

Title: Why is 0 false?


答:
Because the math works.

```<code>FALSE OR TRUE is TRUE, because 0 | 1 is 1.

... insert many other examples here.
</code>```

Traditionally, C programs have conditions like

if (someFunctionReturningANumber())
```

<p>rather than</p>

<pre class="lang-c prettyprint-override"><code>if (someFunctionReturningANumber() != 0)
</code>```

because the concept of zero being equivalent to false is well-understood.

Title: Why is 0 false?

Body:
This question may sound dumb, but why does 0 evaluates to false and any other [integer] value to true is most of programming languages?

String comparison

Since the question seems a little bit too simple, I will explain myself a little bit more: first of all, it may seem evident to any programmer, but why wouldn't there be a programming language - there may actually be, but not any I used - where 0 evaluates to true and all the other [integer] values to false? That one remark may seem random, but I have a few examples where it may have been a good idea. First of all, let's take the example of strings three-way comparison, I will take C's strcmp as example: any programmer trying C as his first language may be tempted to write the following code:

if (strcmp(str1, str2)) { // Do something... }
```

<p>Since <code>strcmp</code> returns <code>0</code> which evaluates to <code>false</code> when the strings are equal, what the beginning programmer tried to do fails miserably and he generally does not understand why at first. Had <code>0</code> evaluated to <code>true</code> instead, this function could have been used in its most simple expression - the one above - when comparing for equality, and the proper checks for <code>-1</code> and <code>1</code> would have been done only when needed. We would have considered the return type as <code>bool</code> (in our minds I mean) most of the time.</p>

<p>Moreover, let's introduce a new type, <code>sign</code>, that just takes values <code>-1</code>, <code>0</code> and <code>1</code>. That can be pretty handy. Imagine there is a spaceship operator in C++ and we want it for <code>std::string</code> (well, there already is the <code>compare</code> function, but spaceship operator is more fun). The declaration would currently be the following one:</p>

<pre class="lang-cpp prettyprint-override"><code>sign operator<=>(const std::string& lhs, const std::string& rhs);
</code>```

Had 0 been evaluated to true, the spaceship operator wouldn't even exist, and we could have declared operator== that way:

sign operator==(const std::string& lhs, const std::string& rhs);
```

<p>This <code>operator==</code> would have handled three-way comparison at once, and could still be used to perform the following check while still being able to check which string is lexicographically superior to the other when needed:</p>

<pre class="lang-cpp prettyprint-override"><code>if (str1 == str2) { // Do something... }
</code>```

Old errors handling

We now have exceptions, so this part only applies to the old languages where no such thing exist (C for example). If we look at C's standard library (and POSIX one too), we can see for sure that maaaaany functions return 0 when successful and any integer otherwise. I have sadly seen some people do this kind of things:

#define TRUE 0
// ...
if (some_function() == TRUE)
{
    // Here, TRUE would mean success...
    // Do something
}
```

<p>If we think about how we think in programming, we often have the following reasoning pattern:</p>

<pre class="lang-none prettyprint-override"><code>Do something
Did it work?
Yes ->
    That's ok, one case to handle
No ->
    Why? Many cases to handle
</code>```

If we think about it again, it would have made sense to put the only neutral value, 0, to yes (and that's how C's functions work), while all the other values can be there to solve the many cases of the no. However, in all the programming languages I know (except maybe some experimental esotheric languages), that yes evaluates to false in an if condition, while all the no cases evaluate to true. There are many situations when "it works" represents one case while "it does not work" represents many probable causes. If we think about it that way, having 0 evaluate to true and the rest to false would have made much more sense.

Conclusion

My conclusion is essentially my original question: why did we design languages where 0 is false and the other values are true, taking in account my few examples above and maybe some more I did not think of?

Follow-up: It's nice to see there are many answers with many ideas and as many possible reasons for it to be like that. I love how passionate you seem to be about it. I originaly asked this question out of boredom, but since you seem so passionate, I decided to go a little further and ask about the rationale behind the Boolean choice for 0 and 1 on Math.SE :)

Body:
Because the math works.

FALSE OR TRUE is TRUE, because 0 | 1 is 1.

... insert many other examples here.

Traditionally, C programs have conditions like

if (someFunctionReturningANumber())

rather than

if (someFunctionReturningANumber() != 0)

because the concept of zero being equivalent to false is well-understood.


问:
I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?
My day job is  java/web developer. I have been using eclipse for ~5years. I think its excellent and I also use Webstorm for javascript and html/jsp.

I do on occasion need to ssh into server and mess around with config files; for this I use vi and it pains me. I have to get up a webpage listing the syntax/commands : press escape, then asterix, turn around three times and the text will be entered two lines above your cursor. Its so unintuitive to me, and I imagine anyone who grew up in the late eighties nineties.

Here are the main reasons I think eclipse is brilliant(and I assume other IDE's), and do not switch to emacs and/or vim.

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

availablity of 3rd party plugins - eg
findbugs/checkstyle.

One of the arguments I hear is that with emacs/vim you can create your own plugins - well OK, but you can do that in eclipse too. But you don't need to as everything is already there!  Its like saying buy this half built car, you can build the rest yourself.

Why are people using emacs/vim ? Do people who use it actually work on complex object-oriented projects in large organisations ?

What are the reasons to switch to vim/emacs. How would my productivity increase if I did switch?

答:
I have no problem with the various UNIX editors available, but I only ever use them under protest. Not, as I say, because I have an issue with them but because if I'm having to use them it means that our deployment process is in some way lacking.

This probably deserves a little more context: I work on large-scale e-commerce solutions, everything that governs the running of our systems is generated by a one-click build/deploy process. We have an array of test environments so at any given time I can make a change via Eclipse, check it into cvs and trigger a build/deploy to prove that my fix has worked. So- if I'm hacking around in 'vi' then it's because we can't wait for the 1-hour turnaround of a deployment or because the deployment doesn't cover the files I'm editing and needs to be extended to do so (otherwise I'll be hacking in vi the next time the file in question needs changing).


答:
As others have said, the math came first. This is why 0 is false and 1 is true.

Which math are we talking about? Boolean algebras which date from the mid 1800s, long before digital computers came along.

You could also say that the convention came out of propositional logic, which even older than boolean algebras. This is the formalization of a lot of the logical results that programmers know and love (false || x equals x, true && x equals x and so on).

Basically we're talking about arithmetic on a set with two elements. Think about counting in binary. Boolean algebras are the origin of this concept and its theoretical underpinning. The conventions of languages like C are just a straightforward application.

Title: Why is 0 false?


问:
How should test for a "for any different than x return false" requirement look like
I tried to find if there's a similar question but didn't even know what keywords should I use :)

I got a method in an interface accepting an other interface as a parameter:

```<code>bool CanDoIt(AnInterface subject)
</code>```

One of the implementations needs to fulfill the requirement that the method should return false for all concrete types (implementing AnInterface) different than X.

Simple implementation could look like (didn't wrote it since got no UT for that):

```<code>bool CanDoIt(AnInterface subject)
{
    if(!(subject is X)) return false;
    else ...
}
</code>```

I know that this is a code smell accepting an interface and then checking it's concrete type - unfortunately for now I got to stick with it.

I would like to write a test that would check if the requirement is implemented correctly. So that test would fail if someone would ever add a new type implementing AnInterface and changed the method not to meet the requirement.

If writing such a test isn't possible then what can I do to consider the coded tested? Would writing a test using few exemplary types would be enough, or is it better not to write it at all?

答:
I don't think you can, because someone can easily write

```<code>bool CanDoIt(AnInterface subject)
{
    if(!(subject is X || subject is Y)) return false;
    else ...
}
</code>```

and you don't know in advance about the new class Y.

Merely calling CanDoIt(someBogusClassThatImplementsAnInterface) would still fail

You should still call CanDoIt(someBogusClassThatImplementsAnInterface) to ensure someone doesn't simply remove the type check within CanDoIt(), but to get complete coverage you're going to have to remove the code smell and require CanDoIt() only accept X instead of anything that implements the interface.  Since you've noted this is not an option, you're pretty much stuck.

Body:
I don't think you can, because someone can easily write

bool CanDoIt(AnInterface subject)
{
    if(!(subject is X || subject is Y)) return false;
    else ...
}

and you don't know in advance about the new class Y.

Merely calling CanDoIt(someBogusClassThatImplementsAnInterface) would still fail

You should still call CanDoIt(someBogusClassThatImplementsAnInterface) to ensure someone doesn't simply remove the type check within CanDoIt(), but to get complete coverage you're going to have to remove the code smell and require CanDoIt() only accept X instead of anything that implements the interface.  Since you've noted this is not an option, you're pretty much stuck.


答:
You can't fix your design problem with testing.

You could write a test for every known implementation of AnInterface. When someone creates a new implementation, they would write a new test for CanDoIt.

It looks like CanDoIt should be a method on AnInterface. If you can, I suggest that you create aCanDoIt method on AnInterface and have your method delegate to AnInterface.

Title: How should test for a "for any different than x return false" requirement look like

Body:
I tried to find if there's a similar question but didn't even know what keywords should I use :)

I got a method in an interface accepting an other interface as a parameter:

```<code>bool CanDoIt(AnInterface subject)
</code>```

One of the implementations needs to fulfill the requirement that the method should return false for all concrete types (implementing AnInterface) different than X.

Simple implementation could look like (didn't wrote it since got no UT for that):

```<code>bool CanDoIt(AnInterface subject)
{
    if(!(subject is X)) return false;
    else ...
}
</code>```

I know that this is a code smell accepting an interface and then checking it's concrete type - unfortunately for now I got to stick with it.

I would like to write a test that would check if the requirement is implemented correctly. So that test would fail if someone would ever add a new type implementing AnInterface and changed the method not to meet the requirement.

If writing such a test isn't possible then what can I do to consider the coded tested? Would writing a test using few exemplary types would be enough, or is it better not to write it at all?


答:
Some unit-testing systems allow you to add a unit test on an interface, with the testing system running that test on any class which implements that interface.  On such a system, you could just write a test which calls CanDoIt and asserts that either it returned false or that AnInterface is X.  A similar "test" would be, if using a contract framework, to add a contract like Contract.Promises(Contract.ReturnValue == (subject is X)); to CanDoIt.

If your system does not support either of these strategies, you may be better off asking a test-framework specific version of this question (on SO).


问:
balancing old cases with agile practices
My team is just getting started integrating agile practices (we've chosen kanban) into our dev, test and design teams, but we have a lot of bug cases and feature cases not written in user stories left over from the old system and we're trying to find a good way to take care of the bugs but still keep the devs that need to stay heads down focused. for now we have a newer dev assigned to bug fixes so the rest can work on new features but we are looking for the right way to structure the team. We have 7 devs, 2 testers and 2 designers.

Thanks in advance for the help :)

答:
What you are maybe missing is a clearly prioritized backlog and proper WIP limits (work in progress limits).

First, assuming you are starting out using 3 states (Open/Backlog, In Progress, Done) the team needs to have a way of pulling items from the backlog according to the priorities set out by the product owner. It does not matter whether or not these are leftovers from the pre-agile time. Everything has to be prioritized against everything else, right? So assemble your backlog, giving the team the possibility to choose from the top of the backlog. It also does not matter whether or not the items are rough sketched bug descriptions or fully blown stories, what matters is that you have some kind of visualized representation of the idea of the product owner that the team can work with it. Transition to a more formalized way of defining these wishes on the way (until you end up with only proper bugs and stories in the end). Bugs are a fact of life in software development, so just treat them as stories when prioritizing.

Second, tell the team to come up with a maximum number of items that they would like to have in progress at the same time and let the team define this as their initial WIP limit. This value can be adjusted over time depending on the way it works out for you.

It also seems as if you think you know best how the team should organize their work (assign one new developer on bugs, keep others focused). I have seen this kind of behavior before and usually it is a sign of dysfunctional behavior. The team should know best how they solve the items on the Kanban board, provided they act and think as a team. This way they can maximize the throughput and utilize everyone to the best of his/her abilities. Interference from outside (micro-management and alike) can hurt the team. This said, there is always two sides of the story, as teams must grow and might need proper guidance to achieve a certain quality where agile practices work effectively. If they have problems splitting up the work this is something that can be addressed as part of retrospectives/feedback loops that are essential to improve things like the distribution of work for example.

Remember that Kanban is based on letting the team pull rather than pushing items onto the team. Finally, should you fail with the one big team approach, you and your team can always consider splitting up the team into several smaller teams, each having own Kanban processes and workflows with individual boards, tailored to the specific team's needs (e.g. a bugfixing team, feature team, tester team). In the end, you and your development team must govern the process, not the other way round.


问:
Is Domain Entity violating Single Responsibility Principle?
Single responsibility ( reason to change ) of an entity should be to uniquely identify itself, in other words, its responsibility is to be findable.

Eric Evan's DDD book, pg. 93:

most basic responsibility of Entities is to establish continuity so
  that behavior can be clear and predictable. They do this best if they
  are kept spare. Rather than focusing on the attributes or even the
  behavior, strip the Entity object's definition down to the most
  intrinsic characteristics, particularly those that identify it or are
  commonly used to find or match it. Add only behavior that is essential
  to the concept and attributes that are required by that behavior.

Beyond that, look to remove behavior and attributes into other objects
  associated with the core Entity .Beyond identity issues, Entities tend
  to fulfill their responsibilities by coordinating the operations of
  objects they own.

1.

... strip the ENTITY object's definition down to the most intrinsic
  characteristics, particularly those that identify it or are commonly
  used to find or match it. Add only behavior that is essential to the
  concept ...

Once an entity is assigned a unique ID, its identity is established and so I would assume such  an entity doesn't need any behavior to maintain its identity or to help it identify itself. Thus, I don't understand what kind of behavior is author referring to ( besides find and match operations ) with "behavior that is essential to the concept"?

2.

... strip the ENTITY object's definition down to the most intrinsic
  characteristics, particularly those that identify it or are commonly
  used to find or match it. ... Beyond that, look to remove behavior and
  attributes into other objects associated with the core ENTITY.

So any behavior that doesn't help identify the entity, but we'd still characterize that behavior as being an intrinsic characteristic of that entity ( i.e. barking is intrinsic to dogs, flying is intrinsic to airplanes, laying eggs is intrinsic to birds ... ), should be put into other objects associated with that entity ( example: we should put barking behavior into an object associated with a dog entity )?

3.

Beyond that, look to remove behavior and attributes into other objects
  associated with the core ENTITY.

a) MyEntity delegates responsibilities A_resp and B_resp to objects a and b, respectively.

Even though most of A_resp and B_resp work is done by a and b instances, clients are still served A_resp and B_resp through MyEntity, which means that from the client's perspective the two responsibilities belong to MyEntity. Thus, doesn't that mean MyEntity also has A_resp and B_resp responsibilities and as such is violating SRP?

b) Even if we assume that A_resp and B_resp don't belong to MyEntity, MyEntity still has a responsibility AB_resp of coordinating the operations of objects a and b. So doesn't MyEntity violate SRP since at minimum it has two responsibilities – to uniquely identify itself and also AB_resp?

```<code>class MyEntity
{
    private A a = ...
    private B b = ...

    public A GetA()
    { ... }

    public B GetB()
    { ... }

    /* coordinates operations of objects a and b */
    public int AworkB()
    { ... }
}

/* A encapsulates a single responsibility resp_A*/
/* A is value object */
class A
{ ... }

/* B encapsulates a single responsibility resp_B*/
/* B is value object */
class B
{ ... }
</code>```

UPDATE:

1.

Behavior in this context is refering to semantic behavior. For
  example, a Property on a class (i.e. attribute on a domain object)
  that is used to uniquely identify it has a behavior. While this is not
  represented in code directly. The expected behavior is that there will
  not be any duplicate values for that property.

So in code we would almost never need to actually implement a behavior ( i.e. an operation ) that would somehow maintain entity's identity, since as you explained such a behavior only exist as a concept in a domain model ( in the form of a ID attribute of an entity), but when we translate this ID attribute into code, part of its semantics is lost ( i.e. the part which implicitly makes sure the ID value is unique is lost )?

2.

Furthmore, a property such as Age has no context outside of a Person
  Entity, and as such, makes no sense to move into a different object
  ... However that information could easily be stored in a separate
  location that the unique identifier, hence the confusing reference to
  behavior. Age could be a lazy loaded value.

a) If Age property is lazy loaded, then we may call it a behavior, even though semantically Age is just an attribute?

3.

You could easily have operations specific to Address such as
  verification that it is a valid address. You may not know that at
  design time, but this whole concept is to break down objects into
  their smallest parts

While I agree that we'd lose context by moving Age into different object, the context wouldn't be lost if we moved DateOfBirth property into a different object, but we usually don't move it.

What is the main reason that we'd move Address into another object, but not DateOfBirth? Because DateOfBirth is more intrinsic to Person entity or because there are less chances that somewhere in the future we may need to define operations specific to DateOfBirth?

4.
I must say I still don't know whether MyEntity also has A_resp and B_resp responsibilities and why MyEntity also having AB_resp isn't considered a violation of SRP

EULERFX

1)

The behaviors that the author is referring to are behaviors associated
  with the entity. These are the behaviors that modify the state of the
  entity

a) If I understand you correctly, you're saying that entity should only contain those behaviors that modify its attributes ( i.e. its state )?

b) And what about the behaviors that don't necessarily modify the state of the entity, but are still  considered as being an intrinsic characteristic of that entity ( example: barking would be intrinsic characteristic of a Dog entity, even if it didn't modify Dog's state )? Should we include these behaviors in an entity or should they be moved to other objects?

2)

As far as moving behavior to other objects, the author is referring to
  value objects specifically.

Though my quote doesn't include it, but author does mention in the same paragraph  that in some cases behaviors ( and attributes ) will also get moved into other entities ( though I understand the benefits of moving behaviors to VOs )

3) Assuming MyEntity ( see question 3. in my original post ) doesn't violate SRP, would we say that a responsibility of MyEntity is among other things also comprised of:

a. A_resp + B_resp + AB_resp ( AB_resp coordinates objects a and b )

or

b.  AB_resp + delegating A_resp and B_resp to objects ( a and b ) associated with MyEntity?

4)
Eric Evan's DDD book, pg. 94:

CustomerID is the one and only identifier of the Customer ENTITY (
  figure 5.5 ), but  phone number and address would often be used to
  find or match a Customer. The name does not define a person's
  identity, but it is often used as part of the means of determining it.

In this example, the phone and address attributes moved into Customer,
  but on a real project, that choice would depend on how the domain's
  customers are typically matched or distinguished. For example, if a
  Customer has many contact phone numbers for different purposes, then
  the phone number is not associated with identity and should stay with
  the Sales Contact.

a)

CustomerID is the one and only identifier of the Customer ENTITY (
  figure 5.5 ), but  phone number and address would often be used to
  find or match a Customer. The name does not define a person's
  identity, but it is often used as part of the means of determining it.

Quote states that only attributes associated with identity should stay in an entity.  I assume author means that entity should contain only those attributes that are often used to find or match this entity, while ALL other attributes should be moved?

b) But how/where should other attributes be moved? For example ( assumption here is that address attribute isn't used to find or match Customer and thus we want to move address attribute out of Customer ):

if instead of having Customer.Address ( of type string ) we create a property Customer.Address of type Address, did we move the address attribute into an associated VO object ( which is of type Address ) or would we say that Customer still contains address attribute?

c)

In this example, the phone and address attributes moved into Customer,
  but on a real project, that choice would depend on how the domain's
  customers are typically matched or distinguished. For example, if a
  Customer has many contact phone numbers for different purposes, then
  the phone number is not associated with identity and should stay with
  the Sales Contact.

Isn't author in the wrong here, since if we assume each of the many contact phone numbers that Customer has only belong to that particular Customer, then I'd say these phone numbers are associated with identity just as much as when Customer only had one phone number?

5)

The reason the author suggests stripping the entity down is that when
  one initially creates a Customer entity, there is a tendency to
  populate it with any attribute that one can think of being associated
  with a customer. This is a data-centric approach that overlooks
  behaviors ultimately leading to an anemic domain model.

Off topic, but I thought anemic domain model results from moving behavior out of an entity, while your example is populating an entity with lots of attributes, which would result in Customer having too much behavior ( since we'd probably also include in Customer the behaviors which modify these additional attributes ) and thus in violation of SRP?

thanks

答:
Once an entity is assigned a unique ID, its identity is established
  and so I would assume such an entity doesn't need any behavior to
  maintain its identity or to help it identify itself. Thus, I don't
  understand what kind of behavior is author referring to ( besides find
  and match operations ) with "behavior that is essential to the
  concept"?

If the identity is established then yes the entity needs nothing else to be identified. The behaviors that the author is referring to are behaviors associated with the entity. These are the behaviors that modify the state of the entity. For example, a Customer entity may have a MakePreferred behavior. The reason the author suggests stripping the entity down is that when one initially creates a Customer entity, there is a tendency to populate it with any attribute that one can think of being associated with a customer. This is a data-centric approach that overlooks behaviors ultimately leading to an anemic domain model.

As far as moving behavior to other objects, the author is referring to value objects specifically. The reason it is a good idea to move behavior to VOs is because VOs are usually "smaller" than entities, thereby more focused. Moreover, aspects such as immutability and closure of operations simplify reasoning about the code while also making it more SOLID.

Together with VOs, an entity serves as a sort of anchor which coordinates the various VOs which implement its behavior.

With regards to SRP, your confusion is not unwarranted. One problem with the stereotypical OOP implementation of entities is the conflation of identity and state. Indeed, from a behavioral perspective, identity has nothing to do with behaviors. In other words, the identity of an entity isn't requires for any of its behaviors. There are implementations where this conflation is eliminated, such as AggregateSource or a functional approach I describe here.

The other problem is that, to an extent, SRP can be a qualitative measure. Anyone can come up with a definition of single responsibility which some class violates. One can say that the responsibility of the entity is to implement the behaviors required of that entity. In that sense, it has a single responsibility. Furthermore, when an entity delegates behaviors to constituent VOs, it isn't violating SRP. SRP doesn't forbid composition of the sort. It does caution one to reduce coupling between objects to an absolute minimum, keep interfaces as bare as possible, etc.

UPDATE

a) If I understand you correctly, you're saying that entity should
  only contain those behaviors that modify its attributes ( i.e. its
  state )?

Yes, though there are exceptions...

b) And what about the behaviors that don't necessarily modify the
  state of the entity, but are still considered as being an intrinsic
  characteristic of that entity ( example: barking would be intrinsic
  characteristic of a Dog entity, even if it didn't modify Dog's state
  )? Should we include these behaviors in an entity or should they be
  moved to other objects?

It is acceptable for entities to contain factory methods for creating instances of entities would are effectively child entities, but where object references aren't used for traversal. In this case, the child entity needs to be persisted by the application service. The application service uses the parent entity to construct the child entity.

3) Assuming MyEntity ( see question 3. in my original post ) doesn't
  violate SRP, would we say that a responsibility of MyEntity is among
  other things also comprised of:

You're looking at responsibility from the implementation perspective. Instead, consider the entity as a sort of black box with responsibilities. How it handles those isn't of interest to you as someone looking from the outside. Partitioning of responsibilities among VOs or even other entities is an implementation concern.

Quote states that only attributes associated with identity should stay
  in an entity. I assume author means that entity should contain only
  those attributes that are often used to find or match this entity,
  while ALL other attributes should be moved?

More specifically, attributes which aren't required for behavior nor look up shouldn't be part of the entity. Why bother? Moreover, with something like the read-model pattern, entities don't need anything beyond attributes that are required for behavior.

if instead of having Customer.Address ( of type string ) we create a
  property Customer.Address of type Address, did we move the address
  attribute into an associated VO object ( which is of type Address ) or
  would we say that Customer still contains address attribute?

Yes, in effect, there is not difference between a string address or an Address VO address.

Isn't author in the wrong here, since if we assume each of the many
  contact phone numbers that Customer has only belong to that particular
  Customer, then I'd say these phone numbers are associated with
  identity just as much as when Customer only had one phone number?

I'm not 100% on author's intent, but I think he's just describing how entity lookup requirements can alter how the entity and its corresponding VOs are structures.

Off topic, but I thought anemic domain model results from moving
  behavior out of an entity, while your example is populating an entity
  with lots of attributes, which would result in Customer having too
  much behavior ( since we'd probably also include in Customer the
  behaviors which modify these additional attributes ) and thus in
  violation of SRP?

Lots of attributes does not imply lots of behavior. In fact, it usually suggest the opposite. Lots of attributes with getters and setters, but no encapsulating behavior.

OwnerDisplayName: EdvRusj


问:
How do I survive in a Waterfall world?
I currently work in a company where the Waterfall model is deeply ingrained. We are pushing Agile principles but it's a long process. Meanwhile, I have to work in a Waterfall world with sequential projects phases.

My question is about the analysis phase. I must provide a list of task and how long they will take. What techniques can I use to improve the accuracy/precision of my estimates, while fulfilling the requirement of having a detailed estimate up front?

One example I know would be to use prototyping to get more knowledge before making the estimate.

答:
In order to get better at providing the list of tasks and the time they will take, you need to practice and record your results. So first make every estimate fairly detailed (don't forget to include communications and meetings, requirements development,  designing, tests, qa, deployment, documentation (always needed in waterfall), research and other non-coding tasks. The first thing people do wrong is they estimate only for the actual coding time. You think,  "Well that will take me about 2 days so that is the estimate" and 12 hours of meetings later, you haven't even started to develop.

When you give an estimate, store it and the time somewhere and when you do the project, mark down how long each task actually took. Soon you will see a pattern (most people consistently estimate too low). You also will now have the data to say what time things take. It becomes harder to argue with your estimates when they are based on hard numbers of what it took for similar tasks in the past.

In a waterfall project, you can assume there will be last minute changes, so estimate for a percentage of time spent on that too! If a task is new (you have no similar tasks in the history), remember to add a more research and design time because figuring out what to do will probably take the most time.

In a waterfall project, the best thing you can do for yourself and your team is to slip the deadline and increase the estimate every single time they change the requirement after the requirements definition phase. If they get new estmates from you consistently that tell them how much that little change will cost, you will reduce the number of "Oh by the way" changes you get drastically. You need to manage the customer in a large project.

And spend the time up front in requirement development and design. That is the purpose of a waterfall project since it is far cheaper to change things at that point than after you have done the development work. There are types of projects that are more suited to waterfall than agile. So don't automatically think it is bad that you use it. Instead learn to use it well to manage projects. If you learn to manage waterfall well, you are ahead of most devlopers in either waterfall or agile environaments because the truth is most developers are lousy at anything involving management of a project and getting projects ouit the door is the name of the game.

Title: How do I survive in a Waterfall world?


答:
A boolean or truth value only has 2 values.  True and false.

These should not be represented as integers, but as bits (0 and 1).

Saying any other integer beside 0 or 1 is not false is a confusing statement.  Truth tables deal with truth values, not integers.

From a truth value prospective, -1 or 2 would break all truth tables and any boolean logic assoicated with them.

0 AND -1 == ?!

0 OR  2 == ?!

Most languages usually have a boolean type which when cast to a number type such as integer reveals false to be cast as a integer value of 0.

Title: Why is 0 false?


答:
Before addressing the general case, we can discuss your counter examples.

String comparisons

The same holds for many sorts of comparisons, actually. Such comparisons compute a distance between two objects. When the objects are equal, the distance is minimal. So when the "comparison succeeds", the value is 0. But really, the return value of strcmp is not a boolean, it is a distance, and that what traps unaware programmers doing if (strcmp(...)) do_when_equal() else do_when_not_equal().

In C++ we could redesign strcmp to return a Distance object, that overrides operator bool() to return true when 0 (but you would then be bitten by a different set of problems).
Or in plain C just have a streq function that returns 1 when strings are equal, and 0 otherwise.

API calls/program exit code

Here you care about the reason something went wrong, because this will drive the decisions up on error. When things succeed, you don't want to know anything in particular - your intent is realized. The return value must therefore convey this information. It is not a boolean, it is an error code. The special error value 0 means "no error". The rest of the range represent locally meaningful errors you have to deal with (including 1, which often means "unspecified error").

General case

This leaves us with the question: why are boolean values True and False commonly represented with 1 and 0, respectively?

Well, besides the subjective "it feels better this way" argument, here are a few reasons  (subjective as well) I can think of:

electrical circuit analogy. The current is ON for 1s, and OFF for 0s. I like having (1,Yes,True,On) together, and (0,No,False,Off), rather than another mix

memory initializations. When I memset(0) a bunch of variables (be them ints, floats, bools) I want their value to match the most conservative assumptions. E.g. my sum is initally 0, the predicate is False, etc.

Maybe all these reasons are tied to my education - if I had been taught to associate 0 with True from the beginning, I would go for the other way around.

Title: Why is 0 false?


答:
From a high-level perspective, you're talking about three quite different data types:

A boolean. The mathematical convention in Boolean algebra is to use 0 for false and 1 for true, so it makes sense to follow that convention. I think this way also makes more sense intuitively.

The result of comparison. This has three values: <, = and > (notice that none of them is true). For them it makes sense to use the values of -1, 0 and 1, respectively (or, more generally, a negative value, zero and a positive value).

If you want to check for equality and you only have a function that performs general comparison, I think you should make it explicit by using something like strcmp(str1, str2) == 0. I find using ! in this situation confusing, because it treats a non-boolean value as if it was a boolean.

Also, keep in mind that comparison and equality don't have to be the same thing. For example, if you order people by their date of birth, Compare(me, myTwin) should return 0, but Equals(me, myTwin) should return false.

The success or failure of a function, possibly also with details about that success or failure. If you're talking about Windows, then this type is called HRESULT and a non-zero value doesn't necessarily indicate failure. In fact, a negative value indicates failure and non-negative success. The success value is very often S_OK = 0, but it can also be for example S_FALSE = 1, or other values.

The confusion comes from the fact that three logically quite different data types are actually represented as a single data type (an integer) in C and some other languages and that you can use integer in an condition. But I don't think it would make sense to redefine boolean to make using some non-boolean types in conditions simpler.

Also, consider another type that's often used in a condition in C: a pointer. There, it's natural to treat a NULL-pointer (which is represented as 0) as false. So following your suggestion would also make working with pointers more difficult. (Though, personally, I prefer explicitly comparing pointers with NULL, instead of treating them as booleans.)

Title: Why is 0 false?


问:
Examples of general purpose algorithms that have benefited from running on a GPU?
I am looking for examples of general purpose algorithms (meaning non-graphics related) that have been proven to run an order of magnitude faster on a GPU than on a CPU. I will use these examples to think creatively about other algorithms that I could implement on a GPU.</p>

答:
Maybe I'm being very Math/Science/Engineering compute specific but one that comes to mind is the FFT algorithm.

I've seen this FFT benchmark thrown around before, and although it is a few years old I think it was well done for what it is: http://www.sharcnet.ca/~merz/CUDA_benchFFT


答:
There are a lot of answers that suggest that correspondance between 1 and true is necessitated by some mathematical property.  I can't find any such property and suggest it is purely historical convention.

Given a field with two elements, we have two operations: addition and multiplication.  We can map Boolean operations on this field in two ways:

Traditionally, we identify True with 1 and False with 0. We identify AND with * and XOR with +.  Thus OR is saturating addition.

However, we could just as easily identify True with 0 and False with 1. Then we identify OR with * and XNOR with +.  Thus AND is saturating addition.

Title: Why is 0 false?


问:
shortening url to cms
Hi
We have a CMS application that lets people create websites under our domain.
The system was built a few years ago and it used a method that transfers parameters such as website id, folder code and more using the url. this method created a giant url for every item in the website

For example:
My domain is www.domain.com

A users website on my domain is www.domain.com/user

and every time that a user enters his website he gets a link like this
www.domain.com/page.aspx?code=blablasdsdsdsdsds&folder=blablablablablabla and more.

We are trying to reduce the string size in the url.
What are our options? can we show the user one url like a virtual one and still work the same with the old url?
We are trying to locate a solution that wont make us rewrite our entire application.

the application is built in c# and the web server is iis 6.
Thanks

答:
You can refer following article:

http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

One of my friend has used similar solution which is working great.

Gaurav Maniar MCP | MCSE | MCST | MCITP | ITILv3 Certified

Title: shortening url to cms


问:
Is XML, HTML/CSS, XSL analogous to Model, View, Controller?
For some time in personal projects I have been using XSL to convert my raw XML data into human-friendly HTML/CSS (in simple projects, I have no JavaScript, so let's leave that out of the equation for simplicity).

Now I'm trying to understand the MVC architectural pattern (not my first experience with it, but it is taking some work to go from understanding it basically to understanding it well), and I'm wondering if there is an analogy between the two.

XML: data model; lacks the complexity/logic of a full-blown model component, but intent seems similar

XSL: converts raw data for viewing—seems like a controller

HTML/CSS (rendered): the viewable output

Is this analogy fitting? What in it matches well and what does not?

(One dissimilarity, I suppose, is that in my example I am not getting any input back from the view—only producing output.)

答: In this case, I would suggest that you don't really have a controller per se. The XML is the model and the XSL (by way of producing an HTML output) is a view on that data. If you had some mechanism which took some user input and filtered (or caused to be filtered) the raw XML prior to the XSL transformation, then you might consider that mechanism to be your controller.</p>


答:
As explained in this article, the values false and true should not be confused with the integers 0 and 1, but may be identified with the elements of the Galois field (finite field) of two elements (see here).

A field is a set with two operations that satisfy certain axioms.

The symbols 0 and 1 are conventionally used to denote the additive and multiplicative identities of a field because the real numbers are also a field (but not a finite one) whose identities are the numbers 0 and 1.

The additive identity is the element 0 of the field, such that for all x:

```<code>x + 0 = 0 + x = x
</code>```

and the multiplicative identity is the element 1 of the field, such that for all x:

```<code>x * 1 = 1 * x = x
</code>```

The finite field of two elements has only these two elements, namely the additive identity 0 (or false), and the multiplicative identity 1 (or true).
The two operations of this field are the logical XOR (+) and the logical AND (*).

Note. If you flip the operations (XOR is the multiplication and AND is the addition) then the multiplication is not distributive over addition and you do not have a field any more. In such a case you have no reason to call the two elements 0 and 1 (in any order).
Note also that you cannot choose the operation OR instead of XOR: no matter how you interpret OR / AND as addition / multiplication, the resulting structure is not a field (not all inverse elements exist as required by the field axioms).

Regarding the C functions:

Many functions return an integer that is an error code. 0 means NO ERROR.

Intuitively, the function strcmp computes the difference between two strings. 0 means that there is no difference between two strings, i.e. that two strings are equal.

The above intuitive explanations can help to remember the interpretation of the return values, but it is even easier to just check the library documentation.

Title: Why is 0 false?

Body:
As explained in this article, the values false and true should not be confused with the integers 0 and 1, but may be identified with the elements of the Galois field (finite field) of two elements (see here).

A field is a set with two operations that satisfy certain axioms.

The symbols 0 and 1 are conventionally used to denote the additive and multiplicative identities of a field because the real numbers are also a field (but not a finite one) whose identities are the numbers 0 and 1.

The additive identity is the element 0 of the field, such that for all x:

x + 0 = 0 + x = x

and the multiplicative identity is the element 1 of the field, such that for all x:

x * 1 = 1 * x = x

The finite field of two elements has only these two elements, namely the additive identity 0 (or false), and the multiplicative identity 1 (or true).
The two operations of this field are the logical XOR (+) and the logical AND (*).

Note. If you flip the operations (XOR is the multiplication and AND is the addition) then the multiplication is not distributive over addition and you do not have a field any more. In such a case you have no reason to call the two elements 0 and 1 (in any order).
Note also that you cannot choose the operation OR instead of XOR: no matter how you interpret OR / AND as addition / multiplication, the resulting structure is not a field (not all inverse elements exist as required by the field axioms).

Regarding the C functions:

Many functions return an integer that is an error code. 0 means NO ERROR.

Intuitively, the function strcmp computes the difference between two strings. 0 means that there is no difference between two strings, i.e. that two strings are equal.

The above intuitive explanations can help to remember the interpretation of the return values, but it is even easier to just check the library documentation.


答:
No, it is not MVC

XML is a data protocol. XSL is a translation specification language, but even with the engine that does the translation, it still is just a mechanism. Server-side frameworks like Struts can use this mechanism to create HTML and CSS

HTML and CSS can define views.

JavaScript can work inside a page to move data in and out of a view, sort of like a controller. I guess, as with anything, you can write a complete MVC in JavaScript -- and others already have (see Atwood's Law).

Cheers

Title: Is XML, HTML/CSS, XSL analogous to Model, View, Controller?

Body:
For some time in personal projects I have been using XSL to convert my raw XML data into human-friendly HTML/CSS (in simple projects, I have no JavaScript, so let's leave that out of the equation for simplicity).

Now I'm trying to understand the MVC architectural pattern (not my first experience with it, but it is taking some work to go from understanding it basically to understanding it well), and I'm wondering if there is an analogy between the two.

XML: data model; lacks the complexity/logic of a full-blown model component, but intent seems similar

XSL: converts raw data for viewing—seems like a controller

HTML/CSS (rendered): the viewable output

Is this analogy fitting? What in it matches well and what does not?

(One dissimilarity, I suppose, is that in my example I am not getting any input back from the view—only producing output.)


问:
"Final" Scheme REPL definitions: how to save them?
Is there a way to show and save all "final" definitions entered into a Scheme REPL into a text file?

Say, if I have defined in the REPL:

```<code>    (define (increase x) (+ 1 x))
    (define (multbytwo x) (* 3 x)) ; let us say this was an error
    (define (multbytwo x) (* 2 x))
</code>```

I want to save this into an .scm-file with the content:

```<code>    (define (increase x) (+ 1 x))
    (define (multbytwo x) (* 2 x))
</code>```

i.e. the multbytwo function that got defined erraneously shall be "forgotten" due to re-definition. Is this possible?

答:
None that I know of. There is however many Lisps that can save it's image so that you can start up with all definitions. You won't be able to actually see the definitions though.

I would have kept my definitions in a file (or in the IDE like in DrRacket) and started the repl with loading that file. When changing definition you copy/past it back to your definition file when you're satisfied.

Alternatively, you could make a small REPL:

```<code>;; These are outside in case we break out of the REPL
(define env '())
(define (print-env)
  (newline)
  (for-each (lambda (x) (display (cdr x)) (newline)) env)
  (newline))

(define (repl)
  (define (define? expr)
    (and (pair? expr)
         (or (eq? 'define (car expr))
             (eq? 'set! (car expr)))))

  (define (define-name expr)
    (if (pair? (cadr expr))
        (caadr expr)
        (cadr expr)))

  (define (extend-env name expr)
    (let ((found (assq name env)))
      (if found
          (set-cdr! (car found) expr)
          (set! env (cons (cons name expr) env)))))

  (let ((expr (read)))
    (if (define? expr)
        (let ((name (define-name expr)))
          (eval expr (interaction-environment))
          (extend-env name expr)
          (repl))
        (let ()
              (display (eval expr (interaction-environment)))
              (newline)
              (repl)))))

(display "Outer REPL: If an error occurs, rerun with (repl)\nIn both REPL and outside yo may print definitions by calling (print-env)\n")
(repl)
</code>```

This one is very crude. At the very first error it will exit the loop. In andoutside repl however, you may print the definitions by running (print-env).

Body:
None that I know of. There is however many Lisps that can save it's image so that you can start up with all definitions. You won't be able to actually see the definitions though.

I would have kept my definitions in a file (or in the IDE like in DrRacket) and started the repl with loading that file. When changing definition you copy/past it back to your definition file when you're satisfied.

Alternatively, you could make a small REPL:

;; These are outside in case we break out of the REPL
(define env '())
(define (print-env)
  (newline)
  (for-each (lambda (x) (display (cdr x)) (newline)) env)
  (newline))

(define (repl)
  (define (define? expr)
    (and (pair? expr)
         (or (eq? 'define (car expr))
             (eq? 'set! (car expr)))))

  (define (define-name expr)
    (if (pair? (cadr expr))
        (caadr expr)
        (cadr expr)))

  (define (extend-env name expr)
    (let ((found (assq name env)))
      (if found
          (set-cdr! (car found) expr)
          (set! env (cons (cons name expr) env)))))

  (let ((expr (read)))
    (if (define? expr)
        (let ((name (define-name expr)))
          (eval expr (interaction-environment))
          (extend-env name expr)
          (repl))
        (let ()
              (display (eval expr (interaction-environment)))
              (newline)
              (repl)))))

(display "Outer REPL: If an error occurs, rerun with (repl)\nIn both REPL and outside yo may print definitions by calling (print-env)\n")
(repl)

This one is very crude. At the very first error it will exit the loop. In andoutside repl however, you may print the definitions by running (print-env).


问:
Good practice -apply paradigm to a language that is not fit for it
For example, what happens if a coder tries to code in purely functional-style paradigm in OO-paradigm language(Java)? Will it work? Or the OO nature of Java will not let it happen?

Also, is applying wrong paradigm to language unfitting to it a bad practice or not?
Is it like trying to drive a jet on road instead of flying it?

答:
OO and purely functional don't form a dichotomy. "purely-functional" usually just means avoiding mutation, OO is a woolly term that IMO only acquires some concreteness when referring to the type system.

Somewhat oversimplifying, the general consensus is with larger, more complex, and more concurrent systems systems, mutation is increasingly an unwieldy tool.

If you try to avoid using mutation, your apt to discover however the verbosity of java et al becomes much worse. A lot of people blame OO, the real problem i think lies more with the influence of C and C syntax. Java gives you full-blown closures in fact, with anonymous classes, it's just the syntax is ridiculously compare to languages that more ostensibly support them.

Again, the point here is not that OO and sparingly using mutation don't mix, its that java is verbose. Scala I think is the foremost example where you have have tons of expressiveness, and an OO which frankly is purer OO than java.

http://www.drdobbs.com/architecture-and-design/interview-with-scalas-martin-odersky/231001802 An interesting interview with Martin Odersky, creater of Scala (and Java's generics).

Coming from the opposite perspective, Haskell's type system really lets you do a lot of what OO accomplishes, especially with extensions. Even if the underlying type theory is slightly different, the usage from a software engineering standpoint is quite similar.

Consider in Java, a common idiom is to write an abstract data type via an interface, and then call some methods in it on a heterogeneous collection, but one where all elements implement that interface. Well first of all, you can write a type class which does exactly what that interface does. Second of all, using existential types (an extension), you can build heterogeneous data structures and so on just like with Java. Just using a type class gives you polymorphism, but only static dispatch. Existential types give you dynamic dispatch.

http://www.haskell.org/haskellwiki/Existential_type <- more information on existential types.

so tl;dr if you pick a language with a strong enough type system and expressive enough syntax, you can stop worrying about paradigms and just do what fits your goal best.


答:
It won't work because there are things you just can't do without draconian measures like writing a code generator (which is effectively making your own, new language).  Of course, if both languages are Turing complete, you can get the same behavior - but the code is so different it isn't reasonable to say you are really doing functional programming.

Let's take a simple example - higher order functions.

Higher order functions are basic, bread and butter parts of functional languages.  To use them, you need to be able to pass a function as a parameter.  Java won't let you do that.  You have use the command pattern.  This means you have to go create another class to hold the code for your command, instead of defining it in-line.

Worse yet, when your command gets evaluated, it is running in a different context than where it was defined.  Variables that were in scope at that time may be gone.  So, any variables that you need have to get stuffed into your command object so that they can get carried into the new scope.  You have to do that manually, each time.  If the language had lexical closures, the computer would figure this out for you.

By now, what would be, say, a simple call to map with a lambda function has turned into a small project, and the code looks completely different.

It just gets worse, too.  Things like an algebraic type system checked at compile time just aren't going to happen for you, ever.

You need to decide if a programming pattern makes sense in the language you are using, the fact that there is an elegant solution in a totally different language might help for inspiration but it can't determine how you structure your code.

Title: Good practice -apply paradigm to a language that is not fit for it

Body:
For example, what happens if a coder tries to code in purely functional-style paradigm in OO-paradigm language(Java)? Will it work? Or the OO nature of Java will not let it happen?

Also, is applying wrong paradigm to language unfitting to it a bad practice or not?
Is it like trying to drive a jet on road instead of flying it?


答:
Emacs and Vi still have a place.

They are ubiquitously available in Unix and Unix-like environments, and can be installed on most other popular platforms.

They are popular and stable, so learning them once pays off over the long run.

They run over a text terminal, so you can use them in telnet and ssh sessions.

They provide editing modes and syntax highlighting for a wide variety of languages, including very new and very rare languages. (This is one of my favorite advantages.)

The key to understanding these programs, though, is to know what problems they were originally meant to solve. For Vi this was editing text files over terminal connections as slow as 300 Baud. In that environment you don't want to display menus or radically change the screen contents if you can avoid it.

Emacs was intended to be used in a faster environment. It's strength was that it could be loaded once and never exited. The user could accomplish any other task they needed from Emacs without leaving, and often in a more friendly way than if they had to do it from the command line. People didn't have a graphical desktop environment with an Emacs window open. Emacs let the user accomplish almost any normal task (and many strange ones) with just a few key strokes. Anything not built in could be scripted.

Obviously peoples' needs have changed a lot since these programs were introduced, but they still have some real strengths. I've learned the basics of both, and use them on a weekly basis. Still, I think their strengths are often overstated. They have achieved such legendary status that people don't admit to their weaknesses and instead tend to think they are doing something wrong if Emacs/Vi doesn't make them more productive than Eclipse  or Visual Studio.

Now to the point.

Java is a popular language with excellent support in Eclipse, and odds are you are developing code on a modern operating system that lets you quickly accomplish common tasks and script others without doing it through your IDE. I don't think it would make sense for you to switch.

Title: I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?

Body:
My day job is  java/web developer. I have been using eclipse for ~5years. I think its excellent and I also use Webstorm for javascript and html/jsp.

I do on occasion need to ssh into server and mess around with config files; for this I use vi and it pains me. I have to get up a webpage listing the syntax/commands : press escape, then asterix, turn around three times and the text will be entered two lines above your cursor. Its so unintuitive to me, and I imagine anyone who grew up in the late eighties nineties.

Here are the main reasons I think eclipse is brilliant(and I assume other IDE's), and do not switch to emacs and/or vim.

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

availablity of 3rd party plugins - eg
findbugs/checkstyle.

One of the arguments I hear is that with emacs/vim you can create your own plugins - well OK, but you can do that in eclipse too. But you don't need to as everything is already there!  Its like saying buy this half built car, you can build the rest yourself.

Why are people using emacs/vim ? Do people who use it actually work on complex object-oriented projects in large organisations ?

What are the reasons to switch to vim/emacs. How would my productivity increase if I did switch?


问:
Is it possible to use the Intel C/C++ compiler on Linux to create object files to be linked on Windows?
Why?

Depending on your source the Intel compiler is likely or most definitely the compiler generating the fastest executables for the x86 architecture (5 to 100 % execution time improvement).

Intel offers its compilers for Linux under a non-commercial license for free (I think I read it is free somewhere on their page: Intel - Non-Commercial Software Development).
There is also a free non-commercial license for students, but this license is not applicable although tools are offered for all three major operating systems (link dropped  due to reputation restriction).

Goal

I (as a non-student) would like to be able to use the Intel compilers for possible execution speed improvements under the non-commercial license to compile object files that can be linked to create executables and dynamic link libraries for Windows (and possibly OS X)

More Details:

What I inferred from this document is that the Intel compilers create object files that are compatible to the dominant compilers of the platform.

Sub-questions:

What are the object file formats of gcc, g++, cl, mingw32, icc, icpc, and icl on Windows and Linux (current versions)?

Could parts of the mingw32 cross-compiler toolchain be used to accomplish the goal?

Am I right that the metadata in the generated object files is the main issue?

ad 2:

mingw32-objcopy seems to be able to convert the Intel compiler output on Linux (presumably ELF) to Microsoft-compatible COFF (with the possible exception of relocateable object files). Could someone confirm that this actually works (for non-trivial applications), please?

答:
With C code linking to nothing (directly) that uses Microsoft’s custom calling conventions, you might stand a chance using MinGW's objcopy. I have used it to convert an assembled object file, but then I didn't have to worry about calling conventions.

I would just spend the time you would trying to do this instead getting GCC or clang to do exactly what you want. If such a speed up is really that important compile a Linux binary with the Intel compiler and try to see exactly what, if anything at all, it does speeding up your code. You can patch the assembly if all else fails.


问:
How to find a programming mentor?
I decided to learn programming. I've been reading SO for few days, and I think I will start with C++, as I read some articles. I am aware of loops, arrays, program logic and objects a little and I need someone to look me over and help me with small questions I get when doing my first projects.

So here is the question - where do I find such guy? I don't got any friends who program and all.

EDIT: 2 years later, I am still looking for mentor. I did not actively code just started 3 months again. I work on Objective-C and iOS programming and game programming with Cocos2d. If you want to become my mentor, drop me a or comment.

答:
For a mentor, go freenode (irc). I swear, you can get most of a CS degree from that place, useful at any skill level. That is where I learned a lot. Shouldn't matter whether the person is on that channel once or 24/7, it's real time and that's what counts.

And, as most others said, don't don't do C++. Instead, start with a statically typed, garbage-collecting language and don't move to manual memory management until you know enough to actually beat the garbage collector. You can write some damn fast Haskell or OCaml if you try.

Title: How to find a programming mentor?


答:
C is used for low-level programming close to hardware, an area in which you sometimes need to shift between bitwise and logical operations, on the same data. Being required to convert a numeric expression to boolean just to perform a test would clutter up the code.

You can write things like:

if (modemctrl & MCTRL_CD) {
   /* carrier detect is on */
}
```

<p>rather than</p>

<pre class="lang-c prettyprint-override"><code>if ((modemctrl & MCTRL_CD) != 0) {
    /* carrier detect is on */
}
</code>```

In one isolated example it's not so bad, but having to do that will get irksome.

Likewise, converse operations. It's useful for the result of a boolean operation, like a comparison, to just produce a 0 or 1:  Suppose we want to set the third bit of some word based on whether modemctrl has the carrier detect bit:

flags |= ((modemctrl & MCTRL_CD) != 0) << 2;
```

<p>Here we have to have the <code>!= 0</code>, to reduce the result of the biwise <code>&</code> expression to <code>0</code> or <code>1</code>, but because the result is just an integer, we are spared from having to add some annoying cast to further convert boolean to integer.</p>

<p>Even though modern C now has a <code>bool</code> type, it still preserves the validity of code like this, both because it's a good thing, and because of the massive breakage with backward compatibility that would be caused otherwise.</p>

<p>Another exmaple where C is slick: testing two boolean conditions as a four way switch:</p>

<pre class="lang-c prettyprint-override"><code>switch (foo << 1 | bar) {  /* foo and bar booleans are 0 or 1 */
case 0: /* !foo && !bar */
   break;
case 1: /* !foo && bar */
   break;
case 2: /* foo && !bar */
   break;
case 3: /* foo && bar */
   break;
}
</code>```

You could not take this away from the C programmer without a fight!

Lastly, C sometimes serves as a kind of high level assembly language. In assembly languages, we also do not have boolean types. A boolean value is just a bit or a zero versus nonzero value in a memory location or register.  An integer zero, boolean zero and the address zero are all tested the same way in assembly language instruction sets (and perhaps even floating point zero). Resemblance between C and assembly language is useful, for instance when C is used as the target language for compiling another language (even one which has strongly typed booleans!)

Title: Why is 0 false?

Body:
C is used for low-level programming close to hardware, an area in which you sometimes need to shift between bitwise and logical operations, on the same data. Being required to convert a numeric expression to boolean just to perform a test would clutter up the code.

You can write things like:

if (modemctrl & MCTRL_CD) {
   /* carrier detect is on */
}

rather than

if ((modemctrl & MCTRL_CD) != 0) {
    /* carrier detect is on */
}

In one isolated example it's not so bad, but having to do that will get irksome.

Likewise, converse operations. It's useful for the result of a boolean operation, like a comparison, to just produce a 0 or 1:  Suppose we want to set the third bit of some word based on whether modemctrl has the carrier detect bit:

flags |= ((modemctrl & MCTRL_CD) != 0) << 2;

Here we have to have the != 0, to reduce the result of the biwise & expression to 0 or 1, but because the result is just an integer, we are spared from having to add some annoying cast to further convert boolean to integer.

Even though modern C now has a bool type, it still preserves the validity of code like this, both because it's a good thing, and because of the massive breakage with backward compatibility that would be caused otherwise.

Another exmaple where C is slick: testing two boolean conditions as a four way switch:

switch (foo << 1 | bar) {  /* foo and bar booleans are 0 or 1 */
case 0: /* !foo && !bar */
   break;
case 1: /* !foo && bar */
   break;
case 2: /* foo && !bar */
   break;
case 3: /* foo && bar */
   break;
}

You could not take this away from the C programmer without a fight!

Lastly, C sometimes serves as a kind of high level assembly language. In assembly languages, we also do not have boolean types. A boolean value is just a bit or a zero versus nonzero value in a memory location or register.  An integer zero, boolean zero and the address zero are all tested the same way in assembly language instruction sets (and perhaps even floating point zero). Resemblance between C and assembly language is useful, for instance when C is used as the target language for compiling another language (even one which has strongly typed booleans!)


问:
Enterprise application with lots of SQL queries
Context:

I'm working on a fairly large Access database (which I inherited) that has its interface and tables separated. In order to make this work together, we have a lot of SQL queries (dozens). Some pointing to that database and some pointing to our datamarts. The code at this moment is somewhere around 12k-14k lines which is not huge by software development standard but not so short that I can just rewrite it. Additionally, that database is fed by a form which is distributed to all our internal clients.

My question:

I'm wondering what's the best way to deal with this. I'd like to know if there is a better way to manage all those queries than to have them in code in string variables. I'm sure it's possible to use files but then we have to distribute those files and that can't happen (i.e. I don't want users to have SQL queries wide open to them).

Is there some clean (in terms of design) way to manage SQL queries that still has a decent amount of security (access to those queries) ?

Just to be clear, we are using Access 2007 with VBA.

答:
It looks like you're using an Access-to-Access setup, with the forms, reports, and queries in one *.accdb file and the tables themselves off in another.

If you want better control of the queries, move them -- ALL of them -- into the back-end accdb.  The queries belong with the tables, and the only exceptions should be exceptional, with clear and distinct reasons to not be on the back-end.

Were it my project, I would plan on a migration away from Access-to-Access over to something like Access-to-SQL (or even Access-to-SharePoint) and then, if appropriate, you can slowly introduce other front-ends to supplant access, such as C#-to-SQL or Web-to-SQL.

Access is a desktop context, not a web context, and if you don't have to pretend to be a website you shouldn't try and make it so.  I've seen excellent things done regarding direct SQL server connections.  Not the least of which is that you can use integrated security and per-object permissions on the server level.

(And that "if appropriate" is important.  If access works and fits your current and expected scale, it's not worth abandoning just to have a "real" program.)


答:
Almost, but not quite. If you had a hypothetical webserver that could pass URL query strings as XSL paramaters I'd say you were quite close, that would allow you to respond to user input.

eg. http://www.example.com/path/file.xml?param1=foo;param2=bar
And your xsl contained:
<xsl:param name="param1"/><xsl:param name="param2"/>

But even then, there is no way to actually change the data itself. So, again no.


问:
What is the name of a grammar which can change its tokenizer in mid parse?
I was creating a language and discovered that my language tokenizer would have to change depending where in the parse it is.

I.e. abc[1] would be parsed as 4 tokens (abc, [, 1, ]), where as { abc[1] } would be parsed as 3 ({, abc[1], }).

Is a grammar that would change its tokenizer mid parse defined somewhere? Does a grammar even define such a thing or is it irrelevant to the grammar and is just not really done on a parser level?

答:
There is no special name for this type of grammar that I know of. What you have there is still a LR(k) grammar that could be parsed by a parser that takes each character to be a token, and has k characters of lookahead.

The division of parsing into tokenization and syntax recognition stems from the desire to increase efficiency by reducing lookahead to 1 symbol. (That and the fact that a token is a concept in the syntax of a programming language, so why not have a matching representation in the language implementation.)

That is to say, the principal technical advantage of parsing tokens rather than characters is that we can distinguish interface and integer with one symbol of lookahead rather than three symbols of lookahead.


答:
0 is false because they’re both zero elements in common semirings. Even though they are distinct data types, it makes intuitive sense to convert between them because they belong to isomorphic algebraic structures.

0 is the identity for addition and zero for multiplication. This is true for integers and rationals, but not IEEE-754 floating-point numbers: 0.0 * NaN = NaN and 0.0 * Infinity = NaN.

false is the identity for Boolean xor (⊻) and zero for Boolean and (∧). If Booleans are represented as {0, 1}—the set of integers modulo 2—you can think of ⊻ as addition without carry and ∧ as multiplication.

"" and [] are identity for concatenation, but there are several operations for which they make sense as zero. Repetition is one, but repetition and concatenation do not distribute, so these operations don’t form a semiring.

Such implicit conversions are helpful in small programs, but in the large can make programs more difficult to reason about. Just one of the many tradeoffs in language design.

Title: Why is 0 false?


问:
Why do so few large websites run a Microsoft stack?
Off the top of my head, I can think of a handful of large sites which utilize the Microsoft stack

Microsoft.com

Dell

MySpace

PlentyOfFish

StackOverflow

Hotmail, Bing, WindowsLive

However, based on observation, nearly all of the top 500 sites seem to be running other platforms.What are the main reasons there's so little market penetration?

Cost?

Technology Limitations?

Does Microsoft cater to corporate / intranet environments more then public websites?

I'm not looking for market share, but rather large scale adoption of the MS stack.

答:
Cost factor definitely contributes to initial adoption of open source technologies.

But even when they grow really really big, they stick to open source stuff. If you have seen videos explaining scale at facebook or google, they invest lot of engineering effort in bettering the technologies they use (unladen swallow for python, hiphop for php). Also if they find there is a need for something completely new or a better implementation (thrift, protocol buffers, cassandra, big table), they not only create it, they open source it too.

I think the reason is control and minimizing risk because you do not have to depend upon a vendor to provide a solution for you.


问:
Other than XML, what are some examples of "coding" a GUI design?
I've been trying to think outside of the box as to how desktop GUIs can be designed in code(not a graphical designer!). I've come across basically three ways this is done:

XML

Raw code (create a window, create a text box, add text box to window, etc)

HTML and friends

I'm sure that someone has done something other than these three though. Are there any existing examples of frameworks or languages which allow you to code a GUI using a format other than these three

答:
Treethon comes to my mind in Python.

It describes GUI in YAML format.

```<code># example base2.triton
_import     : gtk
view        : gtk.Window(gtk.WINDOW_TOPLEVEL)
add         :
    - view      : gtk.Label('Hello World')
</code>```

Body:
Treethon comes to my mind in Python.

It describes GUI in YAML format.

# example base2.triton
_import     : gtk
view        : gtk.Window(gtk.WINDOW_TOPLEVEL)
add         :
    - view      : gtk.Label('Hello World')