答:
If you're working in a language or environment that either warns or produces an error on variable = constant, I would suggest sticking with the variable-on-the-left standard that you already use.

Technically, both are equivalent. I'd argue that the former better expresses how we tend to think about truth values, however. For example, taking variable == constant and constant == variable and replacing them with some values:

```<code>if (boolResult == True) { ... } // variable == constant
</code>```

or

```<code>if (True == boolResult) { ... } // constant == variable
</code>```

These are both valid comparisons, but we generally don't think in terms of the constant value (True) as being the thing tested. It's less obvious when using literals like 34 or "string" but I think the concept still holds. In English, at least, we express this kind of statement where the variable, the thing to be tested, is the subject.

```<code>"If The-Weather is Nice, I'll talk a walk"
</code>```

Granted, this may not be true for all natural languages, and it's getting a bit nit-picky to argue over this for too long.

It's more important to be consistent about how you approach your conditional checks. This is true for most aspects of programming. Pick the method that makes more sense to you, and stick with it.

Title: In which order should I do comparisons?

Body:
I'm a strong proponent of writing if statements like this:

```<code>variable == constant
</code>```

Because to me it just makes sense, it is more readable than the inverted:

```<code>constant == variable
</code>```

Which seems to be used a lot by C-programmers. And I see the use, namely that the interpreter or compiler will throw an error and let you know if you're not doing a comparison. But still it is less readable, and for that reason alone I don't think comparisons should be written in the manner of the second example.

The actual question is:

Does it exist a general best practice for this, or is it different depending on language/religion/age/etc..?

I'm happy that so many seem to understand why you'd want to do as in the latter example, but that is not what I'm asking about.

Body:
If you're working in a language or environment that either warns or produces an error on variable = constant, I would suggest sticking with the variable-on-the-left standard that you already use.

Technically, both are equivalent. I'd argue that the former better expresses how we tend to think about truth values, however. For example, taking variable == constant and constant == variable and replacing them with some values:

if (boolResult == True) { ... } // variable == constant

or

if (True == boolResult) { ... } // constant == variable

These are both valid comparisons, but we generally don't think in terms of the constant value (True) as being the thing tested. It's less obvious when using literals like 34 or "string" but I think the concept still holds. In English, at least, we express this kind of statement where the variable, the thing to be tested, is the subject.

"If The-Weather is Nice, I'll talk a walk"

Granted, this may not be true for all natural languages, and it's getting a bit nit-picky to argue over this for too long.

It's more important to be consistent about how you approach your conditional checks. This is true for most aspects of programming. Pick the method that makes more sense to you, and stick with it.


问:
What are best practices for caching paginated results whose ordering/properties can change?
What is the best practice for caching paginated search results whose ordering/properties can be changed?

Say, in my application, someone wants to see the last 20 discussion threads (out of 10,000). A request would be sent to the database, via servlet, to fetch the first 20 records from the discussion threads table as XML/JSON. If they then want to see the next 20, they go onto the next page of results and this fires off another request to get the next lot (limit and offset = 20, etc.).

In order to reduce server load and client-waiting, I would like to cache the previous pages of results. However, I have two questions:

The table the results are shown in can be ordered by more than one attribute (i.e., thread-creation-date, thread-author, last-post-date). This means that a statement like 'first 20 results' makes no sense without context (i.e., what are we ordering by).  How does the front-end, then, communicate to the back-end what it has already loaded? My first thought was to use IDs for each result but sending these back to the server on subsequent requests (and filtering results based on them) would just as time-consuming as sending everything back blindly. How can I do this?

What if an attribute of a previously returned result (i.e., most-recent-post-date) has changed? We then need a way of checking each result to see if it's been modified server-side since it was paged in. How can I do this?

答:
Just a thought - in your server call, pass in the usual parameters plus an array of MD5 hashes representing currently cached previously viewed pages of data.

The return call would contain all the usual data for the new current page, plus updates for any outdated previously viewed pages.  You can use the old hash as the key.

I'd recommend a lot of performance & timing tests first - your client side code is going to be a lot more complicated than it would be if you simply hit the server for each page of data.  Be sure the extra complexity results in a meaningful improvement.

ContentLicense: CC BY-SA 3.0


问:
is down-casting always bad?
At my company, we have many different "services" that work in parallel and send messages to each other using a common messaging system. All message objects are derived from a common generic object we defined for messaging. When any service receives a message, the first thing it must do is downcast the object to the derived type so that it can extract the data needed.

I have read all over the internet that you should not have to downcast a base object pointer to a derived object pointer and that having to do this is often a sign of bad design. I agree with this sentiment for most cases. And I can imagine different designs for the generic message object that wouldn't necessitate down-casting. But I don't see any big reason to handle this situation differently.

So my overall question is: Is down-casting always a bad thing? Are there situations in which down-casting is necessary or acceptable?

答:
Yes, downcasting is always bad. Yes, occasionally you will run into scenarios (like messaging constructs) where the alternatives are worse.

And of course "worse" is subjective. In some scenarios, the fragility of down casting is very unacceptable. In others, simplicity of design or readability might have higher priority. Like any other design decision, it is a trade-off you'll need to evaluate for your situation.

Title: is down-casting always bad?


答:
Downcasting a pointer vs making a generic payload into a specific object are two different things.

The common messaging system API should have a set of functions for returning the exact object you want so that you aren't constantly downcast in your application code (which is more error-prone).

You're basically talking about passing around objects using XML or JSON or some other data interchange format. Talking about downcasting is unnecessary because it should already be handled by the common messaging system API since you know exactly what sorts of objects are being passed around.

I'm assuming the system API looks like this:

```<code>GeneralObject* getObject(Message *message);
</code>```

It should look like this:

```<code>GeneralObject* _getObject(Message *message); // the _ is just to indicate this is a private function that shouldn't be used outside of this module

// these raise exceptions if the object doesn't exist or return null or whatever
Person* getPerson(Message *message);
Place* getPlace(Message *message);
</code>```

Never in your code will you use the generic function that returns the base class, you'll always use the code that returns the derived classes and let the API handle or raise errors if it can't downcast.

Downcasting in this case is basically failing to parse or de-serialize an object.

Google's protobuf library has an example of what I'm talking about

Title: is down-casting always bad?

Body:
At my company, we have many different "services" that work in parallel and send messages to each other using a common messaging system. All message objects are derived from a common generic object we defined for messaging. When any service receives a message, the first thing it must do is downcast the object to the derived type so that it can extract the data needed.

I have read all over the internet that you should not have to downcast a base object pointer to a derived object pointer and that having to do this is often a sign of bad design. I agree with this sentiment for most cases. And I can imagine different designs for the generic message object that wouldn't necessitate down-casting. But I don't see any big reason to handle this situation differently.

So my overall question is: Is down-casting always a bad thing? Are there situations in which down-casting is necessary or acceptable?

Body:
Downcasting a pointer vs making a generic payload into a specific object are two different things.

The common messaging system API should have a set of functions for returning the exact object you want so that you aren't constantly downcast in your application code (which is more error-prone).

You're basically talking about passing around objects using XML or JSON or some other data interchange format. Talking about downcasting is unnecessary because it should already be handled by the common messaging system API since you know exactly what sorts of objects are being passed around.

I'm assuming the system API looks like this:

GeneralObject* getObject(Message *message);

It should look like this:

GeneralObject* _getObject(Message *message); // the _ is just to indicate this is a private function that shouldn't be used outside of this module

// these raise exceptions if the object doesn't exist or return null or whatever
Person* getPerson(Message *message);
Place* getPlace(Message *message);

Never in your code will you use the generic function that returns the base class, you'll always use the code that returns the derived classes and let the API handle or raise errors if it can't downcast.

Downcasting in this case is basically failing to parse or de-serialize an object.

Google's protobuf library has an example of what I'm talking about


答:
Obviously, if it were always a bad thing, there would be no need for the language to even support the operation.  Serialization/messaging is one big exception, because the downcast generally greatly simplifies the code, although you should really build the cast into the message queue object.  Templates are often useful in that case.

The other situation I've seen where downcasts are often unavoidable is in equals(Object obj) overrides, since that specific signature is part of a published, widely-used interface.

Title: is down-casting always bad?


问:
Can commented-out code be valuable documentation?

I wrote the following code:

