问:
What is an alternative to bitwise flags?
I was trying to be smart and elegant, and I ended up shooting myself in the foot by coding my entire application to use flags to store various combinations of settings.

Now, I have hit a point where I have > 64 options.  I need to move away from flags or I will be forced to create additional fields, which will make my application really messy given its current state.

What should I consider as an alternative to using flags other than creating a separate boolean variable for each option?

Update

By flags, I mean bitwise flags, e.g.:

```<code>[Flags]
public enum Time
{
    None = 0
    Flag1 = 1,
    Flag2 = 2,
    Flag3 = 4,
    // ...
    Flag63 = ...
}
</code>```

答:
You could use a BitArray in conjunction with static fields to provide labels for the bits:

```<code>static class Flags
{
  public static int WorkProperly = 0;
  public static int CompileFaster = 1;
  public static int AutoImproveCodeQuality = 2;
}

class FlagTest
{
  static void Main(string[] args)
  {
    BitArray bits = new BitArray(100); // > 64
    bits[Flags.AutoImproveCodeQuality] = true;
  }
}
</code>```

Or, with an enum, but you'd have to cast the value every time:

```<code>enum Flags
{
  Never = 0,
  MostOfTheTime,
  Sometimes,
  OddThursdays,
  WhenPigsFly
}

...

BitArray bits = new BitArray(1000); // lots of bits
bits[(int)Flags.Sometimes] = true;
</code>```

Body:
You could use a BitArray in conjunction with static fields to provide labels for the bits:

static class Flags
{
  public static int WorkProperly = 0;
  public static int CompileFaster = 1;
  public static int AutoImproveCodeQuality = 2;
}

class FlagTest
{
  static void Main(string[] args)
  {
    BitArray bits = new BitArray(100); // > 64
    bits[Flags.AutoImproveCodeQuality] = true;
  }
}

Or, with an enum, but you'd have to cast the value every time:

enum Flags
{
  Never = 0,
  MostOfTheTime,
  Sometimes,
  OddThursdays,
  WhenPigsFly
}

...

BitArray bits = new BitArray(1000); // lots of bits
bits[(int)Flags.Sometimes] = true;


答:
If you have a lot of options, figure out if you can:

reduce the number. How about making an assumption instead of making something configurable?

group the options together. See this answer to Is a single config object a bad idea?:

If you need to change the config class you may have to visit every instance in which it is used and check that you haven't broken anything.

One way to deal with this is to create multiple interfaces that expose parts of the config object that are needed by different parts of the app. Rather than allowing other classes to access the config object, you pass instances of an interface to the classes that need it. That way, the parts of the app that use config depend on the smaller collection of fields in the interface rather than the whole config class.

ContentLicense: CC BY-SA 3.0

Title: What is an alternative to bitwise flags?

Body:
I was trying to be smart and elegant, and I ended up shooting myself in the foot by coding my entire application to use flags to store various combinations of settings.

Now, I have hit a point where I have > 64 options.  I need to move away from flags or I will be forced to create additional fields, which will make my application really messy given its current state.

What should I consider as an alternative to using flags other than creating a separate boolean variable for each option?

Update

By flags, I mean bitwise flags, e.g.:

```<code>[Flags]
public enum Time
{
    None = 0
    Flag1 = 1,
    Flag2 = 2,
    Flag3 = 4,
    // ...
    Flag63 = ...
}
</code>```


问:
Does assigning NULL in a GC'ed Environment have similar effects to using free()?
I was just writing a function (in C# in this case) that stored huge amounts of data in a local variable early on in the code, let's say at 5% of the functions code.

After that point, the data in this memeory are no longer used,

also the following 95% of code have a variable runtime, as part of it depends on external ressources.

My Idea was (inspired by C) to 'actively free' that block of memory.

In an evironment with a GC this is mostly just plain impossible.

My idea:

memeoryMonster = null;

Why this?

The GC would never collect that object while the execution is still inside the function, because the variable is still in scope and thus connected to the object graph.

This line would remove the reference to the object and thereby disconnect it from the object graph.

I'm not actively calling the GC, but we know it runs if either the memory runs low, which might happen in the second part of the function or at any time

or all other threads are idle, which might very well happen when the code waits for the external ressources i.e..

This way I want the GC to be able to collect that memory, if need be.

Also I realize that it's probably better to split that function into several parts, which I have done by now, or at least pack the memory-heavy part into a pair of {} to make it get its own scope, so the question is of theoretical nature.

My question:

Does this work like I think it does?

Does setting local variables to NULL enable the GC to collect the memory they occupied?

答:
I wouldn't say that, but your explanation in the middle of the question text is basically sound.

First, the object may be reachable through another reference. This should be obvious, but it's a common beginner mistake to "make the object null" when there are three other references in the same function.

Second, in some environments (.NET is one example off the top of my head), the optimizer may very well drop the reference before the end of its scope if it's never used through the latter 95% of the code. If so, it's redundant.

Finally, free is a bad analogy. I understand why you chose it, and this is more of a nitpick, and you phrase it better in other parts of your answer, but thinking of it as an analogue to free is not helpful IMHO. It's not prompt, it only possibly enables deallocation instead of forcing it (see the above point about other references), and a misplaced = null is not nearly as dangerous as a misplaced free().

After all these caveats though, yes, if a local variable is the only reachable reference to an object (graph), then setting it to null will enable the GC to collect those objects earlier if the GC runs between the null assignment and the end of the scope of the variable. How common this situation is is a whole other question, among other things it depends on how many objects are created by the rest of the code. In my experience, this is an extremely rare situation, hence my skepticism if this course of action is necessary.


问:
What are your decision critera in C++ to make something a data member or virtual method?
(Figured this was too subjective for SO, so posting here...)

I have some behavior that I can implement in various ways.  At least two methods are shows in the code snippet below.  Presume that the m_well data member is correctly set somehow at object construction time.

```<code>struct Behavior
{
    virtual bool behavesWell() { return true; }

private:
    bool m_well;
public:
    bool behavesMemberWell() { return m_well; }
};

struct OtherBehavior : public Behavior
{
    virtual bool behavesWell() { return false; }
};
</code>```

Obviously the one relies upon virtual dispatch, and the other merely the return of a data member.

A third, non-shown method would likely have the non-virtual public member function not return a fixed data member, but instead call a virtual - lets leave that aside for the purpose of this please.

What would lead you to one or other other of these two methods of implementing functionality, such that a user of this class can interrogate an object's behavior?

答:
In your example, I would use a data member.  It's simple and straightforward.

I would use a virtual method where behavior of the function actually changes in the derived class.  In your example, it's still just returning a boolean, even if the value is different.  Methods to me should be accomplishing something -- computation or I/O or what have you -- not just being an obtuse interface for data.

ContentLicense: CC BY-SA 2.5


问:
Can software with a restrictive open source license (GPL,AGPL) be used as part of a tool chain in a commercial software package?
If we use a nice library like TetGen, generate a simple application-wrapper that simplifies our needs and publish it as open source, can we use it inside some Pipe/Chain of applications used in our commercial product?

Is this allowed by the GPL and AGPL licenses, or they do force all of a commercial product that consists of many such applications to be open source?

答:
When I was developing commercial software for a customer who had a lot of wishes, I used Open Source components. That did mean the product he received was Open source, too, but it also was commercial. I wouldn't have written that code if I wasn't paid for it.

So yes, you can use Open Source components in commercial software, and yes, with GPL that software then has to be GPL as well.


问:
When would someone be considered a bad programmer?
How would you consider that a programmer is bad at what he or she is doing?

If possible... How should he/she improve?

答:
When starting a Quality Improvement program and somebody's first suggestion for how we could most dramatically improve quality is to "fire Vito", then Vito is a bad programmer.

True Story. Vito was fired. He was beyond bad, venturing far into unethical while bordering on illegal.


问:
Algorithm to create custom ConcurrentHashMap?
I tried to look into concurrent HashMap source code to look in to how it is implemented. To me it looked very difficult to understand((In no way i am saying its not required :))). I thought if i need to implement it myself and how should i go about it. Here is brief algo about it :-

1) Maintain a list of 16(Default) custom lock objects extending Reentrant lock.

2) Lock will have the state(of type AtomicInteger) say lockState which will be 0 if not in use. If somebody has acquired the lock, it will be 1

3) Before any update/create operation (For example :- in PUT operation), CMH will see if any lock in the list is available with lockState.compareAndSet(int 0, int 1) If result of compareAndSet is true then acquire the lock

4) Once done set lockState to 0 again.

This is just skelton and in know there will be much scope of optimization. But just wanted to confirm if i am on write track or you guys see some serious flaw in it? .

答:
ConcurrentHashMap does not use any Lock instances at all. It uses directly the Unsafe class which calls directly processor instructions (such as compareAndSet or volatile read). This means it's way more faster than with Lock.

What you can do is to use ReadWriteLock instead of ReentrantLock to have a better performance when reading.


问:
Should the sender of an event always be a generic Object?
When programming events in C#, it is advised to create a delegate in form of:

```<code>delegate XEventHandler(object sender, XEventArgs e);
</code>```

My question is on the first argument of the delegate, object sender. Does it always have to be a generic object? Having a sender of type object always results in code similar to this.

```<code>val = ((ConcreteType)sender).Property;
</code>```

or, even more verbose,

```<code>ConcreteType obj = sender as ConcreteType
if (obj != null) { ... }
</code>```

One argument against strongly typed senders is that other objects can forward the event without worrying about the type. While this might make sense in GUI environments, I am not sure if it could benefit outside a GUI.

What if the class of the sender is always known (at least as an abstract class)? For example, if I am implementing a ListChanged event in an abstract List class, and if other classes are going to inherit it (e.g. LinkedList, ArrayList), is it all right to define my delegate with a sender of type List?

