问:
Using a Directory Service instead of a Database
I've just started working on an existing application that uses an LDAP directory service as its object store instead of a database. Many of my coworkers have been commenting how an application should never use a directory service instead of a database as its object store. I've got to work on it regardless, and won't be able to change it from LDAP to a database anytime soon.

That said, my coworkers comments brings up the question in my mind: Why is it bad to use a directory provider instead of a database as an object store? Could there ever be cases where this would not only acceptable, but even better than using a database?

答:
LDAP servers are often used in a web environment and often back user data. Single Sign On is nearly always backed by an LDAP data store. That one should always use a (relational) database rather than other data stores is... poor.

The key with any data store is to use the one that is most appropriate for the data.  Sometimes the data fits better in a traditional database, sometimes it is best in a nosql style data store, other times its a directory.  One should use the appropriate data store for the data.

The thing that LDAP excels at is fast lookups for rarely changing data. Going back to the user data (as an example), the email, password, name, and roles rarely change.

Similarly, cached data often fits well into a directory where you compute the data and then load it (which is then frequently read).

Directories, however, don't like frequently updating data.  Its a trade off - you can optimize for reads if you penalize writes.  Rebuilding indexes on the fly is not something that LDAP does well when comparing it to a relational database.

How (and how well) transactions work are still within flux within LDAP.  If you want to have multiple updates be a single atomic operation, this may cause problems.

Referential integrity (foreign keys, unique constraints) does not exist within LDAP.  Similarly, if this is what you need, you may find it difficult.

While one could pack JSON data into a field within LDAP, LDAP itself doesn't try to do the data structures that are present in other databases.

If you are doing a not-occasional number of writes or updates (and thus impacting performance), 'joins' of data rather than filters, or want faster consistency than ldap replication offers you may find that LDAP data store is not appropriate.

But as a data store for stuff that rarely changes, it is often one of the best.


问:
Where does paypal's 92233720368547800 number come from?
There has been a story in the news about a man whose Paypal account was accidentally credited with $92,233,720,368,547,800.

Where does this number come from? What sort of programming bug is likely to give rise to this number?

答:
It's the maximum value of a long (64 bit signed integral type).

from http://msdn.microsoft.com/en-us/library/system.int64.maxvalue.aspx

The value of this constant is 9,223,372,036,854,775,807; that is, hexadecimal 0x7FFFFFFFFFFFFFFF.

This would be the maximum value for a 64-bit signed integral type in any language, I'm not assuming paypal uses .NET, the link to MSDN above is just illustrative.