if (boutique == null) {
    boutique = new Boutique();

    boutique.setSite(site);
    boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
    boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
    boutique.setNom(fluxBoutique.getNom());
    boutique.setSelected(false);
    boutique.setIdWebSC(fluxBoutique.getId());
    boutique.setDateModification(new Date());

    boutiqueDao.persist(boutique);
} else {
    boutique.setSite(site);
    boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
    boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
    boutique.setNom(fluxBoutique.getNom());
    //boutique.setSelected(false);
    boutique.setIdWebSC(fluxBoutique.getId());
    boutique.setDateModification(new Date());

    boutiqueDao.merge(boutique);
}
```

There is a commented-out line here. But I think it makes the code clearer, by making obvious what the difference is between if and else. The difference is even more noticeable with color highlighting .

Can commenting out code like this ever be a good idea?

答:
In this specific example, I find the commented-out code very ambiguous, largely for the reasons outlined in Dibkke's answer. Others have suggested ways that you could refactor the code to avoid even the temptation to do this, though, if that's not possible for some reason (e.g., the lines are similar, but not quite close enough), I would appreciate a comment like:

// No need to unselect this boutique, because [WHATEVER]

However, I think there are some situations where leaving (or even adding commented out) code is not reprehensible. When using something like MATLAB or NumPY, one can often write equivalent code that either 1) iterates over an array, processing one element at a time or 2) operates the entire array at once. In some cases, the latter is much faster, but also a lot harder to read. If I replace some code with its vectorized equivalent, I embed the original code in a nearby comment, like this:

%% The vectorized code below does this:

```<code>% for ii in 1:N
%    for jj in 1:N
%      etc.
</code>```

% but the matrix version runs ~15x faster on typical input (MK, 03/10/2013)

Obviously, one needs to take care that the two versions actually do the same thing and that the comment either stays in sync with the actual code or is removed if the code changes. Obviously, the usual caveats about premature optimization also apply...

Body:
In this specific example, I find the commented-out code very ambiguous, largely for the reasons outlined in Dibkke's answer. Others have suggested ways that you could refactor the code to avoid even the temptation to do this, though, if that's not possible for some reason (e.g., the lines are similar, but not quite close enough), I would appreciate a comment like:

// No need to unselect this boutique, because [WHATEVER]

However, I think there are some situations where leaving (or even adding commented out) code is not reprehensible. When using something like MATLAB or NumPY, one can often write equivalent code that either 1) iterates over an array, processing one element at a time or 2) operates the entire array at once. In some cases, the latter is much faster, but also a lot harder to read. If I replace some code with its vectorized equivalent, I embed the original code in a nearby comment, like this:

%% The vectorized code below does this:

% for ii in 1:N
%    for jj in 1:N
%      etc.

% but the matrix version runs ~15x faster on typical input (MK, 03/10/2013)

Obviously, one needs to take care that the two versions actually do the same thing and that the comment either stays in sync with the actual code or is removed if the code changes. Obviously, the usual caveats about premature optimization also apply...


问:
In which order should I do comparisons?
I'm a strong proponent of writing if statements like this:

```<code>variable == constant
</code>```

Because to me it just makes sense, it is more readable than the inverted:

```<code>constant == variable
</code>```

Which seems to be used a lot by C-programmers. And I see the use, namely that the interpreter or compiler will throw an error and let you know if you're not doing a comparison. But still it is less readable, and for that reason alone I don't think comparisons should be written in the manner of the second example.

The actual question is:

Does it exist a general best practice for this, or is it different depending on language/religion/age/etc..?

I'm happy that so many seem to understand why you'd want to do as in the latter example, but that is not what I'm asking about.

答: if (a = 2) will get caught the first time the programmer tests with a value other than 2, and no one can claim to be programming "safely" who didn't perform that test at least once.  In other words, it only increases safety if you're already programming somewhat recklessly, so most people go with the version that is more readable.  In English, that's variable == constant.  That might be different in other languages, or in very specific domains, but in general most people expect to see conditions written in that order.

Title: In which order should I do comparisons?


问:
Is there a way to calculate whether to spawn a new thread or use current thread
I am building an interpret DSL in which parallelism is part of the language - the user simply states that a calculation can be done in parallel and the interpreter may decide whether to make the calculation in parallel or not. Since it is not always helpful to do parallel calculations, specially for very small jobs (context switch, memory copying between cores, etc may actually make the program slower).

I want to know if there are any "best practices" available that can calculate (with high degree of certainty) whether to do a new calculation in the current thread or spawn a new thread for the calculation. Note that since my language is interpreted, I can do all kinds of monitoring on the executed program and make this decision depending on how the program executes (kind of a JIT compiler).

Update By "Spawn" I didn't mean that I will create a new thread, but transfer the processing to a different thread, maybe from a thread pool. Note that even when using a thread pool there is overhead of possible memory transfer between processor cores and stuff like that, so even in this case the amount of work should be relatively high.

答: My initial thought is that everytime you find a parallel construct, you first run it serially measuring the time it takes to complete. If it takes a long enough time, switch over to parallel the next time the operation executes. The theory is that the operation probably takes a similar amount of time each time it is executed.</p>


答:
No, commented code gets stale, and is soon worse than worthless, it is often harmful, as it cements some aspect of implementation, along with all of the current assumptions.

Comments should include interface details and intended function; "intended function": can include, first we try this, then we try that, then we fail this way.

The programmers that I have seen try to leave things in comments are just in love with what they have written, don't want to lose it, even if it is not adding anything to the finished product.

Title: Can commented-out code be valuable documentation?

Body:
I wrote the following code:

if (boutique == null) {
    boutique = new Boutique();

    boutique.setSite(site);
    boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
    boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
    boutique.setNom(fluxBoutique.getNom());
    boutique.setSelected(false);
    boutique.setIdWebSC(fluxBoutique.getId());
    boutique.setDateModification(new Date());

    boutiqueDao.persist(boutique);
} else {
    boutique.setSite(site);
    boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
    boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
    boutique.setNom(fluxBoutique.getNom());
    //boutique.setSelected(false);
    boutique.setIdWebSC(fluxBoutique.getId());
    boutique.setDateModification(new Date());

    boutiqueDao.merge(boutique);
}
```

There is a commented-out line here. But I think it makes the code clearer, by making obvious what the difference is between if and else. The difference is even more noticeable with color highlighting .

Can commenting out code like this ever be a good idea?


答:
This approach is also known as "Yoda conditions" ("if true the condition is"), and its purpose is to catch the common error in C-like languages, where you accidentally use a single = when you mean ==, causing an assignment. Because the return value of such an assignment is the newly assigned value, such a bug can go unnoticed, and surface only much later in the code, at a seemingly unrelated location, and seemingly at-random. Such bugs are obviously the worst kind you can have, and so the "Yoda" convention reverses the operands - a constant is not an lvalue, and accidentally putting one on the left side of an assignment causes a compiler error, which is good because it means the error surfaces early on, in an easy-to-debug way.

However, the Yoda convention has some significant downsides:

It comes at the cost of readability. "If the number of items is 4" is easier to read than "If 4 is the number of items", and this is also true for code.

It relies solely on convention; there is nothing stopping a programmer from forgetting the convention, and you're back to square one. In other words, the convention cannot be enforced, and so you still don't have any guarantees.

It only works for comparing against non-lvalues. If you compare two variables, both sides are lvalues, and you're not winning anything.

At the same time, compilers have advanced, in such a way that they are now able to detect what is probably an unintended assignment in a condition - quite simply, if you use = inside an if condition, the compiler will throw a warning. This check is easy to automate and enforce: just turn on the relevant compiler flags in your build script to treat this as a fatal error. This, of course, works for any kind of equals-comparison, regardless of lvalues, and it doesn't compromise readability in any way.

You are most likely to find Yoda conventions used in older projects, and when it is in place, it's probably better to stick with it, but I would not recommend using it in new projects - the benefit today is practically zero, and it's not worth the sacrifice in readability.

Title: In which order should I do comparisons?


问:
When to pay for C++ compilers
Recently I have began to wonder when developers should pay for compilers. Compilers come for free with most platforms or there is a free version easily obtainable.

Example:

OS X - GCC and Clang/LLVM come with the developer tools. No limitations here for how and what you can turn out with them.

Linux - GCC and I am sure more. I dont know the current state of linux compilers. No limitations here for how and what you can turn out with them.

Windows - MinGW and Microsoft does offer a free version of Visual Studio. No limitations with MinGW but I think with the free Visual Studio there are severe limitations.

However, as an example, Intel produces C/C++ compilers. They are hefty in price. Educationally I think that one can get the OS X version for $49 and Windows/Linux for $129 each. They then offer a complete "Studio" product too. Obviously using the educational pricing there are imposed limitations.

But what I am wondering is when should one really considering paying for compilers. One example I can think of is a video game. If you are using a compiler that works on the major platforms there would be no more switching tools for the platform. It seems there would be a level of ease in switching among platforms if the tools were the same.

Can anyone shed some light on paying for compilers like the Intel compilers and the true cross-platform benefits one might get from using them? Does one's code become less portable even trying very hard to not do platform specific techniques?

答:
I have worked with some people that used a paid compiler.

They were doing serious data-crunching in a cluster. Supposedly, the Intel compiler managed to produce slightly faster code for them, and paying for the compiler was cheaper than running more nodes. My understanding is that the difference was very small, but multiplied out with electricity costs factored in it was deemed worth it.

To that effect, I wouldn't be surprised if most of the HPC super-computers run on specialized compilers provided by the chip manufacturers.

Title: When to pay for C++ compilers


问:
How to know if an Open Source project is mature enough to use in a product?
There are some open source projects that I'd like to incorporate into a product at work.  We don't have the bandwidth nor the subject matter expertise to do it ourselves.  I found these by searching in Google.  I'm unaware of any "major players" that utilize the projects, but I'm pretty encouraged by what I see.

Now, I'm a bit concerned about the amount of risk I'm exposed to by using joe-blow's open source project.  If it takes me 95% of the way there, perhaps the remaining 5% is easy to add or fix.  Perhaps it's non-trivial.

How do people go about determining whether an open source project is mature enough to use in a product?

This is not a hobby project, so stability, maintainability, etc. are paramount.

答: Look in the project's bug tracker.  If you see lots of tickets filed by lots of different people, and responses coming from a variety of people too, then that's a good sign.  More bug tickets == bigger user community == more likely to be ready for production use by you.</p>

ContentLicense: CC BY-SA 4.0


问:
3 Tier Application Architecture, logic and database
(Note: The examples are simplified)