```<code>delegate ListChangedEventHander(List sender, ListChangedEventArgs e);
</code>```

Or, would there be a downside of changing the conventional object sender to a more specific type?

答:
At this point, it is mostly a (pretty strong) convention. That is, it will be weird if you write a library that does not follow that convention.

The Event Design Guidelines say:

DO use object as the type of the first parameter of the event handler, and call it sender.

However, you may note that current guidance says that you should not define your own custom delegate for events, but use EventHandler<T> instead, if you can.

As for the design, I would guess that it also promotes the reuse of event handlers, even in contexts not originally foreseen by the original designer of the event.


答:
There are no explicit restrictions on use in commercial products, only on distribution of derived works (or use as a service for AGPL code) without distribution of their source code.

So, if you want to use this library, you will either have to comply with the GPL license or pay for it to be licensed under annother license.

Comply with the GPL/AGPL license

Whether an application is considered a derived work, and thus whether you have to license it under a compatible license, depends on how the GPL code is called.

If you share interfaces and data structures between GPL/AGPL software and your own software, then they will most likely be considered derived works and your own software will need to be licensed under a compatible license.

If you use something like a unix pipe to feed a stream of data from one program to another, those programs are in separate process spaces and share no data structures, then they would most likely not be considered derived works, and you can attach whatever license you like to your own code.

From Frequently Asked Questions about the GNU Licenses:

What is the difference between an “aggregate” and other kinds of “modified versions”?

An “aggregate” consists of a number of separate programs, distributed together on the same CD-ROM or other media. The GPL permits you to create and distribute an aggregate, even when the licenses of the other software are non-free or GPL-incompatible. The only condition is that you cannot release the aggregate under a license that prohibits users from exercising rights that each program's individual license would grant them.

Where's the line between two separate programs, and one program with two parts? This is a legal question, which ultimately judges will decide. We believe that a proper criterion depends both on the mechanism of communication (exec, pipes, rpc, function calls within a shared address space, etc.) and the semantics of the communication (what kinds of information are interchanged).

If the modules are included in the same executable file, they are definitely combined in one program. If modules are designed to run linked together in a shared address space, that almost surely means combining them into one program.

By contrast, pipes, sockets and command-line arguments are communication mechanisms normally used between two separate programs. So when they are used for communication, the modules normally are separate programs. But if the semantics of the communication are intimate enough, exchanging complex internal data structures, that too could be a basis to consider the two parts as combined into a larger program.

For more information and additional suggestions, see this answer to Can I dynamically call a LGPL/GPL software in my closed-source application?

As always though, unless your situation is clear cut, you may want to consult an lawyer who is an expert in open source licensing before basing your business model on it.

Pay for use via a commercial license

If you determine that your product would form a derived work, and you do not wish to open source your product, the other option is to simply license the library under commercial terms. According to the TetGen Licensing FAQ (question 2) the library is dual licensed, and you can contact them for prices and terms.

If this fits with your business model, then this can be a great way to pay back the open source community, encourage it's growth and future development and help share some of the profit you generate through distributing their software more widely. Everybody wins.

Title: Can software with a restrictive open source license (GPL,AGPL) be used as part of a tool chain in a commercial software package?

Body:
If we use a nice library like TetGen, generate a simple application-wrapper that simplifies our needs and publish it as open source, can we use it inside some Pipe/Chain of applications used in our commercial product?

Is this allowed by the GPL and AGPL licenses, or they do force all of a commercial product that consists of many such applications to be open source?


问:
Debugging xml and annotations
By now, most web containers have an annotation variant of their xml configurations for Java EE. I'm guessing this is because it's better to keep things in Java where they can be managed, coded with and controlled. The problem, however, still remains that with annotations you cannot efficiently debug and diagnose an issue because when an exception is thrown it doesn't give you the full stack but instead, just the head.

The reason why this happens is because annotations use reflection and debugging will not work in reflection unless a coder places their own breakpoints which is not always possible.

Does anyone have a way around this or has anyone experienced the same problem when fixing issues on a Java EE web application?

答:
Annotations by design, aren't meant to be debugged.  They're just markers on your code, for instance in Hibernate, to say if a entity is related to another entity.

To put that into perspective, you wouldn't debug a table relationship or the actual

@OneToMany(fetch=FetchType.LAZY, mappedBy="person")

Just as if you were using Spring for MVC as you mention web applications, if you were debugging a web application, you wouldn't actually be debugging the @Controller annotation, you'd be debugging what the controller method actually did.

Title: Debugging xml and annotations


问:
Should I bother to develop for JavaScript disabled?
Should I bother to develop for JavaScript disabled?

I feel that my time is better spent developing for the majority.

答:
Can I recommend an article from "A List Apart"?:

Progressive Enhancement with JavaScript

...We’ve reviewed the mindset needed to implement progressive enhancement in JavaScript and several techniques through which to do it. We’ve also touched on the concept of unobtrusive scripting and learned a little about how to manage the inter-relationship of CSS and JavaScript.

When you combine the general approach with that article with useful tools like JQuery (or Prototype, or whatever your JavaScript framework of choice is), it's really trivial to apply the JavaScript behavior after the fact.

There are several types of browsers out there that still do not have JavaScript or at least very limited JavaScript support.  Not to mention that rule #1 for both WCAG and section 508 compliance (accessibility for non-US folks) is that the sight does not depend on a scripting language to function.  If the page reloads every time I make a change, but it still allows me to make changes it is functioning.  The AJAX layer on top of the base site makes it possible for me to do the same without the page reloads.

Top reasons I can see for supporting no JavaScript users are:

Supporting folks with disabilities (screen readers, alternate input devices, etc.)

Supporting security conscious people: let's face it there's bad people doing heinous things with JavaScript, so the easiest solution is to get rid of JavaScript

It's the easiest way to disable ads without a plugin

Mobile and embedded devices

Command line browsers used to download tools on headless servers

Search engine spiders only follow real links--JavaScript confuses them

Please, if you are going to require cookies and JavaScript on your site for it to function, then properly do your due diligence to avoid the following problems with the following:

Cross-site scripting attacks

3rd party user tracking

Hacking/Defacement through DOM manipulation

Phishing (if a script can access your DOM, it can send any information on the page to the server it was loaded from)

