问:
Is requiring attribution GPL-compatible?
Can code licensed under a clause like this:

```<code>Redistribution of this work, with or without modification, is permitted if
Bob Joe is attributed as the original author or licensor of
this work, but not in any way that suggests that Bob Joe endorses
you or your use of the work.
</code>```

be used in a project using GPL, or does this make it incompatible with the GPL?

答:
You need a lawyer to get an absolute answer to this question, and I am not one.

However, what you're describing is very close to the BSD 3-clause license:

Copyright (c) -=YEAR=-, -=OWNER=-

  All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Neither the name of the -=ORGANIZATION=- nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

That license is generally agreed to be GPL compatible.  When you say Bob Joe is attributed as the original author, that's very much like saying that Redistributions of source code must retain the above copyright notice assuming it was copyright by Bob Joe.  Also, saying but not in any way that suggests that Bob Joe endorses you or your use of the work is very similar to the 3rd clause.  So if I had to guess, I'd say your quoted license is probably GPL compatible.

I would add, the reason the BSD 3-clause appears to be compatible is that the GPL (v2 in this case) has the following:

You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.

So the question might be "Does 'Bob Joe is attributed as the original author or licensor of this work' impose an extra condition?"  Again, if the copyright says Copyright (c) 2012 Bob Joe then I think by including that you've satisfied the original license and you're not adding a restriction that wasn't there in the GPL.  At least, I don't see how you're adding any restrictions.

Finally, you weren't really clear if this was a license you were going to use on a new work you're creating, or if it's one you came across and you want to use it in a GPL project.  If it's the first case, then for goodness sake, please just use the BSD 3-clause license.  No need to create any confusion by adding a new license to the pile.


问:
Something similar to Objective-C categories in other languages?
I understand Objective-C categories and how they become useful, but I always have a hard time explaining the concept to other programmers that are not familiar with Objective C.

Maybe I'm just bad at explaining things, but I was thinking at another way to explain it by comparing to similar features offered by other (more popular) languages. (ex : I can explain the similarities between Objective C protocols and Java Interfaces)

Any examples similar to Categories ?

答: C#'s class extension methods are basically the same thing done safely: you can only define methods that don't already exist, you can't violate encapsulation, and you can't compile code that imports the same extension method twice from different static classes.</p>

ContentLicense: CC BY-SA 3.0


问:
Task ownership with Wordpress - CSS - Designer or Developer?
We have a dispute regarding who owns which tasks when it comes to the CSS on our live site.

Our designer argues that he is not responsible to log-in to word press and modify the css or use ftp for any changes because that's not his job description while developer argues that since it is css, it belongs to designer and that he is to update the changes to the server and then compare and correct the output.

I'd like experienced people working in professional development environment to put a light on this scenario. I'm not sure if this is the right place to ask this question, or is there a separate forum for business development or project management specific questions?

答:
In short, it is a team work. Needs a collaboration to achieve the results. As my previous company logo was saying, "Results matter..."

The developer and designer in your team need to learn how to work and make job done, rather shifting responsibilities from one to another.


问:
Is Creative-Commons license compatible with Apache License?
For example if I have code that contains parts of code rewritten from code found here or on Stack Overflow or other Creative-Commons licensed code, can my final code be licensed with an Apache License?</p>

答:
You should read and understand any license that you agree to. CC licenses, like CC-BY-SA-3.0, explicitly state:

You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License.

There are currently no approved compatible licenses.

IANAL, but it seems to me that you cannot sublicense CC content under the Apache license.

See also:

What is up with the source code license on Stack Overflow?

Re-using ideas or small pieces of code from stackoverflow.com


答:
Generally, CSS modifications belong to the designer not the developer.  So it would be the designer's responsibility to update the live site.

However, there are some exceptions to that rule.

The designer may not have access to the live site.  If so, then someone else is now responsible for promoting to production.

Separation of duties would dictate that someone other than the designer promotes to production.  This would imply that your team's developer wouldn't be promoting to production either.  Or at least, not for pieces they wrote.

More importantly, what's the past precedent and what does everyone's boss say on the matter?

Title: Task ownership with Wordpress - CSS - Designer or Developer?

Body:
We have a dispute regarding who owns which tasks when it comes to the CSS on our live site.

Our designer argues that he is not responsible to log-in to word press and modify the css or use ftp for any changes because that's not his job description while developer argues that since it is css, it belongs to designer and that he is to update the changes to the server and then compare and correct the output.

I'd like experienced people working in professional development environment to put a light on this scenario. I'm not sure if this is the right place to ask this question, or is there a separate forum for business development or project management specific questions?


问:
Pronunciation in programming?
How do you correctly or erroneously pronounce programming terms?  Any that you find need strict correction or history into the early CS culture?

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

regex = "rej ex" not "regg ex"?

sql = "s q l" not "sequel" (already answered, just i.e.)

Unixen

| = pipe not vertical bar?

bin = bin as in pin , not as in binary?

lib = lib as in library , not as in liberate?

etc = "ett see" , not "e t c" (as in /etc and not "&c")

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"

答:
char = 'chaar' as in 'the charred remains of the pointy-haired boss were found in the server room'

! = 'bang' if i'm talking to a linux/unix geek, 'exclamation mark' if i'm talking to a normal person

# = 'pound' if i'm talking to a programmer, 'number sign' for everyone else

#! = hash-bang if i'm talking to a Perlie, no need to say this to anyone else

* = asterisk, occasionally star

regex = regg as in reggae, ex as in ex-employee

sql = SQUEAL

| = 'pipe' when talking to systems programmers, 'vertical bar' for normal people

bin = 'bin' as in 'bin thar, dun that'

lib = 'lib' as in liberation

etc = et cetera

/ = forward slash, so there's no ambiguity

LaTeX = lahy tehx, since I'm Southern

ContentLicense: CC BY-SA 2.5

Title: Pronunciation in programming?


问:
Pair programming and unit testing
My team follows the Scrum development cycle. We have received feedback that our unit testing coverage is not very good.

A team member is suggesting the addition of an external testing team to assist the core team, but I feel this will backfire in a bad way.

I am thinking of suggesting pair programming approach. I have a feeling that this should help the code be more "test-worthy" and soon the team can move to test driven development!

What are the potential problems that might arise out of pair programming??

答:
If your projects are big, a separate test team is the way to go. Most big software firms have separate test teams.

Pair programming does improve the quality of the code, but it has one big potential problem: most managers don't like it and will try no prevent it. They think they are paying two people to do the work of one.

Edit after reading @Giorgio 's comment:

"You should not test your own code", that's true. Working knowing that other people will test, means you have to programm according to accepted standards. No "I understand my own mess" kind of logic.

Title: Pair programming and unit testing


答:
From my personal experience as a team member which has gone through a similar process, the choice of pair-programming and TDD was very successful and useful. Our coverage has increased significantly.

What we did was:

force pairs for production code. No code was allowed to be committed if not created in pairs.

force TDD, no code was allowed to be committed if not TDDed.

It was hard and slow at first (a few weeks, about a month and a half), but than it became very practical and natural.

EDIT: Naturally we had very high code coverage an new code, and we refactored old code and added test to it slowly. When an old class / module had to be modified, we added tests and modifications. Gradually coverage became pretty good at the level of the whole project.

Finally, after we were used to both processes, the mandatory nature of the 2 processes was removed and now we pare naturally most of the time (about 90%) but we also commit simple stuff made single or without TDD.

Title: Pair programming and unit testing

Body:
My team follows the Scrum development cycle. We have received feedback that our unit testing coverage is not very good.

A team member is suggesting the addition of an external testing team to assist the core team, but I feel this will backfire in a bad way.

I am thinking of suggesting pair programming approach. I have a feeling that this should help the code be more "test-worthy" and soon the team can move to test driven development!

What are the potential problems that might arise out of pair programming??


答:
In our business, the designer is the architect and the developer is the carpenter. CSS is code so the developer writes it up.

However, some of our designers are very good at CSS and we let them write it up. Even then our developer oversees their work.

The problem you may have is that your developer is not design oriented and feels uncomfortable handling that and your designer is uncomfortable handling code. You may just have the wrong people for the job. Or you need a go-between person.


答:
In fact, Pair Programming will not help you.  The main benefit of pair programming is to spread or combine knowledge to solve some problems.

The test "discipline" is a huge new universe. We have a lot of approaches to do testing, and it is a long time process. If your company does not have time, money, and employers to implement a good test process, an external testing team can be the viable solution.

Title: Pair programming and unit testing


问:
Where can I find accessible bug/issue databases with complete revision history
I'm performing some research and analysis on bug/issue tracking databases and more specifically on how programmers and teams of programmers actually interact with them. What I'm looking for involves understanding how those databases change over time.

So what I don't need for example: is a database of all the bugs of some open source project as the bugs exist today. What I do need is a complete set of revision history for every issue/bug in the database. This would enable me to pick a specific datetime and say here were the list of all the issues/bugs that existed at that moment in time.

Anyway know of some publicly accessible issue/bug databases that expose this revision data?

Ideally, the revision would look something like this (shown for a single bug, with two revisions)

```<code> ISSUEID  PRI  SEV  ASSIGNEDTO  MODIFIEDON      VALIDUNTIL
 1        2    2    mel         apr-1-2010:5pm  apr-1-2010:6pm
 1        2    3    steve       apr-1-2010:6pm  NULL
</code>```

答:
You might want to have a look at Philip Guo's publications (and maybe get into contact). If I remember correctly, he published a few papers for which he had access to data of big bug trackers.
http://www.pgbovine.net/academic.htm#pubs</p>