I've seperated my solution into 3 projects

WebSite

Business Logic

Data Access Logic

The Website has access to BL and DAL

The BL has access to nothing

The DAL has access to the BL

On the website I can do something like

```<code>BL.User user = DAL.GetUser(1)
</code>```

I also have this type of logic in the website

```<code>user = [new user information]

If Not DAL.DoesEmailExists(user) Then
    DAL.InsertNewUser(user)
End If
</code>```

What would be my option to remove this if/insert from the website?

My ideal option would be to put this logic inside the BL.User but that's not possible. If the BL has access to the DAL it will make a circular reference.

答:
I assume its ASP.NET webforms, go through building layered applications series by Imar Spaanjaars which explains same concept you've described. In short, below is the approach.

Presentation Layer

From aspx.cs:

```<code>var objCustomer = CustomerBLL.GetCustomerById(id);
if(objCustomer != null)
{
  //assign values to UI controls
}
</code>```

In Business Logic Layer

```<code>public static class CustomerBLL
{
  public static Customer GetCustomerById(int id)
  {
    //call database layer
    return CustomerDAL.GetCustomerById(id);
  }
}
</code>```

In Data Access Layer

```<code>public static class CustomerDAL
{
  public static Customer GetCustomerById(int id)
  {
    Customer objCustomer = new Customer();
    //use ADO.NET or any data access methodology to retrieve data
    //and assign properties of objCustomer
    return objCustomer;
  }
}
</code>```

Business Objects

These are just DTO's that are used to pass data between layers. It gets referenced in both Business Logic and Data Access Layers.

```<code>public class Customer
{
   public string Name {get;set;}
  //other properties
}
</code>```

IMO, it works well with small to medium scale applications.

Edit

Depending upon your code, both layers DAL and BLL are getting called from presentation layer. So there is no right answer, unless we know responsibility of each layer and how it is designed.

On the website I can do something like

```<code>BL.User user = DAL.GetUser(1)
</code>```

I also have this type of logic in the website

```<code>user = [new user information]

If Not DAL.DoesEmailExists(user) Then
    DAL.InsertNewUser(user)
End If
</code>```

From existing code, as mentioned in the comments section, try this way:

Website

```<code>DAL.UpsertUser(objUser);
</code>```

In store proc:

```<code>IF EXISTS(select 1 FROM users where userid = @userid)
BEGIN
    --insert
END
ELSE
BEGIN
   --update
END
}
</code>```

It works for both insert/update.

Body:
I assume its ASP.NET webforms, go through building layered applications series by Imar Spaanjaars which explains same concept you've described. In short, below is the approach.

Presentation Layer

From aspx.cs:

var objCustomer = CustomerBLL.GetCustomerById(id);
if(objCustomer != null)
{
  //assign values to UI controls
}

In Business Logic Layer

public static class CustomerBLL
{
  public static Customer GetCustomerById(int id)
  {
    //call database layer
    return CustomerDAL.GetCustomerById(id);
  }
}

In Data Access Layer

public static class CustomerDAL
{
  public static Customer GetCustomerById(int id)
  {
    Customer objCustomer = new Customer();
    //use ADO.NET or any data access methodology to retrieve data
    //and assign properties of objCustomer
    return objCustomer;
  }
}

Business Objects

These are just DTO's that are used to pass data between layers. It gets referenced in both Business Logic and Data Access Layers.

public class Customer
{
   public string Name {get;set;}
  //other properties
}

IMO, it works well with small to medium scale applications.

Edit

Depending upon your code, both layers DAL and BLL are getting called from presentation layer. So there is no right answer, unless we know responsibility of each layer and how it is designed.

On the website I can do something like

BL.User user = DAL.GetUser(1)

I also have this type of logic in the website

user = [new user information]

If Not DAL.DoesEmailExists(user) Then
    DAL.InsertNewUser(user)
End If

From existing code, as mentioned in the comments section, try this way:

Website

DAL.UpsertUser(objUser);

In store proc:

IF EXISTS(select 1 FROM users where userid = @userid)
BEGIN
    --insert
END
ELSE
BEGIN
   --update
END
}

It works for both insert/update.


答:
This type of code actually belongs in the Business Layer, from where you control the behavior of your application, make decisions about inserting an object or displaying an alert to the user, etc.,

```<code>// BL
If Not DAL.Exists(user) Then
    DAL.InsertNewUser(user)
Else
    // Maybe warn the user about inserting a duplicate user object
    WL.Alert("User already exists!")
End If
</code>```

You BL should then have access to both the DAL and the WL, and your DAL should not have a dependency on the BL (it only knows how to retrieve data on demand). Do not confuse a Business Object (BO), which can also be a Data Transfer Object (DTO), with a BL: a BO is simply for transferring or passing data from layer to layer.

Title: 3 Tier Application Architecture, logic and database

Body:
(Note: The examples are simplified)

I've seperated my solution into 3 projects

WebSite

Business Logic

Data Access Logic

The Website has access to BL and DAL

The BL has access to nothing

The DAL has access to the BL

On the website I can do something like

```<code>BL.User user = DAL.GetUser(1)
</code>```

I also have this type of logic in the website

```<code>user = [new user information]

If Not DAL.DoesEmailExists(user) Then
    DAL.InsertNewUser(user)
End If
</code>```

What would be my option to remove this if/insert from the website?

My ideal option would be to put this logic inside the BL.User but that's not possible. If the BL has access to the DAL it will make a circular reference.

Body:
This type of code actually belongs in the Business Layer, from where you control the behavior of your application, make decisions about inserting an object or displaying an alert to the user, etc.,

// BL
If Not DAL.Exists(user) Then
    DAL.InsertNewUser(user)
Else
    // Maybe warn the user about inserting a duplicate user object
    WL.Alert("User already exists!")
End If

You BL should then have access to both the DAL and the WL, and your DAL should not have a dependency on the BL (it only knows how to retrieve data on demand). Do not confuse a Business Object (BO), which can also be a Data Transfer Object (DTO), with a BL: a BO is simply for transferring or passing data from layer to layer.


问:
Visiting points on a number line while minimizing a cost not related to distance
I need some help on this ACM ICPC problem. My current idea is to model this as a shortest path problem, which is described under the problem statement.

Problem

There are N = 1000 nuclear waste containers located along a 1-D number line at distinct positions from -500,000 to 500,000, except x=0. A person is tasked with collecting all the waste bins. Each second that a waste container isn't collected, it emits 1 unit of radiation. The person starts at x = 0 and can move 1 unit every second, and collecting the waste takes a negligible amount of time. We want to find the minimum amount of radiation released while collecting all of the containers.

Sample Input:

4 Containers located at [-12, -2, 3, 7].

The best order to collect these containers is [-2, 3, 7, -12], for a minimum emitting of 50 units. Explanation: the person goes to -2 in 2 seconds and during that time 2 units of radiation are emitted. He then goes to 3 (distance: 5) so that barrel has released 2 + 5 = 7 units of radiation. He takes 4 more seconds to get to x = 7 where that barrel has emitted 2 + 5 + 4 = 11 units. He takes 19 seconds to get to x = -12 where that barrel has emitted 2 + 5 + 4 + 19 = 30 units. 2 + 7 + 11 + 30 = 50, which is the answer.

Notes

There is an obvious O(N!) solution. However, I've explored greedy methods such as moving to the closest one, or moving to the closest cluster but those haven't worked.

I've thought about this problem for quite a while, and have kind of modeled it as a graph search problem:

We insert 0 in as a baseline position (This will be the initial state)

Then, we sort the positions from least to greatest.

We then do a BFS/PFS, where the state consists of

Two integers l and r that represent a contiguous range in the sorted position array that we have visited already

An integer loc that tells us whether we're on the left or right endpoint of the range

An integer time that tells us the elapsed time