(And that's just the short list)

When the solution isn't that hard, why not do it?

Also, while you're at your JavaScript fiesta, don't forget to support sane keyboard navigation.


问:
Is it permissible to use explicit interface implementation to hide members in C#?
I understand how to work with interfaces and explicit interface implementation in C#, but I was wondering if it's considered bad form to hide away certain members that would not be used frequently. For example:

```<code>public interface IMyInterface
{
    int SomeValue { get; set; }
    int AnotherValue { get; set; }
    bool SomeFlag { get; set; }

    event EventHandler SomeValueChanged;
    event EventHandler AnotherValueChanged;
    event EventHandler SomeFlagChanged;
}
</code>```

I know in advance that the events, while useful, would very rarely be used. Thus, I thought it would make sense to hide them away from an implementing class via explicit implementation to avoid IntelliSense clutter.

答:
It's good form to do so when the member is pointless in context. For example, if you create a readonly collection that implements IList<T> by delegating to an internal object _wrapped then you might have something like:

```<code>public T this[int index]
{
  get
  {
     return _wrapped[index];
  }
}
T IList<T>.this[int index]
{
  get
  {
    return this[index];
  }
  set
  {
    throw new NotSupportedException("Collection is read-only.");
  }
}
public int Count
{
  get { return _wrapped.Count; }
}
bool ICollection<T>.IsReadOnly
{
  get
  {
    return true;
  }
}
</code>```

Here we've got four different cases.

public T this[int index] is defined by our class rather than the interface, and hence is of course not an explicit implementation, though note that it does happen to be similar to the read-write T this[int index] defined in the interface but is read-only.

T IList<T>.this[int index] is explicit because one part of it (the getter) is perfectly matched by the property above, and the other part will always throw an exception. While vital to someone accessing an instance of this class through the interface, it is pointless to someone using it through a variable of the class's type.

Similarly because bool ICollection<T>.IsReadOnly is always going to return true it is utterly pointless to code that is written against the class's type, but could be vital to that using it through the interface's type, and therefore we implement it explicitly.

Conversely, public int Count is not implemented explicitly because it could potentially be of use to someone using an instance through its own type.

But with your "very rarely used" case, I would lean very strongly indeed toward not using an explicit implementation.

In the cases where I do recommend using an explicit implementation calling the method through a variable of the class's type would either be an error (attempting to use the indexed setter) or pointless (checking a value that will always be the same) so in hiding them you are protecting the user from buggy or sub-optimal code. That's significantly different to code you think is just likely to be rarely used. For that I might consider using the EditorBrowsable attribute to hide the member from intellisense, though even that I would be weary of; people's brains already have their own software for filtering out what doesn't interest them.

Body:
It's good form to do so when the member is pointless in context. For example, if you create a readonly collection that implements IList<T> by delegating to an internal object _wrapped then you might have something like:

public T this[int index]
{
  get
  {
     return _wrapped[index];
  }
}
T IList<T>.this[int index]
{
  get
  {
    return this[index];
  }
  set
  {
    throw new NotSupportedException("Collection is read-only.");
  }
}
public int Count
{
  get { return _wrapped.Count; }
}
bool ICollection<T>.IsReadOnly
{
  get
  {
    return true;
  }
}

Here we've got four different cases.

public T this[int index] is defined by our class rather than the interface, and hence is of course not an explicit implementation, though note that it does happen to be similar to the read-write T this[int index] defined in the interface but is read-only.

T IList<T>.this[int index] is explicit because one part of it (the getter) is perfectly matched by the property above, and the other part will always throw an exception. While vital to someone accessing an instance of this class through the interface, it is pointless to someone using it through a variable of the class's type.

Similarly because bool ICollection<T>.IsReadOnly is always going to return true it is utterly pointless to code that is written against the class's type, but could be vital to that using it through the interface's type, and therefore we implement it explicitly.

Conversely, public int Count is not implemented explicitly because it could potentially be of use to someone using an instance through its own type.

But with your "very rarely used" case, I would lean very strongly indeed toward not using an explicit implementation.

In the cases where I do recommend using an explicit implementation calling the method through a variable of the class's type would either be an error (attempting to use the indexed setter) or pointless (checking a value that will always be the same) so in hiding them you are protecting the user from buggy or sub-optimal code. That's significantly different to code you think is just likely to be rarely used. For that I might consider using the EditorBrowsable attribute to hide the member from intellisense, though even that I would be weary of; people's brains already have their own software for filtering out what doesn't interest them.


问:
Database design: 4 types of users but have different functionality , separate or one table?
I have 4 types of users:

Admins ,
normal user ,
company ,
service provider

admins and normal user share some attributes (id .first name ,last name ,phone ,mail)
company and service provider share some attributes too (id .company name ,phone ,fax ,mail )

and they interact too with other entities in application to access some feature like post job or event or apply for it

Is it better to put them all in one user table like tbl_users or is it better to create separate table to every one ? or add to two tables one for (Admins and normal user) and other for ( company and service provider)

and this is some details about the entity attributes.

答:
I'd keep them all in one table, and add a field to indicate what type of user it is. You'll have some blank fields (for example admins and normal users don't have fax numbers) but this shouldn't be an issue unless you have lots and lots of users and some fields are only used for a very small proportion of them. You could also fill in the blanks since there's no reason why normal users can't have a fax number, or why service providers can't have first and last names.

If necessary you could have a "users" table and a "user attributes" table but it's probably not worth it for a small number (i.e. a few hundred) users.


答:
What you expose depends highly on your application needs.

One typically do dissociate users from contact informations allowing maximum flexibility. I'd recommend also to factorize the contact informations data into a single table.

User (1,1) --- (0,1) Contact_Information

Company (1,1) --- (0,1) Contact_Information

Service Provider (1,1) --- (0,1) Contact_Information

The user table would include login data and an addition is_admin field. The existence of a link between two entities would also let you the flexibility such a "real person" can represent both a normal user and a company.

I'd also recommend you to read about how to model inheritance in a database -> https://stackoverflow.com/questions/190296/how-do-you-effectively-model-inheritance-in-a-database

Title: Database design: 4 types of users but have different functionality , separate or one table?

Body:
I have 4 types of users:

Admins ,
normal user ,
company ,
service provider

admins and normal user share some attributes (id .first name ,last name ,phone ,mail)
company and service provider share some attributes too (id .company name ,phone ,fax ,mail )

and they interact too with other entities in application to access some feature like post job or event or apply for it

Is it better to put them all in one user table like tbl_users or is it better to create separate table to every one ? or add to two tables one for (Admins and normal user) and other for ( company and service provider)

and this is some details about the entity attributes.


问:
how to enumerate/generate all possible binary trees from N leaves and N-1 nodes?
I am trying to implement the 24 Game in ansi C. This game goes as follows:

For a list of four given numbers, try to find a solution involving these four numbers, that, using addition(+), subtraction(-), multiplication(*) and division(/) ends up at 24. Each number can only appear once, but the order of the numbers might be changed of course. It is possible to use brackets to change the order of the operands (and you have to do so for many of the solutions).

I wanted to build on top of this problem, and invent a M Game, where M can be an arbitrary number, and you can give an arbitrary length N list of values.

What I know:

Operators can be re-used multiple times in the formula. Thus, when iterating over the operators, I can just use flags to check if a certain operator should be used at a certain place.

Numbers can only be used once. There exist great tutorials out there that explain how to permute an array until all different orders have been exhausted.

However, what I still am having trouble with, is how to decide the different combinations of operators.

Say I have a function

op(A, B)

This function is non-commutative, e.g. op(A,B) != op(B,A). Now, if I have four values, I want to know in what ways I need to combine these functions.
I know that the sequence of Catalan numbers tells us how many options there are. (for four numbers, there are 5 sequences).
These are:

op(A, op(B, op(C,D)))

op(op(op(A,B),C),D)

op(op(A,op(B,C),D))

op(A,op(op(B,C),D))

op(op(A,B),op(C,D))

Using a simple bitVector with recursion I am able to find the first four. But not the fifth, where two nodes share the same 'level'.

Is there an iterative way to test all these different options?

Or, as Ordous aptly put it:

how to enumerate/generate all possible binary trees from N leaves and N-1 nodes?

答:
Define a recursive function that takes an array of values and will generate a list of all the trees we want.

When the function receives just one value, it should return a list containing as it's sole element that value.

When the function receives two values, it should returns list containing as it's sole element the op of those two values in order.

When the function receives more than two values, it should keep a list to return, and iterate through the indices between the members of the array. For each index between members of the array, split the array into a left array and a right array based on the index. Recurse on these arrays, generating the list of trees for each. Then take the cross product of the lists this generated and add it to the list to return.

The way this works is that for any array of more than two values, we can split it multiple ways. For each way to split the array, there is at least one possible tree on the left side, and at least one possible tree on the right side. Each combination of possible trees on the right and left sides is a possible tree.

Edit: Here's some pseudo code (roughly Java/python):

```<code>List<Tree> getOpTrees(List<Value> values):
    if (length(values) == 1):
        return new List(new IdentityTree(values[0]))
    if (length(values) == 2):
        return new List(new OpTree(values[0], values[1]))
   treeList = new List<Tree>()
   for (index from 1 to length(values)-1):
       leftList, rightList = values.split(index)
   for (leftTree : getOpTrees(leftList)):
   for (rightTree : getOpTrees(rightList)):
        treeList.add(new OpTree(leftTree, rightTree))
return treeList
</code>```

Actually, I don't think we even need the n=2 base case. If n=2, we will only ever have index=1. Then we split the left and right lists, which will each have exactly one element. They will each return a single element list containing the identity tree of their element. Then the only thing added to treeList will be OpTree of the two IdentityTrees.

Body:
Define a recursive function that takes an array of values and will generate a list of all the trees we want.

When the function receives just one value, it should return a list containing as it's sole element that value.

When the function receives two values, it should returns list containing as it's sole element the op of those two values in order.

When the function receives more than two values, it should keep a list to return, and iterate through the indices between the members of the array. For each index between members of the array, split the array into a left array and a right array based on the index. Recurse on these arrays, generating the list of trees for each. Then take the cross product of the lists this generated and add it to the list to return.

The way this works is that for any array of more than two values, we can split it multiple ways. For each way to split the array, there is at least one possible tree on the left side, and at least one possible tree on the right side. Each combination of possible trees on the right and left sides is a possible tree.

Edit: Here's some pseudo code (roughly Java/python):

List<Tree> getOpTrees(List<Value> values):
    if (length(values) == 1):
        return new List(new IdentityTree(values[0]))
    if (length(values) == 2):
        return new List(new OpTree(values[0], values[1]))
   treeList = new List<Tree>()
   for (index from 1 to length(values)-1):
       leftList, rightList = values.split(index)
   for (leftTree : getOpTrees(leftList)):
   for (rightTree : getOpTrees(rightList)):
        treeList.add(new OpTree(leftTree, rightTree))
return treeList

Actually, I don't think we even need the n=2 base case. If n=2, we will only ever have index=1. Then we split the left and right lists, which will each have exactly one element. They will each return a single element list containing the identity tree of their element. Then the only thing added to treeList will be OpTree of the two IdentityTrees.


问:
Is there a canonical way to cache instance methods in python?
I have some computationally intensive functions in my python script that I would like to cache. I went looking for solutions on stack overflow and found lots of links:

https://stackoverflow.com/questions/4431703/python-resettable-instance-method-memoization-decorator

https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize

http://pythonhosted.org/cachetools/

https://pythonhosted.org/Flask-Cache/ (I've used this one for flask applications, but this one is not a flask application).

In the end, I ended up pasting this into my program. It seems simple enough -- and works fine.

```<code>class memoized(object):
    '''Decorator. Caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned
    (not reevaluated).
    '''
    def __init__(self, func):
        self.func = func
        self.cache = {}

    def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            return self.func(*args)
        if args in self.cache:
            return self.cache[args]
        else:
            value = self.func(*args)
            self.cache[args] = value
            return value

    def __repr__(self):
        '''Return the function's docstring.'''
        return self.func.__doc__

    def __get__(self, obj, objtype):
        '''Support instance methods.'''
        return functools.partial(self.__call__, obj)
</code>```

However, I am wondering if there is a cannonical best practice in Python. I guess I assumed that there would be a very commonly used package to handle this and am confused about why this does not exist. http://pythonhosted.org/cachetools/ is only on version .6 and the syntax is more complex than simply adding a @memoize decorator, like in other solutions.

答:
There is no canonical, uniquely Pythonic way to do this. None of which I am aware, at any rate--and I'm speaking as someone who has looked, and who is the author of a successful memoizing package.

However, I believe your lack of found prior art may be a terminology issue as much as anything. You asked for caching. That is a proper term, but it's overly broad. Caching the results of a particular function call or activity for later use is more specifically referred to as memoizing or memoization. And indeed there are many memoizing packages available from the community, as well as many recipes (for example, this one). I have also seen memoizng functions in many multi-purpose utility packages. Many of them are mature, battle-hardened, and constantly used in production--not mere "version 0.6 code."

Why memoizing is not more canonically or idiomatically handled I cannot say. Perhaps because there are various ways to accomplish it with differing virtues and tradeoffs. Or perhaps because there are already so many different approaches in use. I often find features--"flatten a list of list" is another--that other language communities eagerly converge around but that the Python community or powers that be seem to prefer handling as recipes rather than committing to a specific API. In any case, if your code works, welcome to the ranks of successful memoizers!

Update

Since the Python 3 standard library (for 3.2 and later) includes an lru_cache decorator (documentation here), I'd have to say that looks like a late-breaking attempt to standardize the most common memoization use case. That it came so late in Python's evolution is probably why there's no common solution, but for new code, that's as close to canonical as you're going to find.

ContentLicense: CC BY-SA 4.0


问:
Heterogeneous Associations - Data Modeling When an Object that Must Relate to One of Many Classes
Suppose you have 3 classes: ClassA, ClassB and ClassC. Now suppose you have a class Message. You want a one-to-many relationship between each one of those three classes and the Message.

The goal is that a Message must 'belong' to either a ClassA, ClassB or a ClassC object. A ClassA/ClassB/ClassC object can have zero or many Messages. The Message class is the same for any of the three classes (i.e. there shouldn't be a different class of Message for each of the three Classes A, B and C).

Now thinking about data-modeling on a relational DB (also, I'm using ORM, in this case Entity Framework Code First), I'll map each one of those 3 classes and the Message class to a table.

But then, the issue is trying to apply the relationships I explained above. I see a few ways to do this:

Add three nullable Foreign Keys (ClassAID, ClassBID, ClassCID) to the Message table. e.g. If a message belongs to a ClassA object, then ClassAID will have that obect's ID as a value and ClassBID and ClassCID will be null. This will force me to write a constraint/trigger to make sure that the Message object only has a value in one of those FK's. It also makes it a bit ugly on the Business Logic and Presentation layers whenever I want to know to which object does a message belong to: the MessageObject would have a nullable reference to a ClassA, ClassB and a ClassC object and I would need to check it before presenting it in the UI (e.g. a link from the Message to its object).

Implement inheritance and generalize ClassA, ClassB and ClassC. The Message has a FK for the generalized class' ID. This adds complexity and doesn't really solve the problem of easily figuring out to which ClassA/B/C a Message is related to.

Add a ClassToMessage table (similar to a link-table) that connects the 3 tables to the Message one, again, via nullable FK's. Sort of a combination of the previous two, but still not exactly a good solution for the same reasons.

I'd like to know if there's an elegant way to achieve the desired scenario, preferably having the Entiy Framework approach in mind. Thanks in advance.

EDIT 1:

Imagine the Message objects as being comments (or files) in a tree-like structure of objects (ClassA objects can have ClassB's and ClassB's can have ClassC's...). You want objects from all of those classes to have zero or many comments. You want the same Comment table for all of the comments (doesn't matter if they're belong to a ClassA or ClassB... instance). You also want it to be easy to find out the comments for a given object or the object a comment belongs to.

EDIT 2:

Two other alternatives:

Implement table per hierarchy (TPH) by having a ClassAMessage, ClassBMessage... that still doesn't quite solve the problem...

The Message stores the ID of the object that owns it and the object Type (whether it was a ClassA, ClassB...). No actual relationship: service layer or business logic does the rest (ouch).

I have seen this issue being addressed in StackOverflow, but I can't seem to find a good solution:

Entity Framework Code First - Entity maps to one or the other

Multiples Object Relationship in Code First

Database design - articles, blog posts, photos, stories

EDIT 3:

I'm pursuing alternative #4 (Table per Hierarchy / Class Table Inheritance) and have evolved this into a more specific S.O. question: Entity Framework 6 Code First - Comments on a Tree Structure

答:
It makes a difference of what ClassA and ClassB really represent - generic names are not helpful for making good design decisions. For example, if those are things which can or should be modeled with a common base class, with a real "is-a" relationship, go that route.

If ClassA and ClassB have nothing in common except those message, then inheritance is probably not the best approach. For this case, your solution 1 and 3 are both possible. Which one is more adequate depends on how "waterproof" you need your database, and what kind of access patterns and queries you expect.


问:
Should I use WADL to describe my RESTful API?
I'm about to embark on a project that makes extensive use of a properly RESTful approach. That is, it uses HATEOAS and serves up resources in a manner that allows for general exploration by a client.

I would like to ensure that I provide a description of my endpoints in a manner that would allow client applications to be automatically generated in a wide variety of languages. I understand that for SOAP based web services I can use WSDL and that apparently there is WSDL2 that provides greater definition of the HTTP verbs in use with REST. However I see many articles swinging back and forth over it's utility.

So, should I use WADL to allow external code generators to quickly build a client for my web application or is there a better standard that is expected?

答:
The W3C has made a formal recommendation for a REST documentation standard based on WSDL 2.0. Here is a quote from the IBM article:

The term Web services is typically associated with operation- or
  action-based services using SOAP and the WS* standards, such as
  WS-Addressing and WS-Security. The term REST Web services generally
  refers to a resource-based Web services architecture that uses HTTP
  and XML. Each of these architectural Web service styles has its place,
  but until recently, the WSDL standard didn't equally support both
  styles. The WSDL 1.1 HTTP binding was inadequate to describe
  communications with HTTP and XML, so there was no way to formally
  describe REST Web services with WSDL. The publication of WSDL 2.0,
  which was designed with REST Web services in mind, as a World Wide Web
  Consortium (W3C) recommendation means there is now a language to
  describe REST Web services.


问:
Using DDL commands in programming language
Hello I am a student with no industry experience. My question may sound dumb, but, me and my friends were having discussions on use of DDL directly in programming language (any language may be Java, PHP etc), I wanted to know to is it a bad practice to use DDL commands (CREATE,ALTER,DROP tables) in a programming language i.e. Whether Database schema should be altered in direct code?

答:
Data definition language (DDL) statements are rarely used anywhere. Often, they are used in scripts that are processed by a SQL front end, initiated manually.

However, programming the SQL front end requires that some Java (C, C++, what have you) programs are directly applying DDL on the database.

Similarly, if you have a large application, it is often necessary to provide a set of maintenance screens, available to highly privileged users, which emit DDL statements. For example, certain kinds of maintenance activities might require dropping and recreating tables, changing indices, and adding or removing triggers. By providing the capability in your program, you can significantly reduce the chance of errors by constraining operations in kind or in time.

Finally, testing of database-oriented applications requires that the test scaffolding be able to emit DDL in many circumstances.


答:
In my experience (and it's possible others will have other experiences), an application that modifies its own schema directly is usually a sign of a bad design, and it is probably unnecessary. I've yet to work on an application where the schema itself needed to change dynamically at runtime.

If you start modifying your schema dynamically from your application, all of the queries in your code will need to keep up with the schema changes. Dynamic schema changes may also make it impossible for other applications to share the database if common components of the schema get modified. Stored procedures may also run into similar problems if the schema changes in such a way that they no longer function. Tracking changes to the database schema also gets tricky, unless you log every DDL.

There might be certain cases where it is better, or even necessary to modify an application's database schema while the application is running, but it would seem to me that this is the exception rather then the rule. One situation where application code might modify database schemas directly is applications that are actually designed for this specific purpose, such as Oracle SQL Developer or Microsoft SQL Studio. However they are modifying the schemas of other applications, not their own schemas.

Title: Using DDL commands in programming language

Body: Hello I am a student with no industry experience. My question may sound dumb, but, me and my friends were having discussions on use of DDL directly in programming language (any language may be Java, PHP etc), I wanted to know to is it a bad practice to use DDL commands (CREATE,ALTER,DROP tables) in a programming language i.e. Whether Database schema should be altered in direct code?


答: The problem with altering the DB scheme in the code is that DDL commands only need to run once per database installation - not once per program instance. However, if you want to run the DDL commands from the application, you can use a migration framework. For example, in Java's Flyway you write migration classes, and the Flyway framework executes them for you. The migration framework makes sure that the DDL are ran in the right order and that no migration is ran twice on the same DB installation.


答:
Generally, schema changes aren't run by a database client application.  If an application needs to create and drop non-temp tables regularly during its normal usage, I'd say that's a sign there might be a problem with the design.  For example, if an application is using ALTER TABLE to add columns to support additional values (address1, address2, etc.), its a sign that the DB wasn't normalized.

But... you have to keep in mind the breadth of software development.  Issuing DDL statements would not only be common, they'd be necessary, for managing local applications connecting to local databases.  So an application that uses SQLite may need to alter the schema automatically when the application updates to support new features.


答:
It is a better practice to treat your database like a separate codebase. I keep my DDL and whole database under source control. There are products like RedGate SQL Source Control which allow you to "check your database in", and I have also developed a similar product. This allows you to do diffs and merges and deployment scripts.

DDL is a one or few time thing. Don't manage it from Java just because it seems novel. There are indeed ORMs that support this, but in all groups I've worked with we frowned upon the practice and did not allow it.

A database may (rarely, but not unheard of) be replaced by a competing vendor's. (Started with MySQL, upgraded to Oracle or SQL Server). Storing DDL in a Java program simply obfuscates the whole life cycle of your app and database.

The real place for your database schema / metadata is in:

An ER modelling tool like ERwin or ERstudio or one of the cheaper alternatives.

A DB source control

The database data dictionary itself. You can simply do DDL-only exports after changes.


问:
Is vanilla JS still considered a library?
I very recently found out that VanillaJS (document?) is a library that's just bundled with 99% browsers and isn't exactly native JavaScript (shock of my life). While writing a lib of my own I normally avoid all helpful things, mostly libs. Now I have three questions:

Is VanillaJS still considered a lib?

Is there a way to do anything with the DOM without VanillaJS?

Are major libs based on VanillaJS or native JS (without the document stuff)

答: It's a joke, or rather, a witty way to make a point. "vanilla X" refers to "X in the most basic fashion" or "X without anything extra", so "Vanilla JS" is JavaScript as exposed by the browser. VanillaJS is native JavaScript. That includes the DOM, various newfangled APIs, the core language features. It excludes third party code, i.e. what one would normally call libraries or frameworks. The people behind it probably want to point out the advantages of doing things this way by framing it like marketing for a third party framework. There is, or at least used to be, a trend in the JavaScript world to throw frameworks at every problem regardless how trivial a solution in "vanilla" JavaScript would be.


问:
Human names in programming examples
In small programming examples, it is established that one will probably use foo, bar, and/or baz as variable/function names.

Are there accepted human names one can use?  For example, if a program is sorting a list of people in alphabetical order, should I just use whatever names I think of?

答: Generally Alice and Bob and various others (mostly from Bruce Schneier's Applied Cryptography though Alice and Bob predate his usage of them by decades) are used in Cryptography. Various other names show up but they tend to represent specific things. They also pop up in other contexts such as networking on occasion but outside that there's no "official" set of names.</p>

Title: Human names in programming examples


答:
Unless the different user types really have different roles in the schema, keep them in one table. I would have fields such as the following:

User type (user, admin, company, provider)

First and last name

Company name

It may even make sense to separate the phone numbers and addresses into other tables, to allow one user to have many phone numbers and addresses (perhaps a company has multiple offices, a user has home, cell, work numbers, etc) although this is technically not part of the question.

The important thing to remember is that a user type is easily represented as a field on a table, allowing other tables to point to any user: this enforces a single relationship type. Furthermore, users can change types without needing to map data between tables, update foreign keys, etc. What if a normal user becomes an admin? What if he is working out of his home and incorporates, maybe hires an additional worker? It is quite feasible for users to change types in the real world, your business rules may be different of course.


问:
setting class members automatically like Photon Servers Operation class does
I'm wanting to mimic something that I saw in Photon Server with my application. Entity Framework does something similar. Photon Server has an Operation class. You pass it a dictionary of <byte,object> and it auto fills the class members and also does some data annotation. For example

```<code>public class MyCustomOperation : Operation
{
    public MyCustomOperation(IRpcProtocol protocol, OperationRequest request) : base(protocol, request)
    {
    }
    [DataMember(Code = 100, IsOptional = false)]
    public string Message { get; set; }
}
</code>```

Now in this, request contains a Dictionary<byte,object> the byte is what the Data annotation refers to as the Code it somehow takes that dictionary looks up the key that matches what code is set to and assigns Message to the value of the key.

I need to do the same thing and have had no luck finding anything on google (although not sure what this is called) I know the [DataMember] line is a custom data annotation and those I do understand its the part of taking the code in the data annotation and assigning the value to the field under it.

What I know about custom data annotations is using validation with them (which this class also does in Photon via a MyCustomOperation.IsValid although this part I can figure out I think).

答:
Ok I finally figured this out without using reflection as well

DataMemberAttribute class:

```<code>[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class DataMemberAttribute : Attribute
{
    public byte Code { get; set; }
    public bool IsOptional { get; set; }
    public string ErrorMessage { get; set; }
}
</code>```

Operation Class:

```<code>public class Operation
{
    private readonly List<string> _errorMessages;
    protected Operation(Dictionary<byte,object> parameters)
    {
        _errorMessages = new List<string>();
        foreach (var prop in GetType().GetProperties())
        {
            var da = prop.GetCustomAttributes(typeof(DataMemberAttribute), false) as DataMemberAttribute[];
            if (!(da == null || da.Length <= 0))
            {
                if (parameters.ContainsKey(da[0].Code))
                {
                    prop.SetValue(this, Convert.ChangeType(parameters[da[0].Code], prop.PropertyType), null);
                }
                else
                {
                    _errorMessages.Add(!string.IsNullOrEmpty(da[0].ErrorMessage) ? da[0].ErrorMessage : string.Format("{0} is Required", prop.Name));
                }
            }
        }
    }

    public bool IsValid
    {
        get {
            return _errorMessages.Count <= 0;
        }
    }

    public List<string> ErrorMessages
    {
        get { return _errorMessages; }
    }
}
</code>```

Sample Derived class:

```<code>public class Operation2 : Operation
{
    public Operation2(Dictionary<byte,object> parameters) : base(parameters)
    {}

    [DataMember(Code = 1, IsOptional = false, ErrorMessage="Username is Required")]
    public string Username { get; set; }

    [DataMember(Code = 2, IsOptional = false, ErrorMessage="Password is Required"))]
    public string Password { get; set; }

    [DataMember(Code = 3, IsOptional = false, ErrorMessage="Email is Required"))]
    public string Email { get; set; }

}
</code>```

Test Program:

```<code>class Program
{
    static void Main()
    {
        var paramters = new Dictionary<byte, object> {{1, "someuser"}, {2, "password"}, {3, "someone@gmail.com"}};
        var operation = new Operation2(paramters);
        var paramters2 = new Dictionary<byte, object> { { 1, "someuser" }, { 10, "password" }, { 3, "someone@gmail.com" } };
        var operation2 = new Operation2(paramters2);

        Console.WriteLine("Operation 1 Contains:");
        Console.WriteLine("Username {0}", operation.Username);
        Console.WriteLine("Email {0}", operation.Email);
        Console.WriteLine("Password {0}", operation.Password);
        Console.WriteLine("operation 1 {0}", operation.IsValid);
        Console.WriteLine();
        Console.WriteLine("Operation 2 Contains:");
        Console.WriteLine("Username {0}", operation2.Username);
        Console.WriteLine("Email {0}", operation2.Email);
        Console.WriteLine("Password {0}", operation2.Password);
        Console.WriteLine("operation 2 {0}", operation2.IsValid);
        Console.ReadLine();
    }
}
</code>```

Produces the following output:

```<code>Operation 1 Contains:
Username someuser
Email someone@gmail.com
Password password
operation 1 True

Operation 2 Contains:
Username someuser
Email someone@gmail.com
Password
operation 2 False
</code>```

Body:
Ok I finally figured this out without using reflection as well

DataMemberAttribute class:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class DataMemberAttribute : Attribute
{
    public byte Code { get; set; }
    public bool IsOptional { get; set; }
    public string ErrorMessage { get; set; }
}

Operation Class:

public class Operation
{
    private readonly List<string> _errorMessages;
    protected Operation(Dictionary<byte,object> parameters)
    {
        _errorMessages = new List<string>();
        foreach (var prop in GetType().GetProperties())
        {
            var da = prop.GetCustomAttributes(typeof(DataMemberAttribute), false) as DataMemberAttribute[];
            if (!(da == null || da.Length <= 0))
            {
                if (parameters.ContainsKey(da[0].Code))
                {
                    prop.SetValue(this, Convert.ChangeType(parameters[da[0].Code], prop.PropertyType), null);
                }
                else
                {
                    _errorMessages.Add(!string.IsNullOrEmpty(da[0].ErrorMessage) ? da[0].ErrorMessage : string.Format("{0} is Required", prop.Name));
                }
            }
        }
    }

    public bool IsValid
    {
        get {
            return _errorMessages.Count <= 0;
        }
    }

    public List<string> ErrorMessages
    {
        get { return _errorMessages; }
    }
}

Sample Derived class:

public class Operation2 : Operation
{
    public Operation2(Dictionary<byte,object> parameters) : base(parameters)
    {}

    [DataMember(Code = 1, IsOptional = false, ErrorMessage="Username is Required")]
    public string Username { get; set; }

    [DataMember(Code = 2, IsOptional = false, ErrorMessage="Password is Required"))]
    public string Password { get; set; }

    [DataMember(Code = 3, IsOptional = false, ErrorMessage="Email is Required"))]
    public string Email { get; set; }

}

Test Program:

class Program
{
    static void Main()
    {
        var paramters = new Dictionary<byte, object> {{1, "someuser"}, {2, "password"}, {3, "someone@gmail.com"}};
        var operation = new Operation2(paramters);
        var paramters2 = new Dictionary<byte, object> { { 1, "someuser" }, { 10, "password" }, { 3, "someone@gmail.com" } };
        var operation2 = new Operation2(paramters2);

        Console.WriteLine("Operation 1 Contains:");
        Console.WriteLine("Username {0}", operation.Username);
        Console.WriteLine("Email {0}", operation.Email);
        Console.WriteLine("Password {0}", operation.Password);
        Console.WriteLine("operation 1 {0}", operation.IsValid);
        Console.WriteLine();
        Console.WriteLine("Operation 2 Contains:");
        Console.WriteLine("Username {0}", operation2.Username);
        Console.WriteLine("Email {0}", operation2.Email);
        Console.WriteLine("Password {0}", operation2.Password);
        Console.WriteLine("operation 2 {0}", operation2.IsValid);
        Console.ReadLine();
    }
}

Produces the following output:

Operation 1 Contains:
Username someuser
Email someone@gmail.com
Password password
operation 1 True

Operation 2 Contains:
Username someuser
Email someone@gmail.com
Password
operation 2 False


问:
Shortest Path Between Two Nodes in a +10 Million Nodes Graph
I have my own knowledge graph representation, read from ConceptNet and NELL, containing tens of millions of nodes in which I want to calculate the nearest distance (if any) between two concept nodes. The application is to find out how two concepts are related in the simplest explainable way. Typical connectedness of the graph lie in the range 100-1000. Do I need some variant of Dijkstras in this case? I want the solution to require at most around 10 GBytes of RAM. My current memory usage is around 2 GB.</p>

答:
2 simple solutions that immediately arise:

Precompute everything via something like Johnson's algorithm, or use a standard search algorithm every time as you suggested - Dijkstra for example (which boils down to simple BFS, since the graph is unweighted).

The first requires way too much storage/RAM to do. The second is prohibitively slow. What you (likely) want is a hybrid solution that combines some precomputation (possibly a long one, but that doesn't require much storage), and a shorter per-query computation.

Clustering

One approach would be to somehow cluster your graph, and compute the distances between the exit vertices of the clusters. Then a search algorithm wouldn't even consider paths in clusters (or rather use the precomputed minimum paths between exits), unless that cluster contains the start or end point.

A-star

Another is to compute a heuristic and use A* (or any other heuristic-assisted search). You mentioned that you do not have any information about the graph, except the connectedness, so you may need to devise and precompute such a heuristic.

One such heuristic may be a minimal "order n spanning graph". There's likely a proper term for this, but it's been too long since my Uni days, so I'll explain what I mean. I call a "order n spanning graph" a collection of vertices, such that any vertex in your original graph is reachable from some vertex in this collection via a path of length at most n.

If you've got such a collection, along with a mapping of Vertex -> closest vertex in spanning graph + distance to it, and the distances between any 2 points in the spanning graph, then you have a heuristic:

The distance between two vertexes is at least the distance between their closest vertices in the spanning tree + distances to them - 2*n. (Why? Because the distance between the spanning vertices is at most the distance between A and B + distances to them).

This is an admissible heuristic, hence A* will do a good job using it.

The smaller the order of the collection, the better the heuristic and faster the search. But that also means that the spanning graph will be larger, and hence you will need a larger matrix of distances. I would probably start off with a graph of order 50 or so, but you can tweak it, depending on the exact shape/nature of the graph.

Optimize for the average use-case

Also worth noting that you can optimize not for the graph you have, but for the queries you answer. If they are typically to compute precise, but small distances, you may want to precompute some, but not all values (For example, distances from each node to anything reachable by 3 or less steps?). You'd need fallback to one of the methods above in this case, but that may be sufficient.

This also begs the question: Is full precision really necessary on longer paths for you? Maybe the specification can be relaxed in this sense?


问:
What's the name for those diagram used to sketch the flow of a program?
What's the name for those diagram used to sketch the flow of a program? What are these sketches called?

The shapes of the objects are by convention ellipse for an action, rhombus for a question, rectangle for a statement, etc.

答:
Flowchart or Decision Tree.

Probably the most traditional term, in spite of my preference, is Flowchart, from the traditional, waterfall engineering model. It is commonly used in software, business, and industrial engineering.

I tend to prefer the latter term in this context. The term Flowchart is often misused (as we know, many people aren't formally educated). I've seen people refer to any sort of diagram with processes, data and system-components as a Flowchart, when actually they have a Data Flow Diagram or Component Diagram, which are other common software engineering diagrams. With "Decision Tree", I feel like I'm being more specific.

Some common engineering diagrams:

Flowchart

Decision Tree

Data Flow Diagram

Component Diagram

Entity Relationship Model (aka ER or ERD)

Logical Data Model (database independant)

Physical Data Model (database specific)

Object Model (differs from an ER Model)


问:
DDD: Alternative view of the Model?
I have a model class, let's say it's a Book. I need it to be displayed on the screen. I want to have an escaped version of it, so I do not need to escape fields manually.

What should I do? I can

add a wrapper over the Book that returns escaped values (e.g. EscapedBook); but every time when I change the book, i need to change the wrapper - at least to add/remove methods.

run the model through some AOP and generate proxy before it is going to be displayed on the screen.

or run the model through some util that is going to escape all string properties.

IMHO this is not quite a business behavior, so I would like to keep this on the UI layer.

答:
A wrapper is the right way to go here -- you really want the UI part of the UI layer to just reflect what is given and not be responsible for more than very technical bits of filtering content. I would run with the first option you are looking at and create a specific subclass for the UI layer to handle this task.

The real cost from a writing code perspective isn't having to update your EscapedBook whenever the underlying class changes -- underlying classes changing is going to change a lot of things down the logical line. You'd be better off having the internal representation talking to a single class rather than speaking directly to a dozen different things in the front end application.

This front-end specific class could very well be generated via a proxy or AOP process -- that is really a tactical decision depending on what the stack is and what other dependencies you have. You might mean having a straight-through dedicated proxy rather than a separate class. This isn't a horrible idea on the surface but I would prefer the dedciated class concept in the end -- it is more flexible to separate the problems in the end.

The utility class is best avoided here -- you will end up with things like ContentUtil.CleanPage(book.Pages[1]) all over the UI layer and that will hurt to fix when you re-think things. Globals are bad, even when globals are stateless utility functions.

One thing I would not throw out is having this be generated in the business layer -- generating properly escaped content is a testable business requirement of the application I'd rather test against the business layer versus trying to write automated tests of the UI.

Title: DDD: Alternative view of the Model?


问:
What activities, outside of writing code, have been shown to improve one skill as a programmer?
The mantra is to become a better software developer, write more software.

However, are there activities I could partake in when I am not actually at the computer programming such as

doing certain kinds of logic puzzles

reading certain kinds of material

doing mathematical problems on paper

nurturing an artistic or musical skill

etc.

that have been shown to exercise the parts of my brain involved in programming, architecture planning, algorithm design, etc. or have been shown to be cognitively similar to those activities?  And thus potentially lead to improvement in those areas?

答:
You're basically describing the "Lumosity Principle;" that brain games will have a "spillover effect" into other cognitive areas.  The only studies that demonstrate this effect seem to be those that are sponsored by Lumosity.  There are even anecdotal studies that appear to demostrate that video games can be better at accomplishing this.

That said, there are substantial transfer effects for programmers solving puzzles, writing math equations and composing music.  Why?  Because programs are essentially puzzles.  Because programs are mathematical in nature, especially the functional ones.  Because programming is a creative endeavor, much like musical composition.  Because the act of writing software is fundamentally a social one; you have to work with stakeholders, gather requirements, make plans, satisfy bosses, and exercise all manner of collaborative skills, technical and otherwise.

These kinds of activities have transfer effects because they are directly related to programming skills.  It has to be the right kind of activities, in other words.  But programming is like that; almost any sufficiently complex activity or human endeavor will achieve that.

Further Reading

Why Brain Training Doesn't Work


答:
It's probably a Flowchart, but the title asks a different question than the body, which I will try to address next.

One common convention is UML (Unified Modelling Language) from the people over at the excellently named, OMG (Object Management Group).
http://www.omg.org/gettingstarted/what_is_uml.htm

There are a number of different diagrams which runs the gamut from Use Case Diagrams, Activity Diagrams (similar to a flowchart), sequence diagrams (my particular favourite), Class diagrams, and many many more including modelling business processes at large organisational scales.

The specifications list might be a good start if you want to know more:
http://www.omg.org/spec/UML/

Body:
What's the name for those diagram used to sketch the flow of a program? What are these sketches called?

The shapes of the objects are by convention ellipse for an action, rhombus for a question, rectangle for a statement, etc.


问:
Should the sender of an event always be a generic Object?
When programming events in C#, it is advised to create a delegate in form of:

```<code>delegate XEventHandler(object sender, XEventArgs e);
</code>```

My question is on the first argument of the delegate, object sender. Does it always have to be a generic object? Having a sender of type object always results in code similar to this.

```<code>val = ((ConcreteType)sender).Property;
</code>```

or, even more verbose,

```<code>ConcreteType obj = sender as ConcreteType
if (obj != null) { ... }
</code>```

One argument against strongly typed senders is that other objects can forward the event without worrying about the type. While this might make sense in GUI environments, I am not sure if it could benefit outside a GUI.

What if the class of the sender is always known (at least as an abstract class)? For example, if I am implementing a ListChanged event in an abstract List class, and if other classes are going to inherit it (e.g. LinkedList, ArrayList), is it all right to define my delegate with a sender of type List?

```<code>delegate ListChangedEventHander(List sender, ListChangedEventArgs e);
</code>```

Or, would there be a downside of changing the conventional object sender to a more specific type?

答:
The reason for the recommendation is that it allows for future changes that do not necessarily require changes to existing code, and especially the public interface.

The event mechanism itself can still be used for "VB6"-style events, but you'll have to change all existing consumers if you ever need to change the signature (or worse: create new versions of the same events). With the recommended approach, as long as the newer items inherit from the existing ones, you can update the signature without fixing existing code.


问:
Architecture: Storing all properties as JsonProperty in NDB?
I am storing the data for my app in Google's NDB, but am confused as to what architecture to use. The app data is mostly text based, but has some non-text properties like DateTimeProperty, FloatProperty and one or two BooleanProperty's.

I could store each property correctly (e.g. a datetime is stored as a DateTimeProperty), or I could already package all the data up as a JSON object and store it as a JsonProperty.

Storing everything as a JsonProperty gives the benefit of taking up less space (there's a compress flag that causes the content to be gzipped), but taking this approach makes it harder to search the database with query().

Which approach is better to take?

答:
Personally, I'd go with using regular data types instead of serialising it to JSON then storing that instead as that is the most natural way to go about it plus you can index it.

Storing JSON objects have its uses too, especially if you want to make quick canned responses or if the one processing your data can readily read JSON(i.e. nodejs and its ilk) and the need to query this field doesn't exist(JSONProperty is stored as a blob, good luck indexing that)


问:
How can I track programming productivity on a daily basis?
How can I track that I'm developing software more or less productive than the previous days? </p>

答:
There's a simple answer: you can't. And moreover, you shouldn't.

You want to measure your own productivity, but you can generalize: how can you measure productivity of programmers? First of all you have to define what you mean for "productivity": amount of code produced? Amount of design (or specification) implemented? Number of issues fixed? Quality of produced code? (Yes, quality is a productivity counter, you can produce a lot of bad code or few good code, what has been more productive?). All these values can hardly be mapped to a daily base, and any attempt to track daily productivity is dangerous for the project, for the company, and for the programmer.

My advice is to clearly define what you mean as "productivity", then define a measure unit, and apply it on a weekly and monthly base.


问:
How would you go about compressing a list of integers that are non unique and retain the original order?
Let's start out with an example

```<code>[1,1,1,5,3,1,1,2,78,2,3,1,1,...,1]
</code>```

As you can tell by the example, 1 is repeated a lot, but there will be outliers (like 78, and really anything that isn't 1).

The catch to my question is, when I uncompress the numbers, they must retain the original order. The algorithms that I have found generally deal with unique numbers, either sorted or unsorted. I wouldn't mind using one of those, but since my integer list is not unique, I'm wondering if there is anything currently out there that is optimized for this sort of thing.

Quickly thinking, My first idea was to do a normal compression tree and just map in values for patterns.

My second Idea was to just describe repeating numbers like so: 3->1, 1->5, 1->3, 2->1, 1->2, 1->78, 1->2, 1->3, x->1.

Of course this only works if values are constantly repeated, which generally the lower numbers will be repeated a lot, but I can't be 100% positive that that will be the case every time.

答:
Any non-lossy compression algorithm should work for your requirements. The easiest one to implement yourself is Run-length encoding, which is basically your second idea.

There are also variants of of Run-length encoding where the repetition count for single occurrences of a number can be left off, which gives a better compression ratio for data like yours.


问:
Data structure for traversing hierarchical hostnames
So, quite often I'll come across a situation where I'd like to process hostnames in a hierarchical manner.

For example, given a hostname "foo.bar.baz.example.com", I might want to compare it against a data structure that contains a higher authority like "example.com" or "baz.example.com" and see if I get a match.

Usually, the way I handle this is to simply use a hashtable, and iteratively remove subdomains until I find a match (or, never find a match, whatever the case may be.)

But, I was thinking that something like a trie/prefix-tree might be a lot better suited for this (if I were to reverse the domain labels).

Of course, the problem is that a trie usually works on individual characters - whereas in this case I'd want to make each subdomain (or "label", in DNS-speak), a single "unit".

Is there a data-structure that might be well suited for something like this?

答:
Use a tree, where each node will be a subdomain. The  top level will be the start symbol. Then it would branch into k nodes, where k is the number of top level domains you have.

For instance, if your entire database was two entities: foo.bar.example.com and boo.car.ample.net, k will be 2 (net and com). Each of net and com nodes will have one children each: ample and example. And so on.

As an another example, let's consider you have only two entities again. But this time it's foo.bar.example.com and boo.bar.example.com. Now the tree would be something like this.

```<code>                                      root
                                       |
                                      com
                                       |
                                    example
                                       |
                                      bar
                                    /     \
                                  foo     boo
</code>```

This will be your tree. If you the input is example.com, you would split by '.' and reverse to get [com, example]. You will go down your tree by matching the list with the tree. Since 'com' is a child of root, you take that path, and from 'com', you search for the next element in your input list 'example'. Since 'example' is a child of 'com' in the tree, we proceed. But now we have exhausted the input list and this means we found a match. At any point in the traversal, if you don't find a child for the current input element from the list, you are guaranteed that there is no match in your database. For instance if you got the input string zoo.bar.example.com. Our input list will be [com, example, bar, zoo]. We would traverse the tree until bar, but in the tree 'bar' doesn't have a child 'zoo'. This implies we don't have zoo.bar.example.com in our database.

You can find a match within O(n), where n is the number of subdomains in your input string that you're trying to match.

Body:
Use a tree, where each node will be a subdomain. The  top level will be the start symbol. Then it would branch into k nodes, where k is the number of top level domains you have.

For instance, if your entire database was two entities: foo.bar.example.com and boo.car.ample.net, k will be 2 (net and com). Each of net and com nodes will have one children each: ample and example. And so on.

As an another example, let's consider you have only two entities again. But this time it's foo.bar.example.com and boo.bar.example.com. Now the tree would be something like this.

                                      root
                                       |
                                      com
                                       |
                                    example
                                       |
                                      bar
                                    /     \
                                  foo     boo

This will be your tree. If you the input is example.com, you would split by '.' and reverse to get [com, example]. You will go down your tree by matching the list with the tree. Since 'com' is a child of root, you take that path, and from 'com', you search for the next element in your input list 'example'. Since 'example' is a child of 'com' in the tree, we proceed. But now we have exhausted the input list and this means we found a match. At any point in the traversal, if you don't find a child for the current input element from the list, you are guaranteed that there is no match in your database. For instance if you got the input string zoo.bar.example.com. Our input list will be [com, example, bar, zoo]. We would traverse the tree until bar, but in the tree 'bar' doesn't have a child 'zoo'. This implies we don't have zoo.bar.example.com in our database.

You can find a match within O(n), where n is the number of subdomains in your input string that you're trying to match.


问:
What is a good way to store geographical data for distance calculations
What would be the best way to store data in a database for geographical calculations? Say I have an ItemsForSale table paired to a Users table which holds their geo location. I know I can use latitude and longitude to look up items that are within a certain mile radius by using Lambert's formula for long lines or the Haversine formula but I am not sure if there is a better approach for this.

答:
I'm not sure standard databases like MySql provide spacial indexing. You need to put them in a persistent spacial index. Like M-trees. Spacial indexes are efficient data structures that can perform range queries over distance metrics.

Wikipedia M tree

Stack Overflow: Storing coordinates in a smart way to obtain the set of coordinates within a certain range from (lat_,lon_)

You might be able to find an implementation of M-tree or other spacial indexing data structures like K-D trees.

EDIT: After Martijn Pieters mentioned MySql having spatial indexes, I looked it up. Turns out it does have a R-tree but the support doesn't seem great. I only use innodb because mostly I end up requiring row level locks.

MySQL 5.6 implements an additional set of functions that can help create geo-enabled applications with MySQL. Storing polygons boundaries (ZIP code boundaries for example) is efficient and the new spatial functions (st_within, st_contains, etc) will produce correct results and will use spatial (rtree) indexes (for MyISAM tables only). The OpenGIS standard is very common and it is easy to obtain the data in this format or use the standard application which can “talk” this language. Unfortunately, st_distance function is not very usable for calculating distance between 2 points on Earth and it does not use an index. In this case it is still more feasible to calculate distances manually using the harvesine formula. Hopefully this will be fixed in the next mysql release.

Using the new spatial functions in MySQL 5.6 for geo-enabled applications


问:
Interface to enumerate over files
I'm trying to design a generic interface for enumerating over a list files. Each iteration will open a file, allow the consuming code to access the file to perform some task, and then close the file.

At first this seemed like like a simple enumeration pattern, but the consuming code actually needs to know the status of each file both after it is opened and after it is closed. So rather then having a single MoveNext() method my interface has OpenNextFile() and CloseCurrentFile() methods, each of which may return a failure status. In addition, CloseCurrentFile() needs a way to report whether each file was saved or not when it was closed.

Here's my current interface.

```<code>public interface IFileEnumerator
{
    //The following properties reflect the current state of the IFileEnumerator
    FileEnumeratorStatus Status { get; }
    string StatusMessage { get; }
    string FileName { get; }
    byte[] FileData { get; }

    //Attempts to open the next file
    FileEnumeratorStatus OpenNextFile();

    //Closes the current file
    FileEnumeratorStatus CloseCurrentFile();
}

public enum FileEnumeratorStatus
{
    AtStart, //Files have not been opened
    Opened, //File currently opened
    Opened_Failed, //Failed to open file
    Close_Saved, //File closed and saved
    Closed_NotSaved, //File closed and not saved
    Close_SaveFailed, //File closed saving failed
    AtEnd //No more files
}
</code>```

Here's an example of the consuming code:

```<code>//FileProcessor is a class which run a ProcesssJob on a set of files returned by a
//IFileEnumerator and returns a ProcesssingJobResult with results of all the files
public class FileProcessor
{
    public ProcesssingJobResult RunJob(IFileEnumerator fileEnumerator, ProcesssJob job)
    {
        List<FileProcessingResult> resultList = new List<FileProcessingResult>();

        while (fileEnumerator.OpenNextFile() != FileEnumeratorStatus.AtEnd)
        {
            FileProcessingResult currentFileResult = new FileProcessingResult();
            currentFileResult.FileName = fileEnumerator.FileName;

            if (fileEnumerator.Status == FileEnumeratorStatus.Opened)
            {
                currentFileResult.JobCompleted = job.RunJob(fileEnumerator.FileData);

                var closureStatus = fileEnumerator.CloseCurrentFile();

                if (closureStatus == FileEnumeratorStatus.Close_Saved)
                    currentFileResult.Saved = true;
                else if (closureStatus == FileEnumeratorStatus.Closed_NotSaved)
                    currentFileResult.Saved = false;
                else if (closureStatus == FileEnumeratorStatus.Close_SaveFailed)
                {
                    currentFileResult.Saved = false;
                    currentFileResult.Message = fileEnumerator.StatusMessage;
                }
            }
            else if (fileEnumerator.Status == FileEnumeratorStatus.Opened_Failed)
            {
                currentFileResult.JobCompleted = false;
                currentFileResult.Message = fileEnumerator.StatusMessage;
                currentFileResult.Saved = false;
            }

            resultList.Add(currentFileResult);
        }

        ProcesssingJobResult jobresult = new ProcesssingJobResult();
        jobresult.TimeStamp = DateTime.Now.ToUniversalTime();
        jobresult.Machine = System.Environment.MachineName;
        jobresult.User = System.Environment.UserName;
        jobresult.Results = resultList;

        return jobresult;
    }
}

//A generic task that can be run on a file
public interface ProcesssJob
{
    bool RunJob(byte[] data);
}

//Result of processing one file
public class FileProcessingResult
{
    public bool JobCompleted { get; set; }
    public bool Saved { get; set; }
    public string FileName { get; set; }
    public string Message { get; set; }

}

//The overall result of processing a set of files
public class ProcesssingJobResult
{
    public DateTime TimeStamp { get; set; }
    public String Machine { get; set; }
    public String User { get; set; }
    public List<FileProcessingResult> Results { get; set; }
}
</code>```

Maybe this is just a question of careful documentation, but I'm having trouble dealing with all these different possible states. Drawing a state diagram doesn't help as it's possible to go from every state to just about every other state. Should the consuming code call CloseCurrentFile() if OpenNextFile() return Open_Failed? What if it does? Would a Closed status be returned even if a file was never opened? If CloseCurrentFile() was not called after OpenNextFile() should it be closed automatically by the next call to OpenNextFile() or should an exception be thrown? I'd rather someone implementing this interface not have to worry about getting all this right.

The problem is much simpler if I have a single OpenNextFile() method which is responsible for both closing the last opened file, and opening the next file. Yet then this single method needs to report both the result of opening the next file, as well as closing the last file. This also becomes tricky for consuming code as the final state of each file is not determined until the following iteration.

```<code>public interface IFileEnumerator_Alternate
{
    string FileName { get; }
    byte[] FileData { get; }
    string StatusMessage {get;}

    //Closes the previous file, and opens the next file
    Result OpenNextFile();
}

public class Result
{
    public bool CurrentFileOpened {get; set;}
    public string CurrentFileName {get; set;}
    public string CurrentFileStatusMessage {get; set;}

    public string LastFileName {get; set;}
    public bool LastFileClosedOk {get; set;}
    public string LastFileClosedStatusMessage {get; set;}
    public bool LastFileSaved {get; set;}
}
</code>```

Is there another way to look at this, or some other common design pattern that is more suited to what I'm trying to do? Here's an activity diagram showing the overall process.

答:
What about approaching the problem from the other side. You have a class, that represents that nice flow diagram of yours and this flow diagram creates "events" based on transitions. Those events then can be represented as either an interface or events:

```<code>public interface IFileProcessor
{
    void HandleFile(string fileName, Stream data);
    void OpenFailed(string fileName);
    void CloseFailed(string fileName);
    void Closed(string fileName, bool saved);
    void AllFilesProcessed(); // maybe?
}
</code>```

Then your "enumerator" will accept instance of class that implements this interface and executes the relevant methods.

```<code>string[] files = ...; // what files?
IFileProcessor processor = ...; // how the files should be handled?
var enumerator = new FileEnumerator(files, processor);
enumerator.Run(); // process all files
</code>```

This solutions seems much simpler, but slightly harder to understand due to inverted control.

Title: Interface to enumerate over files

Body:
What about approaching the problem from the other side. You have a class, that represents that nice flow diagram of yours and this flow diagram creates "events" based on transitions. Those events then can be represented as either an interface or events:

public interface IFileProcessor
{
    void HandleFile(string fileName, Stream data);
    void OpenFailed(string fileName);
    void CloseFailed(string fileName);
    void Closed(string fileName, bool saved);
    void AllFilesProcessed(); // maybe?
}

Then your "enumerator" will accept instance of class that implements this interface and executes the relevant methods.

string[] files = ...; // what files?
IFileProcessor processor = ...; // how the files should be handled?
var enumerator = new FileEnumerator(files, processor);
enumerator.Run(); // process all files

This solutions seems much simpler, but slightly harder to understand due to inverted control.


问:
DDD: How to refer/select a value object inside aggregate?
We have an aggregate of:

entity: Poll (representing a question)

two or more value objects Choice

Adding choices is done through Poll, repository stores only the aggregate, i.e. everything is done as expected.

Now, I need to select specific Choice that user chose. From the UI I will have only the choiceId of selected choice. So would my Poll.voteForChoice() method be:

voteForChoice(choiceId) - where I pass the choice id to the aggregate root, so he iterates it's choices and finds the target choice so to increment the count. However, we are using ID here for the choice, and choice is value object.

voteForChoice(Choice) - where we are sending the full value object, meaning I need to create it first before I do the voting. That also means I will need to have a Repo for choices, and they are value objects, so that clashes with all what I've learned ;)

or it should be: Poll.getChoice(choiceId).vote().

or the Choice is actually an entity, so we would use Repository to fetch choice: ChoiceRepo.find(id).vote().

Simple case, but what is the correct answer in DDD world?

答:
I believe that a value object should be referred by its value because that's what makes it unique, neither a GUID nor a local ID.

Consider a real world example

1) What web browser do you use at work?

A) Chrome

B) Firefox

C) Internet Explorer

D) Opera

E) Safari

2) What web browser do you use at home?

A) Chrome

B) Firefox

