问:
storing map template in database
I am working on an application that displays choropleth maps. These maps are of all different types, some display state by county, country by state/province, or world by country.

How should I handle storing the map information in the database?

My Thoughts:

I won't need to do queries to find POI inside a region, so I don't think there is a need to use spatial datatypes.  I am considering storing a map as a geoJSON object (I am using JS mapping library that accepts geoJSON).

The only issue is what if I want a map of the US northeast.  Then I would have geoJSON for the US and a separate one for the US northeast, which would be redundant.

Would it make sense to have a shape database where I had each state then when I needed a map of the US I could query for each state, and when I needed a map of the US Northeast I could again query for what I need?

Note: I am not concerned with storing the data for each region, just the region itself.  I will query for the data on the fly for the specific region.

答:
Having GeoJSON information for the US and a separate one for the US northeast is not redundant.  One is telling you information pertaining to the entire US while the other is just telling you information pertaining to the US northeast.  Without the latter, you'd have to accumulate information pertaining to all regions of the US in order to arrive at the same value.

This may not seem like much work, but when you consider that having GeoJSON information for the US northeast is redundant when you have New York, Maine, Massachusetts, etc., you quickly see a fractal pattern emerge.  To be able to then calculate the accumulative value for the united states, you must potentially query and cycle through all counties of every state in the united states, which when done in runtime is no small order.

If it bothers you that modifying this information will render every parent region no longer accurate, you need only save the delta of the change in each parent region until you hit the country level.  If you prefer, you can even decide to save calculated information in its own collection in case you wanted to clear it out and start from scratch.

If you must save lots of different types of information pertaining to a region, consider keeping region information in its own collection and region data information separate with a reference to the region itself, so you can avoid repeating it for each type of possible query you'd like to perform.  You may also wish to cache region information since it isn't likely to change, whereas the data you're querying might.

I hope that helps!

Title: storing map template in database


问:
Is there a Design Pattern for preventing dangling references?
I was thinking about a design for custom handles. The thought is to prevent clients from copying around large objects. Now a regular handle class would probably suffice for that, but it doesn't solve the "dangling reference problem";

If a client has multiple handles of the same object and deletes the object via one of them, all the others would be invalid, but not know it, so the client could write or read parts of the memory he shouldn't have access to.

Is there a design pattern to prevent this from happening?

Two ideas:

An observer-like pattern where the destructor of an object would notify all handles.

"Handle handles" (does such a thing even exist?). All the handles don't really point to the object, but to another handle. When the object gets destroyed, this "master-handle" invalidates itself and therefore all that point to it.

答:
C++11 introduced two new utility classes: std::shared_ptr and std::unique_ptr. If you need to control a resource through multiple handles, then wrap it in a std::shared_ptr, which is a reference-counted smart pointer that cleans up the resource when there are no more pointers to it. std::unique_ptr is designed for single ownership, but it too will automatically clean up the resource it holds when the handle itself is destroyed.

While the name _ptr seems to imply pointers, both classes can be customized to work with any kind of resource that needs to be manually given back to the OS. Here's a hypothetical example that uses FILE* handles from C (why you would use this instead of streams is up to you...)