The error is likely just a poor conversion error (like from decimal or float or etc to long that didn't work correctly) resulting in some overflowing of a value, or bad defaulting code for some strange scenario, or it could have been a test in production by their engineering/QA team gone hay-wire. Memory leak/pointer error, the list of ways to cause this are really countless. Could have been a parsing error deserializing some information that came to them across the wire, tremendously numerous ways to accidentally end up with an unexpected or misaligned integral value.

ContentLicense: CC BY-SA 3.0


问:
Make shareware program free in some countries
Idea. To make my shareware program free in less-developed countries. Or release a free edition for these countries.

Purpose. More users, bug reports, extensions, active forum, etc. Anyway, 90% sales are in ~30 richest countries. Why not make it free in China, India, Russia...

Question. What are possible problems? I can't find info on this topic. It seems that almost nobody does it (I know only Windows 7 Home Basic).

Algorithm. How would you implement it? I know it's possible to detect country using IP. It's OK if would fail to detect in 20% cases. When country is detected, the user would get license key for free. Country detection and license key generation can be implemented in web server.

EDIT:
Country detection can be performed when user wants (clicks button 'Register for free'). Then program connects to my website, which detects country and generates a license key from user's hardware ID. Then the free key can be used on that PC like a purchased key, and no internet connection required. On other PC/hardware the user can simply repeat the procedure, as long as he/she is in one of these countries.

EDIT:
Country detection is easy and fast, i tested it with this php script+database. It worked with all IPs of my website visitors of this month. However some of them may actually live in other countries (see jwenting answer).

答:
You might consider a different approach.  Rather than embedding country checking into the software itself (which opens the door to potential support issues), do it on your web site when you distribute your application.  When visitors visit from one set of countries, you make the download free.  From another, you require a purchase.  Its not 100% guaranteed to be accurate, but between Geo IP and browser geolocation support, you should get 90%+.

Keep in mind this whole approach assumes that the specific user in a developing country is less able to spend money on software than a specific user in a richer country, and that may not be the case.  There are lots of billionaires in Russia and China, for example.


问:
Queries on online project outsourcing sites
I have been looking at RentACoder, Freelancer and eLance from last few years but I always hesitated to register at these site. Hesitation includes little worry too. These questions fill me:

(1) Is there a legal contract between the bidder and the coder? Just in case my delivery date extends, what happens?

(2) After delivery, payment reach without trouble or not.

(3) In case the customer didn't find the project useful, then? Probably he might say that it is not useful to me and you return money. He might copy the source code and return another copy to me.

(4) What are further recommendations? How should I start?

答:
Just to expand on a few things previously contributed:

If a worker doesn't complete a project by an agreed upon deadline, the project's employer doesn't have to pay for it. A project's deadline is part of a contract that must be complied with. In my experience, employers willingly extend a deadline when they see favorable progress. So as long as you put forth a good, honest effort within a reasonable amount of time, a 3-5 day deadline extension (or whatever's required) is typically honored.

Should an employer not find a project useful and refuse to pay for it, you can take the matter up with the site's arbitration service and have an arbitrator decide whether or not the project complies with the project's contract. A project that complies with its contract warrants payment, and Rentacoder (now vWorker) will release the project's funds to the worker whether the employer agrees with that decision or not. That's one of the benefits of freelancing through Rentacoder. The site's staff actually takes the time to verify a contract has been honored (some other sites don't bother). It's not a risk at all and neither the worker or employer are favored as a result.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Just Outsourcing

LastEditorDisplayName: Just Outsourcing


问:
Premature optimization in deciding how to optimize?
We have a class that has been properly identified for optimization. We've done the profiling and testing, and it's a problem.

Now we have two possible approaches for optimizing this class:

There is some very low-hanging fruit. We can rewrite this in a few days in such a way that the interface and results aren't changed, so we don't have to change any code that uses the class. We can see what effect this has on performance and go from there. This seems to me to be a very low risk, low investment approach.

Since we're already going to be making changes, we could go all out in our optimization. The suggested approach would implement a third-party engine and require us to change the code that uses this class, as well as transform the existing client data that is sent to the class into a format usable by the third-party engine. This may not take too much longer to code, but there would be much more testing required. This seems like a very high-risk, high-investment change and will require a lot of extra testing to make sure we don't break the calling code and don't break the existing client data.

I of course can't test ahead of time, but the second approach will probably execute more quickly and be more memory-efficient. However, I'm not sure how much faster, and I'm not sure if the extra effort will even be worth it. I'm not sure that once we made the low-risk changes, we would still consider the the code to be a valid target for optimization.

You can probably guess which approach I would rather take. I'm at odds with a coworker on this one.

So here's my question: Is the second option premature optimization despite the fact that we've already identified this code for optimization? What's the approach that should be taken in this situation?

答:
This is what so many people do - the "ready, fire, aim" approach.
They fix a problem before knowing if it is a problem.
Then if a little time was saved they say "See, it worked! Can we move on now?", or if it doesn't save much they say "Well, we need to try another guess".

Don't invest any time in fixing stuff unless you know it will save significant time, and here's how I find out. Keep an open mind and let it tell you what to fix.
It will probably be different from what you would have guessed.

Then rinse, and repeat.
That's how you do serious performance tuning.


问:
Writing map of data to XML according to a format which is user-defined
I need to write a map of string data to an XML document. The XML document has a specific format. An entry key determines where in the XML document the value will be written to. See below for an example (pseudo-code where appropriate);

```<code>map = {"document_id": "123"; "document_type": "type_A"}
</code>```

Produces an XML file like this;

```<code><document>
    <document_id>123</document_id>
    <document_type>type_A</document_type>
</document>
</code>```

I need the format of the target XML document (and where the map data is written to in it) to be user-configurable. For example;

```<code><node name="document">
    <node name="document_id">${document_id}</node>
    <node name="document_type">${document_type}</node>
</node>
</code>```

I feel like my proposed solution would be complex and a re-invention of the wheel. I figure there must be some established way to do this but after searching the internet I can't seem to find it. Can anyone offer suggestions on how I may achieve what I want to do?

答:
have you looked into using an XSLT file for transforming the information?

I imagine that you could take the Data entered into a form and create a new XML file and then use an XSLT file to format it to the right XML format and insert it into your target XML.

I think this is kind of what you are looking for if i read the question correctly


问:
NHibernate and complex domain model against a legacy database
I'm trying to refactor (actually, rewrite) an application which currently uses only stored procedures to access the database (hundreds of SPs). My goal is to use Nhibernate and follow a good design as much as possible.
But since the database (and the SPs) are used by dozens of other apps, I can't really change the db design. And off course, it's awful.

I'm facing a design problem and I can't really find a good solution.
I have a table called movies which contains movies, but these movies can be different "things". For example, this table contains movies as well as episodes of tv shows and the only way to know the difference is a field named "episode" which is set to 0 for movies and 1 for episodes.

My objective is to expose the following class hierarchy :

```<code>public abstract class Program {}
public class Episode : Program {}
public class Movie : Program {}
</code>```

Currently, I have mapped the whole movies table to a model class MoviesModel and then I build my Episode/Movie class through AutoMapper and a factory method in the Program class :

```<code>public static Program Load(MoviesModel movieModel)
    {
        if (movieModel.Episode > 0)
            return Mapper.Map<Episode>(movieModel);
        return Mapper.Map<Movie>(movieModel);
    }
</code>```

This seems really wrong on many levels : I have an anemic data model since my MoviesModel is totally empty of any business logic, the automapper stuff becomes really hard to maintain when I add many other entities with relations to Movies, and I break the lazy loading with AutoMapper.

I heard about the any mapping of nhibernate but it doesn't really solve my issue, it just creates sub components of a class.

So my questions are :

Ideally, where should be my business logic ? I guess in the MoviesModel class but I don't really like the idea to expose my database fields.

Is there a way with nhibernate to map the same table in different classes based on a field value ?

Is there a point to wrap the nhibernate objects if I want to provide a "clean" public API ?

My goal is to build a base library which will be used (hopefully) on other legacy apps so I want to provide a clean API with logical methods and without exposing the database mess even if I still have to deal with it.

Thanks for any help to put me in the right direction.

答:
Unfortunately I don't know much about AutoMapper but I can offer a solution to your second question. Fluent NHibernate is a tool to aide with your NHibernate mappings, allowing you to configure them in a programmatic way rather using than XML. One of the methods you can call when setting up your mappings is DiscriminateSubClassesOnColumn() which allows you to specify the database column that will be used to create your sub-classes. Then in your sub-classes you specify the DiscriminatorValue which can be an enum.

Here is what I imagine your mappings to look like (untested code):

```<code>public class ProgramMap : ClassMap<Program>
{
    public ProgramMap()
    {
        //map your fields as normal, eg: Map(p => p.Id), Map(p => p.Name)
        DiscriminateSubClassesOnColumn<int>("Episode");
    }
}

public class MovieeMap : SubclassMap<Movie>
{
    public MovieMap()
    {
        DiscriminatorValue(0);
    }
}
</code>```

The problem may actually be specifying the DiscriminatorValue for your Movies but hopefully this gives you something to go on. For reference I've used the following links to put this answer together so they may be worth a look in case I've missed something out.

https://stackoverflow.com/questions/10737531/table-per-class-inheritance-with-fluentnhibernate-identity-generation

http://fluentnhibernate.wikia.com/wiki/Fluent_mapping

https://stackoverflow.com/questions/1345426/fluent-nhibernate-table-per-hierarchy-mapping-problem

Note that if you don't specify the DiscriminatorValue, Fluent NHibernate assumes that the discriminator column contains your class name (which would be a terrible database design!).

Body:
Unfortunately I don't know much about AutoMapper but I can offer a solution to your second question. Fluent NHibernate is a tool to aide with your NHibernate mappings, allowing you to configure them in a programmatic way rather using than XML. One of the methods you can call when setting up your mappings is DiscriminateSubClassesOnColumn() which allows you to specify the database column that will be used to create your sub-classes. Then in your sub-classes you specify the DiscriminatorValue which can be an enum.

Here is what I imagine your mappings to look like (untested code):

public class ProgramMap : ClassMap<Program>
{
    public ProgramMap()
    {
        //map your fields as normal, eg: Map(p => p.Id), Map(p => p.Name)
        DiscriminateSubClassesOnColumn<int>("Episode");
    }
}

public class MovieeMap : SubclassMap<Movie>
{
    public MovieMap()
    {
        DiscriminatorValue(0);
    }
}

The problem may actually be specifying the DiscriminatorValue for your Movies but hopefully this gives you something to go on. For reference I've used the following links to put this answer together so they may be worth a look in case I've missed something out.

https://stackoverflow.com/questions/10737531/table-per-class-inheritance-with-fluentnhibernate-identity-generation

http://fluentnhibernate.wikia.com/wiki/Fluent_mapping

https://stackoverflow.com/questions/1345426/fluent-nhibernate-table-per-hierarchy-mapping-problem

Note that if you don't specify the DiscriminatorValue, Fluent NHibernate assumes that the discriminator column contains your class name (which would be a terrible database design!).


问:
is there a programming language designed to express data combinations?
Very often, when using the command line or just programming, you want to express some kind of combination that you end up using a for - which is often verbose.

```<code>for (int i = 0; i<10; ++i)
    std::cout << "img_" << i << std::endl;

for f in *; do echo "$f"; done
</code>```

I always wondered if there is some kind of language made to simplify this case? For example:

```<code>"mv img_[0~6] imgs"
</code>```

Would translate to

```<code>mv img_0 imgs
mv img_1 imgs
mv img_2 imgs
mv img_3 imgs
mv img_4 imgs
mv img_5 imgs
</code>```

img_[0~1][0~1] could work for img_00, img_01, img_10, img_11

img_[x:0~2][x] could work for img_00, img_11, img_22

Etc.

I'm not asking for this particular syntax, just if there is any kind of language/feature ever implemented with the purpose of expressing such combinations as easy as possible?

答:
To answer your immediate concern, bash can do some range-based actions on existing files.

```<code>$ ls
sample1.txt  sample2.txt  sample3.txt  sample4.txt  samples

$ mv sample[1-3].txt samples/

$ ls *
sample4.txt

samples:
sample1.txt  sample2.txt  sample3.txt
</code>```

But there is a bigger trend at play here. Array programming tries to get away from explicit loops. It was really pushed by APL in the beginning and is now common in many mathematical languages like MATLAB or Mathematica. For example, I can add two numerical arrays with a simple

```<code>c = a + b
</code>```

Likewise, list comprehension uses set notation to build an array. This is a common feature in many languages today, including Python and Haskell.

```<code>S = [2 * x for x in range(101) if x ** 2 > 3]
</code>```

Within the realm of shell scripting, I can use xargs to execute a command on multiple inputs.

```<code>hg st | cut -d ' ' -f 2 | xargs rm     # delete my leftovers from Mercurial
</code>```

In the world of databases, SQL can perform queries and updates on an entire column.

```<code>select sym from stocks where price < 20.0 order by sym;
</code>```

And lastly, recursion obviates loops by defining an entity in terms of itself:

```<code>fac 0 = 1
fac x = x * fac (x-1)
</code>```

So there are lots of examples where languages have gone away from explicit iterations in favor of declarative structures.

Body:
To answer your immediate concern, bash can do some range-based actions on existing files.

$ ls
sample1.txt  sample2.txt  sample3.txt  sample4.txt  samples

$ mv sample[1-3].txt samples/

$ ls *
sample4.txt

samples:
sample1.txt  sample2.txt  sample3.txt

But there is a bigger trend at play here. Array programming tries to get away from explicit loops. It was really pushed by APL in the beginning and is now common in many mathematical languages like MATLAB or Mathematica. For example, I can add two numerical arrays with a simple

c = a + b

Likewise, list comprehension uses set notation to build an array. This is a common feature in many languages today, including Python and Haskell.

S = [2 * x for x in range(101) if x ** 2 > 3]

Within the realm of shell scripting, I can use xargs to execute a command on multiple inputs.

hg st | cut -d ' ' -f 2 | xargs rm     # delete my leftovers from Mercurial

In the world of databases, SQL can perform queries and updates on an entire column.

select sym from stocks where price < 20.0 order by sym;

And lastly, recursion obviates loops by defining an entity in terms of itself:

fac 0 = 1
fac x = x * fac (x-1)

So there are lots of examples where languages have gone away from explicit iterations in favor of declarative structures.


答:
In bash, you can write

```<code>mv img_{0..5} imgs/
</code>```

which is expanded by the shell to

```<code>mv img_0 img_1 img_2 img_3 img_4 img_5 imgs/
</code>```

You can also use a character class:

```<code>mv img_[0-5] imgs/
</code>```

which would only work for those files that already exist and match the expression, while the former expands to all the possibilities even if the files do not exist. The curlies can also pad the expanded number with zeros ({001..030}), reverse the order ({z..a}) or generate combinations ({a..z}{0..5}).

Title: is there a programming language designed to express data combinations?

Body:
Very often, when using the command line or just programming, you want to express some kind of combination that you end up using a for - which is often verbose.

```<code>for (int i = 0; i<10; ++i)
    std::cout << "img_" << i << std::endl;

for f in *; do echo "$f"; done
</code>```

I always wondered if there is some kind of language made to simplify this case? For example:

```<code>"mv img_[0~6] imgs"
</code>```

Would translate to

```<code>mv img_0 imgs
mv img_1 imgs
mv img_2 imgs
mv img_3 imgs
mv img_4 imgs
mv img_5 imgs
</code>```

img_[0~1][0~1] could work for img_00, img_01, img_10, img_11

img_[x:0~2][x] could work for img_00, img_11, img_22

Etc.

I'm not asking for this particular syntax, just if there is any kind of language/feature ever implemented with the purpose of expressing such combinations as easy as possible?

Body:
In bash, you can write

mv img_{0..5} imgs/

which is expanded by the shell to

mv img_0 img_1 img_2 img_3 img_4 img_5 imgs/

You can also use a character class:

mv img_[0-5] imgs/

which would only work for those files that already exist and match the expression, while the former expands to all the possibilities even if the files do not exist. The curlies can also pad the expanded number with zeros ({001..030}), reverse the order ({z..a}) or generate combinations ({a..z}{0..5}).


问:
How do you get into the zone? How long does it take? What steps do you take before?
Getting into zone is a pleasurable and fruitful process. We produce good source code and we get lots of satisfaction from our work done while being in the zone. But, how does one get into the 'zone'? Do you follow a specific process? Apart from switching of email system, mobiles and other mundane non-productive applications, is there anything else that can be done?</p>

答:
Concentrate on what you need to do. Make the effort to actually start doing it. This can be one of the hardest things - to actively stop fluffing about.

Don't have email open. Don't have Fakebook in another window. Don't have any StackExchange going. No forums. Only quiet. And then get on with it.

It generally takes me (and pretty much everyone else I know) about 15-20 mins to get there.

You can generally sustain "the zone" for about 2 hours, and generally only once per day - its mentally pretty tiring. If you are super-duper you might manage it twice in a day. After "the zone" the rest of your day is pretty much lightweight by comparison, you get things done but the burst of huge productivity is over.

Oh - and getting out of the zone takes about 3 seconds - eg a phone call, or somebody sticking their head and saying: "Can I bother you for a moment" - to which the answer is: "yes, you already did". Bang. The zone is gone. Another 15-20 to get back.

Amazing how many stupid s/w defects get introduced by getting knocked out of the zone.

Amazing also how many people (esp managers) think that open plan is a really good way to develop quality software (where nobody EVER gets into the zone let alone stays there).


问:
Why does git use hashes instead of revision numbers?
I always wondered why git prefers hashes over revision numbers. Revision numbers are much clearer and easier to refer to (in my opinion): There is a difference between telling someone to take a look at revision 1200 or commit 92ba93e! (Just to give one example).

So, is there any reason for this design?

答:
Data integrity.

I respectfully disagree with the current answers. Hashes are not necessary for a DVCS, see the Bazaar way. You could do as well with any other kind of globally unique identifier. The hashes are a measure to guarantee data integrity: They represent a digest of the information contained in the object (commit, trees, ...) referred to by the hash. Altering the contents without altering the hash (i.e., a preimage attack or collision attack) is believed to be difficult, although not impossible. (If you're really into it, take a look at  the 2011 paper by Marc Stevens).

Hence, referring to objects by their SHA hash allows to check if the contents have been tampered with. And, given that they're (almost) guaranteed to be unique, they can be used as revision identifiers, too -- conveniently so.

See Chapter 9 of the Git book for more details.


问:
Object Oriented Design
Suppose you have the following:

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+------+     +----+-+
       ^                 ^
       |                 |
       |                 |
  +------+              +-------+
  | Deer |              | Grass |
  +------+              +-------+
</code>```

Deer inherits from Animal, and Grass inherits from Food.

So far so good. Animal objects can eat Food objects.

Now lets mix it up a bit. Lets add a Lion which inherits from Animal.

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+-----++     +----+-+
       ^     ^           ^
       |     |           |
       |     |           |
  +------+ +------+     +-------+
  | Deer | | Lion |     | Grass |
  +------+ +------+     +-------+
</code>```

Now we have have a problem because Lion can eat both Deer and Grass, but Deer is not  Food it is Animal.

With out using multiple inheritance, and using object oriented design, how do you solve this problem?

FYI: I used http://www.asciiflow.com to create the ASCII diagrams.

Title: Object Oriented Design

Body:
You want to further break down animals into their sub classes (or at least as far as makes sense for what you're doing). Given that you are working with what look like basic animals and two types of food (plants and meat), it makes sense to use carnivores and herbivores to further define an animal and keep them seperate. Here's what I drew up for you.

             +----------------+                   +--------------------+
             |    Animal      |                   |      Food          |
             |----------------|<--+Interfaces+--->|--------------------|
             |                |                   |                    |
             +----------------+                   +--------------------+
                +           +                       +                 +
                |           |    Abstract Classes   |                 |
                |           |        |          |   |                 |
                v           v        v          v   v                 v
   +-----------------+  +----------------+     +------------+      +------------+
   |   Herbivore     |  |  Carnivore     |     |   Plant    |      |   Meat     |
   |-----------------|  |----------------|     |------------|      |------------|
   |Eat(Plant p)     |  |Eat(Meat m)     |     |            |      |            |
   |                 |  |                |     |            |      |            |
   +-----------------+  +----------------+     +------------+      +------------+
            +                    +                    +                   +
            |                    |                    |                   |
            v                    v                    v                   v
   +-----------------+  +----------------+     +------------+      +------------+
   |  Deer           |  |   Lion         |     |  Grass     |      |  DeerMeat  |
   |-----------------|  |----------------|     |------------|      |------------|
   |DeerMeat Die()      |void Kill(Deer) |     |            |      |            |
   +-----------------+  +----------------+     +------------+      +------------+
                                 ^                    ^
                                 |                    |
                                 |                    |
                              Concrete Classes -------+

As you can see, they both expose an eat method, but what they eat changes. The Lion can now kill a deer, the deer can die and return DeerMeat, and OPs original question of how to allow a lion to eat a deer but not grass is answered without engineering an entire ecosystem.

Of course, this gets interesting very quickly because a Deer could be considered a type of meat as well, but to keep things simple, I would create a method called kill() under deer, which returns a deer meat, and put that as a concrete class extending meat.


答:
OO is just a metaphor that patterns itself after the real world. But metaphors only go so far.

Normally there is no right way to model something in OO. There is a right way to do it for a particular problem in a particular domain and you shouldn't expect it to work well if you change your problem, even if the domain objects are the same.

I think this is a common misconceptions most Comp. Eng. students have in their first years. OO is not a universal solution, just a decent tool for some kind of problems that can model your domain reasonably well.

I didn't answer the question, precisely because we lack domain info. But with the above in mind you might be able to design something that suits your needs.

Title: Object Oriented Design

Body:
Suppose you have the following:

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+------+     +----+-+
       ^                 ^
       |                 |
       |                 |
  +------+              +-------+
  | Deer |              | Grass |
  +------+              +-------+
</code>```

Deer inherits from Animal, and Grass inherits from Food.

So far so good. Animal objects can eat Food objects.

Now lets mix it up a bit. Lets add a Lion which inherits from Animal.

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+-----++     +----+-+
       ^     ^           ^
       |     |           |
       |     |           |
  +------+ +------+     +-------+
  | Deer | | Lion |     | Grass |
  +------+ +------+     +-------+
</code>```

Now we have have a problem because Lion can eat both Deer and Grass, but Deer is not  Food it is Animal.

With out using multiple inheritance, and using object oriented design, how do you solve this problem?

FYI: I used http://www.asciiflow.com to create the ASCII diagrams.


问:
searching for a user given word in a webpage using c# and selenium
I am trying to develop a selenium application (using c# win forms). So, while the application starts, the users will enter an app name in the text box. I have many fields such as cost, validity etc corresponding to each app.

Example webpage:

```<code>description  appname  cost  validity  xyzattribute
--------------------------------------------------
some desc     app1     10      30     someattribute
</code>```

I want selenium to search the entire page for that given app name and if it finds any, I want selenium to retrieve all the attributes (cost, validity) and store those in a variable. How can I achieve this?

Please note that none of these fields have a unique attribute (such as name/id/any other).

答:
If I were you, I would take advantage of Seliniums ability to run and get results from arbitrary javascript commands. Let's assume you have a structure something like this:

```<code><table id="mytable">
    <tr>
       <th>description</th>
       <th>appname</th>
    <tr>
    <tr>
       <td>description 1</td>
       <td>appname 1</td>
    <tr>
    <tr>
       <td>description 2</td>
       <td>appname 2</td>
    <tr>
<table>
</code>```

To get the the description column value on the second row, you could run this javascript code:

```<code>var secondDescription = document.getElementById("mytable").rows[1].children[0].innerHtml
</code>```

In C#, you first create an instance of IJavascriptExecutor (http://selenium.googlecode.com/svn/trunk/docs/api/dotnet/html/M_OpenQA_Selenium_IJavaScriptExecutor_ExecuteScript.htm):

```<code>IWebDriver driver = new FirefoxDriver(); //or whatever
IJavascriptExecutor jsDriver = (IJavaScriptExecutor) driver;
</code>```

Then to get a value in C#, you simply run the javascript command:

```<code>string secondDescription = jsDriver.ExecuteScript("document.getElementById(\"mytable\").rows[1].children[0].innerHtml");
</code>```

Body:
If I were you, I would take advantage of Seliniums ability to run and get results from arbitrary javascript commands. Let's assume you have a structure something like this:

<table id="mytable">
    <tr>
       <th>description</th>
       <th>appname</th>
    <tr>
    <tr>
       <td>description 1</td>
       <td>appname 1</td>
    <tr>
    <tr>
       <td>description 2</td>
       <td>appname 2</td>
    <tr>
<table>

To get the the description column value on the second row, you could run this javascript code:

var secondDescription = document.getElementById("mytable").rows[1].children[0].innerHtml

In C#, you first create an instance of IJavascriptExecutor (http://selenium.googlecode.com/svn/trunk/docs/api/dotnet/html/M_OpenQA_Selenium_IJavaScriptExecutor_ExecuteScript.htm):

IWebDriver driver = new FirefoxDriver(); //or whatever
IJavascriptExecutor jsDriver = (IJavaScriptExecutor) driver;

Then to get a value in C#, you simply run the javascript command:

string secondDescription = jsDriver.ExecuteScript("document.getElementById(\"mytable\").rows[1].children[0].innerHtml");


答:
My design would be like this:

Foods are declared as interfaces; there is an IFood interface and two derivated interfaces from it: IMeat and IVegetable

Animals implement IMeat and Vegetables implement IVegetable

Animals have two descendants, Carnivores and Hebivores

Carnivores have the Eat method that receives an instance of IMeat

Herbivores have the Eat method that receives an instance of IVegetable

Lion descends from Carnivore

Deer descends from Herbivore

Grass descends from Vegetable

Because Animals implement IMeat and Deer is an (Herbivore) Animal, Lion, which is a (Carnivore) Animal that can eat IMeat can also eat Deer.

Deer is a Herbivore, so it can eat Grass because it implements IVegetable.

Carnivores can´t eat IVegeable and Herbivores can´t eat IMeat.

Title: Object Oriented Design


答:
What foods an animal can eat don't actually form a hierarchy, in this case nature failed inexcusably to conform to simple object oriented modelling (note that even if it did, animal would have to inherit from food, since it is food).

Knowledge of what foods an animal can eat can't live entirely with either of the classes, so simply having a reference to some member of the food hierarchy can't be enough to tell you what things you can eat.

It's a many to many relationship.  This means every time you add an animal, you need to figure out what it can eat, and every time you add a food, you need to figure out what can eat it.  Whether there is further structure to exploit depends on what animals and foods you are modeling.

Multiple inheritance doesn't really solve this very well either.  You need some kind of collection of things an animal can eat, or of animals that can eat a food.

Title: Object Oriented Design


答:
With out using multiple inheritance, and using object oriented design,
  how do you solve this problem?

Like most things, it depends.

It depends on what you see 'this problem' to be.

Is it a general implementation problem, e.g. how to 'get around' the
absence of multiple inheritance in your chosen platform?

Is it a design problem just for this specific case, e.g. how to
model the fact that animals are also food?

Is it a philosophical problem with the domain model, e.g. are 'food'
and 'animal' valid, necessary, and sufficient classifications for the
envisioned practical application?

If you're asking about the general implementation problem, the answer will depend on the capabilities of your environment. IFood and IAnimal interfaces could work, with an EdibleAnimal subclass implementing both interfaces. If your environment doesn't support interfaces, just make Animal inherit from Food.

If you're asking about this specific design problem, just make Animal inherit from Food. It's the simplest thing that could possibly work.

If you're asking about these design concepts, the answer strongly depends upon what you intend to do with the model. If it's for a dog-eat-dog video game or even an application to track feeding schedules at a zoo, it might be enough to work. If it's for a conceptual model for animal behavioral patterns, it's probably a tad shallow.

Title: Object Oriented Design


问:
In MVC, what is the difference between controller and router?
Do they mean the same thing (attaching URLs to actions, or actions to URLs) or is there any difference I'm missing?

Example: http://github.com/dannyvankooten/PHP-Router vs. http://konstrukt.dk

答:
Quite simply a router works out a journey through the application, usually based upon external input such as GET or POST variables.

A Router is not however any part of an MVC, several MVC and HMVC frameworks use routers, but this does not bind them to the pattern of MVC.

Additionally several early implementations of MVC I have seen actually relied on file-based separation of actions with one file per controller for accessing separate controllers. This serves the application much better, because by having skinny controllers, with more robust models, you never have to scroll to a particular method in the controller, and you can therefore access the logic in one place (the model), allowing you to composite behaviours.


答:
IS A relationships = Inheritance

Lion is an animal

HAS A relationships = Composition

Car has a wheel

CAN DO relationships = Interfaces

ICanEat

Title: Object Oriented Design


问:
Starting Development with Python
I'm currently a beginning developer (3 years). I have been mainly doing Web Development for as long as I have been developing. This is my comfort zone when it comes to programming.

I like both JavaScript and PHP because they are easy to use; however, I would really like to further my knowledge when it comes to programming. I've been doing some research on many different languages just getting to know the look and feel of other languages.

I like C as it has a similar syntax to JavaScript. I also like Ruby and Java. However, I think I need to learn one at a time. I have decided on Python because of its clean syntax and the fact that a lot of people consider it a good beginner language.

My Problem

I'm coming from languages that are both easy to learn and use (JavaScript and PHP). For example, for JavaScript all you need is:

```<code><script type="text/javascript">
    //script here
</script>
</code>```

And you can execute a script and you can do things such as DOM manipulation.

For PHP all you need is a server that has PHP installed and you can use:

```<code><?php
    //script here
?>
</code>```

You can then just execute it either through AJAX or a request in a form.

I don't understand how to use Python. I don't believe you can just do AJAX requests with python files like you can with PHP files. What can I do with Python? Or do I use it? What have you made using it?

答: Consider using a web framework. I recommend using Django, they have a good tutorial that will guide you step by step through creating an application.</p>

Title: Starting Development with Python


答:
Python isn't a web development language by default. You can run CGI scripts manually or you can run something like the Django framework to use it as a server-side language or Brython to use it client side.

It is otherwise a massively flexible language used for everything from games to hard science. Python.org has a much more extensive list.

Be aware that there are two main versions of Python: 2.7 and 3.x. The future is 3.x but many libraries and tools still only work with Python 2.7.

Title: Starting Development with Python

Body:
I'm currently a beginning developer (3 years). I have been mainly doing Web Development for as long as I have been developing. This is my comfort zone when it comes to programming.

I like both JavaScript and PHP because they are easy to use; however, I would really like to further my knowledge when it comes to programming. I've been doing some research on many different languages just getting to know the look and feel of other languages.

I like C as it has a similar syntax to JavaScript. I also like Ruby and Java. However, I think I need to learn one at a time. I have decided on Python because of its clean syntax and the fact that a lot of people consider it a good beginner language.

My Problem

I'm coming from languages that are both easy to learn and use (JavaScript and PHP). For example, for JavaScript all you need is:

```<code><script type="text/javascript">
    //script here
</script>
</code>```

And you can execute a script and you can do things such as DOM manipulation.

For PHP all you need is a server that has PHP installed and you can use:

```<code><?php
    //script here
?>
</code>```

You can then just execute it either through AJAX or a request in a form.

I don't understand how to use Python. I don't believe you can just do AJAX requests with python files like you can with PHP files. What can I do with Python? Or do I use it? What have you made using it?


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
There are a couple of factors:

The type of personality that does well on social web sites (let's be bluntly rude and generalise that as the "pontificating, likes to hear self talk, theoretically-obsessed, anorak type") is by absolutely no means necessarily the type of personality who does well leading and/or working with a group of human beings (let's be bluntly rude and generalise that as the "smooching, glad-handling, compromising, deal-maker type").

As a broad rule, businesses are looking for the latter, not the former.

This is both very sad (I mean sad for us pontificators) and very true.

An interesting point: think of your actual BOSS, the person who has to handle all your problems all day, make you feel at least OK about yourself, balance everyone's renumeration, try to keep enough money coming in to your department so that all of you can feed your children while you fondle memory algorithms, deal with the chumps upstairs in management so you don't have to, and so on.  Would you really give a flying crap if that poor person has any connection, whatsoever, to some chat website? Of course the answer is no, you just want your boss to be good at to pulling off all that juggling.

Talk about "superstars" (let's be bluntly rude again) is a little star-struck. You're a superstar if you're so clever you've made millions (or at least the odd hundred thousand) because you're so clever. Oh, by the way, to do, that as well as being so clever, you have to as an incidental matter be utterly A+ rated at memory management and tricky algorithms.  If you're looking at only the latter incidental part, i.e., being utterly A+ rated at memory management and tricky algorithms, then sadly --- horribly ---- unfaily ---- bitterly ---- how can the world be so miserable? ---- you're "just" someone who's utterly A+ rated at memory management and tricky algorithms.

(OK, for all this bitterness and sadness, there is the exception of the extremely small number of purely extremely technical, really research, type ways to make money - in those cases sure, the only thing that matters is your various research breakthroughs, perhaps as a humorous side issue your amazing score on grouptheoryoverflow, and so on.  But there are so few such jobs it's probably not really in the spirit of the question "getting a job in the real world." And - bitterly - they don't pay that much.)

The question further is emphasising "high paying" jobs.  (We'll ignore the issue of whether $100,000 p/a is high paying or not, since Bernanke's hyperinflation makes it hard to keep up with such numbers.) It's probably sadly even more true that the kind of realistic bitterness outlined in this answer, is more and more and more true if you are talking about not merely "a job" (where you are expected to do something specific that you will be told to do, provide a cog in the process), but A Real Job (where you are expected to positively generate massive amounts of money for the company somehow or other as a matter of course, day in and day out)

It's hard to keep up with current salaries everywhere; it could be that "$100,000 !" fits in to the "rare purely proufoundly technical" job I mention in the aside just above.

However, the spirit of the question in some sense seems to be - to paraphrase and simplify - do top jobs have anything much to do with specifically purely technical, mathematical, expertise?

Sadly the answer there is pretty much definitively no.

It's more the "smooching, glad-handling, compromising, deal-maker type" - or, if you prefer to be bitter in another direction - the "big picture, ideas driven and generating and follow-through type" - that can - simply - generate enough money that some business can afford to give the person that much money.

Don't forget - to say you want to "earn" some fabulous salary, what you're essentially saying is you can generate jobs.  How so? If you're making 200k somewhere, you're a horse that is carrying a number (10? 25?) normal "do a job" employees on your back. You have to be a producer.

It is, sadly, difficult to see how some essentially test of excellence of technical knowledge (SO chat web site) can help with that.

Steve Jobs said it all - good engineers (he said) are not merely worth 10 or 20 ordinary engineers, they are worth some 100s of ordinary engineers ... they can generate that much product, stuff, free monthly cashflow, for the company.  I think that's more what Jobs would think of as one of his superstars. It's difficult to see how purely the technical aspect (a necessity) can bring that.

If that's the sense of the question in terms of "big jobs," then that's probably the answer.


问:
Why (not) segmentation?
I am studying operating systems and the x86 architecture, and while I was reading about segmentation and paging I naturally was curious how modern OSes handle memory management. From what I found Linux and most other operating systems essentially shun segmentation in favor of paging. A few of the reasons for this that I found were simplicity and portability.

What practical uses are there for segmentation (x86 or otherwise) and will we ever see robust operating systems using it or will they continue to favor a paging based system.

Now I know this is a loaded question but I am curious how segmentation would be handled with newly developed operating systems. Does it make so much sense to favor paging that no one will consider a more 'segmented' approach? If so, why?

And when I say 'shun' segmentation I am implying that Linux only uses it as far as it has to. Only 4 segments for user and kernel code/data segments. While reading the Intel documentation I just got the feeling that segmentation was designed with more robust solutions in mind. Then again I was told on many occasions how over complicated the x86 can be.

I found this interesting anecdote after being linked to Linux Torvald's original 'announcement' for Linux. He said this a few posts later:

Simply, I'd say that porting is impossible.  It's mostly in C, but most
  people wouldn't call what I write C.  It uses every conceivable feature
  of the 386 I could find, as it was also a project to teach me about the
  386.  As already mentioned, it uses a MMU, for both paging (not to disk
  yet) and segmentation. It's the segmentation that makes it REALLY 386
  dependent (every task has a 64Mb segment for code & data - max 64 tasks
  in 4Gb. Anybody who needs more than 64Mb/task - tough cookies).

I guess my own experimentation with x86 led me to ask this question. Linus didn't have StackOverflow, so he just implemented it to try it out.

答:
For 80x86 there are 4 options - "nothing", segmentation only, paging only, and both segmentation and paging.

For "nothing" (no segmentation or paging) you end up with no easy way to protect a process from itself, no easy way to protect processes from each other, no way to handle things like physical address space fragmentation, no way to avoid position independent code, etc. Despite all these problems it might (in theory) be useful in some situations (e.g. embedded device that only runs one application; or maybe something that uses JIT and virtualises everything anyway).

For segmentation only; it almost solves the "protect a process from itself" problem, but it takes a lot of work-arounds to make it usable when a process wants to use more than 8192 segments (assuming one LDT per process), which makes it mostly broken. You almost solve the "protect processes from each other" problem; but different pieces of software running at the same privilege level can load/use each other's segments (there's ways to work around that - modifying GDT entries during control transfers and/or using LDTs). It also mostly solves the "position independent code" problem (it can cause a "segment dependant code" problem but that's much less significant). It doesn't do anything for the "physical address space fragmentation" problem.

For paging only; it doesn't solve the "protect a process from itself" problem much (but let's be honest here, this is only really a problem for debugging/testing code written in unsafe languages, and there's much more powerful tools like valgrind anyway). It completely solves the "protect processes from each other" problem, completely solves the "position independent code" problem, and completely solves the "physical address space fragmentation" problem. As an added bonus it opens up some very powerful techniques that aren't anywhere near as practical without paging; including things like "copy on write", memory mapped files, efficient swap space handling, etc.

Now you'd think that using both segmentation and paging would give you the benefits of both; and in theory it can, except that the only benefit you gain from segmentation (that isn't done better by paging) is a solution to the "protect a process from itself" problem that nobody really cares about. In practice what you do get is the complexities of both and the overhead of both, for very little benefit.

This is why almost all OSs designed for 80x86 don't use segmentation for memory management (they do use it for things like per-CPU and per-task storage but that's mostly just for convenience to avoid consuming a more useful general purpose register for these things).

Of course CPU manufacturers aren't silly - they aren't going to spend time and money optimising something that they know nobody uses (they're going to optimise something that almost everyone uses instead). For this reason CPU manufacturers don't optimise segmentation, which makes segmentation slower than it could be, which makes OS developers want to avoid it even more. Mostly they only kept segmentation for backward compatibility (which is important).

Eventually, AMD designed long mode. There was no old/existing 64 bit code to worry, so (for 64-bit code) AMD got rid of as much segmentation as they could. This gave OS developers yet another reason (no easy way to port code designed for segmentation to 64-bit) to continue avoiding segmentation.

OwnerDisplayName: Mr. Shickadance

Title: Why (not) segmentation?


答:
I will approach the problem from different side : OOP is about behavior. In your case, does Grass have some behavior to be child of Food? So in your case, there won't be Grass class, or at least, it won't be inherited from Food. Also, if you need to enforce who can eat what at compile time, it is questionable if you need Animal abstraction. Also, it is not rare to see carnivores eating grass, albeit not for sustenance.

So I would design this as (not going to bother with ASCI art):

IEdible with property Type, which is enum of meat, plant, carcass, etc.. (this won't change often and doesn't have any specific behavior, therefore there is no need to model this as class hiearchy).

Animal with methods CanEat(IEdible food) and Eat(IEdible food), which are logical. Then, specific animals can check whenever then can eat given food in given circumstances and then eat that food to gain sustenance/do something else. Also, I would model classes Carnivore, Herbivore, Omnivore as Strategy pattern, than as part of animal hierarchy.

Title: Object Oriented Design


问:
What's the best approach to handle javascript/ajax code in a project?
In a general sense, for medium/big projects, what's the best way to handle javascript/ajax code?

Is it better, to have a script file where to put each script or, to add the script directly into the html file between  tags?

I know it doesn't make any difference in terms of result, but i would like to understand what's is easier to mantain in long terms.

答:
To put it in the html file is a very bad approach and will give you a bad headache sooner or later. To start with it would make it impossible to handle code shared between multiple pages.

I think a good way is to have one js file for every main html file, another one for every main functional group and one or more for the whole project. For example if you do complicated stuff with tables all over the site then your table.js would grow large enough to become a file of its own.

Your deployment process should then create one javascript file out of those files and minify it (or at most a very small number of files). This is important for page load performance. A good web framework should be able to do this without too much overhead.


答:
In my opion it's always easier to maintain a seperation between html, css and javascript, and keep everything in seperate files.

As for handling ajax, I often write code as object literals and create an ajax method that is easy to use, and where there is a similar method on the serverside that parses whatever I decide to send etc.

```<code>var main = {
    init: function() { // do stuff on page init
        this.events().render();
    },
    events: function() { // bind event handlers
        var self = this;

        $('#element').on('click', function() {
             var value = $('input.search').val();

             self.ajax('search', value).done(function(data) {
                  $('#results').html(data);
             });
        });
        return self;
    },
    render: function() {
        $('body').append('some elements').fadeIn(1000);
    },
    ajax: function(type, value) {
        return $.ajax({
             url : '/controller/ajax/',
             data: {type:type, value:value}
        });
    }
}
</code>```

Title: What's the best approach to handle javascript/ajax code in a project?

Body:
In a general sense, for medium/big projects, what's the best way to handle javascript/ajax code?

Is it better, to have a script file where to put each script or, to add the script directly into the html file between  tags?

I know it doesn't make any difference in terms of result, but i would like to understand what's is easier to mantain in long terms.

Body:
In my opion it's always easier to maintain a seperation between html, css and javascript, and keep everything in seperate files.

As for handling ajax, I often write code as object literals and create an ajax method that is easy to use, and where there is a similar method on the serverside that parses whatever I decide to send etc.

var main = {
    init: function() { // do stuff on page init
        this.events().render();
    },
    events: function() { // bind event handlers
        var self = this;

        $('#element').on('click', function() {
             var value = $('input.search').val();

             self.ajax('search', value).done(function(data) {
                  $('#results').html(data);
             });
        });
        return self;
    },
    render: function() {
        $('body').append('some elements').fadeIn(1000);
    },
    ajax: function(type, value) {
        return $.ajax({
             url : '/controller/ajax/',
             data: {type:type, value:value}
        });
    }
}


答:
Get the first task on your well maintained list.

The secret is having that list!

There is one really effective way to beat procrastination. It has been described in the book Getting Things Done.

First you have to maintain a list of things to do. The methodology proposed is great (read it on wikipedia).

Then it's the way you write your tasks.

Rather than writing:

Do the documentation of the new ui (ouch a good candidate for procrastinators)

Write:

Call Robert to ask him to include Take screenshots of the new UI Write a summary about what to say Etc.

The trick is that tasks are small, and are actual actions. It's easy to start. And everybody here know that when you started, you have beaten procrastination.

Title: How do you get into the zone? How long does it take? What steps do you take before?

Body: Getting into zone is a pleasurable and fruitful process. We produce good source code and we get lots of satisfaction from our work done while being in the zone. But, how does one get into the 'zone'? Do you follow a specific process? Apart from switching of email system, mobiles and other mundane non-productive applications, is there anything else that can be done?</p>


问:
Mixing Fowlers Transaction Script and Domain Model
I am developing a large application where the previous developer used Martin Fowlers Transaction Script pattern.

The requirements are becoming more complex and it is becoming a bit of a maintenance nightmare. Therefore I have started to use Fowlers Domain Model and Table Data Gateway in an attempt to separate concerns and reuse code. It is becoming a refactoring process.

My question is: is it bad practice to mix and match patterns? e.g. using Transaction Script and Domain Model in the same application or is this relatively common practice?

答: It is fine to mix domain logic patterns. A large system can be broken down into modules with domain logic patterns selected based on complexity of each module e.g. Complex stuff - Domain Model Pattern and simple stuff can use Transaction Script. If then you find some simple modules are beginning to become complex you can refactor to the domain model pattern. I cover this in a book I am writing at the moment https://leanpub.com/Practicing-DDD</p>


问:
Fowlers Data Access Layer patterns
Fowler talks about a number of design patterns available for the data access layer e.g. Table Data Gateway, Row Data Gateway, Active Record and Data Mapper.

In the book it suggests using Data Mapper with Transaction Script and Active Record with Domain Model.  This doesn't seem to be logical to me as Transaction Script classes contain business logic and data logic and domain model separates business logic and data logic.  Active Record combines business logic and data logic (like Transaction Script rather than domain model) and Data Mapper separates business logic and data logic (like domain model rather than Transaction Script).  What am I not understanding here?

答:
Point 1 Patterns are a means to simplify communication about various concepts.  Patterns are not intended to be used as LEGOs where they snap together and solve problems.  Combinations of concepts may help resolve a problem, but you should not expect to be able to simply pick and choose patterns for your needs.  First and foremost, they are a communication aid.

Point 2 Domain logic != Business logic, and I think this is the crux of your misunderstanding.

Per Fowler:

Active Record and Data Mapper are Data Source Architectural Patterns.

Transaction Script and Domain Model are Domain Logic Patterns.

And he defines them as:

Active Record

An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.

Data Mapper

A layer of Mappers (473) that moves data between objects and a database while keeping them independent of each other and the mapper itself.

Transaction Script

Organizes business logic by procedures where each procedure handles a single request from the presentation.

Domain Model

An object model of the domain that incorporates both behavior and data.

You mentioned that Fowler suggests using

Data Mapper with Transaction Script

Active Record with Domain Model

and that you didn't understand the following aspects.

Transaction Script classes contain business logic and data logic

Which isn't correct.  Transaction script groups together similar business logic and doesn't say anything about data logic.

Domain Model separates business logic and data logic

Domain Model doesn't address business logic or data logic.  It puts together rules that are domain specific.  Those could be considered business rules, but they're not.  Domains have inherent rules to them that all businesses must conform to.  External regulation is a good example of domain logic that is not necessarily business logic, but still rules that must be conformed to.

Active Record combines business logic and data logic

No, Active Record merely deals with data logic and provides a wrapper around what may be a very complicated storage mechanism for the data.  No business logic here.

Data Mapper separates business logic and data logic

Factually, this is true, but that's disingenuous for this question.  Data Mapper is an isolation layer.  It would be a useful approach if there were multiple data sources to glom together.

Title: Fowlers Data Access Layer patterns


问:
Why do CSV file formats normally use quoting instead of escaping?
There are a lot of variants of the CSV "standard" (or lack thereof). I've never personally see any that use an escape character (like \) instead of surrounding each field with double quotes. Instead of foo,bar,"foo,bar" it would be foo,bar,foo\,bar.

This would be handy for situations where a file needs to manually inspected or edited by hand. When counting commas to find the right field, it seems that it would be easier to tell which ones were not field separators if they escaped instead of quoted.

I don't see how it would make a difference from a parsing perspective, though.

Why quote instead of escape?

答:
Your question includes the answer, when you wrote "I don't see how it would make a difference from a parsing perspective, though"

There is no compelling reason, it just is. Csv is a data format, so the main goal is to be parseable.


问:
How to save during real-time collaboration
I want multiple users to edit same document. Problem I'm facing is when a new user joins, he might see an outdated document. How do I make sure that new users get most recent changes?

Some solutions I thought of:

Save on every change. I don't like this solution because it will slow things down on UI and put load on db.

When new user joins, trigger save on all other clients. After other clients saved, load document.   With this there can be inconsistency still.

Any other suggestions would be helpful.

UPDATE: After looking into suggested solution, Google Realtime API, I found out that:

Users of your app must have Google Drive and give you access to their drive. This could at best present awkward UI flow or prevent users who don't have Google Drive from using realtime feature.

All the sharing settings that are done on your side, have to be replicated for Google document.

UPDATE 2: To acoomplish the goal, I went with Google's Firebase

答:
The solution is Operational Transformation (OT). If you haven’t heard of it, OT is a class of algorithms that do multi-site realtime concurrency. OT is like realtime git. It works with any amount of lag (from zero to an extended holiday). It lets users make live, concurrent edits with low bandwidth. OT gives you eventual consistency between multiple users without retries, without errors and without any data being overwritten.

But implementing OT is a difficult task and time consuming. So you might want to use an external library like http://sharejs.org/.


答: Close all browser windows pointing to StackExchange and enough, good coffee might be a good place to start.</p>


答:
Chicken and egg.

If I was defining a spec, I'd escape for the reasons that you state.  But any CSV parsing tool that you encounter (including Excel, sqloader, etc) is almost certain to use quoting, not escaping.  So if you want to produce it, you need to produce it quoted.  If you want to consume it, it is safe to assume that whoever generates it will quote.

Title: Why do CSV file formats normally use quoting instead of escaping?

Body:
There are a lot of variants of the CSV "standard" (or lack thereof). I've never personally see any that use an escape character (like \) instead of surrounding each field with double quotes. Instead of foo,bar,"foo,bar" it would be foo,bar,foo\,bar.

This would be handy for situations where a file needs to manually inspected or edited by hand. When counting commas to find the right field, it seems that it would be easier to tell which ones were not field separators if they escaped instead of quoted.

I don't see how it would make a difference from a parsing perspective, though.

Why quote instead of escape?


问:
How to accurately predict release items?
We are having a disconnect between development and business needs.

Business is asking me to produce an accurate list of deliverables for a fixed date and development being difficult to predict is pushing back saying that can only produce a list 80 or 90% accurate.

So my question is, how do we solve this problem? How to provide an accurate list of deliverables weeks before they are completed and fully tested?

答:
Take 80% of the features and give a 99% confidence level given the original timeframe.

For example:

If there is a 80% confidence for 10 features in 3 months, then give them a list of 8 features (80% of 10) for a 3 month time frame with a 99% confidence.

You should also show what the risks are, how you will mitigate them and what happens if the risk occurs.

Update

Many times the business side is asking for estimates and confidence levels in order to make proper marketing decisions.

I love Joel's blogs. I wish more companies read him and understood the principals behind proper development project management and time estimations. Unfortunately many companies are still stuck in a manufacturing mentality - "If you can build 1 part in 1 hour, why can't you build 10 parts in 10 hours?"

As proper engineers we read books, go to sites such as stack exchange and participate in the community. Proper time estimation is as much about math as it is people management. You have to manage your stakeholders (bosses, customers, project manager, etc) while not over burdening your engineering staff with impractical schedules and feature lists.

Too often management sees the end goal and wants to understand the time and effort to get to the finish line. This is where projects fall apart and estimations become fiction. Build a project plan in which your confidence level starts high and ends low.

If there are 5 features and 6 months your confidence scale could look like this:

Feature 1: 90%

Feature 2: 80%

Feature 3: 60%

Feature 4: 30%

Feature 5: 5%

You feel very confident you can complete Feature 1 in 6 months. However as the features start adding up you feel less and less confident you'll make it through all 5 features given 6 months. As the project progresses and features are completed this confidence scale is adjusted. As you can see the only way to be reasonably confident in completing the project on time is to only release Feature 1.

To give a significantly high confidence level in completing a set of features, the confidence scale needs to extend out until each of the required features are within a desirable range and only at the last feature does the confidence start slipping. This brings in it's own difficulties though. The longer a project takes the high the risk. This is why I like the idea of SCRUM.

Disclaimer All the numbers I have given are made up based on analysis of a fictitious company. Each engineering group is different. The numbers are here only to illustrate that as the features increase the confidence level significantly drops.

There is actual math that should be used when performing these scales. I have willfully and shamefully decided not to use math to ensure my numbers add up.


问:
Is it necessary to follow the standard, take the C standard for that matter?
There are some very experienced folks on Stack Overflow who always talk about the C standard. People seem to not like non-portable solutions, even if they work for me. Ok, I understand that the standard needs to be followed, but doesn't it put shackles on programmer's creativity?

What are the concrete benefits that come from following a standard? Especially since compilers may implement the standard slightly differently.

答:
There are a few reasons why sticking to the standard is a good thing.

Being locked into a compiler sucks hard. You're completely at the mercy of a group of developers with their own agenda. They're obviously not out to get you or anything, but if your compiler starts lagging on optimizations, new features, security fixes etc, too bad; You're stuck. In extreme cases some companies have to start patching whatever tool they have made themselves dependent on. This is a huge waste of money and time when there are other working tools out there.

Being locked into a platform sucks harder. If you're pushing software on Linux and and want to switch to Windows because you realize your market is really there, you're gonna have a heck of a time changing every non-portable hack you've got in your code to play nice with both GCC and MSVC. If you've got several pieces of your core design based around something like that, good luck!

Backward incompatible changes sucks the hardest. The standard will never break your code (Ignore python). Some random compiler writer though might decide that really this implementation specific add-on is not worth the trouble and drop it. If you happen to rely on it, then you're stuck on whatever old outdated version it was last in.

So the overriding message here, sticking to the standard makes you more flexible. You have a more limited language sure, but you have more

Libraries

Support (people know the standard, not every intricate compiler-specific hack)

Available platforms

Mature tools

Security (future proofness)

It's a delicate balance, but completely ignoring the standard is definitely a mistake. I tend to organize my C code to rely on abstractions that might be implemented in a non-portable way, but that I can transparently port without changing everything that depends on the abstraction.


问:
Getting related foreign keys from parent entities
I'm thinking about a design issue which affects my project's data base. Supposing there are three diferent tables:

CLIENT

ORDER

PACKING_SLIP

Each order has its client and different packing slips. So there are some foreign keys which are compulsory, there would be clientId for the ORDER and orderId for the PACKING_SLIP table. That makes full sense.

Now suppose in my logic I want to have access to the client from the packing slip. As I'm using an ORM tool as Hibernate, that involves firstly accessing the order from the packing slip and after getting the client from it.

If I want to have access to the client directly, I should add the clientId foreign key also to the PACKING SLIP table.

My question is, is that a correct design if there's a possibility to get the client joining the ORDER table? Isn't it a bit redundant? I think it's a control problem and the data base part shouldn't take care about it...

答:
Generally you'd do exactly what you've described -- have clientId in ORDER and orderId in PACKING SLIP, and join the two tables to geth the clientId for the PACKING SLIP.  Unless you have a really performance critical application, or unless you have a large number of orders, packing slips or clients, this is not a problem.

If you're really worried about performance, there is nothing wrong with adding clientId to the PACKING SLIP, though that would require adding code (or other logic) to ensure that clientId in PACKING SLIP will stay consistent with clientId in ORDER.  This may be best in situations when the application frequently needs to access clientId from PACKING SLIP without getting a corresponding ORDER and if you will be updating clientId in ORDER rarely.

Ideally this would be done using a stored procedure on the DB side, where updating an ORDER or adding a PACKING SLIP would be done through a stored procedure that will enforce the consistency of clientId, but I'm not sure whether your ORM allows that.  Alternatively, some ORMs provide a way to add such logic through code.


答:
I understand that the standard needs to be followed , but doesn't it put shackles on programmer's creativity?
  there are still some differences in the way different compilers follow the standards. I can for example write a code which works, very good in performance and speed i.e, all that matters, but still that may not necessarily strictly follow the standards.

No. The standard tells what is allowed to do. If it is not specified, you are in undefined behaviour territory, and then all bets are off - the program is free to do anything.

Since you mentioned specific example of void main() vs int main(), I can improve my answer.

void main() is not a standard declaration of the main function. It may work on some compilers through extensions, but it rely on the implementation. Even if it works, you have to check if it does what you want. The problem is, compiler developers may decide to remove void main() with next compiler release, breaking your application.

On the other hand, the standard clearly defines the signature of main as int main() and it tells what it should do.

On the other hand, there are things not defined in the standard. Then, another standard may apply (like for example, POSIX). The best example may be with threads implementation in c++03, since c++03 standard programs were 1-threaded. In that case, you are forced to use platform dependent library, or something like boost.

Title: Is it necessary to follow the standard, take the C standard for that matter?

Body:
There are some very experienced folks on Stack Overflow who always talk about the C standard. People seem to not like non-portable solutions, even if they work for me. Ok, I understand that the standard needs to be followed, but doesn't it put shackles on programmer's creativity?

What are the concrete benefits that come from following a standard? Especially since compilers may implement the standard slightly differently.


答:
The disconnect is that neither side understands the situation; business wants what it wants when it wants it and thinks that IT can just magically deliver regardless of the features and timeframes.

While it's nice for the business side to have that much confidence in IT, it is a 'fairy godmother syndrome' in action. IT is not Santa Claus, there are no magic elves, it all takes planning and work and time and experience, and it's never perfect.

Time is incompressible. It cannot be created. It can certainly be wasted though.

Accuracy can only be measured after you're done.

Confidence is a statistical measure based on estimates and black magic math.

If you say "we can have these 10 features done in 3 months with a confidence level of 80%" this implies a better than 97.79% confidence level for each feature [they multiply, it's not an average]. What you probably mean is "8 out of 10 of us think we can do this in 3 months", which is not the same thing.

All that aside, this is a fundamental project management issue, not limited to IT. It has nothing to do with Agile. There is no crystal ball that will guarantee an accurate list of deliverables months in advance. Businesses must understand the variables, but most of all the risks involved. IT must deliver the estimates along with the risks.

There are methods to help measure and improve, but gnat's comment about steady improvement is the most practical immediate advice - if the business side will go for it.

If not, then you guess, promise, fail, apologize, measure, and improve, like everyone else. And just when your numbers start lining up, the team dynamic will change and throw them off again, or the business will shift direction into new domains, restarting the learning curve.

That's the nature of project management.

Title: How to accurately predict release items?

Body:
We are having a disconnect between development and business needs.

Business is asking me to produce an accurate list of deliverables for a fixed date and development being difficult to predict is pushing back saying that can only produce a list 80 or 90% accurate.

So my question is, how do we solve this problem? How to provide an accurate list of deliverables weeks before they are completed and fully tested?


答:
This comment is far, far too short to properly explain why estimation is hard, and how to do it better.

Software Estimation: Demystifying the Black Art by Steve McConnell is the right length.

Often referred to as the “black art” because of its complexity and uncertainty, software estimation is not as difficult or puzzling as people think. In fact, generating accurate estimates is straightforward—once you understand the art of creating them. In his highly anticipated book, acclaimed author Steve McConnell unravels the mystery to successful software estimation—distilling academic information and real-world experience into a practical guide for working software professionals. Instead of arcane treatises and rigid modeling techniques, this guide highlights a proven set of procedures, understandable formulas, and heuristics that individuals and development teams can apply to their projects to help achieve estimation proficiency.

Discover how to:

Estimate schedule and cost—or estimate the functionality that can be delivered within a given time frame

Avoid common software estimation mistakes

Learn estimation techniques for you, your team, and your organization * Estimate specific project activities—including development, management, and defect correction

Apply estimation approaches to any type of project—small or large, agile or traditional

Navigate the shark-infested political waters that surround project estimates...

Just remember that in most organizations, the estimated delivery date tends to be the first date that nobody can prove it won't be done by.  That is part of why most organizations tend to underestimate schedules by a factor of 2, and manage to hit that schedule only because they strip out an average of half the promised features.


问:
Is it possible to learn maths via programming, or you should learn maths for programming?
I am not the best in maths, not very horrid either, but lower than the average, I've always been thinking to improve my maths, but schools and books didn't do the job because I get bored too fast. The only thing I don't get bored with is coding and gaming, so I thought what if coding a program that solves mathematical problems will help me understand maths better, most of these problems are limits (calculus), functions, Differential calculus, and some other subjects (I already said am not that good) similar to the previous noted.

My question is: Am I able to achieve a better knowledge in maths if I do some specific program coding, and if possible, is physics possible that way too? Or am I wrong and Maths should be learned before programming to help improve my coding?

P.S : C++ is the preferred language.

答:
Mathematics is a science with a very broad domain. There are different kinds of math that have explicitly nothing at all in common (apart from being math).

Now programming is often associated with math because computers compute and calculate, most fundamentally they do this with integer or floating point datatypes in discrete steps.

There are fields of math that you can study by programming by "approximating" mathematics in a program. Lets say you study differential calculus and calculate numerical values for small intervals thus "emulating" the limit of the "pure" math.

Other aspects of programming are easily mapped to math (maybe not part of your high school math class but still valuable math that does not happen to be part of a traditional curriculum). Type theory for example -- or mathematical induction.

Often the only way to reason about "correctness" of a piece of code is mathematical induction for example. This kind of reasoning can be seen especially in functional languages (recursion, etc.).

I.e. there are many ways to learn math while programming, but not all math is easily approachable in the computational model of our computers and programming languages.


答:
TL;DR: Design or model with a context.

I think your question is difficult because it lacks context of the actual problem you are trying to solve.  You have some models and some relationships, but lack the framework in which it needs to work.  Without context,  modeling and metaphors don't work well leave the door open to multiple interpretations.

I think it more productive to focus on how the data will be consumed.  Once you have the pattern of data usage it's easier to work backwards to what the models and relationships should be.

For example more detailed requirements will necessitate different object relationships:

support Animals eating non-Food like Gastroliths

support Chocolate as Poison for Dogs, but not for Humans

If we start in on the exercise of how to model the simple relationship presented the Food Interface may be best; and if that is the sum total how the relationships in the system then your fine.  However, just a few additional requirements or relationships can vastly affect the models and relationships that worked in the simpler case.

Title: Object Oriented Design


问:
How to justify migration from Java 6 to Java 7?
We were migrating from Java 6 to Java 7. The project is behind schedule and risks being dropped, in which case it will continue to use Java 6.

What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that  I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, Java 2D/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use.

[I am going through many sites like Oracle adoption guide, bug database, questions on Stack Overflow].

Update: Thanks for the answers.  We rescheduled the update to next release.  Closest we got was security.  Accepting the highest voted answer.

答: There may be a reason why you should not switch to Java 7: If you have to use Oracle's VM and your software either runs on embedded hardware or you will distribute it with embedded hardware: Oracle changed the JRE's license so that it's not licensed if above conditions are met; you'll need to buy a Java SE embedded license. See What does "general purpose system" mean for Java SE Embedded?


问:
Java naming conventions vs. C++/C naming conventions
I am a Java developer who is starting to pick up more and more C++/C (yes I know they're different, bear with me).  One thing that struck me as odd was the different naming conventions used by these languages.  In Java, is is very common to see something like this:

```<code>int someVariable = someFunction(someParameterToPass);
</code>```

However, in C++/C, it would look a bit different:

```<code>int some_variable = some_function(some_parameter_to_pass);
</code>```

The reason I ask is because I (alone, no team) have just started a large project using C++, and right now am using Java naming conventions in my code (it's what I'm used to).  But then I add in some external libraries to my code and it mixes the naming conventions together.  I understand the code easily, and use the differences to tell my code apart from library code.

Should I switch my naming convention for the sake of readability to others (while the LOC is relatively low), or stick with what I'm doing now (since I am the only developer)?

Note - my code has been peer reviewed, however, the reviewers mainly focused on the function of the code. They didn't mention mixed conventions, and I did not specifically ask them about this. They also didn't have experience with switching naming conventions.

答:
This is where you find the big issue with coding standards based on style - if your team doesn't write the entire codebase, then you're going to find you have mismatches with the other code's standard.

So, my advice is not to sweat it. As long as your code is clear, it really doesn't matter whether you use camel case, pascal case, or underscore style. Its more important that the code is readable.

You should never alter the style of the 3rd parties as that will make comparison with new versions impossible, so you have to stick with them. If you have 2 different-style libraries, you have no choice but to follow a standard that ignores code style. Its not that bad, if you're a good coder you can read any code style. If you're not, having a solitary style won't help you at all.


答:
The one line answer

There is probably nothing you can do now, but you can plan to improve over time.

An analogy

Ask your business partners how long it will take them as a team to mow the grass surrounding one of the hotels in your town. Most likely they won't be able to do it, because they've never mowed the lawn of a hotel before. However, if they mow that lawn, and then you ask them to estimate how much to mow the yard of another hotel, they will be able to give you a slightly better estimate.

Keep doing this over the course of the whole summer, and after a few months they can probably tell you with a fairly high level of accuracy how long it will take for any hotel, once they've seen and measured the hotel in person. Even though every hotel is different, they will be able to break the job down into pieces ("mow around the pool", "mow around the entrance", etc), estimate each piece reasonably accurately, and thus estimate the entire job.

Plan to do better

There is no way to look at a specification or idea and estimate how long it will take. However, if you are able to break a project down into a set of stories and accurately estimate the amount of time it will take to do each story, you can then use the historical velocity of your team(s) to predict when those stories will be done. With a mature team this can yield fairly accurate results. You still won't be 100% correct, but the probability is high that you will be pretty close.

The trick here is that this only works well for experienced, mature teams. There are two variables in play that are hard to stabilize. First, your team needs a stabile velocity. That is, they need to be able to regularly produce X units of work in a fixed period of time. Once they are able to do that, then it becomes much, much easier to estimate new stories because they have a frame of reference ("we spent Y time on feature A last month, and feature B is about as hard as feature A, so we expect to spend Y time on feature B, too").

When you have that stable velocity, you need to use what you've learned to estimate stories. This means that stories need to be small, no more than few days worth of work. Once you are able to accurately size your stories, the deadlines largely become an exercise in mathematics.

All that being said, even the best of teams can't predict what will happen over the course of several months. Make sure your releases (even if only internal milestones) are relatively short. Work on a couple months worth. Hit that goal, then use the data to figure out how much you can do in the next month or two. Hit that goall, then lather, rinse, repeat.

Summary

Giving accurate estimates is hard, because for many teams every project is like doing something new.

Giving accurate estimates is a skill. Like other skills, it takes practice.

Giving accurate estimates requires team maturity.

Giving accurate estimates requires that the feature to be built is well defined (ie: broken down into estimable chunks).

Giving accurate estimates requires commitment. When your team gives an estimate, they need to commit to doing what they said they would do. This will force them to take estimation much more seriously.

One final thought

This isn't a software engineering problem, and this isn't a business team problem. This is an organizational problem. The organization needs to learn to work together to determine how much can be done by what date. It's not you versus them, it's us.


问:
At what stage of an Open Source project should you invite contributions from the community?
I've been wondering about getting contributions to a new open source product my team will be developing.  There's encouragement for us to get as much support from the wider community as we're able, but I can also see this absorbing a lot of time making sure that 3rd parties located outside our office are on track regards things like code quality.  Also at the start of the project we're likely to have a lot of informal discussions within the core team regarding design of the system, spikes etc. and taking these online to allow community involvement will be time consuming and I can imagine could make the discussion less effective.

There is a more human side to this which probably needs to be considered: allowing community involvement in the design process may also have its benefits regards perceived ownership of the project, and there's always a chance that early involvement could pick up on problems that the core team haven't noticed.

So the question: at what stage of an Open Source project should you invite contributions from the community?

答:
Right at the very beginning!  You want the community to feel that they have a genuine stake in your project, otherwise they will feel like they are being used as free labour.

All communication should be over a public mailing list or forum, again this enhances the idea of the community.

You can mitigate the 'design by committee' problem by laying out a clear vision in your initial posts to the mailing list, e.g.

"So we're looking at a domain model to represent our Pet Store (as per JIRA-4).  Does anyone see any major issues with this model?"

In terms of accepting actual physical contributions, you should start by accepting patches and performing public code reviews on them.  That way contributors can already publicly see what sort of coding standards they need to adhere to.  Make sure your commits are available in a commit mailing list as well - you need to be held to the same standards!

It also pays to have project standards on a Wiki or some such document.

Read http://www.producingoss.org for more details on how to run a successful open source project.


问:
Advanced .NET Generics, and where to start?
I have been reviewing C# code that has a lot of generics (and generics with generics...) and its taking me longer to grok the code.

I know the gang of four patterns, and I know some of the fowler enterprise patterns (learning them as I go).

Are there any techniques you could suggest when tackling understanding systems like this?

Are there any resources on developing systems like this?

答:
A generic is essentially a type parameter.

Type - a class, struct or enum.

Parameter - something you pass into a method.

So a type parameter is a type that you pass into a method.  Why is this important?  Why not just pass object variables around?  For a couple of reasons.

Using a type parameter instead of an object avoids boxing.

Using a type parameter preserves static type safety, and allows type inference.

Beyond that, there isn't a lot to say.  You have to think in terms of what can be done with objects generically, without having to think about their type.

Can you put them in a list, without regards to their type?  Sure you can.  Since the list takes objects of all the same type, the type of the list is determined by how you create the list, and the type is determined at that time.  For example:

```<code>var list = new List<string>();
</code>```

creates a list of strings.

Can you sort the items in the list?  Of course, as long as the type you specify when you create the list implements the IComparable interface.

```<code>list.Sort();
</code>```

works because String implements IComparable.

Naturally, you can have composite types in a list:

```<code>var list = new List<KeyValuePair<string, MyClass>>();
</code>```

or recursive types

```<code>public class Node<T>
{
    public T Item { get; set; }
    public List<Node<T>> Children { get; set; }
}
</code>```

Body:
A generic is essentially a type parameter.

Type - a class, struct or enum.

Parameter - something you pass into a method.

So a type parameter is a type that you pass into a method.  Why is this important?  Why not just pass object variables around?  For a couple of reasons.

Using a type parameter instead of an object avoids boxing.

Using a type parameter preserves static type safety, and allows type inference.

Beyond that, there isn't a lot to say.  You have to think in terms of what can be done with objects generically, without having to think about their type.

Can you put them in a list, without regards to their type?  Sure you can.  Since the list takes objects of all the same type, the type of the list is determined by how you create the list, and the type is determined at that time.  For example:

var list = new List<string>();

creates a list of strings.

Can you sort the items in the list?  Of course, as long as the type you specify when you create the list implements the IComparable interface.

list.Sort();

works because String implements IComparable.

Naturally, you can have composite types in a list:

var list = new List<KeyValuePair<string, MyClass>>();

or recursive types

public class Node<T>
{
    public T Item { get; set; }
    public List<Node<T>> Children { get; set; }
}