C) Internet Explorer

D) Opera

E) Safari

How would you vote in the real world? You would probably say something along the lines "For the first poll I vote for 'Firefox'" or "For the second poll I choose 'A'". Hence, there are few ways you can go about modeling the voting behavior

```<code>// 1st poll (GUID = 1)
Poll poll1 = pollRepo.find(1);

// 2nd poll (GUID = 2)
Poll poll2 = pollRepo.find(2);

poll1.voteForChoice("Firefox");
poll2.voteForChoice("Chrome");
</code>```

On the other hand, there's nothing wrong in creating an instance of a value object outside the scope of its aggregate without using a repository

```<code>poll1.voteForChoice(new Choice("Firefox"));
poll2.voteForChoice(new Choice("Chrome"));
</code>```

So, it seems like you can use the second option for the voteForChoice method. The first one uses ID which suggests that Choices be modeled as entities. The third one feels wrong like a leaky abstraction and breach of encapsulation. The forth one is wrong because of using a repository for a value object.

UPDATE

Important point. There's no a single recipe how to model your domain even if it's a common case in the real world. You may design your Choices as value objects and have a Map<Choice, Counter> choices property in your Polls. Or, you may design it as entities and have the counter as a part of a Choice. Additionally, you might want to have a List<User> users collection in the Choice entity to keep a track of users who voted for a particular Choice.

