问:
PHP passing parameters to a function
I want to pass a parameter to a function as below for clarity. It doesn't give any error. But is this a bad practice. Do I have to avoid this.</p>

```<code>test('','','',$d='text','');

function test($a, $b, $c, $d, $e){

}
</code>```

答:
Is there any reason to assign the $str variable inline like that? Does it improve clarity at all?

I believe it's just evaluating $str = 'test' and passing the result $str to the function call.

$str remains assigned in the current scope so you could continue to use $str after the test() call if you wanted to.

It's the same as

```<code>$str = 'test';
test($str);
</code>```

It's a bit weird looking and may be misleading when reading the code later so I would avoid doing that.

Title: PHP passing parameters to a function

Body:
Is there any reason to assign the $str variable inline like that? Does it improve clarity at all?

I believe it's just evaluating $str = 'test' and passing the result $str to the function call.

$str remains assigned in the current scope so you could continue to use $str after the test() call if you wanted to.

It's the same as

$str = 'test';
test($str);

It's a bit weird looking and may be misleading when reading the code later so I would avoid doing that.


问:
Exception handling in a program that needs to run 24/7
I have read that we should only catch exceptions that can be handled, which makes catching the base exception class (C# in this case) a bad idea (on top of other reasons). I am currently part of a project in which I so far have yet to see anything but the base exception being caught. I mentioned that it is considered bad practice to do so, but the response was "This service needs to run 24/7, so that is the way it is.".

Since I did not have a good response for how to properly handle exceptions in a program that needs to run 24/7, I am now here. I have not managed to find any information / suggestions on how to deal with exception handling in "critical" programs / services that needs to run around the clock (and in this case I believe it may be ok if the service is down for a minute or two, so not even critical). I understand it depends on the exact nature of the program. The requirements for a program that can cause life threatening issues are quite different compared to a log scanner for an online game.

Two examples:

1: A type-ahead service for customers of the Brittish railways, used when they searching online for railway stations.

2: A program that automatically controls the railway switches for the above railways based on realtime information provided from various sensors in the tracks, trains etc.

The first program would probably not cause a major issue if it went down for a minute or two, wheras the latter could cause human casualties. Suggestions on how to deal with each? Pointer to where I can find more information and thoughts on this issue?

答:
Certain language features like

Garbage Collection

Exception Systems

Lazy Evaluation

are not generally useful in a real-time system. One should probably choose a language without these features, and try to prove certain properties like maximum memory usage, or maximum response time.

When a program needs to run continuously, but short and non-global failures are acceptable, then we could use an Erlang-like strategy. Erlang is a concurrent, functional programming language. Usually, a program written in Erlang will consist of multiple worker processes which can communicate with each other (actor model). If one worker thread encounters an exception, it is re-started. While this does imply a short downtime, the other actors can carry on as usual.

To summarize this: In a robust program, various parts are isolated from each other and can be restarted or scaled independently.

So basically we need a piece of code equivalent to this:

```<code>while (true) {
  try {
    DoWork();
  }
  catch (Exception e) {
    log(e);
  }
}
</code>```

plus a way to terminate the loop. Such a loop would then drive each worker thread.

A problem with ignoring errors via a catch-all is that invariants of your program might have been violated by the error cause, and that subsequent operations could be useless. A good solution to this is to share no data between independent workers. Restarting a worker will rebuild all necessary invariants. This means that they must communicate differently, e.g. through message sends. An actor's state may not be part of other actors' invariants.

Another problem with catching too many exceptions is that not all exceptions are fixable by restarting, even when taking such precautions. Otherwise-hard problems like running out of memory can be handled by restarting. But a restart won't help you to regain internet connectivity when a physical cable was pulled out.

ContentLicense: CC BY-SA 3.0

Body:
Certain language features like

Garbage Collection

Exception Systems

Lazy Evaluation

are not generally useful in a real-time system. One should probably choose a language without these features, and try to prove certain properties like maximum memory usage, or maximum response time.

When a program needs to run continuously, but short and non-global failures are acceptable, then we could use an Erlang-like strategy. Erlang is a concurrent, functional programming language. Usually, a program written in Erlang will consist of multiple worker processes which can communicate with each other (actor model). If one worker thread encounters an exception, it is re-started. While this does imply a short downtime, the other actors can carry on as usual.

To summarize this: In a robust program, various parts are isolated from each other and can be restarted or scaled independently.

So basically we need a piece of code equivalent to this:

while (true) {
  try {
    DoWork();
  }
  catch (Exception e) {
    log(e);
  }
}

plus a way to terminate the loop. Such a loop would then drive each worker thread.

A problem with ignoring errors via a catch-all is that invariants of your program might have been violated by the error cause, and that subsequent operations could be useless. A good solution to this is to share no data between independent workers. Restarting a worker will rebuild all necessary invariants. This means that they must communicate differently, e.g. through message sends. An actor's state may not be part of other actors' invariants.

Another problem with catching too many exceptions is that not all exceptions are fixable by restarting, even when taking such precautions. Otherwise-hard problems like running out of memory can be handled by restarting. But a restart won't help you to regain internet connectivity when a physical cable was pulled out.


答:
Declaimer: these are only thoughts, I haven't the experience.

I would guess that a program, satisfying the requirements of the second example should be extremely modular. Consequently, modules will be capable of being restarted, without destabilizing the system.

For example, an object, failing an assert for internal state, should be able to be destroyed and re-created, notifying in the process all it's consumers and suppliers. More concretely, if the program is controlling the switches of the railway and fails an assert in the decision loop, it can still run an emergency module, which stops all involved trains, and waits for the main decision module to re-initialize.

More realistically, one would introduce redundancy - duplication of the hardware and software. One instance is wired to the controlled system, and the other is free-running. If an error is detected, the systems are switched.

An example are two processes on the same machine, which monitor one another and if one is killed, the other re-spawns it and disassociates it's parent PID from itself.

Title: Exception handling in a program that needs to run 24/7

Body:
I have read that we should only catch exceptions that can be handled, which makes catching the base exception class (C# in this case) a bad idea (on top of other reasons). I am currently part of a project in which I so far have yet to see anything but the base exception being caught. I mentioned that it is considered bad practice to do so, but the response was "This service needs to run 24/7, so that is the way it is.".

Since I did not have a good response for how to properly handle exceptions in a program that needs to run 24/7, I am now here. I have not managed to find any information / suggestions on how to deal with exception handling in "critical" programs / services that needs to run around the clock (and in this case I believe it may be ok if the service is down for a minute or two, so not even critical). I understand it depends on the exact nature of the program. The requirements for a program that can cause life threatening issues are quite different compared to a log scanner for an online game.

Two examples:

1: A type-ahead service for customers of the Brittish railways, used when they searching online for railway stations.

2: A program that automatically controls the railway switches for the above railways based on realtime information provided from various sensors in the tracks, trains etc.

The first program would probably not cause a major issue if it went down for a minute or two, wheras the latter could cause human casualties. Suggestions on how to deal with each? Pointer to where I can find more information and thoughts on this issue?


问:
What is a good approach for permissions of this application's users?
I have an app that have multiple users. In my app an user can
- create contacts (people)
- edit contacts
- view contacts
- create an entry to agenda
- view entry from agenda

Also I need that User A is allowed to view User's B contacts but is not allowed to edit that contact.

User B can view and edit User's A entries in Agenda.  The app will have about
10-15 permission for each module (Agenda, Contacts, Documents, EmailMarketing) and the number of modules can reach to about 20

Let's say "User A" is a sales person, and "User B" is the sales manager.

For sure, each Business Object (contact, agenda entry,etc) will have a owner id.

What is the best approach/design patter/good practice to use to handle this situation?

答:
Use a database table that encodes the user permissions for various operations.

Write an access manager that sits in front of the DB.

For each potentially restricted operation, first check as a precondition that the access is valid. This is too complex for most type systems so it will have to be done as code. If the access in invalid, throw an exception or abort otherwise.

Example:

abstract class BusinessObject {
  User owner;
  AccessManager access;
  ...
}

class Contact extends BusinessObject {
  void edit(User byUser) {
    access.validate(this, byUser, Operation.EDIT);
    ... // normal code
  }
}

class AccessManager {
  ...
  boolean check(BusinessObject subject, User user, Operation op) {
    // pseudocode
    results = db.execute("SELECT 1 FROM permissions WHERE subject=? AND user=? and operation=?", subject.id(), user.id(), op.id());
    return results.length > 0;
  }

  void validate(BusinessObject subject, User user, Operation op) {
    if (check(subject, user, op))
      return;
    throw AccessViolation(user + " does not have permission to " + op + " on " + subject);
  }
}

class Context {
  void execute() {
    try {
      someContact.edit(someUser);
    }
    catch (AccessViolation e) {
      logger.log(e);
      displayPrettyError("Sorry, you don't have permission to edit that contact. " +
                         "You can ask " + someContact.owner().name() + " for permission.");
    }
  }
}
```

ContentLicense: CC BY-SA 4.0


问:
Good practice using signals and event driven system
I am using signals (specifically Boost signals2) to create an event driven protocol API and model.

Most elements have their own signals, and there are usually multiple of each element.

Consider a basic entity, a user; amongst others, the user may leave the system, so I need to have a leave signal.

The question is, should the user object itself be passed to the signal handler? I.e.:

```<code>class user {
    signals<void(user&)> on_leave;
    //...
};
</code>```

If there was std::bind and lambda then this decision would be easier to make, but with those passing the user back seems rather redundant, i.e.:

```<code>user.connect_on_leave(
    [](user& u) {
        //well I could already refer to user if I wanted to
    }
);
</code>```

And same with binding, I could do something like this

```<code>user.connect_on_leave(std::bind(my_hander, std::ref(usr));
</code>```

Also, generally speaking, is it better for each signal to just pass to the user whatever it's concerned about, or have some sort of message type which all signals operate with?

And my final question: at what point should I stop normalising data? If several signals share the same "payload", is it better to have separate signals like,

```<code>on_change_name(str)
on_msg_sent(str)
on_leave(str)
</code>```

or

```<code>on_action(action, str)
</code>```

答:
When sending messages/events across a system, you should use specialized data messages for the payload.

If not, if for example your user class changes, everything that listens to messages that have a user as payload, could be affected by that change as well.

As to your question about normalizing: it's not because the signals share the same payload now, that they always will in the future. Reusing messages (or message parts) introduces a form of coupling which could hinder you later on when events need to evolve separately from one another.


答:
To answer your question, one has to understand what exceptions are, and how they work.

Exceptions are usually thrown when such errors occurs, where user's assistance is required. In such cases, it doesn't matter how long it takes to unwind the stack and handle the exception.

Without catch handlers, the program stops execution. Depending on your setup and requirements, it may be acceptable.

In your specific cases :

if the query can not be executed (for example, wrong city name), then inform the user of the error, and ask to fix it.

if you are not getting information from a critical sensor, there isn't much sense in continuing without asking for the operator to fix the issue.

That means that in both cases it may make sense to use exceptions, with more care in a RT program to indicate only serious problems where it is not possible to continue the execution.


问:
Should I convert the whole project to UTF-8?
I am working on a highly customized shop software, based on a open-source one, written in PHP and usual web techniques (CSS, HTML, JS).

I did a lot of customization in the past months/years and developed specific, individual features which are necessary to be successful at our branch.

The shop and the project files are encoded in ISO-8859-1 (company is located in Germany).

Now we want to spread out and use the shop system in different countries (e.g. Sweden, Poland, Great Britain) and customize it to the domestic needs.

But I am afraid that I could encounter some encoding problems afterwards, so my question is:

Is it wise to change the encoding of the whole project and the environment to UTF-8 before I prepare the shop for "multi-shop" usage or should I leave the source at it is and handle (possible) encoding problems for each country as they approach afterwards?

答:
A few things to take into account:

On PHP side:

PHP 5.4 defaulted settings for functions such as
htmlentities/htmlspecialchars to UTF8 in version 5.4.

The default charset will be enforced in php.ini to UTF8 in PHP 5.6
next quarter.

The PSR recommandations says that UTF8 is the mandatory encoding for files in PHP

All frameworks and modern libraries are UTF8

On the front end side:

browser makers and W3C/WHATWG advise using UTF8 for front end files
(css, js, html)

On Operating systems side:

all modern OSes in use use UTF8 as defaut encoding, I think the last
OS I used that isn't set up by default to UTF8 is Windows XP (it does
support UTF8, it's just not necessarily the default)

you are most likely using a LAMP stack, Linux distros are UTF8 by
default

So basically, you are swimming in an UTF8 ecosystem and all the modern frameworks, libraries and other external PHP code default to UTF8. PHP itself progressively enforces UTF8 as the default setting, which means that if you keep your code in Latin1, you will likely meet bugs in the long run.

Switching to UTF8 is not really hard, unless you have to deal with data sources for which you can't control the encoding, my advice is to switch, it will solve a lot of headaches for you in the long run :)


问:
help me understand Rails and attributes as class methods
This is from the Hartl Rails tutorial. We are automatically logging in a user in the process of creating that user with a callback to #create_remember_token. It works great but there are some things, I am not clear on. Please bear with me as I'm thoroughly confused to the point that I don't even know how to ask my question.

I have a user model:

```<code>class User<ActiveRecord::Base
...
...

before_create :create_remember_token
def User.new_remember_token
  SecureRandom.urlsafe_base64
end

def User.encrypt(token)
  Digest::SHA1.hexdigest(token.to_s)
end

private

  def create_remember_token
    self.remember_token = User.encrypt(User.new_remember_token)
  end
</code>```

...

I am confused about the ::new_remember_token and the encrypt being methods attached to User. It looks as though they are attributes of User like name, email, password etc, because they are being accessed with dot notation. But they are defined like methods and seem to return a computed value. I don't understand, why an attribute of the User model is referred to with self for assigning self.remember_token and User.encrypt for accessing the class method.

My question

What's the difference between the above and the following where User, is replaced with self. ?

```<code>class User<ActiveRecord::Base
...
...

before_create :create_remember_token
def new_remember_token
  SecureRandom.urlsafe_base64
end

def encrypt(token)
  Digest::SHA1.hexdigest(token.to_s)
end

private

  def create_remember_token
    self.remember_token = self.encrypt(self.new_remember_token)
  end
</code>```

...

I'm a novice in the ruby language, but pretty good with javascript, so if there's a js analog it might help me to put it in those terms.

答:
I don't understand why an attribute of the User model is referred to with self for assigning self.remember_token and User.encrypt for accessing the class method.
  What's the difference between the above and the following where User. is replaced with self.

Functionally there is no difference between User, and self in the context of class User, but the differs to each other in the context of User class instance. So for the context User class you are able to call the ::new_remember_token methods as both of User class, and self, and they return the same (for the context) results.

```<code>self.new_remember_token

User.new_remember_token
</code>```

However, as you correctly denote, that attribute of the User model is referred to both with self, and with User. So I believe, the author put that difference by the two main reasons:

Since the ::new_remember_token is declared as of the property the class User itself, i.e. as a singleton method, the call to it shell be done with call to the class User ifself, in case when self isn't User class, or to using self operator, when self === User.

In order to split meanings of real properties that is mirrored unto DB, and the class singleton methods that have no that function. So you saw:

```<code>self.remember_token = ... # call to property 'remember_token'

User.new_remember_token # call to User model's singleton method
</code>```

However, the #new_remember_token could be declared as of User instance method as follows:

```<code>def new_remember_token
   ...
end
</code>```

And call to it shell be done with:

```<code>self.remember_token = self.encrypt(self.new_remember_token)
</code>```

But the author have in mind that the purpose of the ::new_remember_token method isn't the same as of attributes.

Body:
I don't understand why an attribute of the User model is referred to with self for assigning self.remember_token and User.encrypt for accessing the class method.
  What's the difference between the above and the following where User. is replaced with self.

Functionally there is no difference between User, and self in the context of class User, but the differs to each other in the context of User class instance. So for the context User class you are able to call the ::new_remember_token methods as both of User class, and self, and they return the same (for the context) results.

self.new_remember_token

User.new_remember_token

However, as you correctly denote, that attribute of the User model is referred to both with self, and with User. So I believe, the author put that difference by the two main reasons:

Since the ::new_remember_token is declared as of the property the class User itself, i.e. as a singleton method, the call to it shell be done with call to the class User ifself, in case when self isn't User class, or to using self operator, when self === User.

In order to split meanings of real properties that is mirrored unto DB, and the class singleton methods that have no that function. So you saw:

self.remember_token = ... # call to property 'remember_token'

User.new_remember_token # call to User model's singleton method

However, the #new_remember_token could be declared as of User instance method as follows:

def new_remember_token
   ...
end

And call to it shell be done with:

self.remember_token = self.encrypt(self.new_remember_token)

But the author have in mind that the purpose of the ::new_remember_token method isn't the same as of attributes.


问:
Why does java.util.Calendar use static factory methods?
It is considered better to have a separate factory class than having static methods in same class. See this question.

But the standard API uses both approaches.

Separate factory:

```<code>DatatypeFactory.newInstance().newXMLGregorianCalendar(...)
</code>```

Static methods in same class:

```<code>Calendar.getInstance(...)
</code>```

Why is this? In what case would having static methods be better than having a separate factory?

答:
It's not a singleton (I've been living a lie...). Now it does seem like poor naming convention.

Seems like the Java conevtion for a singleton getInstance(), is ClassName.getClassName()

You can see it in Desktop.getDesktop() (java.awt).

The getInstance() belongs to factory patterns, which means that Calendar is a factory.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#getInstance()

<s>Factory methods usually start with newXYZ() while a singleton usually has the getinstance() method.

In your example, DataTypeFactory is, in fact, a factory.

On the other hand, Calendar is a singleton, and as such it has a getInstance() method.
</s>


问:
State pattern vs Inheritance
In the following image for the State Pattern from Applying Domain-Driven Design and Patterns: With Examples in C# and .NET

I'm trying to persist the SalesOrder entity into the database. Normally I would have a salesOrder table in my database with a field currentState pointing to the current state of the entity.

This implementation is fine as there is a single entity and its states only contain different behavior.

However, what if I had to track other properties for the different states?
Examples:

When a SalesOrder is cancelled I need to track the cancelled quantity,cancellationReason, cancelledBy, cancellationDate.

When a SalesOrder is Refunded I need to track refundQuantity, refundPrice, refundFee.

So basically it is like I have a CancelledSalesOrder and RefundedSalesOrder entities with additional attributes. Same can be said for the other states as well.

So my problem now is that I will have to change the design from using the state pattern into using inheritance. However, inheritance doesn't allow my to dynamically change my state at run time (the problem which the state diagram solves initially).

so my questions:

Does the state pattern fail when an entity in each state has additional attributes? what's the alternative?

How should I persist my entities in this case? Single table inheritance? table per class? table per concrete class?

If I have to maintain some attributes from a former state (Refund a Shipped order, but don't delete the Shipping address from Shipped state ), how would one approach this problem?

How do you keep track of the order of which the states occurred?

答:
No, the state pattern does not fail. Just make the additional "cancel" attributes part of the "Cancelled" state, and the  additional "refunded" attributes part of the "Refunded" state ( you just forgot the latter state in your diagram, I guess?)

Since any "state" entity is an aggregate of the SalesOrder, any attributes of "state" can be seen just an "addition of details" to the SalesOrder.

Which kind of inheritance mapping you choose for your OrderState hierarchy actually does not matter for your problem, any of the typical three will work .

The state pattern also allows you to keep attributes of a former state even when the state changes afterwards. For example, you might need to keep the "shipping address" even when the state changes from "Shipped" to "Invoiced". This can be solved by allowing multiple states at once, just make the relationship between SalesOrder and OrderState "1:n" instead of "1:1". So you don't "change the state from shipped to invoiced" but add the additional state "invoiced" to an entity "StateOrder", without removing the state "invoiced" beforehand. Of course, using this model, when looking for all orders to be shipped, you must check not only for orders which are "granted", but for "orders which are granted but not already shipped". But that's only a detail in the processing which should not be too hard to handle.

Having multiple states is IMHO the "better" model, since it reflects the real world situation more adequate. For example, something you have shipped and invoiced is "shipped and invoiced", not "invoiced instead of shipped".

Title: State pattern vs Inheritance


答:
I actually find this question interesting :)

My take is that this is a bad practice today in PHP. That kind of syntax is typical of Python which has a feature called "named parameters" that allows calling a function without using the same order of variable calls.

There is an RFC in the php community to add this syntax to the language:
https://wiki.php.net/rfc/named_params

The internal discussion about this feature is not finished yet, personally I would like to have this feature.

As of today (PHP 5.5), you get no benefit at all in using this syntax as you are just evaluating the variable.

Title: PHP passing parameters to a function

Body:
I want to pass a parameter to a function as below for clarity. It doesn't give any error. But is this a bad practice. Do I have to avoid this.</p>

```<code>test('','','',$d='text','');

function test($a, $b, $c, $d, $e){

}
</code>```


问:
How to ensure that a member variable is initialized before calling a class method
There's a class with a parametrized constructor that initializes a member variable. All public methods of the class then use this member variable to do something.

I want to ensure that the caller always creates an object using the parametrized constructor (there is also a setter for this member variable) and then call that object's methods. In essence, it should be impossible for the caller to call any method without setting a value to the member variable (either by using the parametrized constructor or the setter). Here's the catch - there is just one method that itself generates a value to be initialized in the member variable (and returns it) - and to call that function, one would need a default constructor.

Currently, a caller can simply make an object using the default constructor and then call that object's method - I want to avoid checking whether or not the member variable is set in each and every one of the 20-odd methods of the class (and throw an exception if it is not) - except for the one method mentioned above.

Though a runtime solution is acceptable (better than the one I mentioned above); a compile-time solution is preferable so that any developer will not be allowed to make that mistake and then waste hours debuggging it!

Update: Here's an artist's impression of the current implementation in code:

```<code>class MyClass
{
private:
string m_strProperty;

void InternalNonStaticMethod(int iSomeParam);

public:
MyClass(string strValue)
{
m_strProperty = strValue;
}

MyClass() {}

void setProperty(string strValue)
{
    m_strProperty = strValue;
}

string MethodOddManOut()
{
    /* Do some computations to generate a value for the property */
    string strGeneratedValue("");
    InternalNonStaticMethod(4);
    /* ... */
    return strGeneratedValue;  // The value has to be returned and this method cannot simply update the member due to design issues that are beyond the realm of this question
}

void MethodLikeEveryoneElse()
{
    /* Do some computation based on the property */
    string strTemp = m_strProperty + "EXTEND";

    /* If strProperty is empty/garbage then this is going to fail miserably
       Trying to avoid the following snippet at 20 other similar methods:
       if (!strProperty.empty()) {
           strTemp = m_strProperty + "EXTEND";
       } else {
           throw exception
       }
    */
}

void MethodLikeEveryoneElse2()
{
    /* Similar to the above method */
}

}
</code>```

The caller would be a function in some other class using it like this:

```<code>void MethodThatUsesThis()
{
    MyClass objA;
    m_strHandle = objA.MethodOddManOut();  // Save the handle as a member of this object

    /* Some other lines of code */

    objA.setProperty(strHandle);
    objA.MethodLikeEveryoneElse();
}

void AnotherMethodThatUsesThisLater(string strHandle)
{
    MyClass objA(strHandle);  // The handle that the above method received was passed to this method since they are in different classes
    objA.MethodLikeEveryoneElse2();
}
</code>```

This code snippet is bound to raise tons of allegations on the horrendous design that is being implemented - but my only defense is, this is legacy code (ha! you saw this coming) and I only have the right to change anything in class A (it's more of an API and a library module) but the caller is not in my jurisdiction.

答:
If MethodOddManOut() does not take arguments, just call it in your default constructor:

```<code>class MyClass {
     // ...
     public:

     MyClass() : m_strProperty( MethodOddManOut()) {}

     // ...
}
</code>```

Body:
If MethodOddManOut() does not take arguments, just call it in your default constructor:

class MyClass {
     // ...
     public:

     MyClass() : m_strProperty( MethodOddManOut()) {}

     // ...
}


问:
Are debugging skills important to become a good programmer?
Along with the other qualities should a programmer need good debugging skills? If I have an applicant who was not able to find the error in the given program, but was able to solve all puzzles and programs, should I consider him for the job? </p>

<p>EDIT :- The puzzles are normal red,blue and red-blue balls like. The programs are like  finding continuous k zeros in an array. The debugging program is something which fails because of condition which should be >=, but instead is >. Everything is on paper. </p>

答:
Debugging is the phase in software development that comes after a certain test has been made on your software, and a bug was discovered. It is the act of searching and correcting the bug in your software.In lots of cases, finding the bug usually requires more time that fixing it.

It is the process of removing the bugs (the vulnerabilities) that are inherent in the computer application/system.
If this isn't done then hackers may take advantage of the bugs & may do a variety a malicious activities:

1) They may expose the vulnerability to the public leading to a loss of revenue, business & reputation for the developers & vendors.

2) Worms search for vulnerable systems that they can exploit & thus, copy themselves onto those servers. eg. In Jan 2003, the Slammer Worm took advantage of the vulnerability in the MS SQL Server.

3) Where worms have been mentioned how can we forget the viruses. Viruses are also let lose by their developers that take advantage of the bugs present in the program for the primary purpose of indecent exposure...

4) And if programs aren't debugged properly, consumers are never going to keep quite if they don't get their money's worth. In that case you don't even need a hacker to do the dirty work- you might as well trust the good ol' public.

ContentLicense: CC BY-SA 2.5


答:
Factory is probably one of the most misused patterns. People always talk about how it allows to easily switch to a different factory that generates different classes, but usually fail to notice that you can't do that with factory alone - you need some sort of dependency injection too!

The overhead seems small - use CalendarFactory.newInstance().newCalendar() instead of Calendar.getInstance(). But we wanted factory in the first place so we could easily switch factories and change the way objects are constructed. Can we really do that here? CalendarFactory.newInstance() is always the same function so it'll always return a factory object constructed the same way, which will create Calendars in the same way. In order to change the Calendar creation process, we need to either change CalendarFactory.newInstace or CalendarFactory.newCalendar. How is that any better from having to change Calendar.getInstance?

If we want to be able to easily change the Calendar creation process, we had to use dependency injection - create a CalendarFactory object somewhere and pass it around. That way we can control which factory the methods we call and objects we construct use.

There is a drawback to this approach though - having to pass that factory object around introduces quite a burden on the programmer. Methods need an extra arguments - for the entire call-chain from where the factory is created to where it's used. Objects need an extra field that you need to supply even if you don't use any method that requires that factory(alternatively - you have to remember if you supplied it or not, and exception will be thrown if the factory field is not set. But this exposes the implementation as it forces the user to know which methods require setting the factory field).

Since the overhead here is much bigger than the naive, worthless use of the factory, we can't just blindly apply the pattern(OK, I take that back - you can always blindly apply design patterns, and too many programmers do) and we actually need to think. Do we really need to be able to switch the Calendar creation process all over the place? Do we need it enough to introduce such burden on the programmers?

In the case of Java's Calendar, the answer was "no". Being able to tell what the time is differently, or to represent it differently in the memory, is not useful enough to have to pass around a CalendarFactory object all over the place.

Title: Why does java.util.Calendar use static factory methods?

Body:
It is considered better to have a separate factory class than having static methods in same class. See this question.

But the standard API uses both approaches.

Separate factory:

```<code>DatatypeFactory.newInstance().newXMLGregorianCalendar(...)
</code>```

Static methods in same class:

```<code>Calendar.getInstance(...)
</code>```

Why is this? In what case would having static methods be better than having a separate factory?


问:
2 closest points between 2 rectangles
On a 2D plane, I have 2 rectangles.
I want to find the closest pair of points (one on each rectangle), which are closest to each other. By points I mean the corners of the rectangles. And no, they do not overlap.

Is there any way to do that other than checking all the distances between all the combinations of points and finding the smallest one?

答:
You could take the "center of mass" average of all corners on the plane (a new point which is at average x and the average y coordinate of all corners), then take the corner of each rectangle that is closest to that center of mass point. After your initial calculation of the center of mass, you would only need to run a single calculation for each corner.

If either rectangles happen to have more than one point that are equally distant from the overall center of mass then you would need to ensure you choose from among the tied points the two (one from each rectangle) that are closest to each other, and in this case you could just do the n^2'ed thing (although if we are dealing with convex polygons, such as rectangles, there could only be a max of 2 ties per polygon, so at this step there would only ever be an additional 2 or 4 calculations - depending on if one or both polygons contained ties).

This algorithm would scale very well (O(n)) for any two convex polygons each containing any number of corners (and their own center of mass equally distant from each corner they contain, like rectangles and all regular polygons), if that matters.

Ultimately, if you are always dealing with rectangles then you would need to decide whether or not the reduced computation time is worth the extra coding and testing of whatever optimized algorithm you go with.

Title: 2 closest points between 2 rectangles


问:
Layering buttons when a number needs to be pressed more than once during an equation?
I am very new to HTML5 (and web coding in general), and I am trying to create an interactive calculator. I will try to explain this as clearly as I can.

The basic idea is that the user will use pre-set equations to add numbers with the calculator. All of the buttons on the calculator will have an animated 'push down' effect, but the buttons that need to be pressed to perform the equation will light up one at a time after each successive button is pressed.

I'm getting stuck developing this when a number needs to be pressed more than once during an equation... i.e. 257+6732. - notice that the # 7 is used twice.

Here are my two ideas (both have failed):

In this example the #7 button would need to preform two functions (1st. light up the 'plus' button on the first click, and 2nd. light with the "three' button on the second click). I know that coding the button to perform two functions this way is possible, however, the button can ONLY be active at correct points in equation. During the remainder of the equation clicking the #7 button will not preform any function, and will only give an animated push down effect.

OR

The #7 button could be duplicated and on the first click the top button disappears. The 2nd #7 button would then stay hidden until the appropriate time during the equation. Again, the #7 button would have a grayed out appearance and only give an animated push down effect while the button is not in use.

Can anyone shed some light on this for me? I'm pulling my hair out over this. The entire design is complete and things look fantastic, but the value of this project is adding up to a POS until I can work out the coding.

答:
You could handle the multiple states using colour.  I'm unclear on how many states there are to handle but if I'm reading this right your buttons need these states: not-pressed-yet, pressed, needs-to-be-pressed and was-pressed.

The not-pressed-yet should be plain

The only one that should be 'pushed down' is 'pressed' or your users will be confused.

The others you could treat more subtly, say, using:

a different background colour

a different border

a visual effect, such as pulsate

If a button is pressed and you need different action to happen you could make the action conditional on the style attributes.  Alternatively, you could add a data tag to a given button with its state, say, <button data-state="needs-to-be-pressed">3</button> and make the action conditional on that attribute.

Do consider your end-user in this and don't make them think


问:
How to fit requirements into MVC
Let's say we have a website requirement to allow User functionality. Simple!

We create the UserModel, UserController and UserView. Works perfectly.

However, let's assume that User has a many-to-one relational table connected to it titled Child which also has its own MVC components: ChildModel, ChildController, ChildView. Now if we had a requirement to create a CSV file for download containing a few details from the User and a few details from its Child, how would we go about designing this requirement?

"DownloadCSV" could essentially have its own CRUD methods, it's own Controller, it's own View but its Model is based on the details from other tables, so should it have its own Controller, View, Model(/DB View) or should it just be another method besides CRUD in User or Child controller?

答:
In terms of a web application (not sure if that is the case here, but the concept is the same I think) On ChildController there is typically an "index" method that is used to render a page listing all children.

I view this "DownloadCSV" functionality as very similar to that, except that the server is sending a CSV file as the HTTP response rather than an HTML page.  Therefore, it seems to me that this would be appropriate as another method of ChildController.

Title: How to fit requirements into MVC


问:
Question regarding ExtJS 4 GPL/commercial license
I am currently in the process of selecting a widget framework to be used for a new project. Current choices are Dojo/ExtJS4. We are leaning on ExtJS4 but might have some issues with the licensing.

From the Sencha license page:

Our open source license is the appropriate option if you are creating an open source application under a license compatible with the GNU GPL license v3.

However on the GPL FAQ:

http://www.gnu.org/licenses/gpl-faq.html#UnreleasedMods

A company is running a modified version of a GPL'ed program on a web site. Does the GPL say they must release their modified sources?

The GPL permits anyone to make a modified version and use it without ever distributing it to others. What this company is doing is a special case of that. Therefore, the company does not have to release the modified sources.

It is essential for people to have the freedom to make modifications and use them privately, without ever publishing those modifications. However, putting the program on a server machine for the public to talk to is hardly “private” use, so it would be legitimate to require release of the source code in that special case. Developers who wish to address this might want to use the GNU Affero GPL for programs designed for network server use.

Seems contradicting on what they have on Sencha's licensing page. Moreover, the webapp will be deployed on the cloud and will offer a subscription model. I've read that this is the so called ASP loophole and that the Affero GPL was made to address this. The project will have multiple modules, but certainly there would be backend/integration and frontend modules. The frontend will just consume exposed REST services and will be an entirely different application.

The question is, would there be any license issues if we use the GPL version and willing to offer the source code (frontend module only) which uses ExtJS for our future clients?

答:
I think the confusion comes from not treating your server side and client side applications separately.

Let's deal with the server side first.

Presumably, you won't need any of Sencha's ExtJS code for the services that you are putting together.  So their license restrictions won't have an impact upon your server side code.  Even if you did use their code within your server's services, the GPL "loophole" (as you called it) means you don't need to distribute your server side source code.

Regarding the client, your client side code will become GPL'd unless you request an exception version from Sencha.  Their licensing page provides the request for exception forms.

It's not clear to me if you need their commercial license or not, and that's a question best asked of Sencha.  Assuming you didn't use ExtJS in your server code and you're selling access to the services and not the client, then you may be able to argue that you are not using ExtJS in a commercial manner.  The polite (and easiest) thing would be to contact them and ask their opinion on the matter.


问:
Are there any ultra high level languages out there?
Historically a HLL is something like C, Fortran or Pascal and a VHLL is something like Ruby or Python. I am familiar with the terms 4GL, 5GL, DSL and LOP, and those who aren't should read Wikipedia for the definitions. I'm looking for UHLLs.

My question is: are there any computer languages out there which are another order of magnitude more productive, and is anyone working on them?

More productive means less authored code and less programmer time to achieve a result, less bugs and less debugging, closer conceptual link between code and requirements, less effort to modify and maintain.

The main domain that interests me is general-purpose business and consumer applications, with a GUI or browser front end, data persistence and connections to other systems such as printing and email. Other people might well focus elsewhere.

I recognise that some of those languages might be domain-specific, and that they might be little more than the configuration capability of a large and capable application. Excel spreadsheets fall into this category.

I recognise that some of those languages might appear general, but might still be narrow in scope and unsuited to many problems. For example, Matlab might not be a good choice for a program that deals mainly with user interaction and textual data.

I know some of the features that might be in a UHLL, by analogy with VHLL. I would expect to find one or more of the following (and feel free to add to the list):

A drawing of a GUI form IS the program for a GUI form

A table containing rows, columns and headers IS the program for a table in a database

Declarative logic says what should be done and when, with no IF statements

Operations on sets of data, with no FOR loops

Non-sequential execution eg data driven, pattern matching, tree walking

The motivation for the question is that I am increasingly fed up with the sheer hard work of translating relatively simple business requirements into large quantities of code to cater for what the computer wants or needs. The question is really about finding others out there who share my pain and are working on raising the level of languages and getting the computer to do more of the hard work. This was a major focus in the 1970s-80s, but is it still happening?

These are some suggested answers to my question, provided here to to summarise or enumerate languages I know about, and which in my view fall short.

There are many languages that are HLL or VHLL and contain individual features that belong to a higher level. I've used most of them (often badly). They include

Lisp, with its macros and ability to self-modify

Haskell, with data dependency and pattern matching

SQL, which deals in rows and tables

Rebol, which seems clever but I don't really get it

APL (and J), with its multi-dimensional arrays and ultra-compact operators

C# with LINQ

AWK/Perl/Python/Ruby with wonderful collections and regexes built in

These languages have too many low level features to be UHLL. The programmer still has to write many low level constructs for any useful program.

There are RAD/4GL packages. I've used some:

dBase/Foxpro

Dataflex/Powerflex (my product)

Access

PowerBuilder

And lots more I haven't used. Mostly the language is HLL at best but the package contains a framework and privileged connections between language and package so that applications can be built fast. I'm not sure why this approach ran out of steam, but in any case UHLL this is not.

There are raw frameworks/libraries. I've used a few:

Rails

Java awt and swing

.NET Windows Forms, WPF and ASP.NET.

These are currently the state of the art. They leave the programmer firmly trapped in the mire of the implementation language, dealing with complexity at every turn. This is not UHLL, but a UHLL might conceivably be built on top of one of these.

There are design tools, like UML and Rational's toolset, which I don't know well. As far as I can see they help articulate business requirements but can never replace the programming step. I don't want to eliminate programmers, just get more done per unit of time and effort.

So having eliminated all contenders I can think, I hope someone else can provide a better candidate.

Late Edit: I think I have an answer: Wolfram Language. http://www.wolfram.com/wolfram-language/

答:
I would expect that Lua, as used by game to script their quests and interfaces would meet this criteria. There's also similar domain specific languages (and map-builder utilities) used to allow level designers to quickly and easily say "when player talks to Bob, start Bob's Epic Quest".

I know of a few more esoteric languages that focus on moving code to describing what is going on, not how it's supposed to be done. Some focus on a very declarative, logic based approach. Some focus on reactive programming to do that. Some focus on actors to do that (especially for things that need to be parallelizable). Some focus on simply making the syntax more natural - with the assertion being that natural syntax leads to fewer bugs caused by translating between natural language and code.

None are really promising as far as producing an order of magnitude more productivity for the rank and file developer.


问:
Should you write down a list of issues, or fix issues as they arise?
I have observed a strange trend in the company I work at.

There are people who insist that there should be a list of tasks. They estimate those tasks, implement them, and try to meet their commitments. However, while they are coding, the requirements are likely to change. The priorities shift, the tasks increase or decrease, and the scope may just down right change, causing the whole work to get discarded.

And then, there is another team, who meet issues and fix them as they arise. There are no estimates, there are no priorities, there are no set deadlines, and mission statements for sprints go something like, “Fix the bugs in the [insert subsystem name here]”.

Now, which is the right way to go about being agile when you have technical sprints that focus only on stabilizing the system? Should you try and gather a list of issues, only to have them change, or should you try and fix-as-you-go, without saying when you’ll be done?

答:
Both methods have a lot going for them, depending on the context.

If you're fixing bugs that block the user's experience, then it is very hard to give a good estimate because clearly something is happening that has not been anticipated. It may turn out to be a one-liner, or a subtle misunderstanding that needs hours if not days of tracking down through event logs and stack traces. You probably also know that it simply must be dealt with - these bugs appear as top priority and stay there until the end user can proceed again.

On the other hand, performance enhancements, some stability enhancements and aesthetic changes - things which degrade the user's experience but don't prevent him using the application - can be treated much more like feature stories. You decide which ones will make the most improvement for the time invested, and review that decision regularly in the light of other changes. Users may find workrounds. The stories may even be rendered moot by changes from the emergency bug fixers.

Ultimately there isn't a unique "right answer" - just find what works best for your teams.


问:
Create ASP.NET input forms from XSD?
I have several types of XML document.

The format of (i.e. the elements in) each document type is defined in an XSD.

Is there a convenient way to create HTML elements (or ASP.NET controls) on an ASP.NET form, to display/edit the elements in (contents of) an XML document, given the XML document and/or the document's XSD definition as input?

Within the XML/XSD:

Complex (i.e. parent) elements may contain sub-elements

Simple elements are of type 'string', 'integer', 'list of string values', etc.: which should map to corresponding HTML input elements

Elements are documented (labelled) using <xs:annotation> in the XSD (these would be suitable HTML  elements for the corresponding <input> elements).

Each element is required, not required, and/or there may be several of them, specified using minOccurs and maxOccurs in the XSD

As well as generating the ASP.NET form, when the user posts the completed form, the software should read the returned data and pack it into an XML document.

How to do this?

I can write software to parse the XSD and generate the forms myself but that seems like a lot of code to write in-house and maintain.

答: There isn't a direct way that I'm aware of off the top of my head. But XSD to form was hawt back in 2001 when .NET was conceived so you can likely use tools like xsd.exe to generate a class from that. Then you should be able to use the EditorFor in ASP.NET to generate a form for that. Or any other form generator that takes classes as input. </p>

Title: Create ASP.NET input forms from XSD?


答:
The highest level programming language that I know of is APL.  It requires a special keyboard to represent all of the necessary symbols.  Check out this video, in which the author writes a complete implementation of Conway's Game of Life in about seven minutes.

The real question, of course, is "is this practical?"  Can I find enough APL programmers in the world to sustain a business this way?  Will APL run on phones and tablets?  Do I really need to buy all of my software developers new keyboards?

If you really want a productivity boost, your best bet is probably some Lisp variant.  Clojure runs on the JVM, and has a .NET port.  I say this because people have already done it; the Orbitz search engine runs on Lisp, and Paul Graham ran an entire business using Lisp, claiming that it gave him a significant advantage over his competitors (who were all using Java).

Do note that, the higher level your programming language is, the more removed it is from the actual hardware, and the more likely it is that you'll have performance problems.  Unless you have really sophisticated compilers, you may still find yourself coding performance-critical portions of your application in more performant, lower-level languages from time to time.

And there is still the matter of having a critical mass of developers versed in the language.  Despite all its warts, you will never have a problem finding a Java programmer.

Note that mainstream languages are still evolving.  Linq was created for the specific purpose of making data-driven programming more declarative.  Several new features were added to the C# language to make Linq work; all of them have to do with improving developer productivity.

Further Reading

Beating the Averages

Title: Are there any ultra high level languages out there?

Body:
Historically a HLL is something like C, Fortran or Pascal and a VHLL is something like Ruby or Python. I am familiar with the terms 4GL, 5GL, DSL and LOP, and those who aren't should read Wikipedia for the definitions. I'm looking for UHLLs.

My question is: are there any computer languages out there which are another order of magnitude more productive, and is anyone working on them?

More productive means less authored code and less programmer time to achieve a result, less bugs and less debugging, closer conceptual link between code and requirements, less effort to modify and maintain.

The main domain that interests me is general-purpose business and consumer applications, with a GUI or browser front end, data persistence and connections to other systems such as printing and email. Other people might well focus elsewhere.

I recognise that some of those languages might be domain-specific, and that they might be little more than the configuration capability of a large and capable application. Excel spreadsheets fall into this category.

I recognise that some of those languages might appear general, but might still be narrow in scope and unsuited to many problems. For example, Matlab might not be a good choice for a program that deals mainly with user interaction and textual data.

I know some of the features that might be in a UHLL, by analogy with VHLL. I would expect to find one or more of the following (and feel free to add to the list):

A drawing of a GUI form IS the program for a GUI form

A table containing rows, columns and headers IS the program for a table in a database

Declarative logic says what should be done and when, with no IF statements

Operations on sets of data, with no FOR loops

Non-sequential execution eg data driven, pattern matching, tree walking

The motivation for the question is that I am increasingly fed up with the sheer hard work of translating relatively simple business requirements into large quantities of code to cater for what the computer wants or needs. The question is really about finding others out there who share my pain and are working on raising the level of languages and getting the computer to do more of the hard work. This was a major focus in the 1970s-80s, but is it still happening?

These are some suggested answers to my question, provided here to to summarise or enumerate languages I know about, and which in my view fall short.

There are many languages that are HLL or VHLL and contain individual features that belong to a higher level. I've used most of them (often badly). They include

Lisp, with its macros and ability to self-modify

Haskell, with data dependency and pattern matching

SQL, which deals in rows and tables

Rebol, which seems clever but I don't really get it

APL (and J), with its multi-dimensional arrays and ultra-compact operators

C# with LINQ

AWK/Perl/Python/Ruby with wonderful collections and regexes built in

These languages have too many low level features to be UHLL. The programmer still has to write many low level constructs for any useful program.

There are RAD/4GL packages. I've used some:

dBase/Foxpro

Dataflex/Powerflex (my product)

Access

PowerBuilder

And lots more I haven't used. Mostly the language is HLL at best but the package contains a framework and privileged connections between language and package so that applications can be built fast. I'm not sure why this approach ran out of steam, but in any case UHLL this is not.

There are raw frameworks/libraries. I've used a few:

Rails

Java awt and swing

.NET Windows Forms, WPF and ASP.NET.

These are currently the state of the art. They leave the programmer firmly trapped in the mire of the implementation language, dealing with complexity at every turn. This is not UHLL, but a UHLL might conceivably be built on top of one of these.

There are design tools, like UML and Rational's toolset, which I don't know well. As far as I can see they help articulate business requirements but can never replace the programming step. I don't want to eliminate programmers, just get more done per unit of time and effort.

So having eliminated all contenders I can think, I hope someone else can provide a better candidate.

Late Edit: I think I have an answer: Wolfram Language. http://www.wolfram.com/wolfram-language/


问:
Web Routing Standards
We are putting together an API to provide our vendors some simplistic direct access. I've built APIs before, and have always routed them as such:

```<code>{controller}/{action}/{id}
</code>```

My boss, however doesn't think that's intuitive. He thinks we should route our API like this:

```<code>{controller}/{id}/{action}
</code>```

His reasoning is this: "For object number 7, get it" or "For object number 15, save it." He thinks it makes more sense that way and that out vendors will understand it better that way. For me, it's about starting with the most detail then drilling down: "I'm dealing with an object, I need to save it, save it with id 15"

I'm trying to build an argument for keeping it standard, and the "Everyone else does it this way and we are just going to confuse people" argument doesn't seem to be effective. His response is, "We've never had an API before, so it will be OK for our customers to use it this way."

I would like to find some stronger arguments, backed up by white papers if I can find them, but I am coming up blank. What arguments would you use, and are there any whitepapers you could point me towards?

答: Tell him that some actions won't have ID's and some will have two or more.  It makes more sense to have them at the end, because otherwise the position of your {action} attribute will jump around, making the construction of your routing table much more difficult.

Title: Web Routing Standards


问:
How do I read the Entity Framework Model and validate it against a given connection?
I have a Entity Framework Database First Model.

I want to write a MSTest/nUnit test to verify that all the stored procs, tables and views that are defined in my edmx model are still valid on the database.

答:
Query the system tables.  This will verify the presence of all of the required objects in your database.

For example, the following query uses the sys.objects catalog view to return all database objects that have been modified in the last 10 days.

```<code>SELECT name AS object_name
  ,SCHEMA_NAME(schema_id) AS schema_name
  ,type_desc
  ,create_date
  ,modify_date
FROM sys.objects
WHERE modify_date > GETDATE() - 10
ORDER BY modify_date;
</code>```

See Also

Querying the SQL Server System Catalog

ADO.NET Code Examples

Body:
Query the system tables.  This will verify the presence of all of the required objects in your database.

For example, the following query uses the sys.objects catalog view to return all database objects that have been modified in the last 10 days.

SELECT name AS object_name
  ,SCHEMA_NAME(schema_id) AS schema_name
  ,type_desc
  ,create_date
  ,modify_date
FROM sys.objects
WHERE modify_date > GETDATE() - 10
ORDER BY modify_date;

See Also

Querying the SQL Server System Catalog

ADO.NET Code Examples


答:
Almost all the criteria you list are things already tried in 4GL / RAD tools like MS Access, Sybase Power Builder, Oracle Forms, Ruby-on-Rails (as a more modern specimen for Web Apps), and many more (see Wikipedia for a very long list of vendors). And indeed, translating relatively simple business requirements into some kind of program can be very quickly achieved with these tools. That's why most vendors of RAD tools advertise their products in a way that everyone should think they have already invented a UHLL in your sense.

The catch is, as soon as you leave the ground of requirements being "relatively simple", and as soon as you have to maintain and evolve programs written with these environments, you will notice that you easily reach the limits and notice the drawbacks of them, or that to implement requirements with them is in no way simpler than with any other "VHLL" you have in mind . IMHO there is a good chance that these kill any efficiency improvement you had in version 1.0 when going further to version 1.1, 1.2 and 1.3 of your program.

If you want to build software for complex requirements, you will need a complex programming environment. There is still no silver bullet, we had only gradually improvements over the years and not "the order of magnitude" in productivity with any current programming language over its predecessors (at least, for the last 30 years, which is approx. the time in the past when Brook's article was published).


问:
How do I explain that we're wasting developer time adding unnecessary features?
So I've lead the charge with my fellow engineers to, at the very least, start "thinking" Lean. We hit on a few major areas of waste, and 2/3 lead to the exact same point..."Extra Features". We dogfood our own software on two fronts, sales and project management. It works great for sales, because that's what a CRM is great for. It's not so great for managing projects, and we're often tasked with adding extra features to make it work for this use case.

Does it make more sense to continue adding features that don't add any customer value, or should we accept that having our sales team using our own product is "good enough" and perhaps look for an off-the-shelf solution?

答:
Draw up all the requests for features from your company as if they were for a customer and show the cost of doing so. Then do a side-by-side comparison with an off the shelf piece of software.

Next, highlight your companys features that are hidden from other customers as there isn't a net benefit unless the feature saves more time / money than it took to produce.

Whoever does the budgeting should immediately see the value of spending the time on the dog fooding as time that could be spent on work producing revenue.


答:
I don't agree with your initial assessment.

First of all, it's highly unlikely that your company is so unique or unusual that your customers might not also benefit from your customized features.

Dogfooding (even if you have to customize the software  to make it work in your company) is one of the best ways to get a "reality check."  The inconvenience would have to be especially egregious to overcome the benefits you get.

Besides, it's cheaper to use your own stuff than it is to buy something else to use internally.  If you're not using your own stuff, then what confidence do you have giving it to your customers?

That said, if your application doesn't lend itself well to dogfooding (i.e. it's not a Project Management application, but you're trying to use it for Project Management), you have to decide whether or not adding features to it to make it work in a Project Management role (when your customers don't use it that way) is worth the trouble, additional expense, and complexity.

Dogfooding features that the customer will never see doesn't make much sense, unless it saves you enough money by not having to buy an off-the-shelf solution that it overcomes all of the drawbacks.

Title: How do I explain that we're wasting developer time adding unnecessary features?

Body:
So I've lead the charge with my fellow engineers to, at the very least, start "thinking" Lean. We hit on a few major areas of waste, and 2/3 lead to the exact same point..."Extra Features". We dogfood our own software on two fronts, sales and project management. It works great for sales, because that's what a CRM is great for. It's not so great for managing projects, and we're often tasked with adding extra features to make it work for this use case.

Does it make more sense to continue adding features that don't add any customer value, or should we accept that having our sales team using our own product is "good enough" and perhaps look for an off-the-shelf solution?


答: Maybe you shouldn't try to force it to fit MVC.  Many times, reporting and data dump tasks don't fit the framework used to build the interactive applications which create and manipulate the data. And that is not a bad thing.  It is quite possible that you could generate this data download using a separate class/task that could use the same stored procedures internally for consistency, but is driven by the reporting needs which are different from needs for the presentation/control of data in the application.</p>

Title: How to fit requirements into MVC

Body:
Let's say we have a website requirement to allow User functionality. Simple!

We create the UserModel, UserController and UserView. Works perfectly.

However, let's assume that User has a many-to-one relational table connected to it titled Child which also has its own MVC components: ChildModel, ChildController, ChildView. Now if we had a requirement to create a CSV file for download containing a few details from the User and a few details from its Child, how would we go about designing this requirement?

"DownloadCSV" could essentially have its own CRUD methods, it's own Controller, it's own View but its Model is based on the details from other tables, so should it have its own Controller, View, Model(/DB View) or should it just be another method besides CRUD in User or Child controller?


问:
How should I test my application?
I have made a simple application which searches for files and folders on users computer. Since, I am a student currently in my 1st year and don't have any formal training and have made my application while I was still learning C# and .Net framework, I didn't have knowledge about unit tests and other good testing methods used by professionals. Although, most of my code is working fine, sometimes it throws exceptions or some other unexpected situation occurs and the code breaks.

Keeping the above experiences in mind, I don't think my application is ready for deployment and so , I would like to test my application in a professional way, and be assured that my application is bug free.

Therefore, I want to ask professionals here, that keeping my situation in mind, how should I start testing my application.

What are the steps that I should follow, to ensure the quality of my application.

答:
Step 0: focus, and don't get overwhelmed

There are several types of testing you can do. There's unit testing, acceptance testing, integration testing, test driven development (TDD), behavior driven development (BDD), acceptance test driven development (ATDD) etc. Don't get bogged down in terminology just yet. Focus on acceptance testing (see note), which roughly means to test the final version of your complete program. Once you get your feet wet with the simplest possible tests, you can start to look at the bigger world of software testing.

Note: Some folks may give advice to start with unit testing. That's
  cool, too. That can be pretty easy if you're using a language with a
  built-in unit testing framework. If not, installing a unit testing
  framework can be a pain. This is why I recommend starting with
  acceptance testing, because you don't need a fancy framework. All you need
  is a way to call your program from a script or from another program. You
  probably already have the tools to do that on your machine.

Step 1: create some test data

Create a folder, and in that folder put some dummy files. Make it so that you can easily find all of them (eg: their names all start with "f"), some of them (eg: some names end with a "Z", some don't), none of them (eg: none have the word "foobar" in their name). This is your test data. If your program can search sub-folders, create a few subfolders, too.

Step 2: create a simple test script

Write a test script using whatever scripting language you are comfortable with -- python, bash, powershell, etc. This script should call your program with parameters to search for files. For example, it should tell it where to search (eg: your new folder) and what to search for (eg: F*, *Z, foobar). Since you control how many files are in your test folder, you should know that a search for F* will return X files, searching for *Z should return Y files, and searching for foobar should return 0.

Note: you don't have to use a scripting language. Usually that's easier than creating a compiled test program. If you only know one language, though, use that language for now.

It really doesn't have to be any fancier than that -- a single script that calls your function, and then verifies that what it returns is what you expect. Do that for several different search criteria. Have your script print out a simple name for each test, and either "PASS" or "FAIL".

Step 3: add more test cases

As you're writing your first tests, you'll probably write tests for the simple cases. Think about edge cases -- testing the boundaries of what your code can do. Does your program accept an argument telling it where to search? Write a test where you don't give it the argument to make sure it prints an appropriate error message. Can you pass more than one argument? Arguments that are empty strings, or paths to folders that don't exist?

As you uncover bugs, add a test case before you fix the bug so that you can duplicate it. Fix the bug, and verify that your test case now passes. As you add new features you can do the same thing -- add a test before adding the new feature. It should fail, until you get that feature working. This is known as TDD, or Test Driven Development.

Step 4: learn

Once you're comfortable with how that works, you can start looking at other tools to make this easier. For example, cucumber or the robot framework are good choices for acceptance testing, but there are many, many others.

Title: How should I test my application?


问:
storing and retrieving millions of documents using c#
I am working on an integration project, where my “app/web service” will sit in the middle serving  documents.

Basically, a request is sent with the document id as part of the query string, I check if it exists and if it does, write the document (pdf) back to the response. Now, this is very simple to do and we have done this many times.

This is where it gets very tricky, there will be about 5200 new files added each week, that’s 3GB per week (so about 150GB of data per year). We are expected to keep 10 years of data.

What is the best way of storing these documents and searching has to be very quick.

Some options are:

If I choose to save all these files on a network share, initially it will be quick but over time it is going to be very slow.

If I choose SQL to store these files, I can’t really store all documents in a single table or utilize table partitioning, DB partitioning etc. If I go with DB partitioning that’s still 150GB DB file each year to backup and restore.

I was thinking implementing RBS for MS SQL but not sure how quick this is going to be.

Any suggestions or other options I might have....?

答:
You could compose the document ID like

yywwdcxxxx

```<code>yy   last two digits of the year
ww   the calendar week 1..53
d    the day 1..7
c    check sum digit from ID+filename (cf. http://en.wikipedia.org/wiki/Check_digit)
xxxx sequence number to distinguish documents from the same day
</code>```

Directly map this ID structure to a directory structure in a filesystem.
Create the new directories on the fly as needed.

Assuming that you want to keep the original document name, you could store the document under

..\yy\ww\d\c\xxxx_original_name

xxxx is the consecutive sequence number for documents for a given day. You can use a dynamic length for the sequence number to increase flexibility.

If you are not free to create your own document ID, you could map the existing scheme to an ID structure as suggested above.

The date oriented structure allows you to easily archive outdated documents year by year and to do a proper backup day by day.

The filesystem should probably be fault-tolerant. Consider using a RAID or store the files in parallel shadow directories to have a chance for recovery.

You also could store your files in a database or in an LDAP server. But 5200 files per week is not asking too much of a filesystem. And you still would need some scheme for unique document IDs.

Be aware that certain filesystems (under Unix) have a maximum number of files.

Body:
You could compose the document ID like

yywwdcxxxx

yy   last two digits of the year
ww   the calendar week 1..53
d    the day 1..7
c    check sum digit from ID+filename (cf. http://en.wikipedia.org/wiki/Check_digit)
xxxx sequence number to distinguish documents from the same day

Directly map this ID structure to a directory structure in a filesystem.
Create the new directories on the fly as needed.

Assuming that you want to keep the original document name, you could store the document under

..\yy\ww\d\c\xxxx_original_name

xxxx is the consecutive sequence number for documents for a given day. You can use a dynamic length for the sequence number to increase flexibility.

If you are not free to create your own document ID, you could map the existing scheme to an ID structure as suggested above.

The date oriented structure allows you to easily archive outdated documents year by year and to do a proper backup day by day.

The filesystem should probably be fault-tolerant. Consider using a RAID or store the files in parallel shadow directories to have a chance for recovery.

You also could store your files in a database or in an LDAP server. But 5200 files per week is not asking too much of a filesystem. And you still would need some scheme for unique document IDs.

Be aware that certain filesystems (under Unix) have a maximum number of files.


问:
How to Know When to Stop Designing?
First some backgrounds, I'm interning at a company that makes parallel processing hardware.

We're currently working out the design for a component of our driver that is supposed to evolve over a few generations of our products. The next gen is still in simulation phase and the specification we have now may change when we actually get the hardware.
Our module is supposed to work on the current gen and all future gens.

I've always been under the impression that a design should be as future-proofing as possible. In this case, we know exactly what to do for current gen hardware but are unclear on some fronts for the next gen.

So my question is:

When do you know that you should stop designing for the future and just keep it simple and correct for what you know right now?

答:
Follow the YAGNI principle, and use sensible design best practices.

Despite the reputation that software developers have among the general public of being in command of some form of black magic, software developers still don't have predictive abilities that extend beyond those of said general public.  So stick with what you know.  Gather requirements, plan your work, act accordingly.

If one of the requirements is "The application shall be future-proof," well, that is not really a requirement, is it?  It's not even a feature; it's just a wish.  Take that wish, and break it down until it becomes testable requirements.

Example

The application shall have a plug-in, extensible interface, with the following specifications: [listed here]

That is a testable requirement.

Title: How to Know When to Stop Designing?


答:
This is actually a very modest number of files for a doc management system.  5200 files x 52 weeks x 10 years is less than 3 million.  Even at your own calculation, its only 1.5 TB of data over 10 years. That will easily fit on a hard drive.

For this volume of files, I would recommend keeping the files in the file system, not the database.  It will give you some more flexibility with regard to how you store and backup the content.  Plus it will take the load of transferring the files off the SQL server.  You'd then just keep the metadata and a pointer to the file in the database.

If you don't want to store the files on site, you might also consider Amazon S3 or similar service.  There'd be a cost, obviously, but you then dont have to worry about the hardware.

Title: storing and retrieving millions of documents using c#

Body:
I am working on an integration project, where my “app/web service” will sit in the middle serving  documents.

Basically, a request is sent with the document id as part of the query string, I check if it exists and if it does, write the document (pdf) back to the response. Now, this is very simple to do and we have done this many times.

This is where it gets very tricky, there will be about 5200 new files added each week, that’s 3GB per week (so about 150GB of data per year). We are expected to keep 10 years of data.

What is the best way of storing these documents and searching has to be very quick.

Some options are:

If I choose to save all these files on a network share, initially it will be quick but over time it is going to be very slow.

If I choose SQL to store these files, I can’t really store all documents in a single table or utilize table partitioning, DB partitioning etc. If I go with DB partitioning that’s still 150GB DB file each year to backup and restore.

I was thinking implementing RBS for MS SQL but not sure how quick this is going to be.

Any suggestions or other options I might have....?


问:
Software process of small company
I'm wondering how should testing take place in small teams (or start-up teams).

I'm talking 5-10 developers that are assigned to multiple development tasks.

From my experience there is little to none testing in the development process, but I also hear small teams can get through the initial level of software process maturity.

How does QA and testing take place during development in a mature-but-small team?

(please, if you can, describe the whole software process including who should be doing what)

EDIT (more detail):

I'm especially interested in a team developing a distributed processing-intensive back-end with a website as it's API. The two parts (back-end, front-end) are developed by two different groups of 3.

I want to understand who tests what, and when. If I write a module and it's unit tests, do I write integration tests when completing the code? Should you assign a developer on such a small group to focus on testing?

答:
If the team is mature, they should be writing both unit-level tests and automated acceptance testing. There's simply no good way to write robust code without testing. All of the good software developers I know are constantly asking themselves "how can I test this?".

I've worked on teams where each developer was responsible for testing their own code, and teams where there were one or more dedicated test engineers. In both cases, the teams were able to deliver high quality software. The teams I've been on that thought testing was not something a software engineer should do generally produced low quality software.

At the end of the day, the team should be responsible for the quality of the software they produce. Somebody needs to be writing tests daily. Whether they each take a part, they take turns, or they have a dedicated tester or two, should be left to the team to decide. To decide to do none of those is to decide to produce crappy code.

In my opinion, every software team needs an appropriate number of people dedicated to testing. The number goes up with the size of the team, and the number should never be less than one. In addition, every software engineer should be responsible for unit-testing their own software.

Title: Software process of small company


问:
Reporting Solution in PHP / CodeIgniter - Server side logic vs client side
I'm building a report for an end user.
They would like to see a list of all widgets... but then also like to see widgets with missing attributes, like missing names, or missing size.

So i was thinking of creating one method that returns json data containing all widgets... and then using javascript to let them filter the data for missing data, instead of requerying the database.

Ultimately, they need to be able to save all "reports" (filtered versions of data) inside a csv file.

These are the two options I'm mulling over:

Design 1

Create 3 separate methods in my controller/model like:

```<code>get_all_data()
get_records_with_missing_names()
get_records_with_missing_size()
</code>```

And then when these methods are called, I would display the data on screen and give them a button to save to csv file.

Design 2

Create one method called get_all_data() and then somehow, give them tools in the view to filter the json data using tables etc... and then letting them save subsets of the data.

The reality is, in order to display all data, I still need to massage the data, and therefore, I know which records are missing attributes.  So i'd rather not create separate methods by each filter.

I'm not sure how I would do that just yet but at this point, i would like to know some pros/cons of each method.

Thanks.

答:
Assuming your using Angular.JS, jQuery or similar, I would recommend loading all the data from the server at once, then writing controllers that are able to filter between the different types of lists.

This solution allows for the least amount of load on your server and makes the client do most of the work.  This along with the idea of having an application whose lag depends on the local machines filtering (local processing = fast) is much better that having an application that can lag due to network instabilities (network = slow).

That being said, if it is a massive amount of data (> 1 million records), migrating the logic from the client to the server may become reasonable.  At this point the local processing may/can take longer that it would be to request the data from the server.


答:
I think this boils down to how development as a whole is understood. If "just getting it done" is the goal, then fixing bugs as they appear may well be the course of action. Also, to avoid wasting time, if you see a bug in code that you already manage AND you already know the fix, I don't think there is much point in creating an issue just to close it a minute later. This bears a risk, though, which the other folks try to address: You'll never get things done if you constantly change the goals.

Consider an agile sprint or a planned version. Both usually set what features to implement and what bugs to fix. It's important to stick to those set goals in order to actually achieve them. Even if you don't create issues for bugs you fix during your development phase, they cost you time. And that's time you might not have. Obviously, you know those bugs need fixing. But even for your management, it's often probably easier to explain to a customer that another release cycle of a week or two is needed in order to get everything bug-free, than to explain why all deadlines were missed. If people depend on releases, development should work toward them and appreciate that no release ever will be perfect. Seeing a bug is half the battle.

Rethink your last paragraph. Creating new issues does not change the list of things you're currently working on. It only changes the backlog that may or may not need addressing (possibly depending on the outcome of the current sprint that you get done in time).

Title: Should you write down a list of issues, or fix issues as they arise?

Body:
I have observed a strange trend in the company I work at.

There are people who insist that there should be a list of tasks. They estimate those tasks, implement them, and try to meet their commitments. However, while they are coding, the requirements are likely to change. The priorities shift, the tasks increase or decrease, and the scope may just down right change, causing the whole work to get discarded.

And then, there is another team, who meet issues and fix them as they arise. There are no estimates, there are no priorities, there are no set deadlines, and mission statements for sprints go something like, “Fix the bugs in the [insert subsystem name here]”.

Now, which is the right way to go about being agile when you have technical sprints that focus only on stabilizing the system? Should you try and gather a list of issues, only to have them change, or should you try and fix-as-you-go, without saying when you’ll be done?


答:
If you need to store data along with documents - take a look at Sql server's FileStream feature.

If you don't - store them on a file system, but put each week/year in its own directory to keep the number of file in a single folder to a few thousands. That will keep it fairly fast.


答:
I've been doing XP for a few years now and I find this discussion a bit off. I've never done a sprint that focuses on bug fixes/stabilization; I've also never fixed bugs as I find them.

Instead, I've always followed a standard process:

If the bug is in the code I am working on, I fix it. I'll also log it and isolate it in SCC so that the bug fix isn't treated as part of my story.

If the bug is in another area of the app, log it.

That allows you to finish your story without constantly being interrupted by other tasks. Without this type of discipline, estimating is near impossible because how long a task will take depends upon the size of the tasks AND how many bugs you'll find.

Additionally, by recording the bug, you allow:
 1. All bugs to be visible to the entire project team.
 2. Let developers group bugs when working on them.
 3. Anyone, not just developers, to report (and record) bugs.
 4. Bugs to be prioritized with user stories which means priority is getting established by your

Product Owner instead of by the dev's.


问:
The user interface in a clean architecture with client / server model
I have been reading (and watching presentations) about subjects like: DDD, TDD, BDD, SOLID (principles), design patterns, clean code, clean architecture, agile project methodologies.

All in all I have quite a clear view on how to approach agile software development. Especially the DDD part really helps in communicating to all involved in the team (stakeholders, product owners, team members, etc).

Developing good software is tough and I really value the opinions of experienced developers. They however say things like: "The user interface (or database) is an implementation detail".

If you are looking from the core value of the product that is certainly true. In reality however, the end user solely deals with the user interface. To make our product really useful we need to have an excellent user experience.

Let's say that we have a single page html/css/javascript client. Designing and creating all of the "only user interface" stuff is quite doable. I run into trouble with the following things:

Domain logic - It lives in my domain model on the server. It feels fragile to duplicate it in the client. Exposing those parts of the domain model on the server might be an option, but that would probably create a lot of requests (a performance issue). Yet requiring the user to enter a value between 0 and 42 is clearly a business rule.

User stories / Scenarios / Behavior / Use cases - Whatever you call it. The server is able to handle the use cases, if we've done it well they are nicely specified by behavioral specifications. The user interface should implement a 'view' or 'guide' for these scenarios. We should probably reuse these right?

I could not find anything about the combination of these things. Do you have any resources or idea's about this?

There must be some smart person that has said something very enlightening about this subject, otherwise: here's your chance

答:
How much domain logic you have in the client-side UI will depend largely on how much interactivity and responsiveness you want in the UI.

For example, let's say you want to validate some field that the user enters.  Maybe that validation involves other fields on the form (you asked for socks, but you didn't specify what color of socks you wanted).  In most systems with low interactivity, this would involve a round-trip to the server, where the server would validate all of the fields, and then send a new page to the client with the fields that didn't validate highlighted, along with some useful error messages.

On a high-interactivity form, you wouldn't get a postback.  Instead, the form would simply tell you "you forgot to specify a color for your socks," and hold off on the postback until you specified a color.

Or maybe you're putting in the Year, Make and Model of a car (what we call "cascading dropdowns").  On most decent web pages, this requires an AJAX trip to the server to update the next dropdown, based on the previous dropdowns.  Poorly-designed web pages require a POST and a complete re-rendering of the entire page just to update the next dropdown list.

Well-designed, high-interactivity pages work just like desktop applications.  This used to be done with Flash, but now you can do it very well with web applications (See Single-Page Applications for a proof of concept).

Of course, you still need to validate again on the server, since you ultimately can't trust the data that a client sends you, even if the client has validation logic.


问:
What would you add in this Software Development Project Checklist?
I'm a big fan of checklists. There is Travel Checklist, Moving Checklist and even a Scrum Checklist.

Context: you have been hired by a large corporation and given the mission to setup the whole software development environment, processes, team, etc. You have "carte blanche". You will be responsible for the creation of the working increments of the software. Project size: 2000 man/days.

What items would you add to the following (intentionally small and incomplete) checklist:

Install a Continuous Integration Server

Write a DoD

Write a one page coding guidelines

Create a product backlog

Install a Bug Tracking System

Schedule Regular Face Time

答:
* 1.)  Talk to the developers to see what they really need! *

2.)  Investigate a solution for bringing up multiple environments really rapidly (think public or private cloud instances or old fashioned virtual machines if you'e not buzzword compliant)

3.)  Source/version control

4.)  Code review system (Crucbile/Fisheye as an example)

5.)  Kanban wall (or something similar)

6.)  Communication protocols (real time chat is a big plus), wikis also encourage collaboration.  This also covers public relations internally - how are you going to engage with your business owners, tech support staff and other groups?

7.)  Electronic whiteboards

8.)  Comfortable environment for developers (couches, tables, chillout areas, good WiFi etc)

9.)  Great coffee!!!


问:
Load all templates at startup?
I am developing a jQuery mobile app. In this app, i often use Mustache.js templates in separate html files. Actually, every template is needed by the user, but my app loads a template (via GET method) only when it is needed.

For now, all the templates are small and they're all used by the client at runtime. But obviously this won't be the case for long, in case I add extensions that will be needed or not by the users.

I could load every template at once, but I'm afraid this could become a blocking point in the future.
Based on your experience, what is the best thing to do? Load all templates at once, or load them one by one, when needed?

答:
When your users are working with smatphones and slow internet connections (gprs, 3g, etc) you should reduce the number of async loaded templates. Cause the low latency networks will slow down your app or maybe break it completely at a request timeout.

On the other side it makes no sense to load so much data in the first initial request if you're talking about hundrets of templates which won't be used, cause your users only see 3 or 5 views. So it depends on your app, the users and their environments.

A better approach would be a seperation of all code (Views + JavaScript) by some kind of area or category of your app. Then the user only has to load what he is currently using.

Title: Load all templates at startup?


问:
In scrum, how do you give an estimate for a backlog item that is primarily research?
A few sprints ago I was assigned a task that was primarily research.  I had to figure out how to get our product to interoperate with a very complex black box that we did not develop.

I couldn't think of a way to estimate this work.  Even if I got the ball rolling and knew the immediate problem I faced, I could not get a sense of how many other problems I'd have to solve after that.  I could never tell if I was almost done or far from it.  How am I supposed to estimate a backlog item like this?

I want to elaborate the nature of this assignment.  I knew what calls I had to make to interoperate with the black box.  That was the easy part.  But the API took a very, very complex object as a parameter.  Calling the API would throw an error and it was not easy to figure out what that error was trying to tell me.  The black box wouldn't tell me all the problems wrong with my request, it would just tell me the first problem it found.  This made it very difficult to know how much work I had left.

答:
That's why they call them estimates.

An accurate estimate for purely research-related work is improbable. That's the nature of research. But I think it's worthwhile to point out that sometimes you think you can't estimate it, when in actual fact, you can.  Scientists know this; most research work is repetitive and mundane... it's the theorizing and changes in direction that cause variations in the required time to occur.

So the way you come up with an estimate for research-related work is the same way you would come up with an estimate for ordinary development:  break the task into smaller pieces, and evaluate each piece separately.  Research work is no different in that regard from ordinary, non-research development; you quantify the work, and then give it your best guess.

For example, you might not be able to estimate the task "Determine how this black box works, and how to interface our software product with it."  But you may be able to come up with independent estimates for:

Evaluate and understand the black box's API

Evaluate the behaviors of the black box

Determine what commands will execute the behaviors we want

Analyze, identify and mitigate possible safety concerns

Map commands from our software to commands in the black box, and evaluate the returned data.

And so forth.

Some estimates may depend on the completion of previous steps.  For example, estimating step #3 may not be possible until step #2 is completed.