An integer 'cost' that tells us the total cost so far (based on nodes we've visited)

From each state we can move to [l - 1, r] and [l, r + 1], tweaking the other 3 integers accordingly

Final state is [0, N], checking both ending positions.

However, it seems that [L, R, loc] does not uniquely define a state, and we have to store L, R, loc, and time, while minimizing cost at each of these. This leads to an exponential algorithm, which is still way too slow for any good.

Can anyone help me expand on my idea or push my into the right direction?

Edit: Maybe this can be modeled as a dynamic programming optimization problem? Thinking about it, it has the same issues as the graph search solution - just because the current cost is low doesn't mean it is the optimal answer for that sub problem, since the time also affects the answer greatly.

Greedy doesn't work: I have a greedy selection algorithm that estimates the cost of moving to a certain place (e.g. if we move right, we double the distances to the left barrels and such).

Could you do a Priority-first search, with a heuristic? The heuristic could combine the cost of the current trip with the amount of time elapsed.

答:
Partial solution - I'll get back to it later.

Assume the "default" strategy is run all the way left or right, whichever is cheaper.  Now ask, is it worth a little side trip the other way to pick up one barrel.  It's fairly easy to calculate the answer.

For you sample input, running all the way right is cheaper than all the way left.  Is going to -2 worth a side trip?  It reduces the cost of running all the way right and then back to 0 by 14 (because you were "paying" 4 radiation units per move from 0 to 3 on the default strategy, now it's down to 3, you  were paying 3 from 3 to 7, now it's 2, etc), plus reduces by one per move your cost of moving from 0 to -2, thus saving 2 more for a total of 16.

However, it adds a cost of going to -2 then back to 0 of 14 (4 units per move to -2, 3 per move back to 0), for a net gain of (16-14)=2.  Note that to calculate this you don't have to evaluate the exact cost of solving the whole problem for each decision - you have enough information to decide just by knowing if running all the way left is cheaper than running all the way right, plus how many waste containers are on each side of you, and the distance to the nearest 2.  So that's O(N^2).

Except for one important problem - I've assumed you will run all the way to the end, and we know you might double back.  To clean that up, we need to update my calculation.  For the sample input, I've assumed you would save 14 by emitting 1 less total radiation per unit per second while running from 0 to 7 and back.  But, if you double back prior to running to 7, the savings will be reduced.

That's pretty bad, because, I don't know how to calculate the next double-back without trying all the possibilities, which puts us back to O(2^N).

Except - it's 2^N with pruning.  I calculated that the "side trip" to -2 cost 14, but gained 16, if I didn't have more side trips before I made it to the rightmost number.  If the rightmost number had been 5, I would immediately know the side trip to -2 couldn't pay off.  (Cost still 14, maximum benefit 12).  Nor do I have to consider going to -2 then making a side trip before reaching 6, since that is always inferior to just going straight to that point in the first place.


问:
Game Netplay Rollback System
Can one explain the specifics and details of a netplay framework for a game that optimizes connection through a "prediction / rollback" mechanic, as seen in games where speed is a priority (first-person shooters, modern fighting games since Street Fighter IV, etc)?

I have previously studied this article as an example: Source Multiplayer Networking, which describes Valve's techniques used in their shooters on a high, abstract level.  However, it is simply too high-level and theoretical to be of use to me.  Other similar articles follow this same pattern; none offer code samples or working examples.

I have previously crafted netplay systems that use unoptimized TCP/IP, which is obviously horrendously slow and non-useful for anything except LAN play.  Although I have taken a college course on network programming, I am only confident and experienced enough to have made this system through approximate copying of other pre-existing code.

答:
Prediction/rollback algorithms work similar to MPEG compression. MPEG predicts possible changes based on a previous frame. Follow up frames end up being mostly diffs off the previous frames. When there is a major change...or every so often a Keyframe is encoded to synchronize the true decompressed image with the actuals.

In a similar way rather than having to synchronize every action across all the clients, the host makes predictions about next frames (aided by facts it knows about the world -- this rocket will travel straight until it hits something) and the clients do the same.

The clients receive differences (player a changed direction) in the form of raw input and "key frame" updates from the server and synchronize their state to that. Sending input operations to the clients and a full synchronization every so often from the server decreases the chatter while still allowing the server to be the "master" of state.

I can't remember where I read this article that gave me an good understanding of the technique (either Gamasutra or one of the Game Programming Gems series), but it discusses how this was an improvement of the network stack between Doom 2 and Quake. I did find a nice example in C# that shows a Prediction algorithm that you can build on.

Here is a similar question on Gamedev about that very topic

Title: Game Netplay Rollback System


问:
Codeigniter/MVC workflow
Bit of a workflow question.

I'm just staring with MVC and wondered how other people usually work in MVC? The 2 options I see is to code the model and controller completely first and then work on the views after. The other option is to code all parts at the same time.

I'm looking for what might be the quickest most efficient way to code in MVC? We don't have inhouse designers or designated jobs so everyone does the same tasks (coding, designing, testing, db, etc).

Thanks!

答:
Work in the controller - get things working - then push the methods to the model, then refactor in the model, then push to more then one model if necessary.

Most of the CI experts I've read recommended 'skinny' model. another reason to do this is the idea of pushing the specific implementation details down. The controller should be as abstract as possible.

For example to do a form a validation - the controller says - 'validate this form' It does not need to know anything about the form. So then when your form changes, you go straight to the model that works with it.

One way to design is for the specific user role - Editor, Admin, Purchaser, etc - the person who is using the application at that moment. So then if you discover your classes are serving very different users (or use cases) - that's a sign they could be difficult to change in the future.

DRY is useless if a new developer can't read the code and understand what is going on. keep things simple and avoid the temptation to mash everything together in one method just because you can. (it updates! it inserts! it slices! it dices! its a maintenance nightmare!)

Learning Object oriented programming is not language dependent. Some of the best books and tutorials on OOP are in Java. Does not matter because the basic concepts are very similar.  It's also not a hot new thing where you have to get the latest book - there are great OOP books that were written a few years ago.

Title: Codeigniter/MVC workflow


答:
It seems what you need is a wrapper for all the parameters that define a page (say, pageNumber, pageSize, sortType, totalCount, etc.) and use this DataRequest object as the key for your caching mechanism. From this point you have a number of options to handle the cache:

Implement some sort of timeout mechanism to refresh the cache (based on how often the data changes).

Have a listener that checks database changes and updates the cache based the above parameters.

If the changes are done by the same process, you can always mark the cache as outdated with every change and check this flag when a page is requested.

The first two might involve a scheduler mechanism to trigger on some interval or based on an event. The last one might be the simpler if you have a single data access point.

Lastly, as @DanPichelman mentioned, it can quickly become an overly complicated algorithm that outweighs the benefits, so be sure the gain in performance justify the complexity of the algorithm.

Title: What are best practices for caching paginated results whose ordering/properties can change?

Body:
What is the best practice for caching paginated search results whose ordering/properties can be changed?

Say, in my application, someone wants to see the last 20 discussion threads (out of 10,000). A request would be sent to the database, via servlet, to fetch the first 20 records from the discussion threads table as XML/JSON. If they then want to see the next 20, they go onto the next page of results and this fires off another request to get the next lot (limit and offset = 20, etc.).

In order to reduce server load and client-waiting, I would like to cache the previous pages of results. However, I have two questions:

The table the results are shown in can be ordered by more than one attribute (i.e., thread-creation-date, thread-author, last-post-date). This means that a statement like 'first 20 results' makes no sense without context (i.e., what are we ordering by).  How does the front-end, then, communicate to the back-end what it has already loaded? My first thought was to use IDs for each result but sending these back to the server on subsequent requests (and filtering results based on them) would just as time-consuming as sending everything back blindly. How can I do this?

What if an attribute of a previously returned result (i.e., most-recent-post-date) has changed? We then need a way of checking each result to see if it's been modified server-side since it was paged in. How can I do this?


问:
Should I use Dependency Injection or static factories?
When designing a system I am often faced with the problem of having a bunch of modules (logging, database acces, etc) being used by the other modules. The question is, how do I go about providing these components to other components. Two answers seem possible dependency injection or using the factory pattern. However both seem wrong:

Factories make testing a pain and don't allow easy swapping of implementations. They also don't make dependencies apparent (e.g. you're examining a method, oblivious to the fact that it calls a method that calls a method that calls a method that uses a database).

Dependecy injection massively swells constructor argument lists and it smears some aspects all over your code. Typical situation is where constructors of more than half classes look like this (....., LoggingProvider l, DbSessionProvider db, ExceptionFactory d, UserSession sess, Descriptions d)

Here's a typical situation I have a problem with:
I have exception classes, which use error descriptions loaded from the database, using a query which has parameter of user language setting, which is in user session object. So to create a new Exception I need a description, which requires a database session and the user session. So I'm doomed to dragging all these objects across all my methods just in case I might need to throw an exception.

How do I tackle such a problem??

答:
You have already listed the disadvantages of the static factory pattern quite well, but I don't quite agree with the disadvantages of the dependency injection pattern:

That dependency injection requires you to write code for each dependency is a not a bug, but a feature: It forces you to think about whether you really need these dependencies, thereby promoting loose coupling. In your example:

Here's a typical situation I have a problem with: I have exception classes, which use error descriptions loaded from the database, using a query which has parameter of user language setting, which is in user session object. So to create a new Exception I need a description, which requires a database session and the user session. So I'm doomed to dragging all these objects across all my methods just in case I might need to throw an exception.

No, you're not doomed. Why is it the responsibility of the business logic to localize your error messages for a particular user session? What if, sometime in the future, you wanted to use that business service from a batch program (which doesn't have a user session ...)? Or what if the error message should not be shown to the currently logged in user, but his supervisor (who may prefer a different language)? Or what if you wanted to reuse business logic on the client (which doesn't have access to a database ...)?

Clearly, localizing messages depends on who looks at these messages, i.e. it is the responsibility of the presentation layer. Therefore, I'd throw ordinary exceptions from the business service, that happen to carry a message identifier that can then be looked up the presentation layer's exception handler in whatever message source it happens to use.

That way, you can remove 3 unnecessary dependencies (UserSession, ExceptionFactory, and probably descriptions), thereby making your code both simpler and more versatile.

Generally speaking, I'd only use static factories for things you need ubiquitous access to, and that are guaranteed to be available in all environments we could ever want to run the code (such as Logging). For everything else, I'd use plain old dependency injection.


问:
Should I make package private my DAO interfaces?
I have several DAO classes that implement an interface. In the other hand, I have Service classes that use those DAO implementations.

So far all the DAO interfaces are public and I was thinking if would it be better to make them package private and to put the service classes in the same package so they are the only ones being able to use them.

The reason is because I wouldn't like that programmers could use DAO implementations in a Controller or a web service without using the service layer. A programmer could think for example that adding  a new order is as simple as calling the addOrder dao method, ignoring that indeed there is a service method that does more than that.

What do you guys think?

答:
First, I would suggest that you package those two independently, and just offer proper documentation as to what the purpose of each library is. It will give you more flexibility in the long run, as you might have to bypass the Service layer at some point or use the Data layer as a common-functionality library for other projects.

That being said, I agree that you should restrict access to the DAOs, specially to avoid direct manipulation of your data store. However, this applies to the concrete version of your DAOs (your question is vague on this aspect). Having the interfaces public might be useful for other developers to provide their own implementation in case they want to use another type of data storage (assuming you provide a way of injecting DAOs into your service layer). This should follow along nicely with the Open/Closed Principle.


问:
Business Objects - Containers or functional?
This is a question I asked a while back on SO, but it may get discussed better here...

Where I work, we've gone back and forth on this subject a number of times and are looking for a sanity check. Here's the question: Should Business Objects be data containers (more like DTOs) or should they also contain logic that can perform some functionality on that object.

Example - Take a customer object, it probably contains some common properties (Name, Id, etc), should that customer object also include functions (Save, Calc, etc.)?

One line of reasoning says separate the object from the functionality (single responsibility principal) and put the functionality in a Business Logic layer or object.

The other line of reasoning says, no, if I have a customer object I just want to call Customer.Save and be done with it. Why do I need to know about another class to save a customer if I'm consuming the object?

Our last two projects have had the objects separated from the functionality, but the debate has been raised again on a new project.

Which makes more sense and why??

答:
I've been mulling over the same question for a while - I think the data component and the logic component must be seperate. I believe this because it gets you into the right frame of mind as regarding business logic as an interface to the data that provides meaning.

I'd also mod up Scott Whitlock's point from above (except I have no points being a new member), data or business logic classes shouldn't really have to worry about how the object is stored persistantly.

That being said, if you're dealing with an existing product, as long as you have clean, contractual interfaces - that's OK and maintainable too...

ContentLicense: CC BY-SA 2.5


问:
What's is the actual reason that JavaScript is not enough to draw?
I'm looking for a pure JS library that allows to draw the mouse trail, but I cannot find anything pure but using canvas. Is there is a reason for that it could not be achieved? I'm on the wrong thoughts?</p>

答:
The reason you require Canvas is because the HTML DOM is an object model. There is not one element in HTML that allows arbitrary drawing (such as lines, per pixel, non-rectangular shapes) hence the requirement for using Canvas.

Is there is a reason that I could not be achieved?

You could achieve this by creating an image at intervals of mouse movement that is a circle with a transparent background, for example, to simulate this. But canvas makes much more sense.


答:
I understand where you are coming from on Encapsulation point of view, and I don't necessarily think it is a bad idea, although I question how important this ultimately is.  Some important points:

Service Orientied or Component Oriented Architecture

You mention specifically that you clients of your services will somehow obtain libraries and possibly your source code.  Typically this runs counter to SOA in that your clients typically will know nothing about the underlying architecture of the service (nor should they care).

Tide goes in, tide goes out.  Never a missed step... you can't explain that - Bill O'Reilly

Ideally your service consumers should be as ignorant of the specifics of your services as our dear friend Bill O'Reilly is on the tides.  Request goes in, Request goes out, you can't explain that.

On the other hand if you have a component oriented architecture in general then while consumers may physically have the component, they should never use it outside of the predesignated interfaces anyway or else you really have deeper problems.

The separation of the DAO layer should be for little more than decoupling the acquisition of data from business logic, for the sole benefit of the component and those tasked with developing and maintaining it.

Transactional Based vs Object Oriented

Transactional based systems operate on transactions and sessions of various individual requests and responses.  Being as this sounds like the architecture choice you have decided on for your application, the importance of fundamental Object Oriented concepts are moot for this particular situation.

Classes denote nothing more than various behavior implementations for various functional areas of your application, however when deployed to an application server they are void of meaningful state, acting more like singletons.  In fact this is typically exactly what they are if coupled with a Dependency Injection framework.

In a truly OO design and architecture, a DI framework for Data Access and Business Logic classes are more or less injecting singletons where the required behavior is, but without state is this really OO to begin with?

Certainly DI can be useful for object oriented classes that actually can be preconfigured with various state, but not here.  So knowing that, the encapsulation concept is essentially moot as your DAO classes are likely being injected where they need to go with Reflection in mind anyway.

Title: Should I make package private my DAO interfaces?

Body:
I have several DAO classes that implement an interface. In the other hand, I have Service classes that use those DAO implementations.

So far all the DAO interfaces are public and I was thinking if would it be better to make them package private and to put the service classes in the same package so they are the only ones being able to use them.

The reason is because I wouldn't like that programmers could use DAO implementations in a Controller or a web service without using the service layer. A programmer could think for example that adding  a new order is as simple as calling the addOrder dao method, ignoring that indeed there is a service method that does more than that.

What do you guys think?


问:
Is a predefined key enough security when performing HTTP requests between two secure servers?
I have an AdWords script that regularly transfers sensitive data to my server using a POST HTTP request. For security I have a predefined 32 character randomized string that is verified by my server before it accepts the data. Is this secure?

I don't know too much about the HTTP protocol, but I know that the data is being sent unencrypted. Is it probable/possible for somebody to access the data during the request? From what I've understood, the HTTPS protocol is most useful when on an untrusted network where it's easy for anybody to spy on your packets. In my case, data is being sent from Google's servers to my host's servers (DreamHost in this case). Would it be prudent of me to upgrade to HTTPS, or would this be pointless? Are there any other security pitfalls I should be aware of?

I will accept the first answer that clears up my situation.

答:
It would indeed be prudent to upgrade to HTTPS. Once upon a time, SSL certificates needed for HTTPS were expensive, but these days I've seen them for ridiculously low prices like $6 per year.

Whether it is actually probable/possible for somebody to access the data during the request - look, realistically, it probably isn't. You're not making this communication over the free wi-fi in a coffee shop. But I honestly don't think it is worth trying to save a few dollars a year by not using HTTPS.

Surely there is (or could be in the future) some other functionality on your web application that could benefit from HTTPS?


答: Your packets including the secure key can be sniffed.  If not encrypted by HTTPS or some other protocol your wide open to the wild wild Internet</p>

Title: Is a predefined key enough security when performing HTTP requests between two secure servers?

Body:
I have an AdWords script that regularly transfers sensitive data to my server using a POST HTTP request. For security I have a predefined 32 character randomized string that is verified by my server before it accepts the data. Is this secure?

I don't know too much about the HTTP protocol, but I know that the data is being sent unencrypted. Is it probable/possible for somebody to access the data during the request? From what I've understood, the HTTPS protocol is most useful when on an untrusted network where it's easy for anybody to spy on your packets. In my case, data is being sent from Google's servers to my host's servers (DreamHost in this case). Would it be prudent of me to upgrade to HTTPS, or would this be pointless? Are there any other security pitfalls I should be aware of?

I will accept the first answer that clears up my situation.


答:
No because somebody could easily inspect your JavaScript, capture the randomized key, and spoof the input.

That is, unless your input is encrypted or hashed; and of the two, hashing is definitely the better option.

Also - Another question - Is your randomized key randomized on a per-user or per-session basis? If it's neither, and you're using a global key, then I'd say that you're very vulnerable to spoofing.

EDIT: In light of the fact that this code is running on Google App Engine, you aren't as vulnerable to spoofing (unless a Google engineer could potentially inspect your code). So generally speaking, as others have already stated, eliminate man-in-the-middle attacks with HTTPS.


问:
Longest subsequence without string
Does there exist a dynamic programming algorithm to find the longest subsequence in a string X that does not contain Y as substring? Just that this problem seems so similar to other DP string algorithms such as longest common subsequence and string.  It must be able to handle occurrences of Y that overlap.

It seems that this might be a 2-state DP problem, with the state [s_pos, t_pos] being the longest subsequence of string S starting at s_pos that does not have sting T[t_pos..M] as a substring. N is the length of string S and M is the length of string T. However, my transitions are not correct: it does not get the case where S=aaabc and T=aabc. The problem is in the else statement - I don't know how to transition if the characters are equal. Actually I feel that the if branch is wrong... anyone know what could be wrong?

It even fails the case S=aaab and T=aab. I can explain why it fails: assuming I call solve(0, 0). solve(0, 0) calls solve(1, 1). solve(1, 1) calls solve(2, 2). Since s[2] != t[2], it restarts the search from solve(3, 0). However, aab is a substring and it never checks this or considers this case...

```<code>int solve(int s_pos, int t_pos)
{
    if (s_pos >= N || t_pos >= M) return 0;
    if (t_pos == M - 1 && s[s_pos] == t[t_pos]) return 0;
    int ret = 0;
    if (s[s_pos] != t[t_pos])
    {
        int tmp = solve(s_pos + 1, 0);
        ret = max(ret, tmp + 1);
    }
    else
    {
        for (int i = s_pos + 1; i < N; i++)
        {
            int tmp = solve(i, t_pos + 1);
            if (tmp != 0)
            {
                ret = max(ret, 1 + tmp);
            }
        }
    }
    return ret;
}
</code>```

答:
I think the main problem is your for loop inside the else statement, that then calls the function recursively.

Pick an approach, either recursion or iterate, but mixing them just seems wrong.

I would go with the iterative approach.

I would create an empty list outside the function.

Then call solve.

In this function try this approach:

Loop through the string:
  If the current character is not the start of the subsequence then put the character in a holding string.  This will build up a string.
  If it starts the subsequence then add those characters to another holding string.
  Mark how many matches you have against the subsequence.
  One each character, if already matching against the subsequence, then look to see if it matches the first character, then if it matches the character at the next position to be matched.
  If it matches the subsequence then everything before that (in the holding string) is put into the list.

So, basically you need to track what may be a possible sequence that may win, and you need to track that a subsequence may be inside another subsequence.

You may need multiple holding strings, but implement a simple approach, with two holding strings, then go through various examples and write down what is happening in each step until you see if there is a need for another holding string.

Title: Longest subsequence without string


问:
In a resume, what all constitutes a Programming Language
In your resume, what would you classify as a Programming Language? For instance, under Programming Languages (or a similarly titled section of your resume), do you list C#, Java, C and leave it at that or do you go and add XML (because, well it is eXtensible Markup Language) and XSLT and jQuery and all that too?

If you are not going to add jQuery under languages, where exactly would you put it?

One resolution to this dilemma would be put in the technologies you have used under the project, but that way, you are forcing the recruiter to go through the projects that you have done rather than giving a highlight of the technologies and languages you are familiar in.

What are your thoughts?

答:
If you have to ask "should I put this as a programming language?" then don't.

You're not going to miss out on an interview because you filed XML and XSLT under "Tools and Technologies". But you might if you file them under "Programming languages" and you hit a grumpy dev lead who takes an instant dislike to you because of it.


问:
Why is Python recommended as an entry level programming language?
I've read here on P.SE more questions in which beginner programmers are advised to pick Python as their first programming language.

Don't get me wrong, I like Python. I like it a lot! But its philosophy revolves around "We are all consenting adults here".

From an experience/knowledge point of view, a beginner programmer is not an adult. Which then kinda means it is easier to shoot yourself in the foot and pick up some bad habits even if you survive the wound.

I'm thinking that in a "more static" language it would be harder to shoot yourself in the foot as it will be more restrictive.

Back to my question. Why is Python recommended as an entry level programming language?

What are the points that make it good for teaching a programming language. Or... is it personal preference of the adviser?

答:
There's one very, very, very important thing about Python for beginning programmers that everyone seems to have overlooked:  Forcing valid indentation.

Like some of the other commenters, I taught beginners for a few years.  It was unnervingly common to see stuff like this:

```<code>#include <stdio.h>

int main(char *args[])
                                                                     {
   int A = 1, B = 1, C;
for (int X = 0;X < 20;X++)
{
   printf("%d\n", A);
C = B + A;
      A = B;  B = C;
}
        }
</code>```

Now imagine this horrid inconsistency over about a hundred lines of code.  For some students, the entirety of all their projects looked like this.

I have no clue how they managed to do it, and it never bothered them.  Every time I asked, their response was something like "Well, it doesn't matter because the compiler will figure it out."  Even when I show them an obvious bug by fixing the indenting, they still never got a clue.

In Python, this type of indentation is just plain invalid.  They're forced to use something that's at least readable, even if it's a little inconsistent.  It gives them a habit that will, hopefully, continue when they eventually learn some other language.

Body:
There's one very, very, very important thing about Python for beginning programmers that everyone seems to have overlooked:  Forcing valid indentation.

Like some of the other commenters, I taught beginners for a few years.  It was unnervingly common to see stuff like this:

#include <stdio.h>

int main(char *args[])
                                                                     {
   int A = 1, B = 1, C;
for (int X = 0;X < 20;X++)
{
   printf("%d\n", A);
C = B + A;
      A = B;  B = C;
}
        }

Now imagine this horrid inconsistency over about a hundred lines of code.  For some students, the entirety of all their projects looked like this.

I have no clue how they managed to do it, and it never bothered them.  Every time I asked, their response was something like "Well, it doesn't matter because the compiler will figure it out."  Even when I show them an obvious bug by fixing the indenting, they still never got a clue.

In Python, this type of indentation is just plain invalid.  They're forced to use something that's at least readable, even if it's a little inconsistent.  It gives them a habit that will, hopefully, continue when they eventually learn some other language.


问:
Time limit on user input
I am trying to put a time limit on the user input, so if they take longer than 2 seconds to put type in an input then the program will terminate. I was wondering if there is a simple way to do this in C language?</p>

答: One simple way to do this would be to spawn a thread that will create a timer for two seconds and end the program if it hasn't received input. Create the thread before your blocking read call, set some sort of flag on input and read the flag in your timeout handler. Note you will need to make this thread safe.</p>

Title: Time limit on user input


问:
Can commented-out code be valuable documentation?

I wrote the following code:

if (boutique == null) {
    boutique = new Boutique();

    boutique.setSite(site);
    boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
    boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
    boutique.setNom(fluxBoutique.getNom());
    boutique.setSelected(false);
    boutique.setIdWebSC(fluxBoutique.getId());
    boutique.setDateModification(new Date());

    boutiqueDao.persist(boutique);
} else {
    boutique.setSite(site);
    boutique.setUrlLogo(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getLogo());
    boutique.setUrlBoutique(CmsProperties.URL_FLUX_BOUTIQUE+fluxBoutique.getUrl());
    boutique.setNom(fluxBoutique.getNom());
    //boutique.setSelected(false);
    boutique.setIdWebSC(fluxBoutique.getId());
    boutique.setDateModification(new Date());

    boutiqueDao.merge(boutique);
}
```

There is a commented-out line here. But I think it makes the code clearer, by making obvious what the difference is between if and else. The difference is even more noticeable with color highlighting .

Can commenting out code like this ever be a good idea?

答:
While this is clearly not a good case for commented out code there is a situation that I think warrants it:

```<code>// The following code is obvious but does not work because of <x>
// <offending code>
<uglier answer that actually does work>
</code>```

It's a warning to whoever sees it later that the obvious improvement isn't.

Edit:  I'm talking about something small.  If it's big you explain instead.

Body:
While this is clearly not a good case for commented out code there is a situation that I think warrants it:

// The following code is obvious but does not work because of <x>
// <offending code>
<uglier answer that actually does work>

It's a warning to whoever sees it later that the obvious improvement isn't.

Edit:  I'm talking about something small.  If it's big you explain instead.


问:
What are best practices for caching paginated results whose ordering/properties can change?
What is the best practice for caching paginated search results whose ordering/properties can be changed?

Say, in my application, someone wants to see the last 20 discussion threads (out of 10,000). A request would be sent to the database, via servlet, to fetch the first 20 records from the discussion threads table as XML/JSON. If they then want to see the next 20, they go onto the next page of results and this fires off another request to get the next lot (limit and offset = 20, etc.).

In order to reduce server load and client-waiting, I would like to cache the previous pages of results. However, I have two questions:

The table the results are shown in can be ordered by more than one attribute (i.e., thread-creation-date, thread-author, last-post-date). This means that a statement like 'first 20 results' makes no sense without context (i.e., what are we ordering by).  How does the front-end, then, communicate to the back-end what it has already loaded? My first thought was to use IDs for each result but sending these back to the server on subsequent requests (and filtering results based on them) would just as time-consuming as sending everything back blindly. How can I do this?

What if an attribute of a previously returned result (i.e., most-recent-post-date) has changed? We then need a way of checking each result to see if it's been modified server-side since it was paged in. How can I do this?

答:
I would probably handle it like this:

Treat different orderings as different sequences all together. It won't be worth the extra bookkeeping to track what each client has (or send it back over and over).

Whenever the user pages, display immediately from cache while at the same time sending a GET to the server that includes either a hash or a last access time. The server only sends back a full page if something has changed.

Retrieve from the server more than one UI page at a time. For example, if your UI displays 20 entries, query 60. I need to test this one, but my expectation is that the most efficient return size will usually be larger than the average amount of data shown on one page. This also makes the UI very responsive for some page turns.

Prefetch reslts when you are nearing a boundary. This helps preserve those fast load times from cache.


答:
Don't confuse languages with libraries. You can list JS and indicate that you are familiar with JQuery (and possibly other JS libs).

My background is mostly in C, which I list as well as my familiarity with several implementations of the standard C library. I don't elaborate on each individual library (in addition to standard C) that I've worked with, unless they are notable (MPI / etc).

Also, if you are extremely well versed in the specifics of any standard, it is a good idea to list that standard. Again, keep it brief and try to confine the list to things that may set you apart from others.

I list my experience with XML and JSON, but only when elaborating on the "API Design" section of my experience.

Title: In a resume, what all constitutes a Programming Language

Body:
In your resume, what would you classify as a Programming Language? For instance, under Programming Languages (or a similarly titled section of your resume), do you list C#, Java, C and leave it at that or do you go and add XML (because, well it is eXtensible Markup Language) and XSLT and jQuery and all that too?

If you are not going to add jQuery under languages, where exactly would you put it?

One resolution to this dilemma would be put in the technologies you have used under the project, but that way, you are forcing the recruiter to go through the projects that you have done rather than giving a highlight of the technologies and languages you are familiar in.

What are your thoughts?


答:
Most of the answers focus on how to refactor this one specific case, but let me offer a general answer to why commented out code is usually bad:

First, commented out code isn't compiled. This is obvious, but it means that:

The code might not even work.

When the comment's dependencies change it will not obviously break.

Commented code is very much "dead code". The longer it sits there, the more it rots and provides less and less value to the next developer.

Second, the purpose is unclear. You really need a longer comment that provides context for why there are randomly commented lines. When I see just a commented line of code, I have to research how it got there just to understand why it got there. Who wrote it? What commit? What was the commit message/context? Etcetera.

Consider alternatives:

If the goal is the provide examples of using a function/api, then provide a unit test. Unit tests are real code, and will break when they are no longer correct.

If the purpose is to preserve a previous version of the code, use source control. I'd much rather checkout a previous version then toggle comments throughout the codebase to "revert" a change.

If the purpose is to maintain an alternate version of the same code, use source control (again). That is what branches are for, after all.

If the purpose is to clarify structure, consider how you can restructure the code to make it more obvious. Most of the other answers are good examples of how you might do this.


答:
The news is not good, but that doesn't mean it's incorrect:  You do not know.

If there were analogous implementations in production, you would know it's feasible, but as you said no "major players" use the projects.

If you had developed in house, then you'd know, but as you said, you don't have the resources.

It's reasonable to want to know, but... you don't.

I hope this answer does help, because you should have contingency plans for pulling the plug on any technology that you depend on but don't control... and knowing that you don't know if it's dependable is a step in that direction.

Title: How to know if an Open Source project is mature enough to use in a product?

Body:
There are some open source projects that I'd like to incorporate into a product at work.  We don't have the bandwidth nor the subject matter expertise to do it ourselves.  I found these by searching in Google.  I'm unaware of any "major players" that utilize the projects, but I'm pretty encouraged by what I see.

Now, I'm a bit concerned about the amount of risk I'm exposed to by using joe-blow's open source project.  If it takes me 95% of the way there, perhaps the remaining 5% is easy to add or fix.  Perhaps it's non-trivial.

How do people go about determining whether an open source project is mature enough to use in a product?

This is not a hobby project, so stability, maintainability, etc. are paramount.


答:
Python is a great first language for most of the reasons stated above.  In particular, one requirement of a first language is a gentle learning curve, which Python has. You don't have to know all about classes, for instance, to get started.  In this respect it's a little like the Basic many of us started on.

One thing that hasn't been highlighted so far is that many languages have a gentle learning curve, but quickly run into a brick wall when trying to do more advanced stuff.  Old-school Basic is a good example of this.  With Python you can get into some very advanced stuff before feeling that some other language might be a better choice.

By that time a beginner is able to understand more about choices and trade-offs, and is ready for C/C++, Java, Assembler, Prolog, Lisp, etc.  Actually, Lisp might be a good first language too, though it's rather austere!

Body:
I've read here on P.SE more questions in which beginner programmers are advised to pick Python as their first programming language.

Don't get me wrong, I like Python. I like it a lot! But its philosophy revolves around "We are all consenting adults here".

From an experience/knowledge point of view, a beginner programmer is not an adult. Which then kinda means it is easier to shoot yourself in the foot and pick up some bad habits even if you survive the wound.

I'm thinking that in a "more static" language it would be harder to shoot yourself in the foot as it will be more restrictive.

Back to my question. Why is Python recommended as an entry level programming language?

What are the points that make it good for teaching a programming language. Or... is it personal preference of the adviser?


问:
Choosing DOCTYPE for an online eBook
I'm about to begin working on a project which involves creating an eBook-like website which will contain lots of large documents with text and images.

The site should have a rather minimalistic design, but it will include a UI with some scripting and animations to make browsing the large documents easier.

I've been thinking on this matter for a while now and I can't decide what markup to use for such a project.

Should it be HTML 4.0 strict? XHTML 1.0 strict? Perhaps HTML5?

It is a likely that people who are not especially internet-savvy will visit the site due to its content, and as such I think it's very plausible for some of the visitors to have relatively old browsers. Can XHTML or HTML5 hurt me in this regard?

Reading about various eBook formats (specifically EPUB), I learned that many of them use XHTML internally; does this mean that if I use XHTML (correctly) the site might also be packaged and delivered as an EPUB in the future? The strictness and cleanliness of XHTML/XML also appeals to me greatly.

Overall XHTML appeals to me the most, but I'm scared about the implication of its use. It has supposedly been discontinued by W3C in favor of HTML 5. However, I don't really see any advantages to using HTML5 over HTML 4 strict, as I won't be using any of it's features. I'm also worried about browser compatiablity of HTML5.

Should I just stick with good ol' HTML 4 strict?

答:
XML is the de facto markup language in the world of books and journals. As MainMa points out in a footnote  “The other syntax that can be used for HTML5 is XML".

O'Reilly have published a free book about their evolution to 'XML first' (I can't find a link since Chrome and Xmarks screwed my bookmarks ).

Book: A Futurist's Manifesto (A collection of essays from the bleeding-edge of publishing) which you can read for free has some useful chapters.
http://book.pressbooks.com/table-of-contents

By all means stick a HTML5 doctype at the top of each page (CV++). Just make sure to stick to XML compliant markup within.

Title: Choosing DOCTYPE for an online eBook


问:
What's the next level of abstraction?
Since programming languages initially only used lines of code executed sequentially, and it evolved into including functions which were one of the first levels of abstraction, and then classes and objects were created to abstract it even further; what is the next level of abstraction?

What's even more abstract than classes or is there any yet?

答:
One could consider Domain Specific Languages like SQL as a higher order of abstraction. SQL is a very targeted language that abstracts away operations such as storage and provides higher level functions based on set theory. Also consider how many mainstream languages today do not target a specific architecture but rather a Virtual Machine (such as the JVM or the .NET CLR). For an example C# is compiled to IL which is interpreted (or more frequently JIT'd --Just In Time Compiled-- to a native implementation) by the native runtime engine.

There has been much hubbub about the concept of DSLs being used to create very high level languages that can be used without much technical experience to create a working program. Think if someone were able to describe their entities and interactions in close to plain English and the operating environment handled everything from presenting a simple UI, to storing data in a database of some kind. Once those operations become abstracted, you can imagine how effortless programming can become.

There are some in existence today such as JetBrains MPS (which is a toolkit for describing DSLs or a language generator). Microsoft had a brief foray (and very promising I might add) into this space with it's M language (the M language was so complete that the language was defined in M).

Critics of the concept point to prior failed attempts to remove programmers from the job of developing programs, the difference with the DSL workbenches (as Fowler calls them) is that, developers would still be involved in codifying concepts that the Domain Experts could use to express the needs of their domain. Just like OS and Language vendors create tools that we use for programming, we would use DSLs to provide tools for business users. One could imagine DSLs that describe the data and logic, while developers create interpreters that store and retrieve data and apply the logic expressed in the DSL.

Title: What's the next level of abstraction?


问:
How to know if an Open Source project is mature enough to use in a product?
There are some open source projects that I'd like to incorporate into a product at work.  We don't have the bandwidth nor the subject matter expertise to do it ourselves.  I found these by searching in Google.  I'm unaware of any "major players" that utilize the projects, but I'm pretty encouraged by what I see.

Now, I'm a bit concerned about the amount of risk I'm exposed to by using joe-blow's open source project.  If it takes me 95% of the way there, perhaps the remaining 5% is easy to add or fix.  Perhaps it's non-trivial.

How do people go about determining whether an open source project is mature enough to use in a product?

This is not a hobby project, so stability, maintainability, etc. are paramount.

答:
The question has to be put differently. What you are really asking is is using this open-source project the best way develop the product?

That necessarily involves not just the open source project in question, but also your other options. If your only other option is writing everything yourself, than you are better off using the project if you can understand it's code enough to be able to modify it.

Than of course the other question arises whether your project is viable at all. I.e. you need to estimate the effort including any risk of having to fix or complete the functionality you hope is provided by the open-source code. If the project is not widely used, you will have to review the code for that.


问:
Which is simpler for REST client call to return JSON - JQuery/JavaScript or Spring RestTemplate?
I've been trying to hack up an annotated Spring MVC web app but it's proving pretty hard to call a URL of my web app which fires a request to a remote API (UK Police data) and recieves a reply which I can then return as JSON. I've been trying to use Spring's RestTemplate.

The odd JavaScript example that I've glanced at does seem to be suited to that task a lot better and more simplistic than a full blown servlet. Is that an opinion that you also share and can back up with a good, clear simple example?

JavaScript does seem to provide a good platform for this kind of task

Or, in other words, is it simpler to create a "web-app" with JavaScript that does some REST calls and renders the response than trying to do it with Spring?

答:
Javascript and JSON do go hand in hand (JSON == JavaScript Object Notation after all).

You can use Javascript on the server side and it's becoming increasingly popular, (e.g. Frameworks like node.js are being used). However, Javascript has not been a long term proven technology in this space (let the howls of outrage begin), so it's a case of let the buyer beware.

Using Spring MVC, Java, .NET, PHP, Python etc on the server side to process JSON request/response should be fairly easy in 2013 (although sometimes much confusing documentation is lying around as the state of play has changed so much).

I'd post a question on stackoverflow with your specific Spring MVC issue - I suspect you'll get some good answers quickly there.  Make sure you specify what type of request (GET/POST etc) and what version Spring MVC you are using.


问:
Web Developer or Software Engineer?
A question that I have been asking myself and really confused which path to take.

So I need your guys help as to the pros and cons of these 2 professions in today's world. I love web applications development as the Web is the best thing to happen in this age and nearly everyone gets by on the World Wide Web. And also tend to keep learning about new technologies and about web services.

On the other hand I like software engineering also for the desktop applications as I have had experience with development small scale software in VB.Net, Java, C++, etc.

Which path has more scope and better future? What's your view?

答:
I'm assuming you mean application developer and web developer. Why not do both? I, for instance, work both web side and app side for an iPad development company. I do things like synchronization, IAP, etc. At a large company you will pretty much be stuck in your position, but if you take a job at a small company, offer to learn PHP and help out with the site once in a while. See which you prefer! No one can answer that for you :)

As for scope and future, neither is going anywhere any time soon. Web development will continue to grow into a more fluid, state filled environment, al la HTML 5, and applications will continue to grow more robust and fill more niches. The question is where would you be happy?

Title: Web Developer or Software Engineer?


问:
How to design member access for an Article-type class?
I am doing a final project in a C++ class writing a very simple usenet-like client/server. I figure that since it's usenet-like I'll have a NewsGroup class and an Article class, I'm now working on my Article class. I can't really decide on a good design, though (this class is not about design patterns and I haven't taken any).

This is what I have:

```<code>class Article {
public:
    const std::string author;
    std::string title;
    std::string text;
    const uint32_t id;
    system_clock::time_point timestamp;

    Article(const std::string auth&,
            const std::string tit&,
            const std::string txt&,
            const system_clock::time_point&);

private:
    Article(const Article&);
    void operator=(const Article&);
    static uint32_t id_pool;
};
</code>```

My motivation is this:

author should never change -> const

title could change if edited -> non-const

text could change if edited -> non-const

id should never change -> const

timestamp could change but probably shouldn't, I'm not sure what to do with it yet.

id_pool is just where I get IDs from. One specification is that IDs should never be reused so I just increment id_pool in the Article constructor.

Coming from Java with all the getters and setters that I really don't like, and then some Python with it's "Everything public" and properties, that I do like, I'm getting a bit confused here.

I mean, I could make the members private and have getters and setters (I can't think of any natural "verb-methods" that an Article can "do"), but it feels like I would gain very little.

I would be thankful for some pointers on good design in this case.

答:
For starters it would make sense to make the member variables private and expose public get/set functions where necessary.  The advantage this provides is that you could then modify the internal member variables if necessary (future refactoring, say) without having to change the calling contexts because the internals are hidden behind the external class interface.

This would generally be considered good extensible, encapsulated design in any language when working on an object oriented project that you plan to maintain.


答: You don't need threads to solve this. Use select() instead. I googled this answer which uses that approach: https://stackoverflow.com/questions/7226603/timeout-function

Title: Time limit on user input

Body: I am trying to put a time limit on the user input, so if they take longer than 2 seconds to put type in an input then the program will terminate. I was wondering if there is a simple way to do this in C language?</p>


问:
Do context diagrams have levels?
I heard that the context analysis diagram has different levels. I couldn't find this in .Net, but I have seen that a DFD has different levels.

Do context diagrams have any levels (level0, level1, level2)? If yes, please suggest some examples.

答:
The answer depends upon what type of Context Diagram you are referring to.

System Context Diagrams have a single layer only.  So the answer is "No".

From the Wikipedia article:

This diagram is the highest level view of a system.

IDEF0 Top Level Context Diagrams have a single top-level context diagram and then have optional 'child' diagrams below that.  So the answer here would be "Yes."

The IDEF0 process starts with the identification of the prime function to be decomposed. This function is identified on a “Top Level Context Diagram,” that defines the scope of the particular IDEF0 analysis. ... From this diagram lower-level diagrams are generated.

Title: Do context diagrams have levels?


问:
When to use DI and when to create yourself in Java
I've a decent amount of OOP with various languages but am pretty new to Java.

I'm reading through a lot of tutorials where large numbers of objects are created within the code of a class, and I'm trying to run through them but build versions of the classes in the tutorials that do Dependency Injection instead of instantiating all the classes themselves.

But Java is not like other languages I've used in that pretty much everything is an object.  If I was to literally inject everything then the result would be very messy and hard to follow.

Obviously you wouldn't inject String objects, and I'm guessing there are other objects you wouldn't inject, but I'm not sure where the line should go.  At what point does DI stop being the right thing to do, and when does it start being a burden?  How do you decide pragmatically what to inject and what to just instantiate?

FYI, the tutorials I'm doing are http://edn.embarcadero.com/article/31995 and http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html for building a simple client and server.  I'm not copying them line for line though, I'm trying to create equivalent classes that follow best practice

答:
"At what point does DI stop being the right thing to do, and when does it start being a burden?..."

First of all i like DI and uses it a lot so don't get me wrong

DI is great for server side but  the games changes all together when it comes to Gui programming.
For e.g. I incorporated Guice to an existing GUI app developed in Swing

You need to refactor alot to get rid of stuff like static factories, nested dependencies, etc.

You need to be aware of how DI container create/handle objects for e.g. if it create objects eagerly on start up
then you can have a performance issues(can be any app but particularly in GUI apps 15-40 sec delay matters alot).
You may tweek the setting providing DI container allows for it.

TO incoprporate DI into an existing project you need revolution than evolution

How to handle nested dependecies?

let say you need to access some dependencies in deeply nested classess , you can use DI in one of the following way:

Modify constructor to have constructor injection (So know we end of with constructor taking lot of params...)?

Use field injection (Which is not good solution because we are exposing our fields)

Use setter injection(So know we need to create unnecessary setters in our code)

How about if you want to create object using new()(because the object need to be created at Runtime depending on some criteris)
and want to register it into the container(Guice doesn't handles objects created with new(), which is good) ?
So now  you need to turn your focus back to container  rather than developing new functioanlities in your app.

Final words in some cases using DesignPatterns + creative thinking and good architecture design, you can avoid situtations  where
gaine is small and hassles are hig as a result of introducing  DI


答:
In general, I find a class should only ever be new'd from one other class.

This is because once you go down the road of dependency injection, every object that's using new has to inject all the dependencies of the objects it creates, which means the parent object has to know all those dependencies too.  If A has a dependency on B and C creates A instances with new then C automatically needs to have a dependency on B, even if C never uses B directly.  First that violates separation of concerns, unless C's only job is to create As.  Otherwise it creates a problem if you ever want to add a dependency to A because all things that create it now need to add that same dependency.  They really shouldn't be concerned with that.  It's better to have C declare a dependency on AFactory and AFactory have a dependency on B.  Then you can add dependencies to A all you want, and only AFactory has to change.

Title: When to use DI and when to create yourself in Java

Body:
I've a decent amount of OOP with various languages but am pretty new to Java.

I'm reading through a lot of tutorials where large numbers of objects are created within the code of a class, and I'm trying to run through them but build versions of the classes in the tutorials that do Dependency Injection instead of instantiating all the classes themselves.

But Java is not like other languages I've used in that pretty much everything is an object.  If I was to literally inject everything then the result would be very messy and hard to follow.

Obviously you wouldn't inject String objects, and I'm guessing there are other objects you wouldn't inject, but I'm not sure where the line should go.  At what point does DI stop being the right thing to do, and when does it start being a burden?  How do you decide pragmatically what to inject and what to just instantiate?

FYI, the tutorials I'm doing are http://edn.embarcadero.com/article/31995 and http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html for building a simple client and server.  I'm not copying them line for line though, I'm trying to create equivalent classes that follow best practice


问:
How do I test my validation without being too much perfectionist, yet to leave most part of logic tested?
For example I would like to validate that name is letters only and is between 4 and 14 letters length. I have the following code in model:

```<code>validates: name, :format => { :with => /^[a-zA-Z]+$/,
                              :message => 'Name should be letters only. },
                 :length => { :minimum => 4, :maximum => 14 }
</code>```

So it clearly lets me do what I want.

But as for unit tests, I have a bit too much perfectionism so I set something like

```<code>invalid_names = ['1234',
                 'qwe',
                 '1%#$#$',
                 'Sam1',
                 '%',
                 random_string(15)] #I also have a test method to create random string with parametrized length

valid_names = %w['test',
                 'Travis',
                 'John',
                 random_string(5),
                 random_string(14),
                 random_string(4)]
</code>```

and test each of them in a loop with asserts, like

```<code>invalid_names.each do |name|
    user = User.new(:name => name)
    user.save
    assert user.errors[:name].any?, "#{name} is valid."
end
</code>```

So it definitely works great. But it is too verbose (because of valid/invalid names arrays, and added random_string method), also I can't be sure my test actually tests all symbols and their combinations possible and all lengths and stuff, even though I am definitely sure it works as expected.

So what is acceptable way to test my validation without being too much perfectionist, yet to leave most part of logic tested?

Am I just set in a mind trick of trying to write a perfect code just to write a perfect code and forgetting about main finish goal: working product?

答:
Some suggestions:

Avoid to use a random generator directly inside unit tests if there is no compelling reason for it. This has a high risk of producing non-reproducible cases. If you want to use a random string, choose the string randomly once and hardcode that choosen string into your test.

An old wisdom of testing is that you cannot test every possible combination of input data if the allowed range of input values is too huge. Choosing good test cases is brainwork, the idea is to use as few test cases as needed to test the largest possible number of failure cases.

For example, classify your input domain into categories:

string with length 0

strings with length between 0 and 4

strings with length 4

strings with length between 4 and 14

strings with length greater 14

And as a second classification

strings with no legal characters

strings with some legal characters

string with only legal characters

Now, make sure you have at least one test case for each category. Of course, this example shows only finding tests by using "equivalence classes". Other techniques are designing your tests for edge cases (like the ones in this answer), or tests for getting full code coverage and branch coverage.