I know I've made it even more confusing for you, but the thing that I want to emphasize is that you have to decide for yourself what kind of domain model you need. My answer was based on the assumption derived from your question that value objects is what you need.

UPDATE 2

It turns out that according to Eric Evans when you tempted to create some sort of identifier for a value object even if it's a local one you should consider making it an entity instead.

Body:
I believe that a value object should be referred by its value because that's what makes it unique, neither a GUID nor a local ID.

Consider a real world example

1) What web browser do you use at work?

A) Chrome

B) Firefox

C) Internet Explorer

D) Opera

E) Safari

2) What web browser do you use at home?

A) Chrome

B) Firefox

C) Internet Explorer

D) Opera

E) Safari

How would you vote in the real world? You would probably say something along the lines "For the first poll I vote for 'Firefox'" or "For the second poll I choose 'A'". Hence, there are few ways you can go about modeling the voting behavior

// 1st poll (GUID = 1)
Poll poll1 = pollRepo.find(1);

// 2nd poll (GUID = 2)
Poll poll2 = pollRepo.find(2);

poll1.voteForChoice("Firefox");
poll2.voteForChoice("Chrome");

On the other hand, there's nothing wrong in creating an instance of a value object outside the scope of its aggregate without using a repository

poll1.voteForChoice(new Choice("Firefox"));
poll2.voteForChoice(new Choice("Chrome"));

