问:
Best way of validating Class properties

Background:

I have a CSV file, which I need to ready and validate each element in each row and create a collection of a class, having valid data.

i.e
CSV File looks like:

```<code>   EmpID,FirstName,LastName,Salary
    1,James,Help,100000
    2,Jane,Scott,1000
    3,Mary,Fraze,10000
</code>```

Class looks like:

```<code>public class Employees
{
    public int EmpID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Salary { get; set; }
    public string ErrorReason { get; set; }
}
</code>```

Here are the validations required for each field:

EmpID:

Its a mandatory field, hence cannot be null or empty

It should be only an integer

It should be not more than 2 digits

It should be present in database (query that database and check if an employee exits       with this empid.

FirstName (same validation for LastName):

Its a mandatory field, hence cannot be null or empty

It should be only alphabets.

Not more than 30 characters are allowed

Salary:

Its a mandatory field, hence cannot be null or empty

It should be a decimal.

To achieve this, here is my approach:

Read CSV file row by row

For each element i.e EmpId, FirstName... etc do the required validations by calling individual methods having validation logic.
eg:
public bool ValidateIsDecimal(string value) { }
public bool ValidateIsEmpIdExists(string value) { }
etc

If valid, fill corresponding property of "Employees" class.

If NOT VALID, fill "ErrorReason" property, with appropriate reason as to what caused the validation to fail.(eg: Required filed was missing or datatype is not decimal etc)

Add this Class to Employees collection (eg: List)

So, my question is, is this the right approach, or is there any other better/cleaner way of validating class properties.

答:
This is quite simple problem so there is not much you can do wrong in this. Your approach looks fine.

Only thing I noticed might be bad is fact you are querying DB for each row. It would be better if you queried the DB just once with all the IDs. But assuming only 100 rows are possible, then this should not be a problem. But I would at least write a comment this might be a problem in the future.

Title: Best way of validating Class properties


问:
What is meant by "Now you have two problems"?
There is a popular quote by Jamie Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

How is this quote supposed to be understood?

答:
Some programming technologies are not generally well-understood by programmers  (regular expressions, floating point, Perl, AWK, IoC... and others).

These can be amazingly powerful tools for solving the right set of problems.  Regular expressions in particular are very useful for matching regular languages. And there is the crux of the problem: few people know how to describe a regular language (it's part of computer science theory / linguistics that uses funny symbols - you can read about it at Chomsky hierarchy).

When dealing with these things, if you use them wrong it is unlikely that you've actually solved your original problem. Using a regular expression to match HTML (a far too common occurrence) will mean that you will miss edge cases. And now, you've still got the original problem that you didn't solve, and another subtle bug floating around that has been introduced by using the wrong solution.

This is not to say that regular expressions shouldn't be used, but rather that one should work to understand what the set of problems they can solve and can't solve and use them judiciously.

The key to maintaining software is writing maintainable code. Using regular expressions can be counter to that goal. When working with regular expressions, you've written a mini computer (specifically a non-deterministic finite state automaton) in a special domain specific language. It's easy to write the 'Hello world' equivalent in this language and gain rudimentary confidence in it, but going further needs to be tempered with the understanding of the regular language to avoid writing additional bugs that can be very hard to identify and fix (because they aren't part of the program that the regular expression is in).

So now you've got a new problem; you chose the tool of the regular expression to solve it (when it is inappropriate), and you've got two bugs now, both of which are harder to find, because they're hidden in another layer of abstraction.

ContentLicense: CC BY-SA 3.0


答:
Jeff Atwood brings out a different interpretation in a blog post discussing this very quote: Regular Expressions: Now You Have Two Problems (thanks to Euphoric for the link)

Analyzing the full text of Jamie's posts in the original 1997 thread, we find the following:

Perl's nature encourages the use of regular expressions almost to the exclusion of all other techniques; they are far and away the most "obvious" (at least, to people who don't know any better) way to get from point A to point B.

The first quote is too glib to be taken seriously. But this, I completely agree with. Here's the point Jamie was trying to make: not that regular expressions are evil, per se, but that overuse of regular expressions is evil.

Even if you do fully understand regular expressions, you run into The Golden Hammer problem, trying to solve a problem with regular expressions, when it would have been easier and more clear to do the same thing with regular code (see also CodingHorror: Regex use vs. Regex abuse).

There is another blog post which looks at the context of the quote, and goes into more detail than Atwood: Jeffrey Friedl's Blog: Source of the famous “Now you have two problems” quote

Title: What is meant by "Now you have two problems"?

Body:
There is a popular quote by Jamie Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

How is this quote supposed to be understood?


答:
It's fairly straight forward unless there are any additional complications that you haven't listed. Something as simple as this (pseudocode) will do:

```<code>var customers = File.ReadAllLines("...")
    .AsParallel()
    .Select(l => l.Split(new char[] { ',' }))
    .Where(s => Tuple.Create(
        validateId(s[0]),
        validateFirstName(s[1]),
        validateLastName(s[2]),
        validateSalary(s[3])))
    .Select(t => new Customer(t.Item1, t.Item2, t.Item3, t.Item4));
</code>```

The only nuance here is that validateXYZ will validate and return the correct type as well.

As far as the "ErrorReason" is concerned, filling bad data and then a reason for the bad data seems like a bad idea.

I've written more complicated queries than this using this exact method over files with millions of lines where it completes in seconds. If you've got more data than that, then there might be more work to do.

(btw: for these types of problems, linqpad is your friend).

Title: Best way of validating Class properties

Body:
Background:

I have a CSV file, which I need to ready and validate each element in each row and create a collection of a class, having valid data.

i.e
CSV File looks like:

```<code>   EmpID,FirstName,LastName,Salary
    1,James,Help,100000
    2,Jane,Scott,1000
    3,Mary,Fraze,10000
</code>```

Class looks like:

```<code>public class Employees
{
    public int EmpID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Salary { get; set; }
    public string ErrorReason { get; set; }
}
</code>```

Here are the validations required for each field:

EmpID:

Its a mandatory field, hence cannot be null or empty

It should be only an integer

It should be not more than 2 digits

It should be present in database (query that database and check if an employee exits       with this empid.

FirstName (same validation for LastName):

Its a mandatory field, hence cannot be null or empty

It should be only alphabets.

Not more than 30 characters are allowed

Salary:

Its a mandatory field, hence cannot be null or empty

It should be a decimal.

To achieve this, here is my approach:

Read CSV file row by row

For each element i.e EmpId, FirstName... etc do the required validations by calling individual methods having validation logic.
eg:
public bool ValidateIsDecimal(string value) { }
public bool ValidateIsEmpIdExists(string value) { }
etc

If valid, fill corresponding property of "Employees" class.

If NOT VALID, fill "ErrorReason" property, with appropriate reason as to what caused the validation to fail.(eg: Required filed was missing or datatype is not decimal etc)

Add this Class to Employees collection (eg: List)

So, my question is, is this the right approach, or is there any other better/cleaner way of validating class properties.

Body:
It's fairly straight forward unless there are any additional complications that you haven't listed. Something as simple as this (pseudocode) will do:

var customers = File.ReadAllLines("...")
    .AsParallel()
    .Select(l => l.Split(new char[] { ',' }))
    .Where(s => Tuple.Create(
        validateId(s[0]),
        validateFirstName(s[1]),
        validateLastName(s[2]),
        validateSalary(s[3])))
    .Select(t => new Customer(t.Item1, t.Item2, t.Item3, t.Item4));

The only nuance here is that validateXYZ will validate and return the correct type as well.

As far as the "ErrorReason" is concerned, filling bad data and then a reason for the bad data seems like a bad idea.

I've written more complicated queries than this using this exact method over files with millions of lines where it completes in seconds. If you've got more data than that, then there might be more work to do.

(btw: for these types of problems, linqpad is your friend).


答:
It's mostly a tongue-in-cheek joke, albeit with a grain of truth.

There are some tasks for which regular expressions are an excellent fit.  I once replaced 500 lines of manually written recursive descent parser code with one regular expression that took around 10 minutes to fully debug.  People say regexes are hard to understand and debug, but appropriately-applied ones are not nearly as hard to debug as a huge hand-designed parser.  In my example, it took two weeks to debug all the edge cases of the non-regex solution.

However, to paraphrase Uncle Ben:

With great expressivity comes great responsibility.

In other words, regexes add expressivity to your language, but that puts more responsibility on the programmer to choose the most readable mode of expression for a given task.

Some things initially look like a good task for regular expressions, but aren't.  For example, anything with nested tokens, like HTML.  Sometimes people use a regular expression when a simpler method is more clear.  For example, string.endsWith("ing") is easier to understand than the equivalent regex.  Sometimes people try to cram a large problem into a single regex, where breaking it into pieces is more appropriate.  Sometimes people fail to create appropriate abstractions, repeating a regex over and over instead of creating a well-named function to do the same job (perhaps implemented internally with a regex).

For some reason, regexes have a weird tendency to create a blind spot to normal software engineering principles like single responsibility and DRY.  That's why even people who love them find them problematic at times.


问:
When should I stop committing to master on new projects?
Whenever a new project starts, it usually makes sense to start by committing straight to master until you've got something "stable", and then you start working in branches.

At least, this is how I normally do it. Is there a way to immediately start branches from second commit? Does it make sense to do it this way? Obviously, "Initial Commit" will always be on master, but after that, when will I know it's the right time to start making branches for new features?

答:
Neal Ford of Thoughtworks advocates the use of feature toggles over branching to avoid the problem of "merge hell". Consider the case in which two programmers dutifully merge daily from the main branch and one of the makes considerable changes over somes weeks and then commits. The other programmer could very well end up in merge hell. To avoid this problem, Ford recommends "bringing the pain forward" (a well-known agile attribute) by having only one branch and committing to it daily. Additional feature are added via feature toggles which disable the feature until it's been fully tested.

This methodology would seem to work best in an environment that implements continuous delivery as problems with a commit would be immediately caught.


问:
PHP - PSR 0 - Configuration Constants
This question is about PSR-0 autoloaded libraries and the way main configuration constants should be declared and used.

From your point of view (lib/framework developer), where/how should be declared your library configuration PHP constants (such as ESCAPE_SOMETHING, USE_DOM, API_URL, ...) in such a way that

your code can easily address them

client code can easily modify them depending on needs

Is there any convention, recommendation, or even something I missed in PSR-0 I should be aware of?

答:
This question is about PSR-0 autoloaded libraries

I think you're conflating two different issues. Finding and loading the PHP code for FooClass is (or ought to be) a different problem from how new FooClass() or FooClass::staticThing() should behave.

Ideally, FooClass shouldn't care whether I (the guy using the library) relied on an autoloader or whether I hard-coded my own require_once() statement.

library configuration PHP constants

One ground-rule first... never with constants from define(). Polluting the global namespace is a bad idea, and IIRC even the new namespace features are a little weird in that regard. Class-constants on the library classes are acceptable, but as the library-consumer you probably aren't hand-editing those.

From your point of view (lib/framework developer), where/how should be declared your library configuration PHP constants

You mean, how would I prefer for consumer code to set options that affect my code? I'd prefer something like:

```<code>FooLibraryConfigurator::set("a","b");
FooClass::doStuffThatNeededConfData();
</code>```

In other words, configure my library based on a mechanism I created for you to use. :p

Title: PHP - PSR 0 - Configuration Constants

Body:
This question is about PSR-0 autoloaded libraries

I think you're conflating two different issues. Finding and loading the PHP code for FooClass is (or ought to be) a different problem from how new FooClass() or FooClass::staticThing() should behave.

Ideally, FooClass shouldn't care whether I (the guy using the library) relied on an autoloader or whether I hard-coded my own require_once() statement.

library configuration PHP constants

One ground-rule first... never with constants from define(). Polluting the global namespace is a bad idea, and IIRC even the new namespace features are a little weird in that regard. Class-constants on the library classes are acceptable, but as the library-consumer you probably aren't hand-editing those.

From your point of view (lib/framework developer), where/how should be declared your library configuration PHP constants

You mean, how would I prefer for consumer code to set options that affect my code? I'd prefer something like:

FooLibraryConfigurator::set("a","b");
FooClass::doStuffThatNeededConfData();

In other words, configure my library based on a mechanism I created for you to use. :p


问:
Why should we be aware of licenses?
I know this is common question, but why should a programmer be aware of software licenses as well as extensions and plugins licenses?

I'm working in a company which focuses on the business process (Ruby on Rails) and I'm curious as to why they are strict on such licenses in the project development.

What licenses should I be aware of and why?

答:
To answer the second part of the question (very roughly), for commercial projects you should probably be aware of:

BSD or Apache style licenses - basically: do what you want

GPL - basically: avoid unless you are ok with having your own code under GPL

LGPL - can use as a library freely as long as you don't change it, other uses gets you back to GPL

Others - look at them individually

Now, this is very rough and IANAL and everything. I recommend you look at opensource.org  for more details.

(Also: why does it matter? Imagine the Ruby on Rails license says 'you have to pay us 50% of your revenue to use it' or 'we own all the code you wrote based on that platform')

Title: Why should we be aware of licenses?


答:
If I needed to input data and capture errors, I would probably do something more like:

```<code>public class Employee
{
    public int EmpID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Salary { get; set; }
}

public class ErrorEmployee : Employee
{
    public string[] ErrorReason { get; set; }
}
</code>```

Read CSV file row by row

For each element i.e EmpId, FirstName... etc do the required validations by calling individual methods having validation logic. eg: public bool ValidateIsDecimal(string value) { } public bool ValidateIsEmpIdExists(string value) { } etc

If valid, fill corresponding property of "Employees" class.  Add this Class to Employees collection (eg: List)

If NOT VALID, fill "ErrorReason" property, with appropriate reason as to what caused the validation to fail.(eg: Required filed was missing or datatype is not decimal etc) Add this Class to ErrorEmployees collection (eg: List)

I wouldn't want to pollute the regular Employee (singular, use the plural for a collection of them) object with error messages.  As in the note above, check out the FluentValidation library for your validation and capture a list of errors rather than just the first found.

Title: Best way of validating Class properties

Body:
If I needed to input data and capture errors, I would probably do something more like:

public class Employee
{
    public int EmpID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Salary { get; set; }
}

public class ErrorEmployee : Employee
{
    public string[] ErrorReason { get; set; }
}

Read CSV file row by row

For each element i.e EmpId, FirstName... etc do the required validations by calling individual methods having validation logic. eg: public bool ValidateIsDecimal(string value) { } public bool ValidateIsEmpIdExists(string value) { } etc

If valid, fill corresponding property of "Employees" class.  Add this Class to Employees collection (eg: List)

If NOT VALID, fill "ErrorReason" property, with appropriate reason as to what caused the validation to fail.(eg: Required filed was missing or datatype is not decimal etc) Add this Class to ErrorEmployees collection (eg: List)

I wouldn't want to pollute the regular Employee (singular, use the plural for a collection of them) object with error messages.  As in the note above, check out the FluentValidation library for your validation and capture a list of errors rather than just the first found.


问:
Highly scalable and dynamic "rule-based" applications?
For a large enterprise app, everyone knows that being able to adjust to change is one of the most important aspects of design. I use a rule-based approach a lot of the time to deal with changing business logic, with each rule being stored in a DB. This allows for easy changes to be made without diving into nasty details. Now since C# cannot Eval("foo(bar);") this is accomplished by using formatted strings stored in rows that are then processed in JavaScript at runtime. This works fine, however, it is less than elegant, and would not be the most enjoyable for anyone else to pick up on once it becomes legacy.

Is there a more elegant solution to this? When you get into thousands of rules that change fairly frequently it becomes a real bear, but this cannot be that uncommon of a problem that someone has not thought of a better way to do this. Any suggestions? Is this current method defensible? What are the alternatives?

Edit: Just to clarify, this is a large enterprise app, so no matter which solution works, there will be plenty of people constantly maintaining its rules and data (around 10).  Also, The data changes frequently enough to say that some sort of centralized server system is basically a must.

答:
One thing that comes to mind is Windows Workflow Foundation, which can be used along with ASP.NET but would be running on the server side (so it may not be applicable to what you're doing).  In Java land there is jBPM (business process management) which also runs on the server side.

Since those solutions probably wouldn't fit the bill for you, the best thing to do may be to implement those business rules in plain old code (using javascript, C#, or whatever is best for the job) and expect that the programming code will have to be updated when design changes happen.  Using object-orientated design patterns will make the code easily extendable.  If you write the code well, the effort needed to change it in the future should be minimal.

ContentLicense: CC BY-SA 2.5


问:
Cascading "Deleted" records that aren't really deleted
Just trying to get some ideas on what people do for this scenario.
We have a system database(SQL Server 2008 R2) that has tables and every table has a field we can call "Deleted".  It's basically a bit field if its a 1 the record is deleted, if it is a 0 it is not deleted.  The field is not nullable and its default is of course 0.

We cannot allow real deletions to the database, so to get around this we set a bit field (Deleted) to true.  In our application we end up with queries that look like this:

SELECT blah FROM MyTable WHERE .. AND Deleted=0

Basically we filter for records so we only get non deleted rows.  Our issue is related records that need to cascade.  What do people prefer, should we be doing this in the server side code so that when you delete a record it delete's (Sets the deleted bit field to true) for all related records?  Or should this be a trigger that has to check this field and sets the bit field for all related records to 1?

Or are we completely on the wrong path?

答:
There is no good solution here. Databases offer special, efficient cascaded deletion via foreign keys, but if, as you say, actual deletion is not an option, then you can't take advantage of that native cascading.

Depending on whether deletes are a common or a rare occurrence, it will be more efficient to emulate the cascading immediately (via extra queries or triggers) when you pseudo-delete something, or just to always fetch everything from the DB and filter on the deletion flag in business logic.

Personally, I've always used a third option: all subsidiary records are only accessible from the master record, which never happens if that one is soft-deleted, so you needn't do anything! Obviously this only works if your data model is a strict tree (comments are only retrieved when viewing the product they apply to, user privileges are only retrieved when administering the user they belong to, etc.) rather than a web (where you might query all comments or all privilege records indifferently), but I find that this can be made to work for surprisingly many scenarios.


问:
Is a development environment required for small projects?
I won a bid on Elance and was had a request to fix some css and html issues with a WordPress site.

How do I make changes to the document without working on the live site? Do you set up a development environment for every job you get? This would be time consuming on a job that pays very little. I was offered access to the wp-admin and the cpanel but any changes would affect the live site immediately.

What is the best practice for changing and updating sites for clients?

Any advice on how to develop on a site that  you do not have the full install on is helpful.

答:
Depends on the scope

If the changes are simple enough you could just test them live using chrome developer tools or firefox firebug plugin and then apply the changes in wp-admin when you are confident enough.

You could retrieve the static source, test and make changes offline and then apply in wp-admin.

Also wp-admin offers mechanisms for previewing most changes before making them live.

Depends on the customer

This increases the risk of issues occurring in production. You should have a conversation with the customer about this and gauge their acceptance of this risk.

When should I have a dedicated development environment?

Most of the time you want a development environment that closely matches the specifications and infrastructure found in the live environment. Whenever possible you should strive for this.

Virtualization technologies and cloud services have made setup and management of multiple environments so easy now. If you do many wordpress contracts you will want to explore ways of quick setup and teardown.


答:
Three classes

CSVLine or a string[]

Employee

Validator

CSVLine:

```<code>{
    public int LineNumber {get; set;}
    public string EmpID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Salary { get; set; }
}
</code>```

Read the line into CSVLine

Call the appropriate Validator methods on CSVLine properties or array elements as
needed

If valid, create an Employee passing in the CSVLine or string array

If its not valid, you can log the CSV line and validation error(s) to a reject file.  You can validate all attributes or fail fast and stop on the first error.  Up to you.  Also, there is opportuity to make CSV a generic structure, like a string[] if you don't want named fields in the CSVLine and just pass the array elements as needed to the validator.  An array may be a better choice because you can validate the number of element it has (in this case 4) as well.

The validator could also be an interface so you could create many different types of validators.  Or you can just have one class if this is the only file you are dealing with.

Title: Best way of validating Class properties

Body:
Three classes

CSVLine or a string[]

Employee

Validator

CSVLine:

{
    public int LineNumber {get; set;}
    public string EmpID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Salary { get; set; }
}

Read the line into CSVLine

Call the appropriate Validator methods on CSVLine properties or array elements as
needed

If valid, create an Employee passing in the CSVLine or string array

If its not valid, you can log the CSV line and validation error(s) to a reject file.  You can validate all attributes or fail fast and stop on the first error.  Up to you.  Also, there is opportuity to make CSV a generic structure, like a string[] if you don't want named fields in the CSVLine and just pass the array elements as needed to the validator.  An array may be a better choice because you can validate the number of element it has (in this case 4) as well.

The validator could also be an interface so you could create many different types of validators.  Or you can just have one class if this is the only file you are dealing with.


问:
Why do we need to use sealed on a class? Do we really need sealed?
Reading this article (by Eric Lippert), it has four arguments as to why you should use sealed, however, I don't understand why we actually need it. Philosophical/aesthetic reasons aside, why do we need to use sealed?

I can see how things like readonly from C# or const from C++ actually catch genuine errors. Is there any type of error that sealed can catch?

An often cited reason for sealing a class is because, it hasn't been to designed to be extended. What does that mean? Why is it important? Are there any real examples of this?

The point on compatibility isn't a reason why we need to seal classes but why it should be default.

The final point again is strange, because sealing your class doesn't prevent someone providing an alternative implementation in a heirachy.

If I didn't put enough emphasis, on it already I'm looking for reasons we actually need it. Not the usual, "someone else might write bad code". I understand that plenty of people like using sealed for design intent, but I'm looking for a practical purpose beyond that.

答:
What does that mean?

It means that it is difficult for people to obey the Liskov Substitution Principle (or less likely, the Open Closed Principle) with the class as is. It has subtle, or difficult to enforce behavior that inheritors are likely to screw up. Or they're not likely to screw up, but the impact of screwing them up is huge.

The final point again is strange, because sealing your class doesn't prevent someone providing an alternative implementation.

Sure it does. If some method takes object A or some other class uses type A, by having A sealed, people cannot override it with B and then pass B into the method or use it in the class. Consumers of A can see it's sealed and know that A is the only behavior they're getting.

All that said, we don't need sealed - just like we don't need readonly. They are tools to help programmers prevent misuse, because misuse leads to bugs. Though personally, I dislike sealed; even in these days where composition over inheritence is well known, it is rare that you can say "nobody will ever need to extend this" and actually be right.

ContentLicense: CC BY-SA 4.0


答:
Do it explicitly on the delete/undelete statement.  There are also probably several scenarios where you do not want to cascade the delete.

```<code>> Update table1 set deleted=@flag where...
> Update table2 set deleted=@flag where...
</code>```

For example; consider a person with several addresses.

Deleting the person, just set Delete flag on person.  No need to cascade the delete to addresses, because when we restore, we want those addresses back.

Let's say the person moved, then we would want update the delete flag on the old address only, leaving the other addresses and person alone.  So, cascading may not always be required and would depend on the scenario.

So, I think you need to be explicit depending on how your model is set up and what your deleting.

Title: Cascading "Deleted" records that aren't really deleted

Body:
Just trying to get some ideas on what people do for this scenario.
We have a system database(SQL Server 2008 R2) that has tables and every table has a field we can call "Deleted".  It's basically a bit field if its a 1 the record is deleted, if it is a 0 it is not deleted.  The field is not nullable and its default is of course 0.

We cannot allow real deletions to the database, so to get around this we set a bit field (Deleted) to true.  In our application we end up with queries that look like this:

SELECT blah FROM MyTable WHERE .. AND Deleted=0

Basically we filter for records so we only get non deleted rows.  Our issue is related records that need to cascade.  What do people prefer, should we be doing this in the server side code so that when you delete a record it delete's (Sets the deleted bit field to true) for all related records?  Or should this be a trigger that has to check this field and sets the bit field for all related records to 1?

Or are we completely on the wrong path?

Body:
Do it explicitly on the delete/undelete statement.  There are also probably several scenarios where you do not want to cascade the delete.

> Update table1 set deleted=@flag where...
> Update table2 set deleted=@flag where...

For example; consider a person with several addresses.

Deleting the person, just set Delete flag on person.  No need to cascade the delete to addresses, because when we restore, we want those addresses back.

Let's say the person moved, then we would want update the delete flag on the old address only, leaving the other addresses and person alone.  So, cascading may not always be required and would depend on the scenario.

So, I think you need to be explicit depending on how your model is set up and what your deleting.


问:
Lead developer unable to do INNER JOIN
I had worked in the past for a small company developing web applications. Back then the current lead developer, who is also one of the bosses, told me that he is incapable of making a JOIN inside a SQL query.

I was amazed how a person who has developed and maintain big ecommerce site is incapable of doing that.

Are database normalization and functional dependencies a waste of time? Are they only necessary in big demanding projects?

答:
Database normalization and functional dependencies are crucial in the smallest of applications.

If you doubt this, just consider a simple Address Book application.

Already you have five normalized tables, and four relations.

Oh sure, you can go the way of NoSQL and do everything with simple Key/Value pairs, but as long as you are using a relational database, why not use the capabilities that such a platform provides?

Normalization provides a number of important benefits, including the removal of data duplication, and the convenience and power that set theory computations provide.  Users of Key/Value systems understand this the first time they try to write a report.

Title: Lead developer unable to do INNER JOIN


问:
Is checking count/size/length less than 0 necessary in modern languages?
Is checking count/size/length less than 0 necessary in modern languages anymore? For instance, in C# I quote often will check if a collection's count is less than or equal to 0.

I assume that this was done in older languages, like C, where you could potentially have a size of less than 0.

Is there ever a case where you can have the size/length/count of an object or primitive type be less than 0?

答:
In the .NET Framework (of which the C# language is a part), most ordinary indexes (with the notable exception of file positions, which use a 64 bit signed long) are standardized to a signed, 32 bit int.

So, for example, when you get the length of a string, you're being returned a number that can hold negative values, but in practice, will never be negative.

However, that's not true of all string operations.  IndexOf() still returns a signed int, but will return a value of -1 if the search string is not found.  This is partly why signed int was chosen for such indexes; to provide the possibility of returning negative values for signaling purposes.

Because signed integers are always returned from such operations, the code

```<code>if (s.length <= 0)
</code>```

is consistent with the idea that "I'm checking to see if this string has something in it," since all such lengths will be a positive number.

But you're right; technically it's not necessary to check for a negative number in those cases where you'll never get one (i.e. Length).

Body:
In the .NET Framework (of which the C# language is a part), most ordinary indexes (with the notable exception of file positions, which use a 64 bit signed long) are standardized to a signed, 32 bit int.

So, for example, when you get the length of a string, you're being returned a number that can hold negative values, but in practice, will never be negative.

However, that's not true of all string operations.  IndexOf() still returns a signed int, but will return a value of -1 if the search string is not found.  This is partly why signed int was chosen for such indexes; to provide the possibility of returning negative values for signaling purposes.

Because signed integers are always returned from such operations, the code

if (s.length <= 0)

is consistent with the idea that "I'm checking to see if this string has something in it," since all such lengths will be a positive number.

But you're right; technically it's not necessary to check for a negative number in those cases where you'll never get one (i.e. Length).


答:
Joining tables is the bread and butter of using relational databases. When you can't do JOINs, you don't really understand them. That's why any good database course usually starts with drawing ERD diagrams before even writing the first line of SQL.

Object-oriented design patterns are often dismissed by people who use them every day, but lack the ability to recognize them. But being able to recognize and use them allows one to read and write a lot more elegant and modular OO code.

You wonder how someone can still write a sufficiently complex and successful application using both relational databases and an object-oriented programming language without understanding these things? It is surprising how far you can get in software development without really knowing what you are doing when you are just persistent enough. You don't know JOINs? No problem, you just select everything from both tables and write a matching-algorithm in the application. It will take five times as much development time, will be ten times slower and have twenty times the amount of sourcecode than just writing a JOIN, but in the end you have the data you want. And you are proud of yourself, because you couldn't imagine a better way to solve this complex problem. When your only tool is a hammer, every problem looks like a nail.

In fact writing a large, feature-complete application isn't the difficult part. The difficult part is maintaining it.

The difference between good and bad code usually isn't that notable during the development phase of a product. I would even argue that an unskilled development team might bring a product to market even quicker, because they tend to overlook some hidden complexity which won't be noticed without proper Test and QA management (they will be noticed after the product is in production - which will usually be worse).

But software quality starts to matter after the product goes from the development-phase into the support-phase and unexpected changes need to be made to the code base. A well thought-out code base written by a skilled and experienced software architect is a lot more flexible than one hacked together by a beginner, which means that modifying the application after release will be a lot easier and thus cheaper. And the worse the initial development team, the more bugs and missing features will need to be fixed.

Title: Lead developer unable to do INNER JOIN

Body:
I had worked in the past for a small company developing web applications. Back then the current lead developer, who is also one of the bosses, told me that he is incapable of making a JOIN inside a SQL query.

I was amazed how a person who has developed and maintain big ecommerce site is incapable of doing that.

Are database normalization and functional dependencies a waste of time? Are they only necessary in big demanding projects?


问:
How to provide data to a web server using a data warehouse?
We have data stored in a data warehouse as follows:

Price

Date

Product Name (varchar(25))

We currently only have seven products. Once every business day, seven new data points are added representing the day's price for each product.

On the website, a user sees this information on a page load. Analytics shows that the amount of page loads is about 100 per day.

The website server is an external server to our data center. The data warehouse server is internal to our data center and has other critical data (in different tables) not related and should not be accessible to the website.

The following approaches have been considered:

1) The data warehouse could daily push (SFTP) a CSV file containing the daily data to the web server. The web server would have a process running on a crontab every 15 minutes. It would check if the file had changed. If so, it would update its database with the data. Then, on page loads, the web server would query its database to get the data to display on the web page.

Usually, the push would only be once a day, but more than one push could be possible to communicate (infrequent) price corrections. Even in the price correction scenario, all data would be delivered in the file. The polling process would pick up the change and overwrite the data in the database.

2) The web server could request data from the data warehouse using JDBC or similar SQL connection technology.

However, a security concerns have been voiced. The concern is that by allowing the web server access to our data warehouse, SQL injection attack or some other external attack through the website could compromise the data warehouse. Measures could be put in place to reduce the risk, but the easiest and safest approach has been suggested to simply not allow any public facing system to directly access the data warehouse. In other words, the data warehouse can establish a communication with other servers (say to SFTP the file), but no server can initiate a connection with the data warehouse. Do these concerns seem reasonable and hard to mitigate?

3) A web service could be built, and the web server could call the web service that is hosted in our internal data center.

4) A process hosted in our internal data center could call the web server when it knows the data warehouse has data available. If so, how should this be done? HTTPS with some way to prevent other unauthorized clients from making the same call?

Which of the above approaches is best or is there a better approach than listed above? What are the pros and cons to an approach?

答:
When you enter the prices each day in the data warehouse why not just put them in a database specific for the webserver that just holds "today's" prices? Does a static list of prices need to be in a database? You can't create a daily price file or are you planning on using it for other data purposes.

SQL databases are used all the time to provide data for websites, but you have to know how to avoid injection attacks. Not that this database for the website is as critical as your data warehouse, but someone in your company better learn how to handle the security.


问:
What do you deliver in the first couple of iterations in Agile?
As I understand, the idea with Agile methodologies is that you deliver something functional and you deliver it often. The application gets into its final shape increment after increment.

But in the early iterations you might build the framework or foundations on which the application will stand so it's something important but not visible to users.

What gets delivered to the client in these first iterations? How do you show progress in the right direction when you build scaffolding code?

答:
You can deliver pretty much anything you want. The building the infrastructure idea is simply wrong/not agile/unsustainable.

For example: building a fully functional Hello World app can be built in hours. Bringing up a server (even temporarily) in the cloud or as a VM can be done in hours.

These are enough to start developing. Then, if you need CI, you can add a CI story, if you neeed a physical server, sure, add a story for that.

But start delivering on Day 1 and never stop!


答:
I am assuming you weren't strictly referring to client side operations and are in .Net since you mentioned c#...

If you are on framework 4 you have the DLR (dynamic language runtime) or on any framework if you are storing the rules in sql you could also process them there or you could always use dynamic linq in the >3 frameworks or write the different functions as assemblies that can be loaded by name at runtime through an assembly load.

Not all of those are elegant in many cases, but I have had to use them all at times.

Title: Highly scalable and dynamic "rule-based" applications?

Body:
For a large enterprise app, everyone knows that being able to adjust to change is one of the most important aspects of design. I use a rule-based approach a lot of the time to deal with changing business logic, with each rule being stored in a DB. This allows for easy changes to be made without diving into nasty details. Now since C# cannot Eval("foo(bar);") this is accomplished by using formatted strings stored in rows that are then processed in JavaScript at runtime. This works fine, however, it is less than elegant, and would not be the most enjoyable for anyone else to pick up on once it becomes legacy.

Is there a more elegant solution to this? When you get into thousands of rules that change fairly frequently it becomes a real bear, but this cannot be that uncommon of a problem that someone has not thought of a better way to do this. Any suggestions? Is this current method defensible? What are the alternatives?

Edit: Just to clarify, this is a large enterprise app, so no matter which solution works, there will be plenty of people constantly maintaining its rules and data (around 10).  Also, The data changes frequently enough to say that some sort of centralized server system is basically a must.


问:
Using MVC strictly with DAAB?
I am the only one at my company that is familiar with MVC and they are getting more pressure to modernize and switch to MVC for future projects, so I was tasked to create a template to use as a base for any training or as a base for new projects. This is perfectly fine and I'm glad to do it.

However, one absolute requirement is that I use EL Data Access Block. Doesn't this kinda defeat the purpose of MVC and using an ORM for simpler data code?

I have tried looking everywhere online for any standard practices when using MVC with DAAB but I cannot find a single good article or tutorial or code anywhere, which leads me to believe I should not do it this way, but i have to..

So, on that note, is it possible for me to use EL Data Access for the Model and set it up so that it can be strongly typed and get it to basically act kinda like EF?

I was thinking that I could just create a t4 template or something to help generate the models based off of the DB tables and add as much of the CRUD operations as I could. No clue if this will be a good idea though.

答:
MVC is primarily a User Interface paradigm.  Part of the benefit derived from its modularity is that it shouldn't matter what your data repository looks like.

Just add a Service Layer to access your data repository, whatever that is.  If your application is complex enough to require a ORM, creating it with T4 templates is certainly one way to go.  In fact, several people have already done the work.

That said, if your employer is big on Microsoft, I don't see why Entity Framework wouldn't be on the table.

Title: Using MVC strictly with DAAB?


问:
Why would you opt to fully qualify a package instead of importing it?
In java, to print the date we could do either of the following:

Fully qualified

```<code>public class MyMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println(new java.util.Date());

    }

}
</code>```

Using an import

```<code>import java.util.*;

public class MyMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println(new Date());

    }

}
</code>```

What are the advantages and disadvantages to for each way?

For me, using an import seems tidier, as you can see at the top of your class, just what packages are being used.

答:
When I need to use two different classes with the same name or the codebase I'm writing for often utilizes classes with the same names (which can happen if the classes are from different packages).

This isn't such a rare conflict to happen:

java.util.Date

java.sql.Date

I can't tell you how many classes I've come across called "Document"

Keep in mind in your example that importing * means that you've increased the odds that you've imported a class with the same name as another class which was already imported.

Often if I'm only using a class in one place, I will not bother importing it but would rather explicitly say where it came from in the one place it's used.


问:
How can I compensate for having gone to a JavaSchool?
In an earlier question, I asked for career advice for new software engineers who did well before and during college.  But what about people who weren't fortunate enough to go to MIT or Yale, for whatever reason?  What if you went to what Joel Spolsky calls a JavaSchool?

What can/should JavaSchool alumni do to develop their skills and make up for the things they missed in college?  (Or, was Joel wrong about those schools being disadvantageous?)

答: Well, you can get a job writing software in Java.  So long as you are good at what you do, the school you went to and/or your major isnt terribly relevant past the first job, if even then.


问:
unit/integration testing web service proxy client
I'm rewriting a PHP client/proxy library that provides an interface to a SOAP-based .Net webservice, and in the process I want to add some unit and integration tests so future modifications are less risky.

The work the library I'm working on performs is to marshall the calls to the web service and do a little reorganizing of the responses to present a slightly more -object-oriented interface to the underlying service.

Since this library is little else than a thin layer on top of web service calls, my basic assumption is that I'll really be writing integration tests more than unit tests - for example, I don't see any reason to mock away the web service - the work that's performed by the code I'm working on is very light; it's almost passing the response from the service right back to its consumer.

Most of the calls are basic CRUD operations: CreateRole(), CreateUser(), DeleteUser(), FindUser(), &ct.

I'll be starting from a known database state - the system I'm using for these tests is isolated for testing purposes, so the results will be more or less predictable.

My question is this: is it natural to use web service calls to confirm the results of operations within the tests and to reset the state of the application within the scope of each test?  Here's an example:

One test might be createUserReturnsValidUserId() and might go like this:

```<code>public function createUserReturnsValidUserId() {
   // we're assuming a global connection to the service
   $newUserId = $client->CreateUser("user1");
   assertNotNull($newUserId);
   assertNotNull($client->FindUser($newUserId);
   $client->deleteUser($newUserId);
}
</code>```

So I'm creating a user, making sure I get an ID back and that it represents a user in the system, and then cleaning up after myself (so that later tests don't rely on the success or failure of this test w/r/t the number of users in the system, for example). However this still seems pretty fragile - lots of dependencies and opportunities for tests to fail and effect the results of later tests, which I definitely want to avoid.

Am I missing some options of ways to decouple these tests from the system under test, or is this really the best I can do?

I think this is a fairly general unit/integration testing question, but if it matters I'm using PHPUnit for the testing framework.

答:
Your test harness needs to have direct access to the data store to run queries developed for the particular test to validate the results and cleanup after the test.

Relying on other functions within the system being tested even if those functions aren't being tested in the same test means those functions must be 100% correct to the assumptions your test is making and in my opinion that can be an unsafe assumption.

I don't believe you can unit test your wrapper - it's just that and doesn't have any independent logic.


问:
Is there any specific reason to use "else if" clause?
We all use if ..else if.. else.

But still I'm confused as to why we use else if. Where if does the same thing as else if.

So why are we using else if?

Any specific reasons behind this?

Is there any algorithm where it's mandatory to use else if?

答:
The main reason to use else if is to avoid excessive indentation.

For example:

```<code>    if(a) {
    } else {
        if(b) {
        } else {
            if(c) {
            } else {
            }
        }
    }
</code>```

Can become:

```<code>    if(a) {
    } else if(b) {
    } else if(c) {
    }
</code>```

Of course both of the pieces of code above are equivalent (which means it's impossible for the latter to be mandatory other than in style guides).

Body:
The main reason to use else if is to avoid excessive indentation.

For example:

    if(a) {
    } else {
        if(b) {
        } else {
            if(c) {
            } else {
            }
        }
    }

Can become:

    if(a) {
    } else if(b) {
    } else if(c) {
    }

Of course both of the pieces of code above are equivalent (which means it's impossible for the latter to be mandatory other than in style guides).


问:
Specifics of Switch and If statements
Why do we need the  switch statement if there is the if statement? Why can't we use several ifs like

if(a==1) do this1;

  if(a==2) do this2;

  ...

instead of

switch (a) {

  case(1): {do this1;break;}

  case(2): {do this2;break;}

  ...

  }

My teacher said that the answer is built on how assembler works, but I've never worked with it.

Explain, please, why we have both switch and if?

答:
switch is more convenient to use than a series of ifs: you only have to type the tested expression once, and you don't have to type else if(...){} multiple times. Readability is the second most important property of code after correctness, so this is very important.

you can easily express that one case subsumes another by the judicious use or disuse of break between the cases. With if, you cannot easily express that one block of code should be executed for condition A and another for condition A or B.

switch on a small integral value can be implemented as a jump table rather than a series of tests. This means that the run time of the decision logic is constant rather than linear. In inner loops, this can provide a huge speed-up. (It is theoretically possible for a compiler to construct a jump table from a series of ifs if it can prove that they behave exactly like a switch would, but this is hard to do and expensive for the compiler, and is rarely done. Using a switch explicitly asserts that you're making multiple tests on the same expression, so it's much easier to detect the potential for this optimization.)

Title: Specifics of Switch and If statements


问:
Is the Observer pattern adequate for this kind of scenario?
I'm creating a simple game development framework with Ruby.

There is a node system. A node is a game entity, and it has position. It can have children nodes (and one parent node). Children are always drawn relatively to their parent.

Nodes have a @position field. Anyone can modify it. When such position is modified, the node must update its children accordingly to properly draw them relatively to it.

@position contains a Point instance (a class with x and y properties, plus some other useful methods).

I need to know when a node's @position's state changes, so I can tell the node to update its children.

This is easy if the programmer does something like this:

```<code>@node.position = Point.new(300,300)
</code>```

Because it is equivalent to calling this:

```<code># Code in the Node class
def position=(newValue)
  @position = newValue
  update_my_children    # <--- I know that the position changed
end
</code>```

But, I'm lost when this happens:

```<code>@node.position.x = 300
</code>```

The only one that knows that the position changed is the Point instance stored in the @position property of the node. But I need the node to be notified!

It was at this point that I considered the Observer pattern. Basically, Point is now observable.

When a node's position property is given a new Point instance (through the assignment operator), it will stop observing the previous Point it had (if any), and start observing the new one. When a Point instance gets a state change, all observers (the node owning it) will be notified, so now my node can update its children when the position changes.

A problem is when this happens:

```<code>@someNode.position = @anotherNode.position
</code>```

This means that two nodes are observing the same point. If I change one of the node's position, the other would change as well. To fix this, when a position is assigned, I plan to create a new Point instance, copy the passed argument's x and y, and store my newly created point instead of storing the passed one.

Another problem I fear is this:

```<code>somePoint = @node.position
somePoint.x = 500
</code>```

This would, technically, modify @node's position. I'm not sure if anyone would be expecting that behavior. I'm under the impression that people see Point as some kind of primitive rather than an actual object.

Is this approach even reasonable? Reasons I'm feeling skeptical:

I've heard that the Observer pattern should be used with, well, many observers. Technically, in this scenario there is only one observer at a time.

When assigning a node's position as another's (@someNode.position = @anotherNode.position), where I create a whole new instance rather than storing the passed point, it feels hackish, or even inefficient.

答:
You could solve this issue by making Point an immutable object. Immutable objects are objects with read-only properties which are set at creation and can not change during the lifetime of the object. This might seem limiting at first, but it greatly simplifies code because you have less effect-at-a-distance.

When you need to change a position, you would create a new Point and assign it. You could have an utility method in Point for this, like position.moveBy(3, -2) which doesn't change the Point object itself but returns a new Point object with a position relative to the current one.


问:
Is there a software engineering principle that relates reuse and regression test cost on a production system?
I've worked on a large financial transaction system for a bank that looked after Pensions and Investments. After 15 years of feature changes, the manual regression test cost had climbed to $200K per release. (10M LOC, $10M transacted per day). This system also interfaces with 19 other systems around the company moving lots of data around. This system was implemented in Java.

What we observe however, is that the more 'reuse' we do, the more regression test costs go up. (The reason being that you need to "test the code you touch" - and reused/shared code impacts a multiplicity of places when it is touched. So despite 'DRY - Do Not Repeat Yourself' - ie don't copy and paste code - we observe a financial incentive to copy and paste code.  This is to drive regression test costs down, because we don't want to modify code that could be shared, because that will cause a big regression test impact. )

My question is is there a software engineering principle that describes the relationship between reuse and regression test costs?

The reason I'd ask this question is that arguably there is a cost benefit in decomposing the system into smaller parts to be tested.

Assumptions:

'Regression test' means 'acceptance test' - ie another group spending time to write new and reuse old tests against the system on behalf of the business, including environment and data setups.

I know the knee-jerk reaction to a big regression test cost is 'more automated tests'. This is a good principle. In this environment there are a couple of challenges.

(a) Automated tests are less useful across system boundaries, unless that system has a high automated test coverage as well. (Sphere of influence challenge).

(b) It is culturally difficult to get momentum on programmer time or capital investment on high automated test coverage when your system is already large and complex.

(c) The cost of maintaining automated tests is hidden on a project, and so they are easily discarded at a project level.

(d) This is just the cultural reality of working in a bank.

(e) I'm working to solve this problem in a different way (decomposition).

答:
While there may be an "observable" rise in cost due to more testing being needed, that type of refactoring usually makes the code more maintainable in the future as you are decreasing the technical debt in the system.

This should hopefully reduce future bugs, and make new features or alterations to existing features easier to implement.

By easier, I mean they should take less time and therefore cost less.

Reduce, easier and less are all rather nebulous terms here and any future saving (or rather hoped for saving) is impossible to calculate as it hasn't happened yet.

A simpler code base should allow new employees, or existing employees moving onto the project get up to speed quicker, especially for large systems.

It may also reduce staff turnover in that existing project members morale could be improved.

It's of course not guaranteed that you will get these benefits, but these are things that should be considered alongside costs (like increased testing) that can be measured.

In fact, better code should eventually reduce the testing costs over time, even if there is an initial increase due to what you describe.


问:
proposed algorithm and representation of an algorithm
What is the difference between an ambiguity in a proposed algorithm and an ambiguity in the representation of an algorithm?

I have done some research and found out that ambiguity in the representation of an algorithm is when the representation can be understood by a group of people and not clear to another group e.g. a layman and a programmer.

答:
There can be no ambiguity in an algorithm. By definition, an algorithm is a procedure by which a computer can achieve a task without having to make any decisions on its own. Everything it does is determined by the algorithm steps and by the input values. Therefore, any ambiguity can only be due to errors in the representation.

Note that there are non-deterministic algorithms; these choose one of a set of possible actions at one step. However, the possible actions still need to be prescribed explicitly and without ambiguity, and the source of randomness is considered an input value. The distribution of randomness is usually also considered part of the algorithm description (usually you'll want to use the best random number available, i.e. one that is equidistributed but not predictable).


答:
Sequences of ifs are fragile and a common cause of error.  Chains of if..else if are even worse.

There are three main causes of error:

Mistyping the check condition

Omitting an option or options, so that there are conditions not catered for, with unexpected consequences for the code.

Unintentionally having overlapping conditions.

Example of error 1:

```<code>if (a == 0) ...
if (a = 1) ...
if (a == 2) ...
</code>```

Look at the second check.  The effect is that if a is not zero, it will always be set to 1. With a switch statement you can't really do this; you only type the condition once, so you either get it wrong for everything (which will soon become evident) or right for everything.

The second and third kinds of error are possible with switch but less likely, firstly because switch offers a default option and secondly because the layout is much clearer.  With chained ifs, you repeatedly type out the whole chec; with switch, you simply type the expected values.  Compare:

```<code>if (objectX.checkFunc(x - y) == 0) ...
if (objectX.checkFunc(x - y) == 1) ...
</code>```

to

```<code>switch(objectX.checkFunc(x - y) {
    case 0: ...
    case 1: ...
    default: ...
}
</code>```

But the most important thing I said in all of the above is this: you only type the condition once.  Code duplication is always a bad smell.  Don't repeat yourself if you have a clean way to avoid it.

Having said all of that, don't forget the break statement.  Most other languages which have something like switch do not allow fall-through; in those languages, it is much harder to have overlapping conditions in switch than in a sequence of if statements.  In C/C++ this is not the case; accidental fall-through is the most common error with switch.

Title: Specifics of Switch and If statements

Body:
Why do we need the  switch statement if there is the if statement? Why can't we use several ifs like

if(a==1) do this1;

  if(a==2) do this2;

  ...

instead of

switch (a) {

  case(1): {do this1;break;}

  case(2): {do this2;break;}

  ...

  }

My teacher said that the answer is built on how assembler works, but I've never worked with it.

Explain, please, why we have both switch and if?

Body:
Sequences of ifs are fragile and a common cause of error.  Chains of if..else if are even worse.

There are three main causes of error:

Mistyping the check condition

Omitting an option or options, so that there are conditions not catered for, with unexpected consequences for the code.

Unintentionally having overlapping conditions.

Example of error 1:

if (a == 0) ...
if (a = 1) ...
if (a == 2) ...

Look at the second check.  The effect is that if a is not zero, it will always be set to 1. With a switch statement you can't really do this; you only type the condition once, so you either get it wrong for everything (which will soon become evident) or right for everything.

The second and third kinds of error are possible with switch but less likely, firstly because switch offers a default option and secondly because the layout is much clearer.  With chained ifs, you repeatedly type out the whole chec; with switch, you simply type the expected values.  Compare:

if (objectX.checkFunc(x - y) == 0) ...
if (objectX.checkFunc(x - y) == 1) ...

to

switch(objectX.checkFunc(x - y) {
    case 0: ...
    case 1: ...
    default: ...
}

But the most important thing I said in all of the above is this: you only type the condition once.  Code duplication is always a bad smell.  Don't repeat yourself if you have a clean way to avoid it.

Having said all of that, don't forget the break statement.  Most other languages which have something like switch do not allow fall-through; in those languages, it is much harder to have overlapping conditions in switch than in a sequence of if statements.  In C/C++ this is not the case; accidental fall-through is the most common error with switch.


答:
Reading around I've found a few things, a bit less abstract than LSP violations (although they could be considered to be):

An immutable type which is subclassed may become mutable (bad for multi-threading, etc)

Polymorphic equality, you can then guarantee that the types are the same and not just equivalent.

Sealing classes also offers some Runtime/Reflection performance improvements

Title: Why do we need to use sealed on a class? Do we really need sealed?

Body:
Reading this article (by Eric Lippert), it has four arguments as to why you should use sealed, however, I don't understand why we actually need it. Philosophical/aesthetic reasons aside, why do we need to use sealed?

I can see how things like readonly from C# or const from C++ actually catch genuine errors. Is there any type of error that sealed can catch?

An often cited reason for sealing a class is because, it hasn't been to designed to be extended. What does that mean? Why is it important? Are there any real examples of this?

The point on compatibility isn't a reason why we need to seal classes but why it should be default.

The final point again is strange, because sealing your class doesn't prevent someone providing an alternative implementation in a heirachy.

If I didn't put enough emphasis, on it already I'm looking for reasons we actually need it. Not the usual, "someone else might write bad code". I understand that plenty of people like using sealed for design intent, but I'm looking for a practical purpose beyond that.


问:
How to test a website?
I found it's really hard to divide the task of developing a website to a team of people.

The problem is a website should have consistent looking and be integrated in users' view. The style and page template need to be shared by all parts. Most of the website is access restricted, the access control system is dependent of all modules. Some modules need data from other modules (you can never ask user the same question again). Although these modules may run independently. The test data have to be generated by other ones.

With the increase of code, the website becomes harder and harder to test. Although we are maintaining a script to automate the deployment. But if anything goes wrong, a developer cannot solve the problem by himself, for he is not familiar with others' work.

What makes things worse is the configuration. Server settings are highly machine dependent. Some functions need to schedule tasks, so there are some crontab configurations. Some modules need other daemons running in the backend. Some applications require URL rewriting. To test the website, we need to configure all dependencies of all modules on all machines.

Is there any suggestion about how to test a website?

答:
just some thinking in case you can find something helpful.

"Server settings are highly machine dependent", "we need to configure all dependencies of all modules on all machines." maybe you can reduce this problem creating the work environments with vagrant provisioned by puppet or whatever.

The more decoupling is your code the easier is going to be the unit testing and mocking. So I just can recommend you to planning refactoring workflows to achieve a more decoupled code.

Regarding the functional testing I just can say you should choose a framework (Cucumber for Ruby, Behat for PHP, etc) I try to make the most of the provided API to fit your necessities.

Title: How to test a website?


答:
This is discussed in a book Computer Science: An Overview (11th Edition) by J. Glenn Brookshear, in Chapter 5 Algorithms. To start with, author formally defines algorithm as follows:

An algorithm is an ordered set of unambiguous, executable steps that defines a terminating process

Further discussion is starting at page 189. Author explains the meaning of ambiguity in what you call "proposed algorithm" as follows:

requirement imposed by the definition... is that the steps in an algorithm be unambiguous. This means that during execution of an algorithm, the information in the state of the process must be sufficient to determine uniquely and completely the actions required by each step. In other words, the execution of each step in an algorithm does not require creative skills. Rather, it requires only the ability to follow directions.

For the sake of completeness, author points out that above requirement is intentionally narrowed: "In Chapter 12 we will learn that “algorithms,” called nondeterministic algorithms, that do not conform to this restriction are an important topic of research."

Ambiguity of algorithm representation is explained as follows:

It is important to emphasize the distinction between an algorithm and its representation — a distinction that is analogous to that between a story and a book. A story is abstract, or conceptual, in nature; a book is a physical representation of a story. If a book is translated into another language or republished in a different format, it is merely the representation of the story that changes — the story itself remains the same.

In the same manner, an algorithm is abstract and distinct from its representation. A single algorithm can be represented in many ways. As an example, the algorithm for converting temperature readings from Celsius to Fahrenheit is traditionally represented as the algebraic formula

```<code>   F = (9/5)C + 32
</code>```

But it could be represented by the instruction

```<code>    Multiply the temperature reading in Celsius by 9/5
    and then add 32 to the product
</code>```

or even in the form of an electronic circuit. In each case the underlying algorithm is the same; only the representations differ.

The distinction between an algorithm and its representation presents a problem when we try to communicate algorithms. A common example involves the level of detail at which an algorithm must be described. Among meteorologists, the instruction “Convert the Celsius reading to its Fahrenheit equivalent” suffices, but a layperson, requiring a more detailed description, might argue that the instruction is ambiguous. The problem, however, is not with the underlying algorithm but that the algorithm is not represented in enough detail for the layperson.

Further in the chapter, author also explains how to resolve it:

the concept of primitives can be used to eliminate such ambiguity problems in an algorithm’s representation.

...A program is a representation of an algorithm. (Here we are using the term algorithm in its less formal sense in that many programs are representations of nonterminating “algorithms.”) In fact, within the computing community the term program usually refers to a formal representation of an algorithm designed for computer application.

...communication problems arise when the language used for an algorithm’s representation is not precisely defined or when information is not given in adequate detail.

Computer science approaches these problems by establishing a well-defined set of building blocks from which algorithm representations can be constructed. Such a building block is called a primitive. Assigning precise definitions to these primitives removes many problems of ambiguity, and requiring algorithms to be described in terms of these primitives establishes a uniform level of detail. A collection of primitives along with a collection of rules stating how the primitives can be combined to represent more complex ideas constitutes a programming language...

Title: proposed algorithm and representation of an algorithm

Body:
What is the difference between an ambiguity in a proposed algorithm and an ambiguity in the representation of an algorithm?

I have done some research and found out that ambiguity in the representation of an algorithm is when the representation can be understood by a group of people and not clear to another group e.g. a layman and a programmer.

Body:
This is discussed in a book Computer Science: An Overview (11th Edition) by J. Glenn Brookshear, in Chapter 5 Algorithms. To start with, author formally defines algorithm as follows:

An algorithm is an ordered set of unambiguous, executable steps that defines a terminating process

Further discussion is starting at page 189. Author explains the meaning of ambiguity in what you call "proposed algorithm" as follows:

requirement imposed by the definition... is that the steps in an algorithm be unambiguous. This means that during execution of an algorithm, the information in the state of the process must be sufficient to determine uniquely and completely the actions required by each step. In other words, the execution of each step in an algorithm does not require creative skills. Rather, it requires only the ability to follow directions.

For the sake of completeness, author points out that above requirement is intentionally narrowed: "In Chapter 12 we will learn that “algorithms,” called nondeterministic algorithms, that do not conform to this restriction are an important topic of research."

Ambiguity of algorithm representation is explained as follows:

It is important to emphasize the distinction between an algorithm and its representation — a distinction that is analogous to that between a story and a book. A story is abstract, or conceptual, in nature; a book is a physical representation of a story. If a book is translated into another language or republished in a different format, it is merely the representation of the story that changes — the story itself remains the same.

In the same manner, an algorithm is abstract and distinct from its representation. A single algorithm can be represented in many ways. As an example, the algorithm for converting temperature readings from Celsius to Fahrenheit is traditionally represented as the algebraic formula

   F = (9/5)C + 32

But it could be represented by the instruction

    Multiply the temperature reading in Celsius by 9/5
    and then add 32 to the product

or even in the form of an electronic circuit. In each case the underlying algorithm is the same; only the representations differ.

The distinction between an algorithm and its representation presents a problem when we try to communicate algorithms. A common example involves the level of detail at which an algorithm must be described. Among meteorologists, the instruction “Convert the Celsius reading to its Fahrenheit equivalent” suffices, but a layperson, requiring a more detailed description, might argue that the instruction is ambiguous. The problem, however, is not with the underlying algorithm but that the algorithm is not represented in enough detail for the layperson.

Further in the chapter, author also explains how to resolve it:

the concept of primitives can be used to eliminate such ambiguity problems in an algorithm’s representation.

...A program is a representation of an algorithm. (Here we are using the term algorithm in its less formal sense in that many programs are representations of nonterminating “algorithms.”) In fact, within the computing community the term program usually refers to a formal representation of an algorithm designed for computer application.

...communication problems arise when the language used for an algorithm’s representation is not precisely defined or when information is not given in adequate detail.

Computer science approaches these problems by establishing a well-defined set of building blocks from which algorithm representations can be constructed. Such a building block is called a primitive. Assigning precise definitions to these primitives removes many problems of ambiguity, and requiring algorithms to be described in terms of these primitives establishes a uniform level of detail. A collection of primitives along with a collection of rules stating how the primitives can be combined to represent more complex ideas constitutes a programming language...


答:
Agreeing to what @verdammelt ,mocking is where we define an expectation for a given input which means we are defining both the input as well as output. If we mock web services similarly, it may be prove costly later.

So we decided not to mock our web services and expose it to actual & garbage values. With this approach we can check how the web service reacts and if any exceptions are thrown.

This was my personal experience with mocking web services. Hope it helps

Title: unit/integration testing web service proxy client

Body:
I'm rewriting a PHP client/proxy library that provides an interface to a SOAP-based .Net webservice, and in the process I want to add some unit and integration tests so future modifications are less risky.

The work the library I'm working on performs is to marshall the calls to the web service and do a little reorganizing of the responses to present a slightly more -object-oriented interface to the underlying service.

Since this library is little else than a thin layer on top of web service calls, my basic assumption is that I'll really be writing integration tests more than unit tests - for example, I don't see any reason to mock away the web service - the work that's performed by the code I'm working on is very light; it's almost passing the response from the service right back to its consumer.

Most of the calls are basic CRUD operations: CreateRole(), CreateUser(), DeleteUser(), FindUser(), &ct.

I'll be starting from a known database state - the system I'm using for these tests is isolated for testing purposes, so the results will be more or less predictable.

My question is this: is it natural to use web service calls to confirm the results of operations within the tests and to reset the state of the application within the scope of each test?  Here's an example:

One test might be createUserReturnsValidUserId() and might go like this:

```<code>public function createUserReturnsValidUserId() {
   // we're assuming a global connection to the service
   $newUserId = $client->CreateUser("user1");
   assertNotNull($newUserId);
   assertNotNull($client->FindUser($newUserId);
   $client->deleteUser($newUserId);
}
</code>```

So I'm creating a user, making sure I get an ID back and that it represents a user in the system, and then cleaning up after myself (so that later tests don't rely on the success or failure of this test w/r/t the number of users in the system, for example). However this still seems pretty fragile - lots of dependencies and opportunities for tests to fail and effect the results of later tests, which I definitely want to avoid.

Am I missing some options of ways to decouple these tests from the system under test, or is this really the best I can do?

I think this is a fairly general unit/integration testing question, but if it matters I'm using PHPUnit for the testing framework.


答:
Regarding the functional testing, you can also have a look to Selenium, a web browser automation tool enabling you to create and run complex functional scenarios.

See http://docs.seleniumhq.org/

Title: How to test a website?

Body:
I found it's really hard to divide the task of developing a website to a team of people.

The problem is a website should have consistent looking and be integrated in users' view. The style and page template need to be shared by all parts. Most of the website is access restricted, the access control system is dependent of all modules. Some modules need data from other modules (you can never ask user the same question again). Although these modules may run independently. The test data have to be generated by other ones.

With the increase of code, the website becomes harder and harder to test. Although we are maintaining a script to automate the deployment. But if anything goes wrong, a developer cannot solve the problem by himself, for he is not familiar with others' work.

What makes things worse is the configuration. Server settings are highly machine dependent. Some functions need to schedule tasks, so there are some crontab configurations. Some modules need other daemons running in the backend. Some applications require URL rewriting. To test the website, we need to configure all dependencies of all modules on all machines.

Is there any suggestion about how to test a website?


问:
Explicitly writing default empty constructor
Does it make sense to write default constructor when it has no arguments, empty body and no other constructors exist?

The only benefit I can think of is reducing the risk of forgetting to add the default constructor when another one is created. But this error would show up anyway if the default constructor is actually being used (at least if the class is "internal" and not in a library), and if it isn't used it can be omitted (yagni).

What benefit can this have?

答:
There is no benefit unless you are interacting with a tool or framework that detects your class's declared methods and constructors via reflection and then silently does different things depending on whether it finds the default constructor or not. (I seem to remember that early versions of Spring or Hibernate did this.)

Otherwise, as you say, any inconsistency would be flagged by the compiler, so there is no point in declaring things that would be auto-generated anyway.


答:
The only benefit I can foresee is that you can add specific documentation to this constructor, for instance to describe how to deal with the object after instantiation, etc...

In any other case, I do not think it is useful.

Title: Explicitly writing default empty constructor

Body:
Does it make sense to write default constructor when it has no arguments, empty body and no other constructors exist?

The only benefit I can think of is reducing the risk of forgetting to add the default constructor when another one is created. But this error would show up anyway if the default constructor is actually being used (at least if the class is "internal" and not in a library), and if it isn't used it can be omitted (yagni).

What benefit can this have?


答:
But this error would show up anyway if the default constructor is
  actually being used (at least in the class is "internal" and not in a
  library), and if it isn't used it can be omitted (yagni).

Xml deserialization. Yes the error would show up, but quite late - as an exception in runtime.


问:
How should I design the class for a database entity?
I'm studying OOP PHP and have watched two tutorials that implement user login\registration system as an example. But implementation varies. Which way will be more correct one to work with data such as this?

Load all data retrieved from database as array into a property called something like _data on class creation and further methods operate with this property

Create separate properties for each field retrieved from database, on class creation load all data fields into respective properties and operate with that properties separately?

Then let's say I want to create a method that returns a list of all users with their data. Which way is better?

Method that returns just an array of userdata like this:

```<code>Array([0]=>array([id] => 1, [username] => 'John', ...),
      [1]=>array([id] => 2, [username] => 'Jack', ...),
      ...)
</code>```

Method that creates a new instance of it's class for each user and returns an array of objects

答:
I would say that both situations are not appropriated:

The use of arrays to represent business objects is not a good practice. Client code needs to know the exact key of each array cell to correctly adress the data. Documented methods focusing on each field of the entity is definitely better for client-code. Moreover, depending on the size of the database, you might consume a lot of memory and searching into this data structure will be slow.

This is better from an OOP perspective. However, you will encouter the same issues as in point 1. As said by Aal, an ORM (Object Relational Mapper) such as Doctrine, will help you to solve memory consumption and slow search issues (see above) because ORMs usually implement querying languages and loading techniques such as Lazy/Eager loading.

To conclude, go for an ORM, or something old fashioned but still valid in small applications like the Active Record or Data Access Object patterns.


问:
What are the advantages of dynamically binding a method to class instance?
I came across Instagram's API client written in Python.

In their class InstagramAPI, they bind the methods to a function in bind.py. When called, the function returns an instance of the class InstagramAPIMethod and execute the request call.

What are the advantages of doing it this way? (over directly creating instances of InstagramAPIMethod in InstagramAPI)?

What will happen if the methods in InstagramAPI are called numerous times? Will it create new a instance every call?

Note, the only advantages I thought of are (probably I'm off track):

The class doesn't/shouldn't care what the implementing class is.

If a particular method is not called, we will never create an instance.

答:
I think in this way you have all the instantiations of that class centralized in only one place ( bind_method() ).

So if you have to make any change related to the constructor or the _call method signature or whatever you have to modify your code in only one place, otherwise you should try to find every line of code where you are making an instantiation of the class and calling _call method an modify it.
Hope this helps.


答:
the question asks, "why do you need else given that you can accomplish the same functionality using only if" (paraphrased). First of all, the two are only really equivalent in fairly simple programs; there are many situations where else if functionality cannot be easily replicated using only if statements.

that said, in such simple situations it is still usually better to use else if.

```<code>if (a==b){}
if (!(a==b) && a==c ){}
</code>```

there are two problems with this that are solved by using else if. First, you perform the comparison between a and b twice, which is unnecessary work. Second, unless you memorize the rules or rely heavily on parenthesis, it's not obvious how the second boolean expression resolves.

```<code>if (a==b) {}
else if (a==c) {}
</code>```

Is cleaner, clearer, and more efficient. It's basically the programming holy grail.

Title: Is there any specific reason to use "else if" clause?

Body:
We all use if ..else if.. else.

But still I'm confused as to why we use else if. Where if does the same thing as else if.

So why are we using else if?

Any specific reasons behind this?

Is there any algorithm where it's mandatory to use else if?

Body:
the question asks, "why do you need else given that you can accomplish the same functionality using only if" (paraphrased). First of all, the two are only really equivalent in fairly simple programs; there are many situations where else if functionality cannot be easily replicated using only if statements.

that said, in such simple situations it is still usually better to use else if.

if (a==b){}
if (!(a==b) && a==c ){}

there are two problems with this that are solved by using else if. First, you perform the comparison between a and b twice, which is unnecessary work. Second, unless you memorize the rules or rely heavily on parenthesis, it's not obvious how the second boolean expression resolves.

if (a==b) {}
else if (a==c) {}

Is cleaner, clearer, and more efficient. It's basically the programming holy grail.


答:
If we think programmatically the main purpose is if we have to choose one thing among many things at that time we should use else if.

Also there can be many ways of doing same things like switch..case in that case we can consider it as another construct.


问:
Bloom filters or similar, but with no false positive
To improve some lookups, I am considering the use of Bloom Filters. But in my use-case, the most probable outcome is that the element do exists in the target set.

Bloom filters can have false positive, but no false negatives. That would make me check the real (big and slow) storage most of the time because of the uncertainties.

Is there another algorithm/data structure with the same properties for space and computation speed (and parallelism of query) that can assure no false positive and a low probability of false negative?

(The max size of the set will be around 300k items, the items will be strings of, at most, 512 characters, and I will have hundreds of sets like that.)

答:
The nice thing about bloom filters is that their space requirement can be scaled arbitrarily, with the cost of more false positives as the size is decreased.

If you want no false positives whatsoever, you can't take probabilistic shortcuts and will not be able to reduce space requirements significantly (which isn't that much of an issue as storing each of your strings sequentially would only use up a few hundred MB per set).

There two important representations of string sets:

hash tables, and

tries.

These data structures allow parallel access, and each access is O(1) with respect to the number of items in the set.

Tries have the advantage that common prefixes of strings are shared, thus potentially reducing space requirements below that of sequential storage. A read-only trie can also be compressed further.


问:
Auto Transaction Failsafe's, Third Party API's, Coldfusion Schedule Files
I have an automated invoicing web app and I'm trying to build in some failsafes and a structure that will, under no circumstance, allow an invoice to be double charged.

All things working perfectly, the scheduled task runs and everything charges as it's supposed to. But there are a few scenarios we know of that can cause problems.

I've had a DB server go down in the middle of a process, which lead to a number of duplicate charges. Also if for whatever reason, the file needs to be checked in a browser, a developer hits refresh before the file is done processing, duplicate charges will occur.

There are a few similar scenarios to protect against, so you can see the need for a way to handle this given the sensitivity of the transactions (imaging seeing your power company auto charging you twice on your bank statement).

Current configuration:

Query

API POST For Transaction

```<code><!--- Parse Reply String --->
if response = "1"

 - Insert Into Payments

 - Update Invoice Amount Due

 - Insert Into Transactions

 - Email Accepted Notification

else

 - Email Declined Notification
</code>```

There's a few more smaller processes that happen between a few of these, as well as quite a few if statements but those are the heavy lifting parts.

What I would like to learn and hear about are what would be the best way to handle safeguarding this with considering the Third Party API for the gateway being there?

How would you break it up?

One idea I had was flagging each process after it ran to give a record of where it was when it failed, and build out the query to handle it accordingly. Not sure how efficient or more likely how inefficient it would be.

答:
If all of the queries are required to run in order for a transaction to be considered complete, then you need to the entire thing in a transaction, and roll it back if there is a problem. You should do something like this:

```<code><cftransaction action="begin">
    <cftry>

         - Insert Into Payments

         - Update Invoice Amount Due

         - Insert Into Transactions

         <cftransaction action="commit" />

        <cfcatch type = "any">
            <cftransaction action="rollback" />
            <cfrethrow />
        </cfcatch>
    </cftry>

</cftransaction>
</code>```

If everything in your inserts, updates, etc happens correctly, then the transaction will commit. If there are any errors, then the transaction will be rolled back, or the commit will simply never happen.

The transaction should also lock the table so that any requests to modify it should be blocked. Before you start doing the inserts and updates you should have a check to make sure that they should be done.

Body:
If all of the queries are required to run in order for a transaction to be considered complete, then you need to the entire thing in a transaction, and roll it back if there is a problem. You should do something like this:

<cftransaction action="begin">
    <cftry>

         - Insert Into Payments

         - Update Invoice Amount Due

         - Insert Into Transactions

         <cftransaction action="commit" />

        <cfcatch type = "any">
            <cftransaction action="rollback" />
            <cfrethrow />
        </cfcatch>
    </cftry>

</cftransaction>

If everything in your inserts, updates, etc happens correctly, then the transaction will commit. If there are any errors, then the transaction will be rolled back, or the commit will simply never happen.

The transaction should also lock the table so that any requests to modify it should be blocked. Before you start doing the inserts and updates you should have a check to make sure that they should be done.


问:
How to simulate a REST API?
I am working on a new project which will query data from a 3rd party REST API. This is for a real time sports data feed, so the feed only works when a game is actually taking place.

Although the 3rd party provides good documentation (XSD, etc), they have no way to simulate a game happening, and so to test code I have written against this API I would have to wait for an actual game to be happening.

My only recourse is to write code to simulate a game on my own, but it seems like a lot of work. How would you approach this?

答:
I recommend writing your own simulator. You can use it to test all sorts of scenarios;

Server accepts connection but doesn't respond

Server times out

Server send back garbage reply
etc...

When I've done this in the past, I've used "special" values in the request messages to prompt the simulator to do what I need. This also makes it possible to run end-to-end tests without going outside your development environment.

Edit: For example, if your project submits XML to a 3rd party service, the request might include e.g. <value>50.00</value>. The simulator can be coded (or, better, configured) so that 50.00 => explode, 60.00 => garbage, 70.00 => close connection, and so on. The idea is that the behaviour of the simulator depends on its input, which you control in each test case.

Title: How to simulate a REST API?


答: This is the perfect use case for a mock object.  There are mocking libraries for every popular language.  You would want to mock the object that provides the REST service responses to return test data.  You can either hand-generate the test data or collect it from previous calls to the live system.</p>

Title: How to simulate a REST API?

Body:
I am working on a new project which will query data from a 3rd party REST API. This is for a real time sports data feed, so the feed only works when a game is actually taking place.

Although the 3rd party provides good documentation (XSD, etc), they have no way to simulate a game happening, and so to test code I have written against this API I would have to wait for an actual game to be happening.

My only recourse is to write code to simulate a game on my own, but it seems like a lot of work. How would you approach this?


问:
Violating SQL principles
I have  to write a decent size database, 1GB more or less.

I have only taken an introductory semester regarding SQL databases. During the course we learned that the relational model under SQL has no implied order and that therefore when querying we should always have a variable that sets the correspondant order in the table.

However, when doing practical work I find 'convenient' to make already ordered small, infinite number of tables.

For example, lets say that you have 5 clients and that their info will never join their data together. Is it admissible to have a potentially infinite number of tables with a table per client?

For example, I append new rows already ordered to the database. The database is already ordered. Is it admissible to make an unordered query and just assume that is implicitly ordered?

All this violates the principles that I know. My boss, who does not know about databases says that if it works it works and that speed is important. What shall answer to him?

答:
It's never guaranteed that the query will be returned in clustered index order which is the only order you're likely to get implicitly. The 'convenience' to you is that the system is behaving the way you expect it to, but someone else querying or modifying the system may have different expectations resulting in bugs.

Having the same table repeated per client is one way of doing multi-tenancy which is a separate topic.

Title: Violating SQL principles