问:
Doesn't "if (0 == value) ..." do more harm than good?
This is one of the things that I hate most when I see it in someone else's code. I know what it means and why some people do it this way ("what if I accidentally put '=' instead?"). For me it's very much like when a child goes down the stairs counting the steps out loud.

Anyway, here are my arguments against it:

It disrupts the natural flow of reading the program code. We, humans, say "if value is zero" and not "if zero is value".

Modern compilers warn you when you have an assignment in your condition, or actually if your condition consists of just that assignment, which, yes, looks suspicious anyway

You shouldn't forget to put double '=' when you are comparing values if you are a programmer. You may as well forget to put "!" when testing non-equality.

答:
Some people use it to make it clear exactly what a conditional is doing. For instance:

Way 1:

```<code>FILE *fp;

fp = fopen("foo.txt", "w+");
if (fp == NULL) {
</code>```

Way 2:

```<code>FILE *fp;

if (NULL == (fp = fopen("foo.txt", "w+"))) {
</code>```

Some people feel that the second example is more concise, or reversing arguments illustrates the point of a test (conditional) prior to the test itself.

In all actuality, I don't really mind either way. I have my pet peeves about style and the biggest one is inconsistency. So, do it the same way, consistently and I won't mind reading your code.

Mix it up to the point where it looks like six different people with their own distinctive style worked on it at once, I get a little annoyed.

Body:
Some people use it to make it clear exactly what a conditional is doing. For instance:

Way 1:

FILE *fp;