So, it seems like you can use the second option for the voteForChoice method. The first one uses ID which suggests that Choices be modeled as entities. The third one feels wrong like a leaky abstraction and breach of encapsulation. The forth one is wrong because of using a repository for a value object.

UPDATE

Important point. There's no a single recipe how to model your domain even if it's a common case in the real world. You may design your Choices as value objects and have a Map<Choice, Counter> choices property in your Polls. Or, you may design it as entities and have the counter as a part of a Choice. Additionally, you might want to have a List<User> users collection in the Choice entity to keep a track of users who voted for a particular Choice.

I know I've made it even more confusing for you, but the thing that I want to emphasize is that you have to decide for yourself what kind of domain model you need. My answer was based on the assumption derived from your question that value objects is what you need.

UPDATE 2

It turns out that according to Eric Evans when you tempted to create some sort of identifier for a value object even if it's a local one you should consider making it an entity instead.


问:
Extending a class for debugging: public API, hidden implementation or something else?
I'm working on a fairly large project that involves 3D drawing, and I want to add some visualizers (for example, to see the bounding boxes of the objects) to make debugging easier. However, I'm having a problem in deciding how to go about this.

One option would be to create a public function to draw the visualizers, and call this function when I enable debugging from the UI. This would have the advantage of not modifying the existing functions, but extending the class with a new function. The disadvantage would be "creating dependencies", as one of my colleagues said, we would need to modify the base class, and all the deriving classes to add this function.

Another option would be to modify the existing drawing function so that it handles the drawing of the visualizers. This hides the implementation details, but also it seems to me it makes the code less modular.

Yet another option is extending the class, adding the visualizer in the drawing function, and swapping classes when debugging is enabled. Mixins would be of help, but C++ doesn't support that.

What would be the best approach to do this? I'm looking for a solution that is modular and respects the SOLID principles.

答:
If you want SOLID, I would go mainly with S(ingle Responsability) and D(ependency Injection):

For example, for the bounding boxes:

create a base abstract class with the, say, drawBox method.

create the "regular" implementation (for example, it does nothing) and the "debug" implementations.

your classes will use a regular implementation by default, but will allow the injection (through a constructor/method, or by a using a factory) of other instances.

Let's check

S: Each class does only one thing (your business class do not have a "debug mode" or a "production mode")

O: If you create a new subclass of the abstract class, you do not need to change your business classes to use it.

D: Well, dependency injection is the mechanism used.