```<code>struct FILE_deleter {
    void operator() (FILE* fp) const {
        fclose(fp);
    }
};

void f()
{
    std::shared_ptr<FILE> sp(fopen("some-file.txt"), FILE_deleter{});

    // Now do whatever you want with sp: make copies of it, pass it around, whatever.
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
C++11 introduced two new utility classes: std::shared_ptr and std::unique_ptr. If you need to control a resource through multiple handles, then wrap it in a std::shared_ptr, which is a reference-counted smart pointer that cleans up the resource when there are no more pointers to it. std::unique_ptr is designed for single ownership, but it too will automatically clean up the resource it holds when the handle itself is destroyed.

While the name _ptr seems to imply pointers, both classes can be customized to work with any kind of resource that needs to be manually given back to the OS. Here's a hypothetical example that uses FILE* handles from C (why you would use this instead of streams is up to you...)

struct FILE_deleter {
    void operator() (FILE* fp) const {
        fclose(fp);
    }
};

void f()
{
    std::shared_ptr<FILE> sp(fopen("some-file.txt"), FILE_deleter{});

    // Now do whatever you want with sp: make copies of it, pass it around, whatever.
}


问:
How to be Agile when new work keeps affecting completed work?
The project I'm working on is to re-skin an existing website. The functionality will stay the same, it's just the styles that are changing. In other words, I'm not modifying the HTML, only the CSS files.

The site is pretty complex, with dozens of pages. Logged-in users can have a number of different roles, and depending on their role, the content of the page and what pages they are allowed to see varies.

We're using Git and Github.

I'm trying to write CSS that works as components, so when the same form elements, headings, etc. appear on multiple pages, they are consistent. Most of time this is working well.

Sadly, the format and class names in the HTML are at times messy and unpredictable. When I fix something on one page it can break another. The job is also harder as no one knows exactly all the variations that are possible due to user roles; as such I'm continuously finding new variations as I go along.

I'm making headway by putting a lot of comments in my CSS. If I need to remove a CSS rule, I'll comment it out so that I can still see it with Chrome dev tools, and I'll put a comment in the CSS saying why I removed it and for what page this was done.

This means that if on another page I'm about to add a rule to fix a different problem, there is a better chance that I'll see how it'll break the first page. This allows me to either find a different solution that will work for both pages, or I can make the override page specific.

This has been working quite well for me. If I had free reign and the only goal was to finish the project by the deadline, then this method would be fine. However, my manager is trying to mitigate risk by breaking the work into areas to be completed per sprint. This is counter to how I have been approaching things as something like my typography styles will affect all other pages on the site.

The other issue is that the different stakeholders want to sign off on each section as I go along. The problem is, once I've finished a section it may change if I change CSS that affects it along with the new section I'm working on. I've asked that the stakeholders have a quick unofficial sign off in stages (e.g. per sprint), and have the final official sign off at the end of the project, but this is being met with resistance. I understand why it would be higher risk to do this, but the only way to guarantee that a signed off section will not change is to make ALL future changes page specific.

In addition to this I'm being told that all work that I push to the Git repo should be ready to go live, and as such should not contain any code comments. This is risky for me as I won't know until I've finished the site if I will ever benefit from these comments or not.

Has anyone else been in a similar situation and managed to find a compromise that worked for my development approach and also the desires of management and stakeholders to have a more Agile approach? A more Agile workflow works great when you can break the work into components and know that once something is done it won't be affected by future work. However the nature of this project makes this hard to achieve.

答:
Suggestions

It looks like testing is not done properly by your team. What your team is expected to do is to have automated testing which ensures that changes to HTML and CSS don't break anything. pdiff would be particularly useful for that.

You consider HTML as "messy and unpredictable". Have you discussed that with your team, and especially the persons who write HTML code? Why would your colleagues make code which you consider being messy and unpredictable? Looks like your team should focus on that.

Code reviews may help. If it's impossible to do code reviews, try to personally discuss the problems you find in HTML with the colleague who wrote the code (or the part of server-side code which generates this HTML).

Try also to narrow the problem. Maybe there is just one person in your team who writes "messy and unpredictable" code. Maybe this HTML code is generated by a single component.

Introducing code standards can also be a solution, depending on your influence on the team.

If you have issues keeping code consistent, why don't you use a CSS preprocessor like LESS or Sass? You can then achieve better code reuse and better consistency.

Remarks

I'm being told that all work that I push to the Git repo should be ready to go live

Exactly. This is called continuous deployment/delivery/deployment.

Continuous integration is when every commit is followed by a build and an execution of automated tests. It helps locating potential regressions.

Continuous delivery is continuous integration followed (if tests are successful) by an additional step: the building of a package which can be deployed in production manually.

Continuous deployment is continuous delivery where the package is actually deployed automatically.

In all three cases, you're expected to commit code which works. You can't commit for example a bunch of unit tests which currently fail, waiting for the actual code to be implemented, or a piece of code which adds debug info all around the UI.

There are several benefits in this approach.

You have a working product at each commit. By comparison, there are projects where the product actually works only twice per year, when it is actually packaged and deployed. This increases the risk of never shipping the product.

You (as well as the stakeholders and other concerned persons) have a better visibility on the project.

There is less chance to stay at 90% done for months.

If I need to remove a CSS rule, I'll comment it out

Instead of commenting code, remove it. Commented code is particularly harmful to the code base, because in six months, nobody knows why is this code here, why was it commented and what to do with it. Comments are intended to clarify the intention of the original author; commented code doesn't have this purpose.

Don't keep commented code just to be able to rollback to it later. You already use a version control, so reverting to a previous version or looking at what was changed shouldn't be a problem.

I don't understand why you're told that production code shouldn't contain comments, and especially why you should remove those comments from your  code. It looks like there is an important step missing in the workflow: the minification. CSS and client-side JavaScript code should be minified automatically, then moved to production. It shouldn't be your task to remove comments from the code you write, and if done manually, it can be a source of human mistakes.


问:
Writing a method to 'transform' an immutable object: how should I approach this?
(While this question has to do with a concrete coding dilemma, it's mostly about what's the best way to design a function.)

I'm writing a method that should take two Color objects, and gradually transform the first Color into the second one, creating an animation. The method will be in a utility class.

My problem is that Color is an immutable object. That means that I can't do color.setRGB or color.setBlue inside a loop in the method.

What I can do, is instantiate a new Color and return it from the method. But then I won't be able to gradually change the color.

So I thought of three possible solutions:

1- The client code includes the method call inside a loop. For example:

```<code>int duration = 1500; // duration of the animation in milliseconds
int steps = 20; // how many 'cycles' the animation will take
for(int i=0; i<steps; i++) color = transformColor(color, targetColor, duration, steps);
</code>```

And the method would look like this:

```<code>Color transformColor(Color original, Color target, int duration, int steps){
    int redDiff = target.getRed() - original.getRed();
    int redAddition = redDiff / steps;
    int newRed = original.getRed() + redAddition;

    // same for green and blue ..

    Thread.sleep(duration / STEPS); // exception handling omitted
    return new Color(newRed, newGreen, newBlue);
}
</code>```

The disadvantage of this approach is that the client code has to "do part of the method's job" and include a for loop. The method doesn't do it's work entirely on it's own, which I don't like.

2- Make a mutable Color subclass with methods such as setRed, and pass objects of this class into transformColor. Then it could look something like this:

```<code>void transformColor(MutableColor original, Color target, int duration){
    final int STEPS = 20;

    int redDiff = target.getRed() - original.getRed();
    int redAddition = redDiff / steps;
    int newRed = original.getRed() + redAddition;

    // same for green and blue ..

    for(int i=0; i<STEPS; i++){
        original.setRed(original.getRed() + redAddition);
        // same for green and blue ..
        Thread.sleep(duration / STEPS); // exception handling omitted
    }
}
</code>```

Then the calling code would usually look something like this:

```<code>// The method will usually transform colors of JComponents
JComponent someComponent = ... ;
// setting the Color in JComponent to be a MutableColor
Color mutableColor = new MutableColor(someComponent.getForeground());
someComponent.setForeground(mutableColor);
// later, transforming the Color in the JComponent
transformColor((MutableColor)someComponent.getForeground(), new Color(200,100,150), 2000);
</code>```

The disadvantage is - the need to create a new class MutableColor, and also the need to do casting.

3- Pass into the method the actual mutable object that holds the color. Then the method could do object.setColor or similar every iteration of the loop.

Two disadvantages:

A- Not so elegant. Passing in the object that holds the color just to transform the color feels unnatural.

B- While most of the time this method will be used to transform colors inside JComponent objects, other kinds of objects may have colors too. So the method would need to be overloaded to receive other types, or receive Objects and have instanceof checks inside.. Not optimal.

Right now I think I like solution #2 the most, than solution #1 and solution #3 the least. However I'd like to hear your opinions and suggestions regarding this.

答:
Here's a case where you can actually use a pattern: Iterator

Your iterator object is constructed with the start and target colors, and a number of steps. Each call to next() returns the next color in the sequence, until you reach the end.

I see that your example includes a sleep, which is an incredibly bad idea for GUI programming. Instead, use a javax.swing.Timer to trigger reads from your iterator. If you want to encapsulate the duration in the iterator object (a good idea), you can add a sleepTime() method.


答:
An alternative to an iterator is to pass in whatever you want to do with the color as an argument to transformColor.

```<code>void transformColor(Color original, Color target, int duration, int steps, Function<Color, Void> f){
    int redDiff = target.getRed() - original.getRed();
    int redAddition = redDiff / steps;
    int newRed = original.getRed() + redAddition;

    // same for green and blue ..
    for (int i = 0; i < steps; i++) {
        f(new Color(newRed, newGreen, newBlue));
        Thread.sleep(duration / STEPS); // exception handling omitted
    }
}
</code>```

On that note I'd argue it's surprising and potentially undesirable for transformColor to take care of timing.

Title: Writing a method to 'transform' an immutable object: how should I approach this?

Body:
(While this question has to do with a concrete coding dilemma, it's mostly about what's the best way to design a function.)

I'm writing a method that should take two Color objects, and gradually transform the first Color into the second one, creating an animation. The method will be in a utility class.

My problem is that Color is an immutable object. That means that I can't do color.setRGB or color.setBlue inside a loop in the method.

What I can do, is instantiate a new Color and return it from the method. But then I won't be able to gradually change the color.

So I thought of three possible solutions:

1- The client code includes the method call inside a loop. For example:

```<code>int duration = 1500; // duration of the animation in milliseconds
int steps = 20; // how many 'cycles' the animation will take
for(int i=0; i<steps; i++) color = transformColor(color, targetColor, duration, steps);
</code>```

And the method would look like this:

```<code>Color transformColor(Color original, Color target, int duration, int steps){
    int redDiff = target.getRed() - original.getRed();
    int redAddition = redDiff / steps;
    int newRed = original.getRed() + redAddition;

    // same for green and blue ..

    Thread.sleep(duration / STEPS); // exception handling omitted
    return new Color(newRed, newGreen, newBlue);
}
</code>```

The disadvantage of this approach is that the client code has to "do part of the method's job" and include a for loop. The method doesn't do it's work entirely on it's own, which I don't like.

2- Make a mutable Color subclass with methods such as setRed, and pass objects of this class into transformColor. Then it could look something like this:

```<code>void transformColor(MutableColor original, Color target, int duration){
    final int STEPS = 20;

    int redDiff = target.getRed() - original.getRed();
    int redAddition = redDiff / steps;
    int newRed = original.getRed() + redAddition;

    // same for green and blue ..

    for(int i=0; i<STEPS; i++){
        original.setRed(original.getRed() + redAddition);
        // same for green and blue ..
        Thread.sleep(duration / STEPS); // exception handling omitted
    }
}
</code>```

Then the calling code would usually look something like this:

```<code>// The method will usually transform colors of JComponents
JComponent someComponent = ... ;
// setting the Color in JComponent to be a MutableColor
Color mutableColor = new MutableColor(someComponent.getForeground());
someComponent.setForeground(mutableColor);
// later, transforming the Color in the JComponent
transformColor((MutableColor)someComponent.getForeground(), new Color(200,100,150), 2000);
</code>```

The disadvantage is - the need to create a new class MutableColor, and also the need to do casting.

3- Pass into the method the actual mutable object that holds the color. Then the method could do object.setColor or similar every iteration of the loop.

Two disadvantages:

A- Not so elegant. Passing in the object that holds the color just to transform the color feels unnatural.

B- While most of the time this method will be used to transform colors inside JComponent objects, other kinds of objects may have colors too. So the method would need to be overloaded to receive other types, or receive Objects and have instanceof checks inside.. Not optimal.

Right now I think I like solution #2 the most, than solution #1 and solution #3 the least. However I'd like to hear your opinions and suggestions regarding this.

Body:
An alternative to an iterator is to pass in whatever you want to do with the color as an argument to transformColor.

void transformColor(Color original, Color target, int duration, int steps, Function<Color, Void> f){
    int redDiff = target.getRed() - original.getRed();
    int redAddition = redDiff / steps;
    int newRed = original.getRed() + redAddition;

    // same for green and blue ..
    for (int i = 0; i < steps; i++) {
        f(new Color(newRed, newGreen, newBlue));
        Thread.sleep(duration / STEPS); // exception handling omitted
    }
}

On that note I'd argue it's surprising and potentially undesirable for transformColor to take care of timing.


答:
I'm writing a method that should take two Color objects, and gradually transform the first Color into the second one, creating an animation. The method will be in a utility class.

OK, so how many unrelated concerns do we have in that sentence?

a method that should take two Color objects, and gradually transform the first Color into the second one - OK, that's a thing!

I'm slightly concerned at your use of the word "gradual" since it could imply mixing the concept of time with the concept of colour. However, I can (and will) choose to read the other meaning, as in gradations of colour. So, we're taking two colours and (somehow) producing a given number of intermediate shades. You haven't specified whether we should do this in RGB, HSV, CMYK or whatever other colour space, but fine.

creating an animation - well, that sounds like a completely separate thing. The function above could be used in, say, creating a colour gradient for shading (where your colour varies in space instead of time). So why tie it to the animation thing?

So now we know we want some function to produce an ordered sequence of colours given some inputs. This could be a container, or it could be an iterator, or it could be a straight loop taking some callback function. These are all similar, with the following trade-offs:

return a container: uses more storage (the other two are constant size, and this scales linearly with the number of steps), and front-loads the computation (it takes a while to populate that container if it's large)

iterator: the client code still needs to write that for loop you objected to, and you need to write an iterator type (unless your language has co-routines or something similar, like Python's generators) but it's very efficient

callback: the client code makes a single call, but instead of the for loop, it has to write some callback function with access to all the right state (unless your language has nice lambdas or lexical closures)

The container option is just for completeness, and I'd recommend either of the other two - depending on preference and language support - unless you know it'll be small or you have no other option.


问:
WPF4 Unleashed - how does converting child elements work?
In chapter 2 of the book WPF4 Unleashed the author shows an example of how XAML processes type conversion. He states that

```<code><SolidColorBrush>White</SolidColorBrush>
</code>```

is equivalent to

```<code><SolidColorBrush Color="White"/>
</code>```

, because a string can be converted into a SolidColorBrush object.

But how is that enough? It doesn't make sense to me. How does XAML know to which property should the value White be assigned?

答:
This is a core feature of XAML.  Microsoft's XAML Overview covers this rather explicitly.

A small number of XAML elements can directly process text as their content. To enable this, one of the following cases must be true:

The class must declare a content property, and that content property must be of a type assignable to a string (the type could be Object). For instance, any ContentControl uses Content as its content property and it is type Object, and this supports the following usage on a practical ContentControl such as a Button: Hello.

The type must declare a type converter, in which case the text content is used as initialization text for that type converter. For example, Blue. This case is less common in practice.

The type must be a known XAML language primitive.

That is, the SolidColorBrush class is able to route text content to its Color property, by declaring "Color" as its content property.

Most likely the separate Color class has an implicit cast from string, allowing a valid string to be sent for any purpose that specifies a Color.


问:
Does it make sense to make a field mandatory which has a default value?
Consider a drop down "Duration" which has 3 options

```<code>1. 30 days
2. 60 days
3. 90 days
</code>```

and by default 30 days will be the selected value. Does it make sense to make this dropdown mandatory? Do we really need to put a * (Mandatory mark) for this field?

答: Depends on the importance of the field and not on the default value. Do you think if this field is not mandatory will give the user shock after 30 days? If yes then it should be mandatory or else it should not. My strategy is to keep minimum fields mandatory and some sufficient default value for others. Then mention in the documentation what each value does, and if something happens which value to change. </p>

ContentLicense: CC BY-SA 2.5


问:
Object-Oriented equivalent of LISP's progn function?
I'm currently writing a LISP parser that iterates through some AutoLISP code and does its best to make it a little easier to read (changing prefix notation to infix notation, changing setq assignments to "=" assignments, etc.) for those that aren't used to LISP code/only learned object oriented programming.

While writing commands that LISP uses to add to a "library" of LISP commands, I came across the LISP command "progn".  The only problem is that it looks like progn is simply executing code in a specific order and sometimes (not usually) assigning the last value to a variable.

Am I incorrect in assuming that for translating progn to object-oriented understanding that I can simply forgo the progn function and print the statements that it contains?  If not, what would be a good equivalent for progn in an object-oriented language?

答:
Everything in Lisp is an expression, meaning that it returns a value. The progn function executes a series of functions/forms, ignoring the return values of all but the last call/form, which it returns as its own return value.

E.g. in the following code

```<code>(progn
  (some-method 'a 'b 'c)
  (another-method 1 2 3)
  (final-method "x" "y" "z"))
</code>```

the value returned by the call to final-method would be the value returned by the enclosing progn call.

An OOP equivalent would be:

```<code>public FinalReturnType prognImpl123()
{
    someMethod(Sym("a"), Sym("b"), Sym("c"));
    anotherMethod(1, 2, 3);
    return finalMethod("x", "y", "z");
}
</code>```

As progns you encounter will likely be nested in other expressions, you'll want your translations to return something.

Body:
Everything in Lisp is an expression, meaning that it returns a value. The progn function executes a series of functions/forms, ignoring the return values of all but the last call/form, which it returns as its own return value.

E.g. in the following code

(progn
  (some-method 'a 'b 'c)
  (another-method 1 2 3)
  (final-method "x" "y" "z"))

the value returned by the call to final-method would be the value returned by the enclosing progn call.

An OOP equivalent would be:

public FinalReturnType prognImpl123()
{
    someMethod(Sym("a"), Sym("b"), Sym("c"));
    anotherMethod(1, 2, 3);
    return finalMethod("x", "y", "z");
}

As progns you encounter will likely be nested in other expressions, you'll want your translations to return something.


问:
Quite confused about what constitutes Current state of a resource
From REST in Practice: Hypermedia and Systems Architecture:

The current state of a resource is a combination of:

The values of information items belonging to that resource

Links to related resources

Links that represent a transition to a possible future state of the current resource

The results of evaluating any business rules that relate the resource to other local resources

a) why would "links to related resources" also represent the current state of a resource?

b) I also don't quite understand why "Links that represent a transition to a possible future state of the current resource" also represent the the current state.

Namely, those links represent the possibility, not the current state. Analogy would be an int variable set to value 10. It's possible that in the future this variable will get processed and set to value 100, but we don't claim its current state also includes possible future state of 100?!

REPLY:

1)

links to related resources: imagine a "chat_room" resource. The links
  to people in that room will change as they come and go. In other
  words, a resource's relationships to other resources may change.

a) I also began learning  domain driven design and there an entity E may have child entities ( thus E is a parent in a relationship ) and E's relationship with its child entities may change ( ie some child entities may be assigned to different parent or may get deleted).

But even though E has one-to-many relationship with its child entities, we don't consider that relationship as also representing the current state of E. That's is why I'm puzzled as to why in REST the links to related resources also represent the current state?!

b)

imagine a university has a "student" resource. There might be a link
  to "register" in a class, a link to "apply for housing", and links to
  "tune in", "turn on" and "drop out". Each link may change the state of
  the object, or may yield appropriate information for the resource
  state. For example, the correct Student Housing application for that
  student.

It sort of makes sense that the state of current resource also constitute those links to related resources, which may state change the state of the current resource. But it doesn't make sense that the state of the current resource also constitute links to those related resources which don't change the state of the current resource?!

2)

But the resource may be a sort of state machine. So a "car" resource
  might have links to "start_engine" if it's stopped. It might links to
  "speed_up", "slow_down", and if the speed is slow enough,
  "stop_engine". In other words, links to transition to other valid
  states based on the current state.

a)

links to transition to other valid states based on the current state.

I assume you've made a typo and what you meant to write is "links to transition to other valid states is based on the current state"?

b) So could we say the reason why links that represent transitions to other states also represent current state of a resource is because every resource with such links could be considered a state machine, and with state machine, links to other valid states do represent current state ( I hope my ramblings make some sense )?!

2. REPLY:

1)

But it seems more natural in handling structured data to just bundle
  the "chat_room" and "chat_room_person" information together.

I assume technically, related resources themselves don't represent the current state of a resource. Instead, only links to these related resources represent the current state of a resource?!

2)

In REST, the goal is to eliminate all out-of-band communication. So we
  supplement the state (ON) with links that represent all the valid
  transitions for that state. So we want to avoid more documentation.
  The resource representation can tell us, "This is where I am, and this
  is where I can go next."

In REST the links that represent transitions to other states also represent the current state of a resource, but could we argue that logically ( thus not in the context of REST ) these links don't really represent the current state of a resource, and thus only reason why in REST they do represent the current state of a resource is because REST is build around that assumption ( or is at least more efficient that way )?

thank you

答:
I'll try to answer with another example, and use some code to explain.

a) why would "links to related resources" also represent the current state of a resource?

Consider this class and assume it is the implementation of the REST resource /Human, abstracting from real live (Python-ish pseudo-code):

```<code>class Human:
  offsprings = [] # array of links (e.g. object id) to other Humans
  age = 20
  def is_adult():
     return age >= 20
  def is_parent():
     return len(offsprings) > 0

peter = Human()
print peter.is_parent()
=> False

kate = Human()
peter.offsprings.append(kate.id)
print peter.is_parent()
=> True
</code>```

Now quite clearly is_parent represents a state information. But this state is one that can only be answered by knowing about the links to related objects.

b) I also don't quite understand why "Links that represent a transition to a possible future state of the current resource" also represent the the current state.

Consider an extension of the above resource:

```<code>class Human:
  offsprings = [] # array of links (e.g. resource id) to other Humans
  avg_expected = [...] # array of statistic resources by birth date
  age = 20
  year_of_birth=1994
  def is_adult():
     return age >= 20
  def is_parent():
     return len(offsprings) > 0
  def live_expectancy():
     # consider the [ ] operator to look up the respective resource
     return avg_expected[year_of_birth] - age
</code>```

Again, live_expectancy is a state information for this resource. And it represents a possible future state, namely end of life. But without the link to the statistics resource, it is impossible to tell.

Body:
I'll try to answer with another example, and use some code to explain.

a) why would "links to related resources" also represent the current state of a resource?

Consider this class and assume it is the implementation of the REST resource /Human, abstracting from real live (Python-ish pseudo-code):

class Human:
  offsprings = [] # array of links (e.g. object id) to other Humans
  age = 20
  def is_adult():
     return age >= 20
  def is_parent():
     return len(offsprings) > 0

peter = Human()
print peter.is_parent()
=> False

kate = Human()
peter.offsprings.append(kate.id)
print peter.is_parent()
=> True

Now quite clearly is_parent represents a state information. But this state is one that can only be answered by knowing about the links to related objects.

b) I also don't quite understand why "Links that represent a transition to a possible future state of the current resource" also represent the the current state.

Consider an extension of the above resource:

class Human:
  offsprings = [] # array of links (e.g. resource id) to other Humans
  avg_expected = [...] # array of statistic resources by birth date
  age = 20
  year_of_birth=1994
  def is_adult():
     return age >= 20
  def is_parent():
     return len(offsprings) > 0
  def live_expectancy():
     # consider the [ ] operator to look up the respective resource
     return avg_expected[year_of_birth] - age

Again, live_expectancy is a state information for this resource. And it represents a possible future state, namely end of life. But without the link to the statistics resource, it is impossible to tell.


问:
Software architecture for two similar classes which require different input parameters for the same method
I am writing Java code to simulate a supply chain.
The supply chain can be simulated in either
an intermediate stocking or a cross-docking configuration.
So, I wrote two simulator objects IstockSimulator and XdockSimulator.
Since the two objects share certain behaviors
(e.g. making shipments, demand arriving),
I wrote an abstract simulator object AbstractSimulator
which is a parent class of the two simulator objects.

The abstract simulator object has a method runSimulation()
which takes an input parameter of class SimulationParameters.
Up till now, the simulation parameters only contains fields
that are common to both simulator objects,
such as randomSeed, simulationStartPeriod and simulationEndPeriod.
However, I now want to include fields that are specific to the type of simulation that is being run,
i.e. an IstockSimulationParameters class for an intermediate stocking simulation,
and a XdockSimulationParameters class for a cross-docking simulation.

My current idea is take the method runSimulation()
out of the AbstractSimulator class,
but to put a runSimulation(IstockSimulationParameters) method
in the IstockSimulator class,
and a runSimulation(XdockSimulationParameters) method
in the IstockSimulator class.
I am worried however, that this approach will lead to code duplication.

What should I do?

Edited

Currently, the AbstractSimulator class defines the runSimulation method
which calls other abstract methods
that are only defined by the concrete child classes.

```<code>public abstract class AbstractSimulator {
    public void runSimulation(SimulationParameters params) {
        int startPeriod = params.startPeriod;
        int endPeriod = params.endPeriod;
        for (int t = startPeriod; t < endPeriod; ++t) {
            submitReports(t);
            makeShipments(t);
            demandArrives(t);
        }
    }
    protected abstract void submitReports(int t);
    protected abstract void makeShipments(int t);
}
</code>```

One of the differences between the IstockSimulator and the XdockSimulator
is that in an intermediate stocking configuration,
tier 3 facilities submit reports to tier 2 facilities,
while in a cross-docking configuration,
tier 3 facilities submit reports to tier 1 facilities.
Thus the IstockSimulator and the XdockSimulator
have their own implementations of the methods submitReports and makeShipments.

What worked for me

Thank you for your answers.
Inspired by your answers, and after sleeping it over,
I came up with my own answer based on refactoring.
See below.

答:
The runSimulation() method has to be defined in the concrete classes because it uses different parameters, so it follows that it behaves differently. If you have common functionality, I would put the runSimulation() method in the concrete class with no parameters. Any common functionality like utility/helper methods can go in the abstract class. The constructor, which is already implementation-specific, accepts the parameters.

Creating a new object for each simulation, using the constructor to pass in parameters, has two benefits. First, it sidesteps the interface issue. Second, it solidifies the idea that a simulation should only be run once (it may have internal state for example, so it might not be reentrant anyway).

If you change the design this becomes the strategy pattern:

```<code>public interface SimulationParameters { ... }

public interface Simulation<T extends SimulationParamters> {
  SimulationResult runSimulation();
}

public class StockSimulation implements Simulation<StockParameters> {
  public StockSimulation (StockParameters p) { ... }
}

public class DockSimulation implements Simulation<DockParameters> {
  public DockSimulation (DockParameters d) { ... }
}
</code>```

Then you use it like this:

```<code>Simulation s1 = new StockSimulation(new StockParameters());
Simulation s2 = new DockSimulation(new DockParameters());
</code>```

You could then pass this off to an Executor or whatever else to run it, possibly in parallel. That is one of the advantages of this approach, it is very flexible.

This may avoid code duplication, and it definitely avoids polluting the interface which is I believe the real concern in your last paragraph.

Code Duplication

To avoid code duplication in the runSimulation() method, I would consider the approach of using composition to encapsulate each atomic step of a simulation in its own child object.

```<code>public interface SimulationComponent {
  void runStep(SimulationState state, ...);
}
</code>```

Then, in your simulation class, you could have simulation components:

```<code>public class StockSimulation implements Simulation<StockParameters> {

  private final List<SimulationComponent> components;

  public StockSimulation (StockParameters p) {
    List<SimulationComponent> c = new LinkedList<>();
    c.add(new SimulationComponentImpl1());
    c.add(new SimulationComponentImpl2());
    c.add(new SimulationComponentImpl3());
    components = Collections.unmodifiableList(c);
  }

  public SimulationResult runSimulation() {
    SimulationState state = ...;
    for (SimulationComponent c : components) {
      c.runStep(state);
    }
    return state.getResult();
  }
}
</code>```

Without detailed information about how the simulation works I cannot say for sure exactly how this code should work, but I believe this is the correct general approach.

Body:
The runSimulation() method has to be defined in the concrete classes because it uses different parameters, so it follows that it behaves differently. If you have common functionality, I would put the runSimulation() method in the concrete class with no parameters. Any common functionality like utility/helper methods can go in the abstract class. The constructor, which is already implementation-specific, accepts the parameters.

Creating a new object for each simulation, using the constructor to pass in parameters, has two benefits. First, it sidesteps the interface issue. Second, it solidifies the idea that a simulation should only be run once (it may have internal state for example, so it might not be reentrant anyway).

If you change the design this becomes the strategy pattern:

public interface SimulationParameters { ... }

public interface Simulation<T extends SimulationParamters> {
  SimulationResult runSimulation();
}

public class StockSimulation implements Simulation<StockParameters> {
  public StockSimulation (StockParameters p) { ... }
}

public class DockSimulation implements Simulation<DockParameters> {
  public DockSimulation (DockParameters d) { ... }
}

Then you use it like this:

Simulation s1 = new StockSimulation(new StockParameters());
Simulation s2 = new DockSimulation(new DockParameters());

You could then pass this off to an Executor or whatever else to run it, possibly in parallel. That is one of the advantages of this approach, it is very flexible.

This may avoid code duplication, and it definitely avoids polluting the interface which is I believe the real concern in your last paragraph.

Code Duplication

To avoid code duplication in the runSimulation() method, I would consider the approach of using composition to encapsulate each atomic step of a simulation in its own child object.

public interface SimulationComponent {
  void runStep(SimulationState state, ...);
}

Then, in your simulation class, you could have simulation components:

public class StockSimulation implements Simulation<StockParameters> {

  private final List<SimulationComponent> components;

  public StockSimulation (StockParameters p) {
    List<SimulationComponent> c = new LinkedList<>();
    c.add(new SimulationComponentImpl1());
    c.add(new SimulationComponentImpl2());
    c.add(new SimulationComponentImpl3());
    components = Collections.unmodifiableList(c);
  }

  public SimulationResult runSimulation() {
    SimulationState state = ...;
    for (SimulationComponent c : components) {
      c.runStep(state);
    }
    return state.getResult();
  }
}

Without detailed information about how the simulation works I cannot say for sure exactly how this code should work, but I believe this is the correct general approach.


答:
I am worried however, that this approach will lead to code duplication.

yes, it might.

What should I do?

I suggest using generics. Like so

```<code>public abstract class AbstractSimulation<T extends SimulationParameters> {
    public void runSimulation(T parameters) {
        // common functionality
    }
}
public class SimulationParameters {
   // common parameters
}
public class StockSimulationParameter extends SimulationParameters {
   // specific parameters
}
public class StockSimulation extends AbstractSimulation<StockSimulationParameter> {
    @Override
    public void runSimulation(StockSimulationParameter parameters) {
        super.runSimulation(parameters);
    }
}

// the same for XDockSimluation and XDocSimulationParameters
(... omitted for brevity ...)
</code>```

If you do this, StockSimulation.runSimulation() will only accept StockSimulationParameters instances, but not SimulationParameters:

```<code>StockSimulation stocksim = new StockSimulation();
// not OK
SimulationParamters simparamCommon = new SimulationParamters();
stocksim.runSimulation(simparamCommon);
// OK
StockSimulationParameter simparam = new StockSimulationParameter();
stocksim.runSimulation(simparam);
</code>```

Title: Software architecture for two similar classes which require different input parameters for the same method

Body:
I am writing Java code to simulate a supply chain.
The supply chain can be simulated in either
an intermediate stocking or a cross-docking configuration.
So, I wrote two simulator objects IstockSimulator and XdockSimulator.
Since the two objects share certain behaviors
(e.g. making shipments, demand arriving),
I wrote an abstract simulator object AbstractSimulator
which is a parent class of the two simulator objects.

The abstract simulator object has a method runSimulation()
which takes an input parameter of class SimulationParameters.
Up till now, the simulation parameters only contains fields
that are common to both simulator objects,
such as randomSeed, simulationStartPeriod and simulationEndPeriod.
However, I now want to include fields that are specific to the type of simulation that is being run,
i.e. an IstockSimulationParameters class for an intermediate stocking simulation,
and a XdockSimulationParameters class for a cross-docking simulation.

My current idea is take the method runSimulation()
out of the AbstractSimulator class,
but to put a runSimulation(IstockSimulationParameters) method
in the IstockSimulator class,
and a runSimulation(XdockSimulationParameters) method
in the IstockSimulator class.
I am worried however, that this approach will lead to code duplication.

What should I do?

Edited

Currently, the AbstractSimulator class defines the runSimulation method
which calls other abstract methods
that are only defined by the concrete child classes.

```<code>public abstract class AbstractSimulator {
    public void runSimulation(SimulationParameters params) {
        int startPeriod = params.startPeriod;
        int endPeriod = params.endPeriod;
        for (int t = startPeriod; t < endPeriod; ++t) {
            submitReports(t);
            makeShipments(t);
            demandArrives(t);
        }
    }
    protected abstract void submitReports(int t);
    protected abstract void makeShipments(int t);
}
</code>```

One of the differences between the IstockSimulator and the XdockSimulator
is that in an intermediate stocking configuration,
tier 3 facilities submit reports to tier 2 facilities,
while in a cross-docking configuration,
tier 3 facilities submit reports to tier 1 facilities.
Thus the IstockSimulator and the XdockSimulator
have their own implementations of the methods submitReports and makeShipments.

What worked for me

Thank you for your answers.
Inspired by your answers, and after sleeping it over,
I came up with my own answer based on refactoring.
See below.

Body:
I am worried however, that this approach will lead to code duplication.

yes, it might.

What should I do?

I suggest using generics. Like so

public abstract class AbstractSimulation<T extends SimulationParameters> {
    public void runSimulation(T parameters) {
        // common functionality
    }
}
public class SimulationParameters {
   // common parameters
}
public class StockSimulationParameter extends SimulationParameters {
   // specific parameters
}
public class StockSimulation extends AbstractSimulation<StockSimulationParameter> {
    @Override
    public void runSimulation(StockSimulationParameter parameters) {
        super.runSimulation(parameters);
    }
}

// the same for XDockSimluation and XDocSimulationParameters
(... omitted for brevity ...)

If you do this, StockSimulation.runSimulation() will only accept StockSimulationParameters instances, but not SimulationParameters:

StockSimulation stocksim = new StockSimulation();
// not OK
SimulationParamters simparamCommon = new SimulationParamters();
stocksim.runSimulation(simparamCommon);
// OK
StockSimulationParameter simparam = new StockSimulationParameter();
stocksim.runSimulation(simparam);


答:
If * only means "mandatory" then it does not make sense, as you do not need to change the value to get the form to submit.

Some users might assume that if they don't add something to a form, it won't be posted on form submission. A * might then be a way of drawing their eye to an important field that will be posted on form submission, even though no action is technically required for the form to submit. In that way a * is more of a "this field will affect submission " marker than a "this field is mandatory " marker.

Title: Does it make sense to make a field mandatory which has a default value?

Body:
Consider a drop down "Duration" which has 3 options

```<code>1. 30 days
2. 60 days
3. 90 days
</code>```

and by default 30 days will be the selected value. Does it make sense to make this dropdown mandatory? Do we really need to put a * (Mandatory mark) for this field?


问:
Describe business logic with diagrams
I am currently developing a web application for my thesis.I was asked by my professor to make diagrams to describe the business logic.
Since I don't have a prior experience, I am pretty confused with all the terminology.
I managed to clarify,I think, what business rules and business logic are, but I can't find out how you describe the business logic. Is it something particular or is it something more general? Do I need to learn UML? Does the fact that I use MVC affects the way I'll describe it?</p>

答:
Is it something particular or is it something more general?

Typically, business rules are of the form "if(condition) then action", while business logic tends to describe a larger set or a sequence of both business rules and other logic. So "business logic" is more general any code that implements logic specific to your problem domain, where "business rule" is a specific concept.

Examples (pseudo code):

```<code>// business rule
if(sales-revenue > 1000) then send("thank you")

//business logic
sales-revenue = sum(all items in order)
bonus-points = sales-revenue * .1
executeBusinessRules()
</code>```

Do I need to learn UML?

No, you don't have to learn UML. But it may help to visualize your solution, and in fact make it easier to describe because you have to think it through more thoroughly - if you can't draw it in UML, probably something is not quite right yet.

Business rules can be nicely described with state charts or activity diagrams, and business logic in general can be described in sequence diagrams or activity diagrams.

Does the fact that I use MVC affects the way I'll describe it?

It shouldn't - if it does, this may indicate poor separation of concerns. MVC is a way to organize your code, or more specifically to keep aspects of your implementation separate (aka 'separation of concerns').
The M(odel) in MVC is what should implement your business logic.

Title: Describe business logic with diagrams

Body:
Is it something particular or is it something more general?

Typically, business rules are of the form "if(condition) then action", while business logic tends to describe a larger set or a sequence of both business rules and other logic. So "business logic" is more general any code that implements logic specific to your problem domain, where "business rule" is a specific concept.

Examples (pseudo code):

// business rule
if(sales-revenue > 1000) then send("thank you")

//business logic
sales-revenue = sum(all items in order)
bonus-points = sales-revenue * .1
executeBusinessRules()

Do I need to learn UML?

No, you don't have to learn UML. But it may help to visualize your solution, and in fact make it easier to describe because you have to think it through more thoroughly - if you can't draw it in UML, probably something is not quite right yet.

Business rules can be nicely described with state charts or activity diagrams, and business logic in general can be described in sequence diagrams or activity diagrams.

Does the fact that I use MVC affects the way I'll describe it?

It shouldn't - if it does, this may indicate poor separation of concerns. MVC is a way to organize your code, or more specifically to keep aspects of your implementation separate (aka 'separation of concerns').
The M(odel) in MVC is what should implement your business logic.


问:
C++ strongly typed typedef
I've been trying to think of a way of declaring strongly typed typedefs, to catch a certain class of bugs in the compilation stage. It's often the case that I'll typedef an int into several types of ids, or a vector to position or velocity:

```<code>typedef int EntityID;
typedef int ModelID;
typedef Vector3 Position;
typedef Vector3 Velocity;
</code>```

This can make the intent of code more clear, but after a long night of coding one might make silly mistakes like comparing different kinds of ids, or adding a position to a velocity perhaps.

```<code>EntityID eID;
ModelID mID;

if ( eID == mID ) // <- Compiler sees nothing wrong
{ /*bug*/ }

Position p;
Velocity v;

Position newP = p + v; // bug, meant p + v*s but compiler sees nothing wrong
</code>```

Unfortunately, suggestions I've found for strongly typed typedefs include using boost, which at least for me isn't a possibility (I do have c++11 at least). So after a bit of thinking, I came upon this idea, and wanted to run it by someone.

First, you declare the base type as a template. The template parameter isn't used for anything in the definition, however:

```<code>template < typename T >
class IDType
{
    unsigned int m_id;

    public:
        IDType( unsigned int const& i_id ): m_id {i_id} {};
        friend bool operator==<T>( IDType<T> const& i_lhs, IDType<T> const& i_rhs );
};
</code>```

Friend functions actually need to be forward declared before the class definition, which  requires a forward declaration of the template class.

We then define all the members for the base type, just remembering that it's a template class.

Finally, when we want to use it, we typedef it as:

```<code>class EntityT;
typedef IDType<EntityT> EntityID;
class ModelT;
typedef IDType<ModelT> ModelID;
</code>```

The types are now entirely separate. Functions that take an EntityID will throw a compiler error if you try to feed them a ModelID instead, for example. Aside from having to declare the base types as templates, with the issues that entails, it's also fairly compact.

I was hoping anyone had comments or critiques about this idea?

One issue that came to mind while writing this, in the case of positions and velocities for example, would be that I can't convert between types as freely as before. Where before multiplying a vector by a scalar would give another vector, so I could do:

```<code>typedef float Time;
typedef Vector3 Position;
typedef Vector3 Velocity;

Time t = 1.0f;
Position p = { 0.0f };
Velocity v = { 1.0f, 0.0f, 0.0f };

Position newP = p + v*t;
</code>```

With my strongly typed typedef I'd have to tell the compiler that multypling a Velocity by a Time results in a Position.

```<code>class TimeT;
typedef Float<TimeT> Time;
class PositionT;
typedef Vector3<PositionT> Position;
class VelocityT;
typedef Vector3<VelocityT> Velocity;

Time t = 1.0f;
Position p = { 0.0f };
Velocity v = { 1.0f, 0.0f, 0.0f };

Position newP = p + v*t; // Compiler error
</code>```

To solve this, I think I'd have to specialize every conversion explicitly, which can be kind of a bother. On the other hand, this limitation can help prevent other kinds of errors (say, multiplying a Velocity by a Distance, perhaps, which wouldn't make sense in this domain). So I'm torn, and wondering if people have any opinions on my original issue, or my approach to solving it.

答:
These are phantom type parameters, that is, parameters of a parameterised type that are used not for their representation, but to separate different “spaces” of types with the same representation.

And speaking of spaces, that’s a useful application of phantom types:

```<code>template<typename Space>
struct Point { double x, y; };

struct WorldSpace;
struct ScreenSpace;

// Conversions between coordinate spaces are explicit.
Point<ScreenSpace> project(Point<WorldSpace> p, const Camera& c) { … }
</code>```

As you’ve seen, though, there are some difficulties with unit types. One thing you can do is decompose units into a vector of integer exponents on the fundamental components:

```<code>template<typename T, int Meters, int Seconds>
struct Unit {
  Unit(const T& value) : value(value) {}
  T value;
};

template<typename T, int MA, int MB, int SA, int SB>
Unit<T, MA - MB, SA - SB>
operator/(const Unit<T, MA, SA>& a, const Unit<T, MB, SB>& b) {
  return a.value / b.value;
}

Unit<double, 0, 0> one(1);
Unit<double, 1, 0> one_meter(1);
Unit<double, 0, 1> one_second(1);

// Unit<double, 1, -1>
auto one_meter_per_second = one_meter / one_second;
</code>```

Here we’re using phantom values to tag runtime values with compile-time information about the exponents on the units involved. This scales better than making separate structures for velocities, distances, and so on, and might be enough to cover your use case.

OwnerDisplayName: Kian

Title: C++ strongly typed typedef

Body:
These are phantom type parameters, that is, parameters of a parameterised type that are used not for their representation, but to separate different “spaces” of types with the same representation.

And speaking of spaces, that’s a useful application of phantom types:

template<typename Space>
struct Point { double x, y; };

struct WorldSpace;
struct ScreenSpace;

// Conversions between coordinate spaces are explicit.
Point<ScreenSpace> project(Point<WorldSpace> p, const Camera& c) { … }

As you’ve seen, though, there are some difficulties with unit types. One thing you can do is decompose units into a vector of integer exponents on the fundamental components:

template<typename T, int Meters, int Seconds>
struct Unit {
  Unit(const T& value) : value(value) {}
  T value;
};

template<typename T, int MA, int MB, int SA, int SB>
Unit<T, MA - MB, SA - SB>
operator/(const Unit<T, MA, SA>& a, const Unit<T, MB, SB>& b) {
  return a.value / b.value;
}

Unit<double, 0, 0> one(1);
Unit<double, 1, 0> one_meter(1);
Unit<double, 0, 1> one_second(1);

// Unit<double, 1, -1>
auto one_meter_per_second = one_meter / one_second;

Here we’re using phantom values to tag runtime values with compile-time information about the exponents on the units involved. This scales better than making separate structures for velocities, distances, and so on, and might be enough to cover your use case.


答:
There is a great book out there called "balancing agility and discipline".  It's not so much that the answer is in the book, it is that there is no one right way to do Agile.  It's just that the book teaches that each company, each project even, needs to find the best way to do things.  In this case, it seems like the HTML is not written such that you can successfully change the CSS and have valid two week sprints.  The choices seem to be to change the HTML or change the Agile method.

In all honesty, most of us who write HTML have never really tried to do what you are doing without changing the HTML, so we have no real experience on what is good HTML and what is bad HTML.  We can't "smell" something wrong.

The harder question, honestly, is how to change the Agile method to work.  It sort of sounds like you have some ideas on the subject, and are just wondering if that is a valid path.  I'd say that you should definitely ask for modifications in the Agile methods you are working under to better achieve your goals.

Oh, and you should definitely leave comments in your CSS.  The build process should remove them.  When the project is finished, you should review them and remove or build upon them for the next person who has to do the same thing, a few years down the road.

Title: How to be Agile when new work keeps affecting completed work?

Body:
The project I'm working on is to re-skin an existing website. The functionality will stay the same, it's just the styles that are changing. In other words, I'm not modifying the HTML, only the CSS files.

The site is pretty complex, with dozens of pages. Logged-in users can have a number of different roles, and depending on their role, the content of the page and what pages they are allowed to see varies.

We're using Git and Github.

I'm trying to write CSS that works as components, so when the same form elements, headings, etc. appear on multiple pages, they are consistent. Most of time this is working well.

Sadly, the format and class names in the HTML are at times messy and unpredictable. When I fix something on one page it can break another. The job is also harder as no one knows exactly all the variations that are possible due to user roles; as such I'm continuously finding new variations as I go along.

I'm making headway by putting a lot of comments in my CSS. If I need to remove a CSS rule, I'll comment it out so that I can still see it with Chrome dev tools, and I'll put a comment in the CSS saying why I removed it and for what page this was done.

This means that if on another page I'm about to add a rule to fix a different problem, there is a better chance that I'll see how it'll break the first page. This allows me to either find a different solution that will work for both pages, or I can make the override page specific.

This has been working quite well for me. If I had free reign and the only goal was to finish the project by the deadline, then this method would be fine. However, my manager is trying to mitigate risk by breaking the work into areas to be completed per sprint. This is counter to how I have been approaching things as something like my typography styles will affect all other pages on the site.

The other issue is that the different stakeholders want to sign off on each section as I go along. The problem is, once I've finished a section it may change if I change CSS that affects it along with the new section I'm working on. I've asked that the stakeholders have a quick unofficial sign off in stages (e.g. per sprint), and have the final official sign off at the end of the project, but this is being met with resistance. I understand why it would be higher risk to do this, but the only way to guarantee that a signed off section will not change is to make ALL future changes page specific.

In addition to this I'm being told that all work that I push to the Git repo should be ready to go live, and as such should not contain any code comments. This is risky for me as I won't know until I've finished the site if I will ever benefit from these comments or not.

Has anyone else been in a similar situation and managed to find a compromise that worked for my development approach and also the desires of management and stakeholders to have a more Agile approach? A more Agile workflow works great when you can break the work into components and know that once something is done it won't be affected by future work. However the nature of this project makes this hard to achieve.


问:
Why are there two different kinds of linking, i.e. static and dynamic?
I've been bitten for the n-th time now by a library mismatch between a build and deployment environment. The build environment had libruby.so.2.0 and the deployment environment had libruby.a. One ruby was built with RVM, the other was built with ruby-build. The reason I ran into a problem was because zookeeper was compiled in a build environment that had the shared library but the deployment environment only had the static library.

In all the years I've been writing application code I have never once wished that the binaries I was using where linked against shared objects. What is the reason the dichotomy persists to this day on modern operating systems?

答:
There are advantages to each, as is the case for pretty much everything in software development.

Say I am developing a Windows application, that involves some sort of cryptographic feature. Because those functions are complicated, and rolling your own is almost always a bad idea, I instead use the libraries provided by the Windows platform.

Pretend, after awhile, a nasty bug is revealed in the Windows libraries, that causes your pets to be murdered if you visit the wrong web page.

If you dynamically linked your application to the libraries, an update can be made to the platform, and your software can be fixed of its vulnerability without you doing anything. Windows update can solve your problems.

If you statically linked your application to the libraries, you would have to recompile an updated version of your software, and distribute it to your users, and feel the guilt of all the puppies murdered while you got around to doing so.

The same principle applies for other platforms and libraries.

Additionally, dynamic linking affords the ability to have stuff like plugins. You can also update shared libraries while an application is using them, and use the new libraries once the application is restarted.

Those benefits are why we have dynamic linking.


答:
Static

With a statically linked application, everything that you need to run the application is part of the application itself.  It depends on nothing else.

If there is a fatal error in a dynamically linked library, it doesn't 'care'.

If the dynamically linked version of a library it uses isn't there (someone accidentally removed /lib on a unix system?) it doesn't care.

It requires no additional installs of libraries to run on any binary compatible platform.  You download the app and you can run it.

There is an entire directory of statically linked applications on every unix system in /sbin that are guaranteed to always work even if significant parts of the system are otherwise broken or missing.  reboot? halt? ifconfig? mount? fsck? ping?  Those are likely all in /sbin so that even if the libraries are missing or corrupt (or not mounted because they're on a network filesystem...) you can still run those commands to get the system working (and mount that networked file system with the libraries you are looking for).

True story:  One sysadmin many years ago, back when an 80 megabyte hard disk was big was looking for some space.  Standard compiles included debugging/symbol information and that took a few kilobytes in each binary.  So, he found every executable on the system and ran strip on it.  Did you know that shared libraries are 'executables' on many systems?  Removing the symbol information from them prevents anything from dynamically linking to them... oops.  The only things working where those in /sbin.  Fortunately, there was enough there that he was able to mount the other system of the same type and copy the shared libraries back over to the messed up system...

Dynamic

You want to update a library?  No problem.  Just put the library in the proper spot and all is well.  Yea, that's a bit simplistic, but its the idea.

```
$ ldd /bin/date
  linux-vdso.so.1 =>  (0x00007fff6ffff000)
  librt.so.1 => /lib64/librt.so.1 (0x00007f54ba710000)
  libc.so.6 => /lib64/libc.so.6 (0x00007f54ba384000)
  libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f54ba167000)
  /lib64/ld-linux-x86-64.so.2 (0x00007f54ba919000)