fp = fopen("foo.txt", "w+");
if (fp == NULL) {

Way 2:

FILE *fp;

if (NULL == (fp = fopen("foo.txt", "w+"))) {

Some people feel that the second example is more concise, or reversing arguments illustrates the point of a test (conditional) prior to the test itself.

In all actuality, I don't really mind either way. I have my pet peeves about style and the biggest one is inconsistency. So, do it the same way, consistently and I won't mind reading your code.

Mix it up to the point where it looks like six different people with their own distinctive style worked on it at once, I get a little annoyed.


答:
There's easier way to achieve higher coverage. Simply make a rule that no code is allowed to be committed unless it is covered by sufficient amount of tests (what sufficient means is another story though). Of course pair programming might help, but there's no guarantee that when your pair consists of two test-reluctant people, they will suddenly produce test-heavy code (I'd even say it's highly likely they'll stick to their test-reluctance together).

For the record, forcing people to write tests might result in very poor tests, which is opposite to what you want to achieve. I think it might be good idea to pre-assign pairs, ie. test-aware person with test-reluctant person, so the former can help out and explain why things are being dealt with in a certain way to the later.

Title: Pair programming and unit testing


答:
Your question is orthogonal to your problem. Sticking two programmers that don't want to or can't write good unit tests together isn't going to get you more/better unit tests.

Sticking a programmer who is poor at writing unit tests with one that is good might propogate good habits, but might not be a good pair for other reasons (unit testing is only a part of the entire development process after all). There are other questions/posts that deal with pair programming's benefits and problems.

Your goal should be to change the culture that caused the problem in the first place. Well done pair programming can help that, but it will usually require a combination of things all pushing towards that end goal. There is no silver bullet (pun intended) for making people write good unit tests.

Title: Pair programming and unit testing


问:
Proper attribution of derived work in a GPL project
This is a continuation of me rewriting GPL project.

What will be the correct way of attributing my project as being a derivative of some other GPL-licensed project? So far I came up with:

```<code>HgSharp

Original Copyright Matt Mackall <mpm@selenic.com> and contributors.

The following code is a derivative work of the code from the Mercurial project,
which is licensed GPLv2. This code therefore is also licensed under the terms
of the GNU Public License, verison 2.

For information on the license of this code when distributed with and used
in conjunction with the other modules in the HgSharp project, please see
the root-level COPYING file.

Copyright 2011-2012 Anton Gogolev <anton.gogolev@hglabhq.com>
</code>```

答:
This is what I came up with after discussing and issue with Matt Mackall directly:</p>

```<code>// HgSharp
//
// Copyright 2005-2012 Matt Mackall <mpm@selenic.com> and Mercurial contributors
// Copyright 2011-2012 Anton Gogolev <anton.gogolev@hglabhq.com>
//
// The following code is a derivative work of the code from the Mercurial project,
// which is licensed GPLv2. This code therefore is also licensed under the terms
// of the GNU Public License, verison 2.
</code>```

Body:
This is what I came up with after discussing and issue with Matt Mackall directly:

// HgSharp
//
// Copyright 2005-2012 Matt Mackall <mpm@selenic.com> and Mercurial contributors
// Copyright 2011-2012 Anton Gogolev <anton.gogolev@hglabhq.com>
//
// The following code is a derivative work of the code from the Mercurial project,
// which is licensed GPLv2. This code therefore is also licensed under the terms
// of the GNU Public License, verison 2.


问:
What can go wrong if the Liskov substitution principle is violated?
I was following this highly voted question on possible violation of Liskov Substitution principle. I know what the Liskov Substitution principle is, but what is still not clear in my mind is what might go wrong if I as a developer do not think about the principle while writing object-oriented code.</p>

答:
If you don't fulfill the contract that has been defined in the base class, things can silently fail when you get results that are off.

LSP in wikipedia states

Preconditions cannot be strengthened in a subtype.

Postconditions cannot be weakened in a subtype.

Invariants of the supertype must be preserved in a subtype.

Should any of these not hold, the caller might get a result he does not expect.


答:
I think it's stated very well in that question which is one of the reasons that was voted so highly.

Now when calling Close() on a Task, there is a chance the call will
  fail if it is a ProjectTask with the started status, when it wouldn't
  if it was a base Task.

Imagine if you will:

```<code>public void ProcessTaskAndClose(Task taskToProcess)
{
    taskToProcess.Execute();
    taskToProcess.DateProcessed = DateTime.Now;
    taskToProcess.Close();
}
</code>```

In this method, occasionally the .Close() call will blow up, so now based on the concrete implementation of a derived type you have to change the way this method behaves from how this method would be written if Task had no subtypes that could be handed to this method.

Due to liskov substitution violations, the code that uses your type will have to have explicit knowledge of the internal workings of derived types to treat them differently. This tightly couples code and just generally makes the implementation harder to use consistently.

Title: What can go wrong if the Liskov substitution principle is violated?

Body: I was following this highly voted question on possible violation of Liskov Substitution principle. I know what the Liskov Substitution principle is, but what is still not clear in my mind is what might go wrong if I as a developer do not think about the principle while writing object-oriented code.</p>

Body:
I think it's stated very well in that question which is one of the reasons that was voted so highly.

Now when calling Close() on a Task, there is a chance the call will
  fail if it is a ProjectTask with the started status, when it wouldn't
  if it was a base Task.

Imagine if you will:

public void ProcessTaskAndClose(Task taskToProcess)
{
    taskToProcess.Execute();
    taskToProcess.DateProcessed = DateTime.Now;
    taskToProcess.Close();
}

In this method, occasionally the .Close() call will blow up, so now based on the concrete implementation of a derived type you have to change the way this method behaves from how this method would be written if Task had no subtypes that could be handed to this method.

Due to liskov substitution violations, the code that uses your type will have to have explicit knowledge of the internal workings of derived types to treat them differently. This tightly couples code and just generally makes the implementation harder to use consistently.


问:
Directly copying third-party API
I'm currently planning on implementing API for HgLab and the obvious role model for me here is GitHub.

My API obviously won't be an exact copy due to inherent differences between Mercurial and Git and due to different tasks GitHub and HgLab solve, but similarity will be quite clear.

How ethical of me will it be to copy their API to a significant extent? Is the API design copyrightable?

答:
I am not a lawyer. If you are genuinely worried about this you should consult one.

It is typically considered fine to duplicate an API as long as you don't look at the implementation at all. For instance, this is what the Wine project does with the Win32 API. In Oracle's recent court case against Google, one of Oracle's arguments was that Google was not allowed to copy Oracle's APIs for Java, however, the court did not agree with this argument.

Title: Directly copying third-party API


问:
Is it a bug or a task when something doesn't work, yet, in development process
We usually have this dilemma in our team.  Sometimes, in order to implement a task or a story we find out that the system must be in a specific state.  For example, a specific system configuration has to be made beforehand.

The task / story can be completed and it is working as specified on it with the proper configuration in place.  Note that the configuration is not directly related with the task.

Next, we have to create a new ... ??? ... something for the process of generating that configuration file.  This is where the problems appear.  Some say that it is a bug others say it is a task or an extra feature.

So, where is the limit between bugs and tasks in the development phase?  Should we even consider something a bug if all the tasks are working as stated in their definitions?  Can a thing be considered a bug because one compares it to the current (unstable) state of the system?

Short example:

A feature requires configuring a communication service for a specific
operation.

In the process of the implementation the team discovers that the service requires the hostnames of the pears to be resolvable to an IP address.

The team adds the hostnames to the DNS server (or hosts files) and continues implementing the required feature.

After the initial feature is working, a question is risen. Should the sysadmin configure the DNS or hosts file or should our application do it automatically?

An automatic solution is possible. So a decision is made to implement it.

... here start the discussions ... is this a bug or an extra feature / task?

PS: I know that I mixed feature / task / story in the question.  It is intentional.  I am interested in separating bugs from the rest.  Doesn't matter what the rest means in a particular case.

答:
What is the difference between a "bug" and a "task/new feature"?

I define a "bug" as something you have to fix/implement for free (the software provider has to pay the costs).

A "task/new feature" is something the customer has to pay for.

With this definition a customer might see every "issue" as a bug because he will get it fixed for free. The software provider on the other hand wants to get paid for his development.

Your example

Should the sysadmin configure the DNS or hosts file or should our application do it automatically?

  An automatic solution is possible. So a decision is made to implement it.

is a classical feature creep.

For a fixed price project the solution for this dilemma is a contract that defines which features are included in the product and which are not.

Every contract-feature that is missing is a bug.


问:
PHP - Data Access Layer
I am currently reviewing a code base and noticed that a majority of the calls (along with DB connections) are just buried inside the PHP scripts. I would have assumed that like other languages they would have developed some sort of data access layer (Like I would do in .Net or Java) for all of the communication to the DB (or implemented MVC, etc). Is this still a common pattern in PHP or is there alternative methodologies/patterns for this technology? I am just trying to understand why the subs would have developed it this way.

Any insight/info on how experienced developers design an approach data access in PHP would be very much appreciated.

答:
It is pretty common in PHP Projects to have some kind of Data Abstraction or Data Access Layer.
Simply because of DRY Principles and cleaner error handling. Experienced Programmers don't like to repeat themselves over and over again and they seperate domain logic from data manipulation as much as possible.

There are lots of very good Frameworks and components out there to help with Data Abstraction or even Object Relational Mapping, see this Post at SO.

You might experience what lots of other code reviewers experienced before:

(from: http://www.osnews.com/story/19266/WTFs_m)

Title: PHP - Data Access Layer


答:
In layman's words:

Your code will have an awful lot of CASE/switch clauses all over.

Every one of those CASE/switch clauses will need new cases added from time to time, meaning the code base is not as scalable and maintainable as it should be.

LSP allows code to work more like hardware:

You don't have to modify your iPod because you bought a new pair of external speakers, since both the old and the new external speakers respect the same interface, they are interchangeable without the iPod losing desired functionality .


问:
PHP PSR-0 + several namespaces in one file and autoload
I've been thinking for a while about defining several namespaces in one php file and so, having several classes inside this file.

Suppose, I want to implement something like Doctrine\ORM\Query\Expr:

```<code>Expr.php
Expr
|-- Andx.php
|-- Base.php
|-- Comparison.php
|-- Composite.php
|-- From.php
|-- Func.php
|-- GroupBy.php
|-- Join.php
|-- Literal.php
|-- Math.php
|-- OrderBy.php
|-- Orx.php
`-- Select.php
</code>```

It would be nice if I had all of this in one file - Expr.php:

```<code>namespace Doctrine\ORM\Query;
class Expr {
    // code
}

namespace Doctrine\ORM\Query\Expr;

class Func {
    // code
}

// etc...
</code>```

What I'm thinking of is directories naming convention and, unlike PSR-0 having several classes and namespaces in one file. It's best explained by the code:

```<code>ls Doctrine/orm/query
Expr.php
</code>```

that's it - only Expr.php

Since Expr.php is somewhat I call a "meta-namespace" for Expr\Func, it make sense to place all the classes inside Expr.php (as shown above).

So, the vendor name is still starts with an uppercased letter (Doctrine) and the other parts of namespace start with lowercased letter. We can write an autoload so it would respect this notion:

```<code>function load_class($class) {
    if (class_exists($class)) {
        return true;
    }
    $tokenized_path = explode(array("_", "\\"), DIRECTORY_SEPARATOR, $class);
    // array('Doctrine', 'orm', 'query', 'Expr', 'Func');
    //                                    ^^^^
    // first, we are looking for first uppercased namespace part
    // and if it's not last (not the class name), we use it as a filename
    // and wiping away the rest to compose a path to a file we need to include
    if (FALSE !== ($meta_class_index = find_meta_class($tokenized_path))) {
        $new_tokenized_path = array_slice($tokenized_path, 0, $meta_class_index);
        $path_to_class = implode(DIRECTORY_SEPARATOR, $new_tokenized_path);
    }
    else { // no meta class found
        $path_to_class = implode(DIRECTORY_SEPARATOR, $tokenized_path);
    }
    if (file_exists($path_to_class.'.php')) {
        require_once $path_to_class.'.php';
    }
    return false;
}
</code>```

Another reason to do so is to reduce a number of php files scattered among directories.
Usually you check file existence before you require a file to fail gracefully:

```<code>file_exists($path_to_class.'.php');
</code>```

If you take a look at actual Doctrine\ORM\Query\Expr code, you'll see they use all of the "inner-classes", so you actually do:

```<code>file_exists("/path/to/Doctrine/ORM/Query/Expr.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/AndX.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Base.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Comparison.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Composite.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/From.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Func.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/GroupBy.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Join.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Literal.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Math.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/OrderBy.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Orx.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Select.php");
</code>```

in your autoload which causes quite a few I/O reads.
Isn't it too much to check on each user's hit?

I'm just putting this on a discussion.

I want to hear from another PHP programmers what do they think of it.
And, of course, if you have a silver bullet addressing this problems I've designated here, please share.

I also have been thinking if my vogue question fits here and according to the FAQ it seems like this question addresses "software architecture" problem slash proposal.

I'm sorry if my scribble may seem a bit clunky :)
Thanks.

答:
You were asking if the classes in question would cause IO on every class. But you might overlooked this code at the beginning of the autoload function

```<code>if (class_exists($class)) {
    return true;
}
</code>```

as soon as the 'container' file Expr.php is loaded, all the classes inside will be registered in php and therefore every subsequent call to autoload would result in class_exists() == true

If you decide to have several classes in one file, simply make sure that the class which would resolve the autoload correctly is used before any other inline classes. This would effectively save I/O compared to the one-class-per-file approach.

Body:
You were asking if the classes in question would cause IO on every class. But you might overlooked this code at the beginning of the autoload function

if (class_exists($class)) {
    return true;
}

as soon as the 'container' file Expr.php is loaded, all the classes inside will be registered in php and therefore every subsequent call to autoload would result in class_exists() == true

If you decide to have several classes in one file, simply make sure that the class which would resolve the autoload correctly is used before any other inline classes. This would effectively save I/O compared to the one-class-per-file approach.


答:
I haven't worked in a PHP project for long now.

But I remember a few data abstraction layers for the PHP:

PDO

PEAR DB (obsolete)

PEAR MDB2

Beside these, PHP frameworks feature helpers and data layers (for example CodeIgniter database library).

Title: PHP - Data Access Layer

Body:
I am currently reviewing a code base and noticed that a majority of the calls (along with DB connections) are just buried inside the PHP scripts. I would have assumed that like other languages they would have developed some sort of data access layer (Like I would do in .Net or Java) for all of the communication to the DB (or implemented MVC, etc). Is this still a common pattern in PHP or is there alternative methodologies/patterns for this technology? I am just trying to understand why the subs would have developed it this way.

Any insight/info on how experienced developers design an approach data access in PHP would be very much appreciated.


答:
Keep using a single file per class.

You use APC, right? If you don't, start doing it right now. APC will cache the opcode, thus there will be no performance hit on the file checking.

It's not worth losing so much readability.

Title: PHP PSR-0 + several namespaces in one file and autoload

Body:
I've been thinking for a while about defining several namespaces in one php file and so, having several classes inside this file.

Suppose, I want to implement something like Doctrine\ORM\Query\Expr:

```<code>Expr.php
Expr
|-- Andx.php
|-- Base.php
|-- Comparison.php
|-- Composite.php
|-- From.php
|-- Func.php
|-- GroupBy.php
|-- Join.php
|-- Literal.php
|-- Math.php
|-- OrderBy.php
|-- Orx.php
`-- Select.php
</code>```

It would be nice if I had all of this in one file - Expr.php:

```<code>namespace Doctrine\ORM\Query;
class Expr {
    // code
}

namespace Doctrine\ORM\Query\Expr;

class Func {
    // code
}

// etc...
</code>```

What I'm thinking of is directories naming convention and, unlike PSR-0 having several classes and namespaces in one file. It's best explained by the code:

```<code>ls Doctrine/orm/query
Expr.php
</code>```

that's it - only Expr.php

Since Expr.php is somewhat I call a "meta-namespace" for Expr\Func, it make sense to place all the classes inside Expr.php (as shown above).

So, the vendor name is still starts with an uppercased letter (Doctrine) and the other parts of namespace start with lowercased letter. We can write an autoload so it would respect this notion:

```<code>function load_class($class) {
    if (class_exists($class)) {
        return true;
    }
    $tokenized_path = explode(array("_", "\\"), DIRECTORY_SEPARATOR, $class);
    // array('Doctrine', 'orm', 'query', 'Expr', 'Func');
    //                                    ^^^^
    // first, we are looking for first uppercased namespace part
    // and if it's not last (not the class name), we use it as a filename
    // and wiping away the rest to compose a path to a file we need to include
    if (FALSE !== ($meta_class_index = find_meta_class($tokenized_path))) {
        $new_tokenized_path = array_slice($tokenized_path, 0, $meta_class_index);
        $path_to_class = implode(DIRECTORY_SEPARATOR, $new_tokenized_path);
    }
    else { // no meta class found
        $path_to_class = implode(DIRECTORY_SEPARATOR, $tokenized_path);
    }
    if (file_exists($path_to_class.'.php')) {
        require_once $path_to_class.'.php';
    }
    return false;
}
</code>```

Another reason to do so is to reduce a number of php files scattered among directories.
Usually you check file existence before you require a file to fail gracefully:

```<code>file_exists($path_to_class.'.php');
</code>```

If you take a look at actual Doctrine\ORM\Query\Expr code, you'll see they use all of the "inner-classes", so you actually do:

```<code>file_exists("/path/to/Doctrine/ORM/Query/Expr.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/AndX.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Base.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Comparison.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Composite.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/From.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Func.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/GroupBy.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Join.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Literal.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Math.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/OrderBy.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Orx.php");
file_exists("/path/to/Doctrine/ORM/Query/Expr/Select.php");
</code>```

in your autoload which causes quite a few I/O reads.
Isn't it too much to check on each user's hit?

I'm just putting this on a discussion.

I want to hear from another PHP programmers what do they think of it.
And, of course, if you have a silver bullet addressing this problems I've designated here, please share.

I also have been thinking if my vogue question fits here and according to the FAQ it seems like this question addresses "software architecture" problem slash proposal.

I'm sorry if my scribble may seem a bit clunky :)
Thanks.


答:
It's still very common.  Please do not invent the wheel - here are two great libraries you can use:

Zend Framework's Db component:

PHP 5.2: Zend_Db (ZF1)

PHP 5.3: Zend\Db (ZF2)

Doctrine's DBAL component

PDO is a nice abstraction layer, but it's lower level than these other two.  I'd recommend Zend Db over Doctrine DBAL, unless you want an ORM, then I highly recommend the Doctrine DBAL/ORM route.

Title: PHP - Data Access Layer


问:
How to learn & introduce scrum in small startup?
In a few months, a friend will establish his startup software company, and I will be the software architect with one additional developer. Though we have no real day-to-day experience with agile methods, I have read much "overview" type of material on them, and I firmly believe they are a good - if not the only - way to build software. So with this company, I want to go for iterative, agile development from day 1, preferably something light-weight.

I was thinking of Scrum, but the question is: what is the best way for me and my colleagues to learn about it, to introduce it (which techniques when etc) and to evaluate whether we should keep it?

Background which might be relevant: we're all experienced developers around the same age with similar professional mindset. We have worked together in the past and afterwards at several different companies, mostly with a Java/.NET focus. Some are a bit familiar with general ideas from the agile movement. In this startup, I have great power over tools, methods and process. The startup's product will be developed from scratch and could be classified as middleware. We have some "customer" contacts in the industry who could provide input as soon as we get to an alpha stage.

答:
No need to spend alot of money to learn scrum man. Just do your work and Im sure you can learn all you need.

Most importantly I just want to say keep it simple. Allow your process to grow organically. Remember you want to be able to embrace change and produce working software early and often. Face to face standup meetings and pair programming are very helpful.

I know with .net their is Scrum Project template that you can use that comes with Team Foundation Server. Not sure if their is the same for JAVA but I would imagine so.

The basics on scrum: http://www.mountaingoatsoftware.com/topics/scrum
There is way more but that website is a good start.

These are some tips I have just come up with:

Define features and break them down into user stories.

User stories are cataloged and placed in backlog.

Iterate over group of users stories.

Standing meeting every 2-3 days.

Deliver working software to customer to test every 3-6 weeks.

Use pair programming to break up stagnation of hard problems by working together.


问:
How to prevent code from leaking outside work?

Possible Duplicate:

  How to manage a Closed Source High-Risk Project?

I'm working on an institution that has a really strong sense of "possession" - each line of software we write should be only ours. Ironically, I'm the only programmer (ATM), but we're planning in hiring others.

Since my bosses wouldn't count the new programmers as people they can trust, they have an issue with the copies of the source code. We use Git, so they would have a entire copy of each of the projects they work on, when they clone the repository.

We can restrict access to them to a single key with Gitolite and bind that to their PC's, but they can copy those keys to another computer and they would have the repository access in another PC. Also (and the most obvious method) they could just upload the files somewhere else, add another remote, or just copy the files to an USB drive.

Is there any (perhaps clever) way to prevent events like these?

EDIT: I would like to thank everyone for their insights in this question, since it has been not only more eye opening, but also a firm support of my arguments (since you basically think like me, and I've been trying to make them understand that) against my bosses in the near future.

I am in a difficult situation work-wise, with my coworkers and bosses (since I'm basically in the middle) being like two gangs, so all this input is greatly, greatly appreciated.

It is true that I was looking for a technical solution to a people problem - both the management and the employees are the problem, so it can't be solved that way (I was thinking about some code obfuscation, perhaps working with separate modules, etc., but that wouldn't work from my developer POV). The main problem is the culture inside and outside the company - development is not taken seriously in my country (Venezuela) so naivity and paranoia are in fact a real issue in here.

The real answer here is an NDA (something that here in Venezuela doesn't completely work), because that's the people solution, because no sane developer would work in those conditions. Things will get ugly, but I think I will be able to handle that because of your help. Thank you all a lot! <3

答:
This is one of the situations where you are looking for a technical solution to a social problem.

A social problem should require a social solution, which, in this case, takes two complementary forms and an additional organizational solution which may help:

Trust. If you don't trust developers, don't hire them. Working with people you don't trust is synonymous of failure. Relations based on mistrust require a lot of formalism, which may severely impact not only the productivity of your employees, but also the number of persons ready to work with you. Chances are, the best developers will avoid your company at all costs.

NDA. Trusting someone doesn't mean you shouldn't take legal precautions. Those precautions can take a form of a contract or a NDA clause with severe consequences for the employee in a case of a disclosure.

How severe are the consequences depends on who you are. Government organizations, terrorists or mafia can permit some deterrent ones. Ordinary companies may be limited, by law, to financial ones only.

Slicing. Trust and contracts are a good start, but we can do better. If the sensitive part of the code base can be sliced so that two or more parts are required for the product to function, make sure that the developer from department 1 never sees the source code developed in department 2, and vice versa.

People from one department shouldn't be able to meet people from other departments, and ideally, they shouldn't even be able to guess what other departments are doing, nor how much departments are there. Each person knows only a small part, which is not enough to have an entire picture (and reconstruct an entire product outside the organization).

Those were social and organizational measures.

Now, technically speaking, there is nothing you can do.

You may try to:

Force the developers to work in a closed room on a machine which is not connected to the internet and doesn't have USB ports.

Install cameras which monitor everything which happens in the room, with several security officers constantly observing the developers working.

Strip-search every developer each time he leaves the room to be sure he don't have any electronic device which can hold the code.

Require every developer to have an ankle monitor. The device will listen to what they say, record their position and attempt to detect any electronic device nearby. If the developer was near a device which is not identified and doesn't have your tracking software installed on it, private investigators and hackers may attempt to check whether the developer wasn't using the device to leak information.

Forbid developers to leave your buildings, unless being under heavy surveillance, and to interact in any way with the outside world.

Some or all those measures are illegal in many countries (unless you represent some government agencies), but the worst part is that even with all those measures in place, developers will be able to get the code, for example by discretely writing it on their skin or on a piece of paper and hiding it in their clothes, or simply memorizing it if they have Eidetic memory.

Or they can just globally memorize the data structures and the algorithms—that is the only important thing where intellectual property matters—and create their own product inspired by those two things.


答:
In short, you need to have a non-disclosure agreement/contract with employees that you are hiring. In addition to this signed agreement hire developers that you can trust.

Technically speaking that code can easily get copied to device and reused somewhere else. What your boss doesn't want is - access of your competitors to this code. You may only enforce such policies through contracts of employment or partnership.

Another thing that may work is provide training on sensitivity of information, how each employee should be alerted when confidentiality of information is violated. In addition, tracking computer activities within your office network will also raise warning level.

Similar type of training is done annually for employees who deal with PHI related information .

However, getting a trusted people on board and providing training how to protect this information might be the optimal way to go.

Title: How to prevent code from leaking outside work?

Body:
Possible Duplicate:

  How to manage a Closed Source High-Risk Project?

I'm working on an institution that has a really strong sense of "possession" - each line of software we write should be only ours. Ironically, I'm the only programmer (ATM), but we're planning in hiring others.

Since my bosses wouldn't count the new programmers as people they can trust, they have an issue with the copies of the source code. We use Git, so they would have a entire copy of each of the projects they work on, when they clone the repository.

We can restrict access to them to a single key with Gitolite and bind that to their PC's, but they can copy those keys to another computer and they would have the repository access in another PC. Also (and the most obvious method) they could just upload the files somewhere else, add another remote, or just copy the files to an USB drive.

Is there any (perhaps clever) way to prevent events like these?

EDIT: I would like to thank everyone for their insights in this question, since it has been not only more eye opening, but also a firm support of my arguments (since you basically think like me, and I've been trying to make them understand that) against my bosses in the near future.

I am in a difficult situation work-wise, with my coworkers and bosses (since I'm basically in the middle) being like two gangs, so all this input is greatly, greatly appreciated.

It is true that I was looking for a technical solution to a people problem - both the management and the employees are the problem, so it can't be solved that way (I was thinking about some code obfuscation, perhaps working with separate modules, etc., but that wouldn't work from my developer POV). The main problem is the culture inside and outside the company - development is not taken seriously in my country (Venezuela) so naivity and paranoia are in fact a real issue in here.

The real answer here is an NDA (something that here in Venezuela doesn't completely work), because that's the people solution, because no sane developer would work in those conditions. Things will get ugly, but I think I will be able to handle that because of your help. Thank you all a lot! <3


问:
How do I organize a GUI application for passing around events and for setting up reads from a shared resource
My tools involved here are GTK and Haskell.  My questions are probably pretty trivial for anyone who has done significant GUI work, but I've been off in the equivalent of CGI applications for my whole career.

I'm building an application that displays tabular data, displays the same data in a graph form, and has an edit field for both entering new data and for editing existing data.  After asking about sharing resources, I decided that all of the data involved will be stored in an MVar so that every component can just read the current state from the MVar.

All of that works, but now it is time for me to rearrange the application so that it can be interactive.

With that in mind, I have three widgets: a TextView (for editing), a TreeView (for displaying the data), and a DrawingArea (for displaying the data as a graph).

I THINK I need to do two things, and the core of my question is, are these the right things, or is there a better way.

Thing the first:  All event handlers, those functions that will be called any time a redisplay is needed, need to be written at a high level and then passed into the function that actually constructs the widget to begin with.  For instance:

```<code>drawStatData :: DrawingArea -> MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO ()
createStatView :: (DrawingArea -> IO ()) -> IO VBox

createUI :: MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO HBox
createUI storeMVar field = do
    graphs <- createStatView (\area -> drawStatData area storeMVar field)

    hbox <- hBoxNew False 10
    boxPackStart hbox graphs PackNatural 0

    return hbox
</code>```

In this case, createStatView builds up a VBox that contains a DrawingArea to graph the data and potentially other widgets.  It attaches drawStatData to the realize and exposeEvent events for the DrawingArea.  I would do something similar for the TreeView, but I am not completely sure what since I have not yet done it and what I am thinking of would involve replacing the TreeModel every time the TreeView needs to be updated.

My alternative to the above would be...

```<code>drawStatData :: DrawingArea -> MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO ()
createStatView :: IO (VBox, DrawingArea)
</code>```

... but in this case, I would arrange createUI like so:

```<code>createUI :: MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO HBox
createUI storeMVar field = do
    (graphbox, graph) <- createStatView (\area -> drawStatData area storeMVar field)

    hbox <- hBoxNew False 10
    boxPackStart hbox graphs PackNatural 0

    on graph realize (drawStatData graph storeMVar field)
    on graph exposeEvent (do liftIO $ drawStatData graph storeMVar field
                             return ())

    return hbox
</code>```

I'm not sure which is better, but that does lead me to...

Thing the second: it will be necessary for me to rig up an event system so that various events can send signals all the way to my widgets.  I'm going to need a mediator of some kind to pass events around and to translate application-semantic events to the actual events that my widgets respond to.  Is it better for me to pass my addressable widgets up the call stack to the level where the mediator lives, or to pass the mediator down the call stack and have the widgets register directly with it?

So, in summary, my two questions:

1) pass widgets up the call stack to a global mediator, or pass the global mediator down and have the widgets register themselves to it?
2) pass my redraw functions to the builders and have the builders attach the redraw functions to the constructed widgets, or pass the constructed widgets back and have a higher level attach the redraw functions (and potentially link some widgets together)?

Okay, and...

3) Books or wikis about GUI application architecture, preferably coherent architectures where people aren't arguing about minute details?

The application in its current form (displays data but does not write data or allow for much interaction) is available at https://bitbucket.org/savannidgerinel/fitness .  You can run the application by going to the root directory and typing

```<code>runhaskell -isrc src/Main.hs data/
</code>```

or...

```<code>cabal build
dist/build/fitness/fitness data/
</code>```

You may need to install libraries, but cabal should tell you which ones.

答:
After a couple of weeks of work, I have what I consider a satisfactory solution which I think I can ultimately refactor into a Good solution.

I decided that there are two types of events in the system.  My basic widgets; the TreeView, DrawingArea, TextView, Submit button, and Clear button; are one logical grouping.  That particular grouping can (and in my application, is) be duplicated.  Interacting with most of them provides a set of GUI events, but those GUI events are only important to other widgets in the grouping.  From that perspective, when I construct the widgets, I wire all of their events together.  Those events never leave the widget set.

Additionally, I have a set of semantic events.  So far, the events amount to "Workout Submitted" and "Workout Updated".  The "Workout Submitted" event is fired off when the submit button is pressed and the data in the text field parses successfully.  The higher-level application processes that event, updates the application state, and then fires off the "Workout Updated" event to indicate to the entire application that a particular workout got updated.

The upshot of all of this seems relatively straightforward:

Create an application-global dispatcher that deals with events that have meaning in the application domain

If a group of widgets are meant to work together as a whole, construct them together.  Bind together all of the GUI events in which they affect one another but not the application.  Hand them a way to register for application events and a way to fire application events.

Make the event handlers take as few parameters as possible, ideally taking only the exact data that has been updated or that needs to be passed around.  Auxiliary data for how to process it should be bound to the handler in the section of code in which the handler is defined.  Partial application is a fantastic thing here, but in C you could use an opaque data structure.

whew This did not take very long to figure out, but figuring out how to actually hack the code took quite a few hours.

I'm going to do a much more in-depth write-up on my website, including significant code samples, some time in the future.


答:
Make them sign a non-disclosure agreement.

Only hire people you trust.

Compartmentalize your code base. Use of dependency injection so you can give them requirements that, when finished, resulting classes would fall right into place into the existing architecture, but they will not have acces to the "complete picture", only loose pieces. Only senior, trusted people would have clearance to the "architectural glue" that makes all work as a complete whole.


答:
If the people in question can't be trusted to keep to their employment contracts, then he needs to not hire them.

If he believes NO ONE can be trusted, then he's being overly paranoid, and he's ultimately going to damage the company if he keeps it up.

At some point you MUST trust your employees. It's not really an option to do otherwise. If you don't trust your employees at all, then they can't possibly be effective, because you're spending too much time distrusting them, and wasting a lot of their time jumping through hoops due to trust issues.

Also, when you make it clear to people that you don't trust them, they tend to get annoyed. And annoyed programmers eventually find another job where they aren't treated that way.

The right solution is a basic background check, a well-thought out employment agreement, and some trust.


答:
You have to trust, but sometimes it's better to just monitor for infractions.  For instance, if your code runs it could phone home to some IP address on the internet whenever it's run, logging the IP address, computer information, perhaps even Geo location of where it's running.  Review that log to look for problems.

Of course there are ways around that, and developers could just be looking at the code, not executing it.

You could configure your firewall to do packet inspection with something like Snort that could a) block the connection immediately if it detects, e.g. your copyright notice, and b) report it to management for follow-up.  In order to get around SSL and HTTPS you'd need to be running an HTTPS proxy on your firewall.

Perhaps you could have a system utility on every PC that checks external drives and USB flash drives for specific files or key phrases while they're plugged in.  You could also disable/ban external drives (I heard the US DOD does this).  You'd have to require they use your hardware, and not bring in any hardware from home.

There are probably programs available that will log everything someone does with a computer.  Just schedule random audits of these logs, and make sure developers are aware of this capability.

Once you've found an infraction, hit the developer over the head with the NDA they signed.


答:
I used to write code for classified computer systems.  They had all sorts of ridiculous hoops to jump through to keep it secret.  For example, we weren't allowed to bring music CDs into certain rooms because they could be CD-RWs in disguise.

The thing is, practicalities of the work open up security holes out of necessity.  Sometimes you had to transport non-classified data/code into or out of a classified area in order to get the job done.  Yes, there were rules and procedures for that, too, but they all eventually boiled down to trusting people.  Instead of trusting people not to put classified data on a convenient usb thumb drive, you're just trusting the exact same people to jump through all the security hoops.

In other words, there are a lot of things you can do to protect from outsiders, but once you let them in, it's pretty much just a question of how much you want to annoy them.


问:
Does your team function well without following a work methodology (such as scrum)?
I've worked in a number of small teams over the last 9 years. Each had the obvious good practices, such as short meetings, revision control, continuous integration software, issue tracking and so on.

In these 9 years, I've never heard much about development methodologies; for example, there's never been a "we're doing scrum", or "lets do agile", or anything more than a passing reference. All of the teams seemed to function fine, without following much process, we were just freeflowing and just naturally worked well.

Has anyone else progressed for long periods of time without encountering scrum/agile/etc?

The only exposure I've had to these is through sites like this one. I read questions like Sprint Meetings - What to talk about ... and all the talk seems to describe almost robotic like people who follow a methodology finite state machine. Is it really (though exaggerated) like that? I wonder if the  people posting on the internet just loud supporters of "best practice", with similar textbook views, not really reflecting how people work... Or that I've encountered some teams making their processes up naturally.

Furthermore (I am in the UK, which may be relevant)... I think if a methodology were introduced to any of the teams I'd work on, they'd just reject it as being silly and unnecessary... then carry on. I'd tend to agree, following processes seems a bit unnatural. Is this typical or common?

答:
Over 20 years of development experience here, and I've never used a formal methodology.  Never needed them, and I dont plan on using one in the future.  Methodologies might be fine for some people, but they are no substitute for skilled programmers who write good, tested code.

Personally, I think it would behoove a lot of people to care less about following the day's hottest new methodology, and focus more on code quality.

OwnerDisplayName: Sam


问:
What is the best way to create HTML in C# code?
I have a belief that markup should remain in mark-up and not in the code behind.

I've come to a situation where I think it is acceptable to build the HTML in the code behind. I'd like to have some consensus as to what the best practices are or should be.

When is it acceptable to build html in the code behind? What is the best method to create this html? (example: Strings, StringBuilder, HTMLWriter, etc)

答:
If you do end up using just strings, don't forget to escape all the HTML reserved characters in your output data.

```<code>&    &
>    >
<    <
"    "
'    '
</code>```

I recommend using an HTML-aware class or library instead of working directly with strings, though.  HTMLWriter looks like a pretty good start.

Body:
If you do end up using just strings, don't forget to escape all the HTML reserved characters in your output data.

&    &amp;
>    &gt;
<    &lt;
"    &quot;
'    &apos;

I recommend using an HTML-aware class or library instead of working directly with strings, though.  HTMLWriter looks like a pretty good start.


答:
I love the idea there might be a "clever" idea that "we" as developers would be baffled by. Given that every developer tool written was written by a developer and all that.

Your boss's biggest problem is naivety with a dash of paranoia. I'm being polite there. Really really polite.

If you really want a shopping list of things to keep your code proprietary, just implement the following:

Disable USB and other IO on all company computers. This can be done through most enterprise anti virus or similar.

All developer machines to be desktops or towers. No laptops.

Do not allow any machine to connect to the internet. No web, ftp, email, IM, no internet. Cut the wires.

No remote working/access (sort of covered by no internet, but some smart spark might suggest a VPN)

No mobile phones or other electronic devices to be taken into the secure "development" room.

Configure all printers to print a large visible watermark on every page, front and back.

bag searches both in and out. Search for hand written notes, anything printed on company printers (anything, they might have hidden code in an image with steganography!). Any electrical or electronic devices. In fact, probably best to ensure bags are kept out of the secure area and developers should wear clean suits, the sort of thing you'd see in drug dens and chip fab plants.

Servers should be equally isolated, back ups should be encrypted and only your boss should know the password to restore from them.


答:
I would use the Html Agility Pack to assemble HTML and then write it out to a text file.

A lot of man-hours went into making the Html Agility Pack robust and HTML-compliant HTML-friendly.

I think it even includes a sample application that generates HTML.

From the home page:

Sample applications:

Page fixing or generation. You can fix a page the way you want, modify the DOM, add nodes, copy nodes, well... you name it.

Title: What is the best way to create HTML in C# code?

Body:
I have a belief that markup should remain in mark-up and not in the code behind.

I've come to a situation where I think it is acceptable to build the HTML in the code behind. I'd like to have some consensus as to what the best practices are or should be.

When is it acceptable to build html in the code behind? What is the best method to create this html? (example: Strings, StringBuilder, HTMLWriter, etc)

ContentLicense: CC BY-SA 4.0


答:
There are, of course, libraries out there, such as HTML Agility Pack that can assist you in these endeavors.

If you realy don't want to use an existing library, and want simple, down-and-dirty code, I like the idea of abstracting out some of the behaviors like a previous answer stated.  I also like the idea of using an underlying StringBuilder, as opposed to a string for a couple reasons:

Strings are less efficient than string builder

StringBuilder is an indexable data structure,

If I don't need a massively engineered HTML engine, I'd build a simple, intuitive interface

```<code>AddLineBreak();
AddSimpleTag(string tagName);
AddSimpleTagAt(string tagName, string content, int index);
Output();
</code>```

Body:
There are, of course, libraries out there, such as HTML Agility Pack that can assist you in these endeavors.

If you realy don't want to use an existing library, and want simple, down-and-dirty code, I like the idea of abstracting out some of the behaviors like a previous answer stated.  I also like the idea of using an underlying StringBuilder, as opposed to a string for a couple reasons:

Strings are less efficient than string builder

StringBuilder is an indexable data structure,

If I don't need a massively engineered HTML engine, I'd build a simple, intuitive interface

AddLineBreak();
AddSimpleTag(string tagName);
AddSimpleTagAt(string tagName, string content, int index);
Output();


答:
FLAME ON!

```<code>var html = "";
html += "<table class='colorful'>";
foreach(var item in collection) {
     html += "<tr>";
     html += "<td class='boldCell'>" + item.PropWhatever + "</td>";
     // more cells here as needed
     html += "</tr>";
}
html += "</table>";
placeholder1.InnerHtml = html;
</code>```

I will prob get downvoted for this, but as a former designer who had to tweak HTML in code before I really knew much about .NET, the above code was way easier to understand than the methods that abstract HTML creation. If you think a designer might ever have to tweak your HTML, use simple strings like this.

Something I see a lot of devs miss when they write HTML in code is that in HTML, single or double quotes are allowed for attributes. So instead of escaping all the quotes in code (which looks wanky as hell to the non-initiated), just use single quotes for the html quotes inside your strings.

FINE. All you string concatenating haters are crampin' my rep. Here's the 'proper' way to do this without string concatenation, but I stand by my opinion that any normal page with normal tables won't present any performance problems outside of some ridiculous Google-like scale:

```<code>var sb = new System.Text.StringBuilder();
sb.Append("<table class='colorful'>");
foreach (var item in collection)
{
     sb.Append("<tr>");
     sb.Append("<td class='boldCell'>" + item.PropWhatever + "</td>");
     // more cells here as needed
     sb.Append("</tr>");
}
sb.Append("</table>");
placeholder1.InnerHtml = sb.ToString();
</code>```

Body:
FLAME ON!

var html = "";
html += "<table class='colorful'>";
foreach(var item in collection) {
     html += "<tr>";
     html += "<td class='boldCell'>" + item.PropWhatever + "</td>";
     // more cells here as needed
     html += "</tr>";
}
html += "</table>";
placeholder1.InnerHtml = html;

I will prob get downvoted for this, but as a former designer who had to tweak HTML in code before I really knew much about .NET, the above code was way easier to understand than the methods that abstract HTML creation. If you think a designer might ever have to tweak your HTML, use simple strings like this.

Something I see a lot of devs miss when they write HTML in code is that in HTML, single or double quotes are allowed for attributes. So instead of escaping all the quotes in code (which looks wanky as hell to the non-initiated), just use single quotes for the html quotes inside your strings.

FINE. All you string concatenating haters are crampin' my rep. Here's the 'proper' way to do this without string concatenation, but I stand by my opinion that any normal page with normal tables won't present any performance problems outside of some ridiculous Google-like scale:

var sb = new System.Text.StringBuilder();
sb.Append("<table class='colorful'>");
foreach (var item in collection)
{
     sb.Append("<tr>");
     sb.Append("<td class='boldCell'>" + item.PropWhatever + "</td>");
     // more cells here as needed
     sb.Append("</tr>");
}
sb.Append("</table>");
placeholder1.InnerHtml = sb.ToString();


问:
Do non-manager coders in their forties or older out there sometimes regret about not being managers?
And why do most programmers quit coding and become managers so early compared to other areas? You can work as a construction worker, a lawyer, researcher, writer, architect, movie director for decades if not your whole life, without quitting the favorite thing you are doing. And yet most programmers think being a manager, or better, a non-coding manager is a cool thing and the ultimate goal of the software career. It's so rare to see an ordinary coder in his 40s or 50s (or 60s!) in a typical software company. Why?

(And I am for being a coder for as long as you love doing it.)

答:
I'm 63 and I love to code.  I have no intention of retiring.  (Well, maybe cutting back to 40 hours a week someday.)

The fellow programmer that shares an office with me is in his 50's.  We have a manager that is just under 50, and he spends at least half of his time coding also.  The company also has one web programmer/database guy.  He's the youngest technical guy and is 40-something.

Around 25 years ago, when I was trying to expand my consulting business, I hired four employees.  I never had time to code and spent all my time managing them and getting new projects to keep everyone busy.  I hated it.  Went back to working solo and have never regretted it, to answer your question.


问:
How to handle bugs that I think I fixed, but I'm not entirely sure
There are some types of bugs which are very hard to reproduce, happen very rarely and seemingly by random. It can happen, that I find a possible cause, fix it, test the program, and can't reproduce the bug. However, as it was impossible to reliably reproduce the bug and it happened so rarely, how can I indicate this in a bugtracker? What is the common way of doing it?

If I set the status to fixed, and the solution to fixed, it would mean something completely fixed, wouldn't it?

Is it common practice to set the status to fixed and the solution to open, to indicate to the testers, that "it's probably fixed, but needs more attention to make sure" ?

Edit: most (if not all) bugtrackers have two properties for the status of a bug, maybe the names are not the same. By status I mean new, assigned, fixed, closed, etc., and by solution I mean open (new), fixed, unsolvable, not reproducible, duplicate, not a bug, etc.

答:
Sometimes the only evidence you have is purely statistical, e.g. it occurs once or twice a month, but otherwise seemingly unconnected to anything.  These are overall the worst type of bug to diagnose and resolve that I have ever encountered, because you cannot tell whether your fixes have an effect with any certainty.  The last one of these I had to resolve ended with a statistical fix:  the symptom's frequency went down to 10% that we started with.  The final piece was never found, or maybe it was, but nobody had any way to tell.

Two pieces of advice I have are (1) assume multiple causes could be in effect until you know otherwise, and (2) hypothesize how the symptoms could possibly exist, then tear apart every line of logic that is even remotely involved.  Deep walkthroughs are sometimes the only means to a satisfying end.


答:
Did you see Paycheck with Ben Affleck? I think that's the only way to guarantee your IP won't be "stolen". I can tell you that because of my memory, I could recreate almost every system I've worked on for any significant amount of time. If not a line by line recreation, I could produce the significant elements and probably improve on them in the process because of how my skills have grown over the years.

Plain and simple, there are only two things you can accomplish by "locking down" your code:

You'll repulse good developers who are offended by your obvious lack of trust

You'll raise a great big flag that tempts the more unscrupulous developers

If you think your software is that novel and amazing, get a patent.


问:
Designing a Database Application with OOP
I often develop SQL database applications using Linq, and my methodology is to build model classes to represent each table, and each table that needs inserting or updating gets a Save() method (which either does an InsertOnSubmit() or SubmitChanges(), depending on the state of the object).  Often, when I need to represent a collection of records, I'll create a class that inherits from a List-like object of the atomic class.

ex.

```<code>public class CustomerCollection : CoreCollection<Customer>
{

}
</code>```

Recently, I was working on an application where end-users were experiencing slowness, where each of the objects needed to be saved to the database if they met a certain criteria.  My Save() method was slow, presumably because I was making all kinds of round-trips to the server, and calling DataContext.SubmitChanges() after each atomic save.

So, the code might have looked something like this

```<code>foreach(Customer c in customerCollection)
{
   if(c.ShouldSave())
   {
       c.Save();
   }
}
</code>```

I worked through multiple strategies to optimize, but ultimately settled on passing a big string of data to a SQL stored procedure, where the string has all the data that represents the records I was working with - it might look something like this:

```<code>CustomerID:34567;CurrentAddress:23 3rd St;CustomerID:23456;CurrentAddress:123 4th St
</code>```

So, SQL server parses the string, performs the logic to determine appropriateness of save, and then Inserts, Updates, or Ignores.

With C#/Linq doing this work, it saved 5-10 records / s.  When SQL does it, I get >100 records / s, so there is no denying the Stored Proc is more efficient; however, I hate the solution because it doesn't seem nearly as clean or safe.

My real concern is that I don't have any better solutions that hold a candle to the performance of the stored proc solution.  Am I doing something obviously wrong in how I'm thinking about designing database applications?  Are there better ways of designing database applications?

答:
In modern SQL Server versions (> 2008 IIRC) you can use User defined types. So your sproc can actually take an array of user types:

Link

In our app we actually use the repository pattern, but hack it a bit to get around slowness issues like you describe.

So, in your example, I'd do something like this:

```<code>using (CustomerBulkContext ctx = customerCollection.GetSaveContext())
{

foreach(Customer c in customerCollection)
{
   if(c.ShouldSave())
   {
       c.Save(ctx);
   }
}
ctx.Save();
}
</code>```

The idea is that all the customers are added to an in-memory list inside the context, and then the actual commit to the DB is handled via the save context's .Save() method. That method then creates a list of SQL objects and hands them to a sproc that does the bulk update/insert/delete.

Body:
In modern SQL Server versions (> 2008 IIRC) you can use User defined types. So your sproc can actually take an array of user types:

Link

In our app we actually use the repository pattern, but hack it a bit to get around slowness issues like you describe.

So, in your example, I'd do something like this:

using (CustomerBulkContext ctx = customerCollection.GetSaveContext())
{

foreach(Customer c in customerCollection)
{
   if(c.ShouldSave())
   {
       c.Save(ctx);
   }
}
ctx.Save();
}

The idea is that all the customers are added to an in-memory list inside the context, and then the actual commit to the DB is handled via the save context's .Save() method. That method then creates a list of SQL objects and hands them to a sproc that does the bulk update/insert/delete.


问:
Are long methods always bad?
So looking around earlier I noticed some comments about long methods being bad practice.

I am not sure I always agree that long methods are bad (and would like opinions from others).

For example I have some Django views that do a bit of processing of the objects before sending them to the view, a long method being 350 lines of code. I have my code written so that it deals with the parameters - sorting / filtering the queryset, then bit by bit does some processing on the objects my query has returned.

So the processing is mainly conditional aggregation, that has complex enough rules it can't easily be done in the database, so I have some variables declared outside the main loop then  get altered during the loop.

```<code>variable_1 = 0
variable_2 = 0
for object in queryset :
     if object.condition_condition_a and variable_2 > 0 :
     variable 1+= 1
     .....
     ...
     .
      more conditions to alter the variables

return queryset, and context
</code>```

So according to the theory I should factor out all the code into smaller methods, so That I have the view method as being maximum one page long.

However having worked on various code bases in the past, I sometimes find it makes the code less readable, when you need to constantly jump from one method to the next figuring out all the parts of it, while keeping the outermost method in your head.

I find that having a long method that is well formatted, you can see the logic more easily, as it isn't getting hidden away in inner methods.

I could factor out the code into smaller methods, but often there is is an inner loop being used for two or three things, so it would result in more complex code, or methods that don't do one thing but two or three (alternatively I could repeat inner loops for each task, but then there will be a performance hit).

So is there a case that long methods are not always bad? Is there always a case for writing methods, when they will only be used in one place?

UPDATE:
Looks like I asked this question a over a year ago.

So I refactored the code after the (mixed) response here, split it into methods. It is a Django app retrieving complex sets of related objects from the database, so the testing argument is out (it would have probably taken most of the year to create relevant objects for the test cases . I have a "this needs done yesterday" type work environment before anyone complains).
Fixing bugs in that part of the code is marginally easier now, but not massively so.

before :

```<code>#comment 1
bit of (uncomplicated) code 1a
bit of code 2a

#comment 2
bit of code 2a
bit of code 2b
bit of code 2c

#comment 3
bit of code 3
</code>```

now:

```<code>method_call_1
method_call_2
method_call_3

def method_1
    bit of (uncomplicated) code 1a
    bit of code 2a

def method_2
    bit of code 2a
    bit of code 2b
    bit of code 2c

def method_3
    bit of code 3
</code>```

答:
I wanted to address the example you gave:

For example I have some Django views that do a bit of processing of the objects before sending them to the view, a long method being 350 lines of code. I have my code written so that it deals with the paramaters - sorting / filtering the queryset, then bit by bit does some processing on the objects my query has returned.

At my company our biggest project is built on Django and we have long view functions too (many are more than 350 lines). I'd argue ours don't need to be that long, and they're hurting us.

These view functions are doing a lot of loosely related work that should be extracted to the model, helper classes, or helper functions. Also, we end up reusing views to do different things, which should instead be divided into more cohesive views.

I suspect your views have similar characteristics. In my case, I know it causes problems and I'm working to make changes. If you don't agree that it's causing problems, then you don't need to fix it.

Title: Are long methods always bad?


问:
Building a website, want to use java
I'd like to make a simple-ish website that is essentially a small game.  Key strokes are to be processed and sent to a server (already acquired and should support SQL and JSP, I believe) which then translate to a location and written to the DB.

SQL queries are to be used to retrieve these locations and written to other clients connected to the website.  Their page is to be updated with these locations.

I have working knowledge of Java, jQuery/Ajax, SQL and JavaScript but I'm unfamiliar with JSP and how everything hooks up.  I'm aware of the MVC paradigm as well.  For my little game idea, would these technologies work?  Am I over thinking this and can make it much easier to implement?  What might be a good tutorial or example to study?

EDIT: I was just informed I will not be able to use WAR files on the server.  I'm not big on php and really don't like developing with it, can I still use Java?

答:
I think these or any other set of web technologies could do the job. Comes down to what you are going to do with what you know best (-;

If you want to stick with Java, check out Core Servlets for a JSP tutorial -- helped me when I was starting out with all things java-web-app.

Sounds like a fun project. Good luck!

Title: Building a website, want to use java


答:
You can use DWR for calling JavaScript functions from Java and vice-versa. </p>

<p>If you want to use the standard Java technology for the web, i.e. JSF, then JSP is kind of deprecated; you should use Facelets (xhtml files). </p>

Title: Building a website, want to use java

Body:
I'd like to make a simple-ish website that is essentially a small game.  Key strokes are to be processed and sent to a server (already acquired and should support SQL and JSP, I believe) which then translate to a location and written to the DB.

SQL queries are to be used to retrieve these locations and written to other clients connected to the website.  Their page is to be updated with these locations.

I have working knowledge of Java, jQuery/Ajax, SQL and JavaScript but I'm unfamiliar with JSP and how everything hooks up.  I'm aware of the MVC paradigm as well.  For my little game idea, would these technologies work?  Am I over thinking this and can make it much easier to implement?  What might be a good tutorial or example to study?

EDIT: I was just informed I will not be able to use WAR files on the server.  I'm not big on php and really don't like developing with it, can I still use Java?

Body:
You can use DWR for calling JavaScript functions from Java and vice-versa.

If you want to use the standard Java technology for the web, i.e. JSF, then JSP is kind of deprecated; you should use Facelets (xhtml files).


问:
How important is the ability to touch-type?
Did you learn to touch-type when you were already working as a programmer?  If so how did it affect your productivity?  Or are you still unable to touch type and do you think it holds you back?

According to Steve Yegge it is essential,

Personally I did not notice much difference, possibly because I was spending less than 25% of my work time actually typing (I was working on a large legacy project at the time and I was spending more time on reading and debugging existing code.)

答:
I've never learned to touch type correctly (bringing my hands back to the home row etc.) but I do type with multiple fingers of each hand and can type 45 wpm without errors.  So yes, I can see that it useful to be able to type efficiently.

Is it worth it for me unlearn the way I do it and add maybe 20 wpm to my typing speed?  I don't know.  For typing something like this, sure.  Typing code in, not sure.  I spend so much time going back and forth to my mouse when I am coding (because I tend to do a lot of stepwise refinement) that I seldom type very long phrases in at a time anyway.


问:
Complex string matching with fuzzywuzzy
I'm attempting to write a process that matches obscure strings to a single 'master string' for further processing. I have a lot of data that looks something like this:

```<code>Basketball
Basket Ball
Football
BasketBallR
BBall
BBall - r
FootB
</code>```

...and so on. These need to be mapped to a master record like so:

```<code>Basketball       = Basket Ball, BBall
Basketball - R   = BasketBallR, BBall - r
</code>```

I also have instances of data resembling this format:

```<code>Football -r
FootBall - r-g/H,Q,HH
</code>```

These situations need to be separated into different categories before being mapped. For example FootBall - r-g/H,Q,HH should be:

```<code>Football - r
Football - g
Football - H
Football - Q
Football - HH
</code>```

At this point, it still needs to be mapped to a master record...

I've tried several different combinations of fuzzywuzzy matching methods, Levenshtein Distance measurements, regex, etc. and can't seem to find a reliable method to logically associate different naming styles of a single item with a master name.

I'm throwing my hands up in desperation. Are there any existing python resources than can help sort out my problem? Are there other options? Can anybody point out an obvious option that I might have overlooked?

Basically, any suggestion, solution, resource or alternative method is greatly appreciated.

答: Fortunately, I'm not one to give up easily. Through reaching out to other sources/communities I found Google Refine which (amazingly) completely resolves my matching issues 90% of the time, and leaves the remaining 10% incredibly manageable and easy to manually resolve. I hope this might help other people facing similar issues.</p>

Title: Complex string matching with fuzzywuzzy


答:
A "rule-of-thumb" to get blazing speed in a database is to use set-based commands instead of separate procedural style commands. It's not only the network round trips that affect performance. Even if you have the loop embedded in the sql, you'll find it orders of magnitude slower than a set-based command.

```<code>--SLOW way, procedural
loop i=0 to 999999
    update foobar set status='test' where id=i;
end loop
</code>```

vs

```<code>--FAST way, set-based
update foobar set status='test' where id between 0 and 999999
</code>```

Anywhere you see data processed in a loop, you can replace it with set-based commands. If there are changing conditions checked mid-loop then you may be forced to use procedural style. But that is very rare.

Just identify the bottle necks. You can keep the rest of the logic controlled with your objects. If you only operate on a single record, the procedural style is just as fast.

NOTE: internally within the RDBMS the "set-based" commands are executed via a procedural loop. Nothing wrong with loops per-say, it's just the interface provided by most RDBMS's are optimized to be used with set-based commands.

Title: Designing a Database Application with OOP

Body:
I often develop SQL database applications using Linq, and my methodology is to build model classes to represent each table, and each table that needs inserting or updating gets a Save() method (which either does an InsertOnSubmit() or SubmitChanges(), depending on the state of the object).  Often, when I need to represent a collection of records, I'll create a class that inherits from a List-like object of the atomic class.

ex.

```<code>public class CustomerCollection : CoreCollection<Customer>
{

}
</code>```

Recently, I was working on an application where end-users were experiencing slowness, where each of the objects needed to be saved to the database if they met a certain criteria.  My Save() method was slow, presumably because I was making all kinds of round-trips to the server, and calling DataContext.SubmitChanges() after each atomic save.

So, the code might have looked something like this

```<code>foreach(Customer c in customerCollection)
{
   if(c.ShouldSave())
   {
       c.Save();
   }
}
</code>```

I worked through multiple strategies to optimize, but ultimately settled on passing a big string of data to a SQL stored procedure, where the string has all the data that represents the records I was working with - it might look something like this:

```<code>CustomerID:34567;CurrentAddress:23 3rd St;CustomerID:23456;CurrentAddress:123 4th St
</code>```

So, SQL server parses the string, performs the logic to determine appropriateness of save, and then Inserts, Updates, or Ignores.

With C#/Linq doing this work, it saved 5-10 records / s.  When SQL does it, I get >100 records / s, so there is no denying the Stored Proc is more efficient; however, I hate the solution because it doesn't seem nearly as clean or safe.

My real concern is that I don't have any better solutions that hold a candle to the performance of the stored proc solution.  Am I doing something obviously wrong in how I'm thinking about designing database applications?  Are there better ways of designing database applications?

Body:
A "rule-of-thumb" to get blazing speed in a database is to use set-based commands instead of separate procedural style commands. It's not only the network round trips that affect performance. Even if you have the loop embedded in the sql, you'll find it orders of magnitude slower than a set-based command.

--SLOW way, procedural
loop i=0 to 999999
    update foobar set status='test' where id=i;
end loop

vs

--FAST way, set-based
update foobar set status='test' where id between 0 and 999999

Anywhere you see data processed in a loop, you can replace it with set-based commands. If there are changing conditions checked mid-loop then you may be forced to use procedural style. But that is very rare.

Just identify the bottle necks. You can keep the rest of the logic controlled with your objects. If you only operate on a single record, the procedural style is just as fast.

NOTE: internally within the RDBMS the "set-based" commands are executed via a procedural loop. Nothing wrong with loops per-say, it's just the interface provided by most RDBMS's are optimized to be used with set-based commands.


答:
I would consider using one of the big-name ORM solutions like Entity Framework or NHibernate. The advantage of doing so is that they perform all kinds of neat tricks to optimise cals to the database. For example:

Caching, so you ony have to read values from the database once.

Tracking changes, so they only update fields that have actually changed.

Lazy loading, so they only read the records in a collection when you actually use them.

In addition, you won't be tied to a single table per class (the so-called "active record" pattern).

The down-sides to my suggestion are that your existing code base will need some (perhaps considerable) modification, and you have a steep learning curve ahead of you.

Nevertheless, having made a similar journey myself, I am pesuaded that this is a worthwhile direction of travel.


问:
What can go wrong if the Liskov substitution principle is violated?
I was following this highly voted question on possible violation of Liskov Substitution principle. I know what the Liskov Substitution principle is, but what is still not clear in my mind is what might go wrong if I as a developer do not think about the principle while writing object-oriented code.</p>

答:
to give a real life example with java's UndoManager

it inherits from AbstractUndoableEdit whose contract specifies that it has 2 states (undone and redone) and can go between them with single calls to undo() and redo()

however UndoManager has more states and acts like an undo buffer (each call to undo undoes some but not all edits, weakening the postcondition)

this leads to the hypothetical situation where you add a UndoManager to a CompoundEdit before calling end() then calling undo on that CompoundEdit will lead it to call undo() on each edit once leaving your edits partially undone

I rolled my own UndoManager to avoid that (I probably should rename it to UndoBuffer though)


答: If you want to feel the problem of violating LSP, think what happens if you have only .dll/.jar of base class (no source code) and you have to build new derived class. You can never complete this task.</p>


问:
Why are some data types Deprecated while others Obsolete?
Why are some data types or functions made Obsolete in a newer version of an API and others are marked as Deprecated? Why not make them all Obsolete or why not make them all Deprecated?</p>

答: Deprecation typically serves as a warning that a feature is no longer in favor with the designers of the language. The reasoning for this is one of reverse compatibility. It gives the users of a language time to adjust their code before the language drops those features. It can also serve as a migration path to a new version of a given feature. The feature in question might be retrofitted at some point in the future or rendered obsolete and removed.</p>


问:
How to initialize object which may be used in catch clause?
I've seen this sort of pattern in code before:

```<code>//pseudo C# code

var exInfo = null;  //Line A

try
{
  var p = SomeProperty;         //Line B
  exInfo = new ExceptionMessage("The property was " + p);           //Line C
}
catch(Exception ex)
{
  exInfo.SomeOtherProperty = SomeOtherValue;  //Line D
}
</code>```

Usually the code is structured in this fashion because exInfo has to be visible outside of the try clause. The problem is that if an exception occurs on Line B, then exInfo will be null at Line D.  The issue arises when something happens on Line B that must occur before exInfo is constructed. But if I set exInfo to a new Object at line A then memory may get leaked at Line C (due to "new"-ing the object there).  Is there a better pattern for handling this sort of code? Is there a name for this sort of initialization pattern?

By the way I know I could check for exInfo == null before line D but that seems a bit clumsy and I'm looking for a better approach.

答: How about creating class that has an event handler?  Then initialize exInfo before initializing var p, which would guarantee that exInfo would not be null?</p>


答:
You should initialize exInfo before the try block. In .NET you won't leak any memory at Line C.

I'm going to try and make a concrete example out of your pseudocode, and see if that helps. Assume db.getList() runs some SQL and returns NULL if nothing found, a list if elements were found, and throws an exception on error.

```<code>List<String> stuff = new ArrayList<String>();

try {
   stuff = db.getList("SELECT someColumn FROM someTable");
}
catch (SqlException e) {
   log.error("Couldn't retrieve stuff!", e);
}

return stuff;
</code>```

In Java and other garbage-collected languages, no memory would be leaked after your line C if you initialized the variable previously. The initial object would have no references associated with it and would be then eligible for garbage collection. This pattern allows you to keep code calling this code null-safe, since it will always return a valid List<>.

Title: How to initialize object which may be used in catch clause?

Body:
I've seen this sort of pattern in code before:

```<code>//pseudo C# code

var exInfo = null;  //Line A

try
{
  var p = SomeProperty;         //Line B
  exInfo = new ExceptionMessage("The property was " + p);           //Line C
}
catch(Exception ex)
{
  exInfo.SomeOtherProperty = SomeOtherValue;  //Line D
}
</code>```

Usually the code is structured in this fashion because exInfo has to be visible outside of the try clause. The problem is that if an exception occurs on Line B, then exInfo will be null at Line D.  The issue arises when something happens on Line B that must occur before exInfo is constructed. But if I set exInfo to a new Object at line A then memory may get leaked at Line C (due to "new"-ing the object there).  Is there a better pattern for handling this sort of code? Is there a name for this sort of initialization pattern?

By the way I know I could check for exInfo == null before line D but that seems a bit clumsy and I'm looking for a better approach.

Body:
You should initialize exInfo before the try block. In .NET you won't leak any memory at Line C.

I'm going to try and make a concrete example out of your pseudocode, and see if that helps. Assume db.getList() runs some SQL and returns NULL if nothing found, a list if elements were found, and throws an exception on error.

List<String> stuff = new ArrayList<String>();

try {
   stuff = db.getList("SELECT someColumn FROM someTable");
}
catch (SqlException e) {
   log.error("Couldn't retrieve stuff!", e);
}

return stuff;

In Java and other garbage-collected languages, no memory would be leaked after your line C if you initialized the variable previously. The initial object would have no references associated with it and would be then eligible for garbage collection. This pattern allows you to keep code calling this code null-safe, since it will always return a valid List<>.