```

Those are all libraries that are already loaded somewhere that you don't have to have in your application.  There can be some savings in disk space size because you don't need to put a full copy of libc or any other library as part of your application.

System patching becomes easier.  Instead of needing to push out a patch for everything in /bin because something changed (you need to do this for /sbin), you just push out a new shared library object and update the symbolic link chain in /lib.

Drop in replacements become possible.  Just provide the same API and symbols, drop in the new library and update the symbolic link chain and all should be good.

On a system that runs multiple processes (almost all of them these days... but it was a significant distinction back in old times) static libraries meant that each application running had a full copy of its libraries taking up memory resources.  Shared libraries means that they can all just point to the same spot in already loaded memory.

Statically linking an application can be considered a derivative work of the libraries.  This becomes an issue with GPL software.  There are differing opinions on if dynamically linking a GPL licensed library creates a derivative work.

Dynamic linking allows for plugins.  The application loads the plugins and dynamically calls the functions available to it.

Multiple languages can use the same calling conventions and call a dynamic library.  Look at Java for an example there - dynamic linking means that Clojure, Scala, Groovy, etc... with dynamic linking they can all use the same shared libraries.  Alternatively look at all the different languages that can invoke a .DLL on windows.

Related reading:

SO Static linking vs dynamic linking

Dynamic linking considered harmful

MSDN Advantages of Dynamic Linking

P.SE How does the GPL static vs. dynamic linking rule apply to interpreted languages? SO Can I dynamically call a LGPL/GPL software in my closed-source application?

Title: Why are there two different kinds of linking, i.e. static and dynamic?

Body:
I've been bitten for the n-th time now by a library mismatch between a build and deployment environment. The build environment had libruby.so.2.0 and the deployment environment had libruby.a. One ruby was built with RVM, the other was built with ruby-build. The reason I ran into a problem was because zookeeper was compiled in a build environment that had the shared library but the deployment environment only had the static library.

In all the years I've been writing application code I have never once wished that the binaries I was using where linked against shared objects. What is the reason the dichotomy persists to this day on modern operating systems?

Body:
Static

With a statically linked application, everything that you need to run the application is part of the application itself.  It depends on nothing else.

If there is a fatal error in a dynamically linked library, it doesn't 'care'.

If the dynamically linked version of a library it uses isn't there (someone accidentally removed /lib on a unix system?) it doesn't care.

It requires no additional installs of libraries to run on any binary compatible platform.  You download the app and you can run it.

There is an entire directory of statically linked applications on every unix system in /sbin that are guaranteed to always work even if significant parts of the system are otherwise broken or missing.  reboot? halt? ifconfig? mount? fsck? ping?  Those are likely all in /sbin so that even if the libraries are missing or corrupt (or not mounted because they're on a network filesystem...) you can still run those commands to get the system working (and mount that networked file system with the libraries you are looking for).

True story:  One sysadmin many years ago, back when an 80 megabyte hard disk was big was looking for some space.  Standard compiles included debugging/symbol information and that took a few kilobytes in each binary.  So, he found every executable on the system and ran strip on it.  Did you know that shared libraries are 'executables' on many systems?  Removing the symbol information from them prevents anything from dynamically linking to them... oops.  The only things working where those in /sbin.  Fortunately, there was enough there that he was able to mount the other system of the same type and copy the shared libraries back over to the messed up system...

Dynamic

You want to update a library?  No problem.  Just put the library in the proper spot and all is well.  Yea, that's a bit simplistic, but its the idea.

$ ldd /bin/date
  linux-vdso.so.1 =>  (0x00007fff6ffff000)
  librt.so.1 => /lib64/librt.so.1 (0x00007f54ba710000)
  libc.so.6 => /lib64/libc.so.6 (0x00007f54ba384000)
  libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f54ba167000)
  /lib64/ld-linux-x86-64.so.2 (0x00007f54ba919000)

Those are all libraries that are already loaded somewhere that you don't have to have in your application.  There can be some savings in disk space size because you don't need to put a full copy of libc or any other library as part of your application.

System patching becomes easier.  Instead of needing to push out a patch for everything in /bin because something changed (you need to do this for /sbin), you just push out a new shared library object and update the symbolic link chain in /lib.

Drop in replacements become possible.  Just provide the same API and symbols, drop in the new library and update the symbolic link chain and all should be good.

On a system that runs multiple processes (almost all of them these days... but it was a significant distinction back in old times) static libraries meant that each application running had a full copy of its libraries taking up memory resources.  Shared libraries means that they can all just point to the same spot in already loaded memory.

Statically linking an application can be considered a derivative work of the libraries.  This becomes an issue with GPL software.  There are differing opinions on if dynamically linking a GPL licensed library creates a derivative work.

Dynamic linking allows for plugins.  The application loads the plugins and dynamically calls the functions available to it.

Multiple languages can use the same calling conventions and call a dynamic library.  Look at Java for an example there - dynamic linking means that Clojure, Scala, Groovy, etc... with dynamic linking they can all use the same shared libraries.  Alternatively look at all the different languages that can invoke a .DLL on windows.

Related reading:

SO Static linking vs dynamic linking

Dynamic linking considered harmful

MSDN Advantages of Dynamic Linking

P.SE How does the GPL static vs. dynamic linking rule apply to interpreted languages? SO Can I dynamically call a LGPL/GPL software in my closed-source application?


答: Generally, probably not.  But if you absolutely want the user to make conscious selection, you can add something like <select one> as the first option in the list and treat it as mandatory in the form's validation.


问:
How to present a stable data model in a public API that allows internal data structures to be changed without breaking the public view of the data?
I am in the process of developing an application that allows users to write C# scripts. These scripts allow users to call selected methods and to access and manipulate data in a document. This works well, however, in the development version, scripts access the document's (internal) data structures directly. This means that if we were to change the internal data model/structure, there is a good chance that someone's script will no longer compile. We obviously want to prevent this breaking change from happening, but still want to allow the user to write sensible C# code (whilst not restricting how we develop our internal data model as a result). We therefore need to decouple our scripting API and its data structures from our internal methods and data structures.

We've a few ideas as to how we might allow the user to access a what is effectively a stable public version of the document's internal data*, but I wanted to throw the question out there to someone who might have some real experience of this problem. NB our internal document's data structure is quite complex and it could be quite difficult to wrap. We know we want to expose as little as possible in our public API, especially as once it's out there, it's out there for good.

Can anyone help?

How do scripting languages / APIs decouple their public API and data structures from their internal data structures?

Is there no real alternative to having to write a complex interaction layer?

If we need to do this, what's a good approach or pattern for wrapping complex data structures that include nested objects, including collections? I've looked at the API facade pattern, which looks like it's trying to address these kinds of issues, but are there alternatives?

*One idea is to build a data facade that is kept stable across versions of our application. The facade exposes a set of facade data objects that are used in the script code. These maintain backwards compatibility and wrap access to our internal document's data model.

答:
Without knowing your structure, I'm not certain this is exactly the right idea, but I'm going to explain what I am thinking and, with a little luck, it will lead you to the right idea.

I'm thinking you want a solution that is:

Easy to do now

Easy to transform if you redo the structure

Somewhat familiar to your users

Has tools available

So I was thinking of what tools we use to interchange and transform data, and the one that occurred to me was XML.

Most languages have some sort of serialization to XML

XML has transformation tools

There are libraries already available to manipulate XML

So my plan would be to take your internal data and serialize it to XML.  If you want to, you can use that for now as your public interface, or you can transform it to something simpler to make it easier for the next iteration of the internal storage (if you can think of something easier).  You let the user iterate over it using common XML techniques, and when they are finished, you can take the resulting structure and transform and de-serialize it back to your structure.  If you change structures, you just have to write a different transformation.

Of course, you don't have to use XML.  There are possibly other structures that would be better for what you are doing.  With any luck, however, this gets you started down the right path.


问:
NLP - Queries using semantic wildcards in full text searching, maybe with Lucene?
Let's say I have a big corpus (for example in english or an arbitrary language), and I want to perform some semantic search on it. For example I have the query:

"Be careful: [art] armada of [sg] is coming to [do sg]!"

And the corpus contains the following sentence:

"Be careful: an armada of alien ships is coming to destroy our planet!"

It can be seen that my query string could contain "semantic placeholders", such as:

[art] - some placeholder for articles (for example a / an in English)
[sg], [do sg] - some placeholders for NPs and VPs (subjects and predicates)
I would like to develop a library which would be capable to handle these queries efficiently. I suspect that some kind of POS-tagging would be necessary for parsing the text, but because I don't want to fully reimplement an already existing full-text search engine to make it work, I'm considering that how could I integrate this behaviour into a search engine like Lucene?

I know there are SpanQueries which could behave similarly in some cases, but as I can see, Lucene doesn't do any semantic stuff with stored texts.

It is possible to implement a behavior like this? Or do I have to write an own search engine?

答:
As you use the terms NP and VP, I think you are talking about syntactic, not semantic. There are differences between the two.
You can check out dependency grammar to see how it is different from CFG syntactic grammar.

I think if you use wildcards for semantic search, people would consider that a 'hack'.

This will be what I would do:

To properly do semantic search, you first need of course a semantic analyzer (for Lucence, if you see in term of Lucene). A semantic analyzer will of course requires a semantic parser. And this is the part where you have problem because semantic parsers right now are not good enough.

Assume you could have a good semantic parser, the next part would be use the semantic graph and store this graph in the search engine. There can be many ways to do it. The most obvious one would be to simplify the graph and to use each edge as a predicate, store the predicates and do search on each predicate in an RDF manner. More on RDF: http://www.w3.org/TR/2014/NOTE-rdf11-primer-20140225/

In your example (remove the article one, because it's syntactic, not semantic), search query would be:
[X of Y] where X = amarda
[X coming to do Z]


问:
How important is XML for a developer?
Is it must that every developer should know XML? How important is XML for a developer? Any suggestion...</p>

答:
XML is like a building block for a developer. </p>

<p>(1) In android application XML is the basic requirement to display graphical user interface.
(2) In mobile applications like for iPhone and Blkackberry developer can use web service which is in xml format.
(3) XML is easy to understand and very easy to learn.
(4) XML gives structural information to display data.</p>

Title: How important is XML for a developer?

Body:
XML is like a building block for a developer.

(1) In android application XML is the basic requirement to display graphical user interface.
(2) In mobile applications like for iPhone and Blkackberry developer can use web service which is in xml format.
(3) XML is easy to understand and very easy to learn.
(4) XML gives structural information to display data.

OwnerDisplayName: Tech Guru


问:
How to quickly search through a very large list of strings / records on a database
I have the following problem: I have a database containing more than 2 million records.
Each record has a string field X and I want to display a list of records for which field X contains a certain string. Each record is about 500 bytes in size.

To make it more concrete: in the GUI of my application I have a text field where I can enter a string. Above the text field I have a table displaying the (first N, e.g. 100) records that match the string in the text field. When I type or delete one character in the text field, the table content must be updated on the fly.

I wonder if there is an efficient way of doing this using appropriate index structures and / or caching. As explained above, I only want to display the first N items that match the query. Therefore, for N small enough, it should not be a big issue loading the matching items from the database. Besides, caching items in main memory can make retrieval faster.

I think the main problem is how to find the matching items quickly, given the pattern string. Can I rely on some DBMS facilities, or do I have to build some in-memory index myself? Any ideas?

EDIT

I have run a first experiment. I have split the records into different text files (at most 200 records per file) and put the files in different directories (I used the content of one data field to determine the directory tree). I end up with about 50000 files in about 40000 directories. I have then run Lucene to index the files. Searching for a string with the Lucene demo program is pretty fast. Splitting and indexing took a few minutes: this is totally acceptable for me because it is a static data set that I want to query.

The next step is to integrate Lucene in the main program and use the hits returned by Lucene to load the relevant records into main memory.

答:
Just in case you missed it. If you use Lucene for your database instead of in-DB supported text search, you will have to be extremely careful when making modification to your DB. How do you make sure that you can have atomicity when you have to make changes in both the DB and the external resources (Lucene)?
Yes it can be done, but there will be lot of work.

In short, you are losing the DB transactional support if you put Lucene in your data schema.


问:
How to design database having multiple interrelated entities
I am designing a new system which is more of a help system for core applications in banks or healthcare sector. Given the nature of the system this is not a  heavy transaction oriented system but more of read intensive.

Now within this application I have multiple entities which are related to each other.
For e.g. Assume the following entities in the system

User

Training

Regulations

Now each of these entities have M:N Relationship with each other.

Assuming the usage of a standard RDBMS, the design may involve many relationship tables each containing the relationships one other entity ("User_Training", "User_Regulations", "Training_Regulations"). This design is limiting since I have more than 3 entities in the system and maintaining the relationship graph is difficult this way.

The most frequently used operation is "given an entity get me all the related entities" . I need to design the database where this operation is relatively inexpensive.

What are the different recommendations for modelling this kind of database.

答:
For such scenarios, it helps a lot if you have a strict convention for using single attribute IDs as primary keys, all of the same type all over your database model.

With this preparation, you could model an universal "Relation" table with attributes "LinkedFromTable", "LinkedFromID" and "LinkedToTable" and "LinkedToID". The "LinkedFromTable " and "LinkedToTable" attributes must hold unique identifiers for the tables you refer to (maybe just the table names), and the LinkedFromID and LinkedToID take the primary key values of the referred data rows.

The operation "get me all the related entities" will be inexpensive due to proper indexing of your ID columns.

But beware: the drawback is that you loose referential integrity for these "manually modeled relations" completely - if you delete a data row, you have to check and update the "Relation" table manually. For a "write-once-read-many" system this may be fine, you have to decide for yourself.


答:
You can do the following:

Having a single entity table
- Entity{id, type, ref_id_to_specific_entity_table}

Having a single relation table
- Relation{id1, id2}

That way you can get all related entities to a given entity with a single query.
Now if you also want to know the relation specifically without having to fetch the second entity, you can add an additional column as can be done with Relation{id1, relation, id2}.

This means you have to worry about consistency if you make changes, but as you mentioned, this is a read intensive, supporting system. Might not be a problem.

Title: How to design database having multiple interrelated entities

Body:
I am designing a new system which is more of a help system for core applications in banks or healthcare sector. Given the nature of the system this is not a  heavy transaction oriented system but more of read intensive.

Now within this application I have multiple entities which are related to each other.
For e.g. Assume the following entities in the system

User

Training

Regulations

Now each of these entities have M:N Relationship with each other.

Assuming the usage of a standard RDBMS, the design may involve many relationship tables each containing the relationships one other entity ("User_Training", "User_Regulations", "Training_Regulations"). This design is limiting since I have more than 3 entities in the system and maintaining the relationship graph is difficult this way.

The most frequently used operation is "given an entity get me all the related entities" . I need to design the database where this operation is relatively inexpensive.

What are the different recommendations for modelling this kind of database.


问:
is it valid that a state machine can have more than one possible state for some transition?
I have a requirement for a workflow which I am trying to model as a state machine, I see that there is more than one outcome of a given transition(or activity).

Is it valid for a state machine to have more than one possible states, but only one state will be true at a given time?

Note: This is my first attempt to model a state machine.

Eg. might be:

s1->t1->s2

s1->t1->s3

s1->t1->s4

where s1, s2, s3, s4 are states and t1 is transition/activity.

A fictitious real world example might be:

For a human, there can be two states: hungry, not hungry
A basket can have only one item from: apple, orange.

So, to model it we will have:

hungry->pick from basket->apple found

hungry->pick from basket->orange found

apple found->eat->not hungry

orange found->take juice out of it and then drink-> not hungry

答:
Yes, you can have that.

In automata theory, people call it non-deterministic state machine.

From the Wikipedia article:

In automata theory, a nondeterministic finite automaton (NFA), or nondeterministic finite state machine, is a finite state machine that:

  (1) does not require input symbols for state transitions and

  (2) is capable of transitioning to zero or two or more states for a given start state and input symbol.

  This distinguishes it from a deterministic finite automaton (DFA), in which all transitions are uniquely determined and in which an input symbol is required for all state transitions. Although NFA and DFA have distinct definitions, all NFAs can be translated to equivalent DFAs using the subset construction algorithm


答:
What you are looking for is not a state machine, but a petri net. It is actually more common for workflows to be modeled using petri nets, than it is using a state machine.

And one thing I want to point out: In correct workflow, one activity can only produce one type of output. In your case, you are probably having different activities producing different outputs. Or at least something that starts as single activity, but soon branches out into different activities. It really doesn't make much sense for same activity to produce different results at different executions.

Title: is it valid that a state machine can have more than one possible state for some transition?

Body:
I have a requirement for a workflow which I am trying to model as a state machine, I see that there is more than one outcome of a given transition(or activity).

Is it valid for a state machine to have more than one possible states, but only one state will be true at a given time?

Note: This is my first attempt to model a state machine.

Eg. might be:

s1->t1->s2

s1->t1->s3

s1->t1->s4

where s1, s2, s3, s4 are states and t1 is transition/activity.

A fictitious real world example might be:

For a human, there can be two states: hungry, not hungry
A basket can have only one item from: apple, orange.

So, to model it we will have:

hungry->pick from basket->apple found

hungry->pick from basket->orange found

apple found->eat->not hungry

orange found->take juice out of it and then drink-> not hungry


问:
Software development based on a reference implementation
Lets say I have library "A2" as a dependency in a project. Library "A2" is derived from library "A1"(A2 is a fork of A1 with some modifications to the original source code) where someone has done few changes to the library "A1" 's source code.

Lets say there is a new version of "A1" I want to use the new version but no modification to its sourcecode at all.

I am planning to identify what are the changes done to the original library when deriving library "A2" out of it and decorate the latest version of the library with those changes. Is it a good approach to solve this? if not can someone suggest the best approach to solve this kind of problems?

答:
Is it a good approach to solve this?

Well, it is most probably not a good way, but your only reasonable choice to solve this in the given situation. But expect this happen again when version V3, V4, V5, ... of lib A1 will be released - as long as you don't take any additional measures, you will always have the effort of merging the A2-changes into the code of A1. If A2 differs only very slightly from A1, and the changes are well documented, that may be fine. Proper use of a version control system or at least a diff-merge tool for generating a patch-set for A1->A2 can also be helpful (at least, when A1 does not change from version to version so much that your patch-set cannot be applied any more).

The better alternative would be to contact the author of A1 beforehand and ask him kindly if he can change A1 in a way that you won't need to the fork in the future any more. He might consider integrating some of the additional features from A2, or (if that is not reasonable) to change the interface of A1 in a way so it will allow the adding of extensions without the need for changing A1. The goal should be to build A2 as a separate library which just links A1, unmodified. Maybe he can provide a "hook" or "plugin" mechanism, or maybe just make some internal methods public, this depends completely on the design of A1 and your requirements for A2.


答:
To me, the answer is very simple: to save resources like space.  If all N applications on a system need library X, and all of them statically link this library into their executables, then there is (N - 1) (size of X) bytes you are wasting.

The reason why statically linking has survived at all is precisely because there is no system that can guarantee that all applications find installed the libraries they need, in the version that they need them, at the same time (see dependency hell).

Many solutions have been tried: keeping versioned libraries, smart package managers, even virtual machines are a way of putting a layer of indirection between your application and the system "as it is now".  Each of these has led to its own hell: DLL hell, RPM hell and JAR hell.

The only bullet-proof way of deploying an executable to another machine is that it contains everything it needs to run. That is, by wasting resources.


问:
Software monetization that is not evil
I have a free open-source project with around 800K downloads to date.
I've been contacted by some monetization companies from time to time and turned them down, since I didn't want toolbar malware associated with my software.
I was wondering however, is there a non-evil way to monetize software ?

Here are the options as I know them:

Add a donation button.

I don't feel comfortable with that as I really don't need "donations" - I'm paid quite well.

Donating users may feel entitled to support etc.  (see the second to last bullet)

Add ads inside your application.

 In the web that may be acceptable, but in a desktop program it looks incredibly lame.

Charge a small amount for each download.

This model works well in the mobile world, but I suspect no one will go for it on the desktop.

It doesn't mix well with open source, though I suppose I could charge only for the binaries (most users won't go to the hassle of compiling the sources).

People may expect support etc. after having explicitly paid (see next bullet).

Make money off a service / community / support associated with the program.

This is one route I definitely don't want to take, I don't want any sort of hassle beyond coding. I assure you, the program is top notch (albeit simple) and I'm not aware of any bugs as of yet (there are support forums and blog comments where users may report them). It is also very simple, documented, and discoverable so I do think I have a case for supplying it "as is".

Add affiliate suggestions to your installer.

If you use a monetization company, you lose control over what they propose. Unless you can establish some sort of strong trust with the company to supply quality suggestions (I sincerely doubt it), I can't have that.

Choosing your own affiliate (e.g. directly suggesting Google Toolbar) is possibly the only viable solution to my mind. Problem is, where do I find a solid affiliate that could actually give value to the user rather than infect his computer with crapware? I thought maybe Babylon (not the toolbar of course, I hate toolbars)?

答:
As you don't seem to like any of the options you've listed, there are a couple of other options:

You could offer to customise the software for users for a fee.

For example, they might want a change which you don't want to have in your main branch, but possibly could do for them for a fee. As you don't want to do paid support, you could give them the source for this, although you probably would not make it publically available if it didn't fit in with your main goals for the project.

You could also allow people to pay to prioritise a change.

You might have your own plan for doing work, publish a roadmap, and then allow people to contact you with a payment to prioritise things which you aren't currently going to do in the near future.

Title: Software monetization that is not evil


答:
The two are different, but consider this, your application might require a value to be entered. However, can you guaranteee that all other applications/dba work that might connect and update to the same database will do the same. if not how would your application handle the exception.

In such cases make it mandatory at the database level to ensure consistancy and save you the headache of working out why some items cause an issue when other don't and you've only got the application front end to look at. Because another process hasn't applied the same criteria.


问:
exception for string literal conventions
If I'm used to use ' for string literals in PHP, would it be better if I'll stick to it in any situation or can there be exceptions when it would increase readability?

example:

$foo = "bar'baz";  // this may be easier to read
 $foo = 'bar\'baz'; // but this would stick to the convention

答:
There is a long held (and mostly untrue) PHP superstition that double-quoted (DQ) strings are "slower" than single-quoted (SQ) strings, due to the fact that DQ strings can do variable interpolation and SQ strings cannot.

Many coding convention guides, such as the Media Wiki coding convention guide (http://www.mediawiki.org/wiki/Manual:Coding_conventions/PHP) say things such as

For simple string literals, single quotes are slightly faster for PHP to parse than double quotes.

This has been generally disproven, with a small number of exceptions. See http://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html for a more in-depth explanation.

The only exception to this rule is if your DQ string contains a $. If it does, the string will be parsed twice, and interpolation performed. So for short strings such as the ones in your example, there is no difference in speed, and in my opinion the gain in readability is an advantage.

https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php (linked above by metacubed) contains much more information on the difference between SQ and DQ strings.