问:
Using static in PHP
I have a few functions in PHP that read data from functions in a class

```<code>readUsername(int userId){
$reader = getReader();
return $reader->getname(userId);
}

readUserAddress(){
$reader = getReader();
return $reader->getaddress(userId);
}
</code>```

All these make a call to

```<code>getReader()
{
require_once("Reader.php");
static $reader = new Reader();
return $reader;
}
</code>```

An overview of Reader

```<code>class Reader{
getname(int id)
{
//if in-memory cache exists for this id return that
//else get from db and cache it
}

getaddress(int id)
{
 $this->getname(int id);
 //get address from name here
}

/*Other stuff*/

}
</code>```

Why is class Reader needed
The Reader class does some in-memory caching of user details. So, I need only one object of class Reader and it will cache the user details instead of making  multiple db calls.
I am using static so that it the object gets created only once. Is this the right approach or should I do something else?

答:
static keywords, represents that, the class methods or attribute can be accessed without having any object instantiated. Due to this reason, they exists separately to maintain their loosely coupled state.

The problem you are having can be solved, with an combination of factory and singleton pattern.

Your Reader class should be singleton, so that multiplexed instances of same class of same purpose will not be created.

For example:

```<code>class Reader {
     private static $singletonObject = null;
     function __construct() { }

     public function static getInstance() {
        if(!SELF::$singletonObject) { SELF::$singletonObject = new Reader(); }
        return SELF::$singletonObject;
     }

     // Other
}
</code>```

Now, whenever you are trying to access the Reader class,

```<code>$reader = Reader::getInstance();
</code>```

Now, use $reader class as you need to. Now, you can create Factory and Singleton pattern to give you the instance of DB class and Cache Class.

Title: Using static in PHP

Body:
static keywords, represents that, the class methods or attribute can be accessed without having any object instantiated. Due to this reason, they exists separately to maintain their loosely coupled state.

The problem you are having can be solved, with an combination of factory and singleton pattern.

Your Reader class should be singleton, so that multiplexed instances of same class of same purpose will not be created.

For example:

class Reader {
     private static $singletonObject = null;
     function __construct() { }

     public function static getInstance() {
        if(!SELF::$singletonObject) { SELF::$singletonObject = new Reader(); }
        return SELF::$singletonObject;
     }

     // Other
}

Now, whenever you are trying to access the Reader class,

$reader = Reader::getInstance();

Now, use $reader class as you need to. Now, you can create Factory and Singleton pattern to give you the instance of DB class and Cache Class.


问:
Headaches using distributed version control for traditional teams?
Though I use and like DVCS for my personal projects, and can totally see how it makes managing contributions to your project from others easier (e.g. your typical Github scenario), it seems like for a "traditional" team there could be some problems over the centralized approach employed by solutions like TFS, Perforce, etc. (By "traditional" I mean a team of developers in an office working on one project that no one person "owns", with potentially everyone touching the same code.)

A couple of these problems I've foreseen on my own, but please chime in with other considerations.

In a traditional system, when you try to check your change in to the server, if someone else has previously checked in a conflicting change then you are forced to merge before you can check yours in. In the DVCS model, each developer checks in their changes locally and at some point pushes to some other repo. That repo then has a branch of that file that 2 people changed. It seems that now someone must be put in charge of dealing with that situation. A designated person on the team might not have sufficient knowledge of the entire codebase to be able to handle merging all conflicts. So now an extra step has been added where someone has to approach one of those developers, tell him to pull and do the merge and then push again (or you have to build an infrastructure that automates that task).

Furthermore, since DVCS tends to make working locally so convenient, it is probable that developers could accumulate a few changes in their local repos before pushing, making such conflicts more common and more complicated.

Obviously if everyone on the team only works on different areas of the code, this isn't an issue. But I'm curious about the case where everyone is working on the same code. It seems like the centralized model forces conflicts to be dealt with quickly and frequently, minimizing the need to do large, painful merges or have anyone "police" the main repo.

So for those of you who do use a DVCS with your team in your office, how do you handle such cases? Do you find your daily (or more likely, weekly) workflow affected negatively? Are there any other considerations I should be aware of before recommending a DVCS at my workplace?

答:
The thing with git/mercurial type version control, is to commit often, and push to centralized server when the code is good. One big plus with this is that it creates small patches, which are easy to apply in cases of conflicts. Also, you workflow should be something in the lines of:

Many local commit

Pull from server

Push to server

This pull from server might create conflicts, but to solve this, all that is needed a lot of times is a simple rebase, instead of a merge. This will, I feel, keep the mainline history quite clean, and remove quite a lot of conflicts.

This is also the case when you pull from the local repo of a co-worker, as two things might happen. Either he pushes to the server first, which is fine since you already have his patches, and no conflicts should occur, or you push first, which means he will only get your patches when he pull.

Of course, sometimes a merge is a better solution, as an example if your working on a feature branch which should be merge into master.

In your workflow you are talking about people having to explicitly go to another developer and telling him to fix the conflict, but that should not be necessary. The central server is the "boss", and what you should be mainly working against. If your changes applies to the central repo, then your ok. If not, it's YOUR job to fix the conflict, which might require the developer you conflict with to help out understanding his/her changes. This is something you see when you try to pull/rebase from the server. So be happy committing, and deal with conflicts when you should pull from the server.

ContentLicense: CC BY-SA 3.0


问:
When calculating how many days between 2 dates, should you include both dates in the count, or neither, or 1?
I am trying to make an algorithm that counts the days between two dates, e.g. between 3/1/2012 and 3/2/2012.

What is the correct answer, or the most popular choice? Should be the one I use?

In this case, if I don't include both dates I am comparing, the days are 0; if I include one of them, the days are 1; if I include both, the days are 2.

答:
You have to consider the context, if my working schedule is from monday to friday my boss will be a bit displeased if I only show up for 4 days.

That's because in this context, monday doesn't only stand for monday but for monday 8:30  and friday stands for friday 17:00.


问:
Approach on working with many programmers on one module/feature
How can 2 or more developers code a certain feature/module of a software?  Let's assume that the module is big and feature rich.  How would they prevent each other from overlapping their code?  Say, we have the same method but is implemented in a different way.  Do you think it might be better to have one focused at a specific feature only?

Is a version control system like Git would help solve the problem?  Is it correct that it allows developers to have these "branches" and then merge it later on?

What's your take on this?

答:
We try to split up the work in different code-parts. For example, one guy can do the webservices, another the GUI.

If two people do change the same functions, with a modern source control system like TFS it's not a big problem. It just gives a merge conflict, you call the other programmer to your desk and you solve it together.

If you are constantly having merge conflicts one part of your code, it's a bottleneck you have to fix. That means splitting up those classes in smaller ones.


答:
The number of days ND between one date D1 and another date D2 is such that:

```<code>ND = D2 - D1
</code>```

or:

```<code>D1 + ND = D2
</code>```

Title: When calculating how many days between 2 dates, should you include both dates in the count, or neither, or 1?

Body:
I am trying to make an algorithm that counts the days between two dates, e.g. between 3/1/2012 and 3/2/2012.

What is the correct answer, or the most popular choice? Should be the one I use?

In this case, if I don't include both dates I am comparing, the days are 0; if I include one of them, the days are 1; if I include both, the days are 2.

Body:
The number of days ND between one date D1 and another date D2 is such that:

ND = D2 - D1

or:

D1 + ND = D2


问:
Bug fixing approach
I have been working on a database project, and I recently received a bug report for the remote execution of some queries.

Usually, you try to find out the actual cause for the bug to occur and then fix it.

But sometimes what I do when I'm fed up of doing some research (and can't find suitable information on the internet) is just change the logic, which takes me much less time compared to the other option.

Is this approach correct, or should I try to fix the original bug involving more R&D?

答:
Good thing about your approach is that one can focus on things requiring immediate attention. Side-stepping to investigate what initially went wrong might take a lot of time and push completion of the bugfix far beyond deadlines.

Bad thing is that potentially important side issue remains unresolved. Since you don't know what really went wrong, there is a chance that this "wrong" bites you painfully in the middle of even more important and urgent bug fix.

To handle "collisions" like that, issue tracker appears to be a tool made in heaven. In cases like you describe, I simply "fork" a new dedicated ticket to handle side issue I discovered. That dedicated ticket hangs in there until I am done with current fix - after that, I return to new ticket and sort it out.

Issue 1234: investigate root cause of Issue 1233 - find out what went wrong with <old logic>

Above trick with "forking a ticket" is a practical application of decomposition principles. Decomposition is known as a powerful strategy in software design; in my experience it has proven to be quite useful in bug tracking, too.

Title: Bug fixing approach


答:
It depends a lot on context, but in my opinion the obvious answer is to include 1 of the dates in the count.

Let's assume you count neither. And also let's assume there's an application that uses your algorithm to determine the difference of 2 dates typed by the user. In this case, the difference between 3/1/2012 and 3/2/2012 is 0. Is it then ok for the user to assume that the 2 dates are equal ? Because that's what 0 suggests: no difference between them -->> they're equal. It's probably wrong...

Let's then assume you count both. In this case, the difference will never be less than 2. Are there 2 days between 3/1/2012 and 3/2/2012 ? Certainly not. What about between 3/1/2012 and 3/1/2012 ? Again: no.

Given the fact that you only have dates as input and no time, I would do the algorithm like this:

if date 1 is equal to date 2, then the answer is 0

if date 1 is different than date 2, then the answer is the number of days between them + 1 (the "+ 1" means than one of the date is included in the count).

As I said in the beginning: this ultimately depends on your business requirements.


答:
Both Dates, because that is what the users expect (in most cases)

I have worked on a few projects that had to work with logic surrounding dates, and expiration of entities. And there are some pitfalls.

The nature of those pitfalls is that what makes sense to a programmer isn't necessarily what makes sense to the people using the application.

People in the business would normally say stuff like, this thing is active from the 1. to the 31. of July. Now what they mean is that both dates are are included, i.e. it should be active for 31 days, not 30. But that defies normal arithmetic rules.

So if you take the question from the end users point of view, then in my experience the answer should be that you need to include both dates when calculating the number of days.

A few examples from my work experience:

I worked at creating an online job board, and we had plenty of problems with end dates for some entity types (expiration for a job, a subscription, etc). These would be specified as the last day this entity was still valid, which is what got stored in the database. But what made sense in the code would be to have the exact time when the entity would change state, i.e. at 00:00 the following date. That lead to very complex domain logic.

At some point, I refactored the entire system, adding one day to every EndDate in the database, and then moved the logic to the presentation layer, specifying that the actual date presented to the user should be the day preceding the one in the database. This lead to much, much cleaner domain logic regarding item expiration.

When I did the next project I worked with where date/entity expiration logic was important, I created a specific Date data type to encompass these rules, including overloading comparison operators with the build in DateTime class, arithmetic operators, etc. This lead to even simpler code, as it much better reflected the domain model, and the requirements for the presentation layer to subtract one day from all end days was removed, also removing the risk that someone would forget to implement this.


答:
I think the crux of the dilemma is that you've named the operation "calculating how many days between two dates".  Clearly there are zero days between 3/1/12 and 3/2/12, but that more likely means that you've named the calculation wrong rather than done the wrong calculation.

Date arithmetic is notoriously tricky because of all the exceptions, so you really have to be rigorous in defining your requirements.  For example, what does "now minus one day" translate into?  You might say it means whatever time it was 24 hours ago, but I think that would be wrong in most applications.  True, most days have 24 hours, but with daylight saving time one day has 23 hours and one day has 25 hours. I thank if it is noon on Sunday then now minus one day means noon on Saturday regardless of how many hours ago that was. I could go on with leap seconds and all the trouble they bring, as well as ensuring all the arithmetic identities and properties hold, but all of this is probably more work than you want to do.

Generally, when doing calendar date arithmetic people are interested in the "difference between dates".  You can visualize this by imagining a paper calendar with the dates printed on it and putting a coin or stone or other marker on the starting date.  If you are only allowed to move the marker to the immediately following date, how many moves would it take you to get to the ending date?  That is the difference between the two dates in days.

One other practical consideration, though, is whether your application really includes the end date.  It is typical for insurance contracts, for example, to not include the end date.  Policies expire at 12:01 am on the end date.  If you buy a policy that expires tomorrow, it's good for less than a day.  On the other hand, in California, a "3 day notice to pay rent or quit" eviction notice gives you more than 3 days to get out. You have until the end of the third business day after the notice is served to pay the rent.  So Wednesday + 3 days is actually Monday unless Monday is a holiday, in which case it is Tuesday and either way you get the whole final day, so a landlord cannot proceed until today > Wednesday + 3 days, i.e Tuesday or Wednesday.  So it's not a straightforward calculation.

The good news is that because it comes up so often, there are libraries you can use to do the calculations and real life situations have reasonably well defined how they want date calculations done in order to clear up just these sorts of confusions.

So you really need to do your homework and correctly specify what interval you are talking about.


问:
How common are generic-case exponential time algorithms in production software?
I know that exponential time algorithms should generally be avoided but are sometimes necessary. A case being the Traveling Salesman. How common are such algorithms in production software? Are these cases typically necessary or a result of rush jobs? I understand that many can be solved with a good heuristic. What is typically done with those that cannot?</p>

答: Commonly used algorithm with exponential worst case complexity is the simplex method used in linear programming. However, what is generic-case complexity of that method is an open issue. With some specific assumptions it's polynomial. </p>


答:
Something that not in production software but done on production software is formal verification. It is probably not adopted for most customer software but gains track for embedded systems and drivers, that is for hard- and software whose correctness is important (and tractable).

Those verficiation problems that are actually computable (barrier #1) are often EXPTIME-hard, in the more lucky cases you get PSPACE-complete problems (barrier #2). Both classes are (suspected to be) harder than NP-complete problems, which are easy in comparison. Doubly-exponential problems are also easily obtained.

In these cases, heuristics (in the sense of end result) don't cut it as you need definite results; therefore you need big machines and time. There are heuristics (in the sense of alternative selection) that often lead to shorter runtime (i.e. clever search space exploration when error states are searched) but in the worst case, waiting is all you can do. Or you can do a pen-and-paper proof and have it checked by machines, which is computationally simpler.

Title: How common are generic-case exponential time algorithms in production software?

Body: I know that exponential time algorithms should generally be avoided but are sometimes necessary. A case being the Traveling Salesman. How common are such algorithms in production software? Are these cases typically necessary or a result of rush jobs? I understand that many can be solved with a good heuristic. What is typically done with those that cannot?</p>


问:
returning null vs returning zero, which would be better?
I inherited a project that I am managing and having to maintain pending the redevelopment of the code base. At the moment I am being tasked with adding little features all over the place and have gotten into the habit of returning null instead of zero in parts of the code where I am working on.

The problem is we have a client that is using this code and parts of code that require data from my implemented features receive a null and dump the stack trace in the UI.

I would like to avoid this entirely from my input but without the NullPointerException there's the potential that errors would be introduced into the client's data which may go un-noticed.

Usually I would have come up with my own error notification system but I have never inherited a project before. So I am unsure whether to continue down this path. I still believe that the stack dump is preferable to un-noticed data corruption/inaccuracies.

答:
Its a matter of personal preference and how important having all correct data is.

Returning an obviously wrong but still valid number is less likely to cause unexpected exceptions in the client but runs the risk of that error going unnoticed. (often -1 is used rather than zero as its more clearly incorrect rather than a real result)

Returning Null or an exception will bring down the client application if not handled correctly but ensures that the error will be noticed or at least handled in some way.

Either approach is acceptable however it is best to be consistent.


问:
Scrum Board for a distributed team
I am looking for recommendations on a digital Scrum Board which can be shared over the internet. I imagine something like a big tablet on which you can draw and which remote users can access, too.

I dislike Scrum software because I think one major benefit of a Scrum Board is its physical presence. It should be hard to ignore.

The best solution would be two big tablets on which you can draw and which can be synchronized.

Has anyone got product recommendations for something like this? Or would you rather use a software?

Kind regards,
Falcon

答:
Try out KanbanTool - online kanban board for organizing work and team collaboration.

The visualization on a board originates from the Kanban process. Scrum is a lot like Kanban. You could call it a concrete Kanban method, thinking in terms of software development.

This application has nice and smart drag & drop interface. If you need, you can modify card's template and board using swimlanes and columns. It also offers features dedicated for distributed teams such as: real time collaboration, permission levels, email notifications for task assigning and comments, adding tasks and comments via email. Moreover, KanbanTool provides powerful analytics for monitoring and improving your work. It works.

Title: Scrum Board for a distributed team


答:
I am currently reading Robert C. Martin's Clean Code and I finished the chapter on exception handling a few days ago. What he says is :

Returning null from methods is bad, but passing null into methods is worse

He goes on listing concrete examples on how you can avoid that, mainly:

when returning lists or arrays, return empty list or arrays

when returning non-collection objects, prefer returning "special case" objects, OR throwing exceptions. By "special case", I suppose it is for example returning an empty string (StringUtils.EMPTY if you work with the Apache Commons package), or a "NullObject" (thanks Thorbjørn I did not know it was a pattern in fact)...

If you build your application this way, you will have fewer "null checks" to write, something he mentions by saying that more often than not, having methods with a lot of "null checks" is a bad sign.

NullPointerException should be expected during development, when working with an API that may not be clear with how it treats its arguments, and I think they should be considered bugs in production code. I mean that if I work with an API I know and understand, I don't expect myself to catch NullPointerException, and I expect to see them in the log files if I do something wrong in fact (which sadly still happens after programming for a few years now :-).

Of course, as always with "best practices", you don't have to blindly follow these principles. These are "best practices", not "this-is-the-only-good-way practices" :-)

I did not read the Andrew Hunt and David Thomas' Pragmatic Programmer ... yet, but this blog link could be interesting. It explains in a few words the slight differences in exception handling between the two books, if you are curious.

Title: returning null vs returning zero, which would be better?

Body:
I inherited a project that I am managing and having to maintain pending the redevelopment of the code base. At the moment I am being tasked with adding little features all over the place and have gotten into the habit of returning null instead of zero in parts of the code where I am working on.

The problem is we have a client that is using this code and parts of code that require data from my implemented features receive a null and dump the stack trace in the UI.

I would like to avoid this entirely from my input but without the NullPointerException there's the potential that errors would be introduced into the client's data which may go un-noticed.

Usually I would have come up with my own error notification system but I have never inherited a project before. So I am unsure whether to continue down this path. I still believe that the stack dump is preferable to un-noticed data corruption/inaccuracies.


答:
The answer here lies with the client code. If you can coordinate testing of your changes with the owners of the client code and have them fix any problems exposed or develop functionality to handle changes you have introduced, that would be an adequate solution. If however it is difficult or impossible to coordinate testing then you have to limit or avoid unexpected use of their APIs.

Given more freedom to improve boundary communication you should try to avoid null as an exceptional value, conventions such as -1 as used in, for example, streams are safer but not ideal and sometimes it is difficult to choose a specific value of a type to represent an exceptional case as there could be ambiguities introduced or no particular value available as all values of the type are potentially legitimate input.

High level languages such as Haskell and Scala promote the use of option types to wrap either a value of a particular type or a value of a different type representing an exceptional value or state. Use of option types as parameters forces the client to handle or propagate the option content rather than rely on conventions on specific values or trust that a null won't be received. Option types open up a whole range of useful techniques and patterns.


问:
What are the alternatives to "overriding a method" when using composition instead of inheritance?
If we should favor composition over inheritance, the data part of it is clear, at least for me.

What I don't have a clear solution to is how overwriting methods, or simply implementing them if they are defined in a pure virtual form, should be implemented.

An obvious way is to wrap the instance representing the base-class into the instance representing the sub-class. But the major downsides of this are that if you have say 10 methods, and you want to override a single one, you still have to delegate every other methods anyway. And if there were several layers of inheritance, you have now several layers of wrapping, which becomes less and less efficient. Also, this only solve the problem of the object "client"; when another object calls the top wrapper, things happen like in inheritance. But when a method of the deepest instance, the base class, calls it's own methods that have been wrapped and modified, the wrapping has no effect: the call is performed by it's own method, instead of by the highest wrapper.

One extreme alternative that would solve those problems would be to have one instance per method. You only wrap methods that you want to overwrite, so there is no pointless delegation. But now you end up with an incredible amount of classes and object instance, which will have a negative effect on memory usage, and this will require a lot more coding too.

So, are there alternatives (preferably alternatives that can be used in Java), that:

Do not result in many levels of pointless delegation without any changes.

Make sure that not only the client of an object, but also all the code of the object itself, is aware of which implementation of method should be called.

Does not result in an explosion of classes and instances.

Ideally puts the extra memory overhead that is required at the "class"/"particular composition" level (static if you will), rather than having every object pay the memory overhead of composition.

My feeling tells me that the instance representing the base class should be at the "top" of the stack/layers so it receives calls directly, and can process them directly too if they are not overwritten. But I don't know how to do it that way.

[EDIT] It seems that many people reading this question think that I am debating if I should use Composition or Inheritance, and that "guiding" me to the one or the other will solve my problem. This is not the case. I always use inheritance when I can, for the simple fact that composition requires more coding, and also more memory. No need to convince me that inheritance is not evil.

I have a very good reason to want to use composition. I want to create a system that model domain objects that can "change nature" over time. That is they can both gain and loose functionality/properties over time, as a result of some actions. This is a lot more natural when modeled as composition.

If the components that can be dynamically added and removed where composed only of properties, it would be easy. In fact I have already found 14 different possible designs that support that case, with varying compromise on code complexity, memory usage, and speed.

The real problem comes when all those components need to be aware of each other, and talk to each other. This is not required when they are just "beans" (in the Java sense). I want to know if there are any, and hopefully several, ways of allowing the components to talk to each other, and more specifically how to have several components of the same type, where one serves as base-class and the others progressively override some of it's methods.

I can see two ways to simulate the overriding present in inheritance.

The first is to have a base component, and all overriding components are built as wrapper on top of another component of the same type. Like that, you can choose at runtime which hierarchy of components you want. This is like pipes and filters. But the problem is that with inheritance, not only can the derived class call methods of the base class, but it works the other way around too. A base class can declare a pure virtual method, which is implemented by the sub-class, and the base class can call this method. I don't see how to accomplish that using whole component wrapping. Also, if we have N inheritance/wrapping layers, then calls to method of the base component then gets N level of delegation, even if the method was not overwritten by any of the wrapping components.

The other alternative, like I said in "One extreme alternative ...", is to do it like above, but forcing each component to contain a single method. In that case we solve the problem of the base-class not seeing/calling the methods of the derived classes, for all methods, except it's own method. So it works now correctly for all cases except for recursion. But the price we pay in memory consumption is high, at least in Java. And Java isn't "functional", so there is a lot of syntax overhead to turn every object method into an individual object.

If there any better alternatives then the two mentioned above, I would like to know about it.

答: "favor composition over inheritance" doesn't mean never use inheritance, but just don't use inheritance when composition will work. IMO, the need of overwriting justifies the use of inheritance.</p>


问:
Is comparing cloud computing to main frames a bad analogy?
They both can be seen as centralized processing, but from a developer's perspective is it returning us to the days when access to computers you could program yourself were limited and expensive? To me that was the problem the PC solved.

Heard this on http://thisdeveloperslife.com/ 1.0.6 Abstraction.

答:
Computing is constantly swinging back and forth between centralized and decentralized architectures. I think it is simply a case of "The grass is always greener".

However, I don't think that the centralized model (IaaS) is necessarily going to make access to computing power more expensive. That, in my opinion, was more a factor of how expensive the computing equipment was and not so much the purchasing model of computing power.

ContentLicense: CC BY-SA 2.5


问:
Is it a bad practice to store large files (10 MB) in a database?
I am currently creating a web application that allows users to store and share files, 1 MB - 10 MB in size.

It seems to me that storing the files in a database will significantly slow down database access.

Is this a valid concern? Is it better to store the files in the file system and save the file name and path in the database? Are there any best practices related to storing files when working with a database?

I am working in PHP and MySQL for this project, but is the issue the same for most environments (Ruby on Rails, PHP, .NET) and databases (MySQL, PostgreSQL).

答:
The old conventional wisdom of storing files outside database might no longer hold. As a matter of principle, I'd favor integrity over speed, and with a modern DBMS, you can have both.

Tom Kyte seems to agree:

I know of no advantages to storing data I want to keep for a long time outside of a database.

If it is in the database I can

be sure it is professionally managed

backed up

recoverable (with the rest of the data)

secured

scalable (try putting 100,000 documents in a single directory, now, put them in table - which one 'scales' - it is not the directory)

I can undelete (flashback) easily

I have locking

I have read consistency...


答:
If you're composing your data, why not also compose your methods? Many languages have a notion of a function as an object, or a function pointer. Your composition target could have methods which are defined as properties and these could be recomposed as you see fit. Here's an example in my primary language, C#:

```<code>public class ComposedClass
{
    public Func<string, string> Format { get; set; }

    public ComposedClass()
    {
        Format = s => s.ToUpper();
    }
}
</code>```

This class has a default implementation of Format which will convert the string to upper case. We could provide an alternative implementation which does something else.

```<code>[TestFixture]
public class Tests
{
    [Test]
    public void Default_implementation_returns_FOO()
    {
        var composedObj = new ComposedClass();

        var result = composedObj.Format("Foo");

        Assert.That(result, Is.EqualTo("FOO"));
    }

    [Test]
    public void Alternative_implementation_returns_foo()
    {
        var composedObj = new ComposedClass();
        composedObj.Format = (string s) => s.ToLower();

        var result = composedObj.Format("Foo");

        Assert.That(result, Is.EqualTo("foo"));
    }
}
</code>```

You would have to implement appropriate guards around set_Format of course, and you would have to explicitly pass around an alternative to this if it is required.

It's worth pointing out that in reality, I would probably do what @AProgrammer is suggesting, and use inheritance anyway, but since you asked what are the alternatives, here is an alternative!

Title: What are the alternatives to "overriding a method" when using composition instead of inheritance?

Body:
If we should favor composition over inheritance, the data part of it is clear, at least for me.

What I don't have a clear solution to is how overwriting methods, or simply implementing them if they are defined in a pure virtual form, should be implemented.

An obvious way is to wrap the instance representing the base-class into the instance representing the sub-class. But the major downsides of this are that if you have say 10 methods, and you want to override a single one, you still have to delegate every other methods anyway. And if there were several layers of inheritance, you have now several layers of wrapping, which becomes less and less efficient. Also, this only solve the problem of the object "client"; when another object calls the top wrapper, things happen like in inheritance. But when a method of the deepest instance, the base class, calls it's own methods that have been wrapped and modified, the wrapping has no effect: the call is performed by it's own method, instead of by the highest wrapper.

One extreme alternative that would solve those problems would be to have one instance per method. You only wrap methods that you want to overwrite, so there is no pointless delegation. But now you end up with an incredible amount of classes and object instance, which will have a negative effect on memory usage, and this will require a lot more coding too.

So, are there alternatives (preferably alternatives that can be used in Java), that:

Do not result in many levels of pointless delegation without any changes.

Make sure that not only the client of an object, but also all the code of the object itself, is aware of which implementation of method should be called.

Does not result in an explosion of classes and instances.

Ideally puts the extra memory overhead that is required at the "class"/"particular composition" level (static if you will), rather than having every object pay the memory overhead of composition.

My feeling tells me that the instance representing the base class should be at the "top" of the stack/layers so it receives calls directly, and can process them directly too if they are not overwritten. But I don't know how to do it that way.

[EDIT] It seems that many people reading this question think that I am debating if I should use Composition or Inheritance, and that "guiding" me to the one or the other will solve my problem. This is not the case. I always use inheritance when I can, for the simple fact that composition requires more coding, and also more memory. No need to convince me that inheritance is not evil.

I have a very good reason to want to use composition. I want to create a system that model domain objects that can "change nature" over time. That is they can both gain and loose functionality/properties over time, as a result of some actions. This is a lot more natural when modeled as composition.

If the components that can be dynamically added and removed where composed only of properties, it would be easy. In fact I have already found 14 different possible designs that support that case, with varying compromise on code complexity, memory usage, and speed.

The real problem comes when all those components need to be aware of each other, and talk to each other. This is not required when they are just "beans" (in the Java sense). I want to know if there are any, and hopefully several, ways of allowing the components to talk to each other, and more specifically how to have several components of the same type, where one serves as base-class and the others progressively override some of it's methods.

I can see two ways to simulate the overriding present in inheritance.

The first is to have a base component, and all overriding components are built as wrapper on top of another component of the same type. Like that, you can choose at runtime which hierarchy of components you want. This is like pipes and filters. But the problem is that with inheritance, not only can the derived class call methods of the base class, but it works the other way around too. A base class can declare a pure virtual method, which is implemented by the sub-class, and the base class can call this method. I don't see how to accomplish that using whole component wrapping. Also, if we have N inheritance/wrapping layers, then calls to method of the base component then gets N level of delegation, even if the method was not overwritten by any of the wrapping components.

The other alternative, like I said in "One extreme alternative ...", is to do it like above, but forcing each component to contain a single method. In that case we solve the problem of the base-class not seeing/calling the methods of the derived classes, for all methods, except it's own method. So it works now correctly for all cases except for recursion. But the price we pay in memory consumption is high, at least in Java. And Java isn't "functional", so there is a lot of syntax overhead to turn every object method into an individual object.

If there any better alternatives then the two mentioned above, I would like to know about it.

Body:
If you're composing your data, why not also compose your methods? Many languages have a notion of a function as an object, or a function pointer. Your composition target could have methods which are defined as properties and these could be recomposed as you see fit. Here's an example in my primary language, C#:

public class ComposedClass
{
    public Func<string, string> Format { get; set; }

    public ComposedClass()
    {
        Format = s => s.ToUpper();
    }
}

This class has a default implementation of Format which will convert the string to upper case. We could provide an alternative implementation which does something else.

[TestFixture]
public class Tests
{
    [Test]
    public void Default_implementation_returns_FOO()
    {
        var composedObj = new ComposedClass();

        var result = composedObj.Format("Foo");

        Assert.That(result, Is.EqualTo("FOO"));
    }

    [Test]
    public void Alternative_implementation_returns_foo()
    {
        var composedObj = new ComposedClass();
        composedObj.Format = (string s) => s.ToLower();

        var result = composedObj.Format("Foo");

        Assert.That(result, Is.EqualTo("foo"));
    }
}

You would have to implement appropriate guards around set_Format of course, and you would have to explicitly pass around an alternative to this if it is required.

It's worth pointing out that in reality, I would probably do what @AProgrammer is suggesting, and use inheritance anyway, but since you asked what are the alternatives, here is an alternative!


问:
How is dependency inversion related to higher-order functions?
Today I've just seen this article which described the relevance of SOLID principle in F# development-

F# and Design principles – SOLID

And while addressing the last one - "Dependency inversion principle", the author said:

From a functional point of view, these containers and injection concepts can be solved with a simple higher order function, or hole-in-the-middle type pattern which are built right into the language.

But he didn't explain it further. So, my question is, how is the dependency inversion related to higher order functions?

答:
Short Answer:

Classical Dependency Injection/Inversion of Control uses a class interfaces as placeholder for dependant functionality. This interface is implemented by a class.

Instead of Interface/ClassImplementation many dependencies can be easier implemented with a delegate function.

You find an example for both in c# at ioc-factory-pros-and-contras-for-interface-versus-delegates.


问:
A measure of development speed
I've seen a lot of tests measuring execution speed of programming languages, but I've never found tests measuring development speed.

I've heard development speed is increased when working with dynamic languages, but is there any proof of that ? I'm not trying to say dynamic languages aren't efficient, but I'd kind of like to see the results of a scientific study, if such a thing exists.

Even better would be informations on maintenance facility. Are some languages easier to debug than others ?

EDIT : I'm mostly interested in the differences between two languages that are close in syntax. For example, I guess programming in C will usually be slower than programming in Java; but is programming in Java faster than programming in C# ?

答: Absolutely the programming language makes a difference. However, I think that difference is far more about how familiar the programmer is with each language than any particular aspect of the language, especially given your constraint of languages with similar syntax.</p>

Title: A measure of development speed


答:
There are many cases where Null is a valid and expected result for a function, and many cases where it is not a valid return value.

For functions that return a reference to "optional" data, then a Null return value can be valid. Examples for this would be reading the column of a database table where Null is allowed. Another example is a reference to a data object that is temporary or defined at a later time.

In those cases, it's programmers error for not checking that the value is set before using the reference.

For functions that should create a new instance of an object, return a reference to a must have object or a function that returns an object that holds the context of the result, then all those cases should always return a valid reference. If it's not possible to do so, then a well documented exception should be thrown.

There are many design patterns out there for handling things in different ways to make it easier for testing or stability.

For example, rather then having a function create a new object to hold a result and return it. The function should take an object as an argument and modify it. Rather then have a constructor that creates objects (which could fail), the constructor should do nothing and have an initialize function with all the required objects as parameters.


答:
First of all, as said, the language used leads to differences in the answer. But the main problem is thing is:

Returning a "0" value will likely lead to silent errors. Whether this is a special NullObject or 0 or "Jan 1, 1900". At the very least it will compound dirty data problems

You are working on an existing product, and existing consumers should remain functional. Not only that, but the rest of the codebase should not regress either.

So, how to handle this?

Use a preprocessor (yes, you can do this even when the language is not defined to use one), and create a NULL token that is replaced either by null or 0 based on whether you're in "debug" mode.

For external clients, isolate them from the "correct" version, by having the interface it uses become a compatibility interface that (preferably automatically generated) translates between the old one and the new (better one)

This allows you to keep things working as they are for "production", but still "debug" or "test" the system with more correctness. Debug mode would also not use the compatibility layer such that client correctness can be (independently) tested.


问:
Why doesn't Visual Studio auto increment your version number?
This question asked how to auto update version number in VS 2010 :
https://stackoverflow.com/questions/4025704/publishing-in-net-produces-application-files-myapp-someversionnumber-how-to-ge

The answer was,
You have to update both Assembly Version AND File version manually

Shouldn't the version number increment each time I publish?  Why should I do it manually?  Is this is a conscious decision by MS to do it this way? What's the thinking behind having people manually update their own version number?

答:
You could always use the "Build Version Increment" open source add-on for visual studio to do it for you.

...I've tested the addin with Visual Studio 2005/2008 on C#, VB.NET and C++.NET projects under Windows XP/Vista SP1.

Functionality

Different auto increment styles can be set per major, minor, build or revision number.

Supports C#, VB.NET and C++.NET projects.

Not required to be installed by all project members. Configuration is shared via properties in the solution and project files. Developers who don't have the addin won't feel a thing.

Automatically checks out required files if under source control.

Can be configured per solution and/or per project.

Can be configured to update only on certain configuration builds (debug, release, any or custom)

Can update assembly attributes in an external source file instead of the default AssemblyInfo...


答:
What I usually try to do when I'm fixing a bug is:

Confirm that the bug exists. Preferrably I'll "document" the bug by writing a  test case that fails due to the bug. This also has the advantage of knowing that this test case now will be part of the test suite of the product, so if the bug pops up again this will be confirmed by the regression tests (assuming that you run regression tests of course!).

Familiarize myself with the code causing the problem. If I'm still unsure if I'll break anything else by my bug fix (oh the irony) I'll write more test cases to document the behavior of the given code. This not only benefits me but also others who will go through the same code eventually.

Fix the bug.

Ensure that all the test cases affecting my bug fix passes.

Basically I try to keep a safety net for all my bug fixes just to make sure that I don't cause additional bugs. I also understand that it sometimes will feel easier to just change the code and be done with it, but at the same time it can definitely be worth the initial time investment, since not only you, but also others who deal with the same code will benefit from having an increased test coverage.

Title: Bug fixing approach

Body:
I have been working on a database project, and I recently received a bug report for the remote execution of some queries.

Usually, you try to find out the actual cause for the bug to occur and then fix it.

But sometimes what I do when I'm fed up of doing some research (and can't find suitable information on the internet) is just change the logic, which takes me much less time compared to the other option.

Is this approach correct, or should I try to fix the original bug involving more R&D?


问:
What is a widely accepted term for a string variable that would probably contain a file path and file name?
For functions that need to index files in a directory and rename them FileName0001, FileName0002, etc... I often need to write a function that splits the file name from the file path and rename the file.  When I put the file name and file path back together, I don't have a very good name for the variable that contains both of them and I usually just wind up concatenating them every time I want to use them (usually using them as parameters for functions labeled either filename or filepath) so I never really know what I'm doing until I notice a lot of files being written in the same directory as my binaries.

Anyway, what do I call a file name and a file path?  I don't want to call it File, because that usually means the binary information behind the file.  I don't want to call it URI because that usually means I've got some sort of protocol, which I don't.  I just want a good way to denote "c:\somedir\somedir\somedir\somefile.txt" so as to deconfuse this mess I've just realized I'm in.

Please don't just list your personal preference.  I think an excellent answer should "'site its sources". (as in, provide a link to a repository with a good example of the code being used as I described)

答:
This differs a lot from time to time, but what I usually do is use names along the lines of absoluteDirectoryPath, absoluteFilePath, relativeDirectoryPath, relativeFilePath, directoryName and fileName. This depends on whether I want to access just the directory or the whole path to where the file is located as well.

In addition to this the names will also most likely reflect e.g. what kind of business logic they are affecting, or the content of the files.


问:
Are There Metrics For Cohesion And Coupling?
Is there a metric analogous to the McCabe Complexity measure to measure how cohesive a routine is and also how loosely (or tightly) coupled the routine is to other code in the same code base?</p>

答:
Afferent coupling: Number of responsibilities

Efferent coupling: Number of dependencies

Instability: Ratio of efferent coupling to total coupling (Afferent + Efferent).

Instability is supported in various code metric tools.


答:
I think the metric you are looking for is LCOM4, although it applies more to classes.

Sonar explains it nicely here:

...metric : LCOM4 (Lack Of Cohesion Methods) to measure how cohesive classes are. Interpreting this metric is pretty simple as value 1 means that a class has only one responsibility (good) and value X means that a class has probably X responsibilities (bad) and should be refactored/split.

There is not any magic here, only common sense. Let’s take a simple example with class Driver. This class has two fields : Car and Brain, and five methods : drive(), goTo(), stop(), getAngry() and drinkCoffee(). Here is the dependency graph between those components. There are three blocks of related components, so LCOM4 = 3, so the class seems to have three different responsibilities and breaks the Single Responsibility Principle.

...

It's a great tool, if you can use it. :)

Title: Are There Metrics For Cohesion And Coupling?

Body: Is there a metric analogous to the McCabe Complexity measure to measure how cohesive a routine is and also how loosely (or tightly) coupled the routine is to other code in the same code base?</p>


答:
Actually, I think that the effect of Cloud Computing will be quite the opposite: it will democratize the building of large web applications by making the required infrastructure available to nearly anyone.

Yes, we will have to be able to pay for the services provided by the cloud providers, but it will be immensely more practical for a single developer or a small team to have viral-level success with a web application than if they had to provide the hardware, co-lo, configuration and maintenance themselves.

Similarly, IaaS provides a marked advantage over traditional hosting in that it accounts for sudden, low-effort scalability. If my application runs on Google AppEngine and goes viral, I have to do nothing; it will scale without any effort on my part. However, if my PHP/MySQL app is on GoDaddy and needs to scale, I will have a good amount of work ahead of me.

Title: Is comparing cloud computing to main frames a bad analogy?

Body:
They both can be seen as centralized processing, but from a developer's perspective is it returning us to the days when access to computers you could program yourself were limited and expensive? To me that was the problem the PC solved.

Heard this on http://thisdeveloperslife.com/ 1.0.6 Abstraction.


问:
SQL Strings vs. Conditional SQL Statements
Is there an advantage to piecemealing sql strings together vs conditional sql statements in SQL Server itself? I have only about 10 months of SQL experience, so I could be speaking out of pure ignorance here.

Where I work, I see people building entire queries in strings and concatenating strings together depending on conditions. For example:

```<code>Set @sql = 'Select column1, column2 from Table 1 '

If SomeCondtion
    @sql = @sql + 'where column3 = ' + @param1
else
    @sql = @sql + 'where column4 = ' + @param2
</code>```

That's a real simple example, but what I'm seeing here is multiple joins and huge queries built from strings and then executed. Some of them even write out what's basically a function to execute, including Declare statements, variables, etc. Is there an advantage to doing it this way when you could do it with just conditions in the sql itself? To me, it seems a lot harder to debug, change and even write vs adding cases, if-elses or additional where parameters to branch the query.

答:
Dynamic SQL is used in situations where the conditions aren't known ahead of time. One example I've run into often is an "advanced" search form where the user can search on multiple fields and can search beyond simple "substring" searches where they can specify a search value must match exactly (OR match as a substring, and case sensitivity is an option), and for numeric/date values they can specify operators >, <, >=, <=. It might also happen that one search form is actually searching multiple joined tables. In this case, it's much easier to build a query on the fly as a string and execute it that way, than to try to imagine every possible query they user could submit and have if-else blocks choose a pre-existing query.

You are correct though. Dynamic SQL can be very difficult to debug (when debugging, I add code to print the query with and without the substitution values before executing it) and can also run slower.


答:
First, string concatenation is a dangerous practice. In theory, it's fine if you're concatenating parameterized strings like:

```<code>sql += "where foo = @param";
...
command["@param"] = <some value>;
</code>```

Otherwise, it's prone to SQL injection attacks.

But more to the point, the answer is the dreaded, "it depends". A huge query can be very fast if the database tables are indexed for those scenarios. On the other hand, often times the client understands the conditions and the subset of data it needs better than the database server. In the example you gave, it's actually reasonable that the client customizes its WHERE clause before executing it.

Having the client customize its query and extracting the data it needs from it can distribute work better, but again, it depends on what the tables are designed for. On one extreme, some schemas are designed to be a la carte, performing best with many little ad-hoc queries against individual tables. Other schemas are designed to expose only a limited set of highly optimized stored procs, from which one should not stray. In the latter case, you'd be right - they should go with larger queries. In the former case, it's entirely reasonable for the client to take its share of the decision making.

Title: SQL Strings vs. Conditional SQL Statements

Body:
Is there an advantage to piecemealing sql strings together vs conditional sql statements in SQL Server itself? I have only about 10 months of SQL experience, so I could be speaking out of pure ignorance here.

Where I work, I see people building entire queries in strings and concatenating strings together depending on conditions. For example:

```<code>Set @sql = 'Select column1, column2 from Table 1 '

If SomeCondtion
    @sql = @sql + 'where column3 = ' + @param1
else
    @sql = @sql + 'where column4 = ' + @param2
</code>```

That's a real simple example, but what I'm seeing here is multiple joins and huge queries built from strings and then executed. Some of them even write out what's basically a function to execute, including Declare statements, variables, etc. Is there an advantage to doing it this way when you could do it with just conditions in the sql itself? To me, it seems a lot harder to debug, change and even write vs adding cases, if-elses or additional where parameters to branch the query.

Body:
First, string concatenation is a dangerous practice. In theory, it's fine if you're concatenating parameterized strings like:

sql += "where foo = @param";
...
command["@param"] = <some value>;

Otherwise, it's prone to SQL injection attacks.

But more to the point, the answer is the dreaded, "it depends". A huge query can be very fast if the database tables are indexed for those scenarios. On the other hand, often times the client understands the conditions and the subset of data it needs better than the database server. In the example you gave, it's actually reasonable that the client customizes its WHERE clause before executing it.

Having the client customize its query and extracting the data it needs from it can distribute work better, but again, it depends on what the tables are designed for. On one extreme, some schemas are designed to be a la carte, performing best with many little ad-hoc queries against individual tables. Other schemas are designed to expose only a limited set of highly optimized stored procs, from which one should not stray. In the latter case, you'd be right - they should go with larger queries. In the former case, it's entirely reasonable for the client to take its share of the decision making.


答:
Sounds like you're working with a bunch of Spaghetti Code. No reason the building of sql strings can't be broken down into structured and more managable pieces.  It probably comes down to do you prefer your programming language or tsql. Personally, I think building sql statements in code is always a mess. In your case, it doesn't look like using an ORM is an option unless you can convince the rest of the team/those in charge.

I'm not sure one pre-written, self-contained SQL statement with all the conditions is any easier to debug than several simpler statements generated by coded conditions in your language of choice. Either one can be done poorly.

EDIT: are you proposing something like this?

```<code>Select column1, column2 from Table 1
where (SomeCondtion = 0 and column3 = @param1)
 or (SomeCondition = 1 and column4 =  @param2)
</code>```

Body:
Sounds like you're working with a bunch of Spaghetti Code. No reason the building of sql strings can't be broken down into structured and more managable pieces.  It probably comes down to do you prefer your programming language or tsql. Personally, I think building sql statements in code is always a mess. In your case, it doesn't look like using an ORM is an option unless you can convince the rest of the team/those in charge.

I'm not sure one pre-written, self-contained SQL statement with all the conditions is any easier to debug than several simpler statements generated by coded conditions in your language of choice. Either one can be done poorly.

EDIT: are you proposing something like this?

Select column1, column2 from Table 1
where (SomeCondtion = 0 and column3 = @param1)
 or (SomeCondition = 1 and column4 =  @param2)


问:
What is the best C++ source code to read for a beginner?
I'm trying to improve my c++ coding technique by reading c++ source code. Which open source project would you recommend? Is the code of Boost C++ Libraries a good one?</p>

答: I wouldn't recommend reading a code base.  I'd recommend reading C++ FAQS. There's also an excellent book that goes along with the site.  Best way to improve your C++ coding skills.</p>


答:
Classic example of needing a Builder pattern

Try to build up a SQL query as the result of a fluent interface. Hibernate for Java does it like this for their Criteria API:

```<code>List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.in( "name", new String[] { "Fritz", "Izi", "Pk" } ) )
    .add( Restrictions.disjunction()
        .add( Restrictions.isNull("age") )
        .add( Restrictions.eq("age", new Integer(0) ) )
        .add( Restrictions.eq("age", new Integer(1) ) )
        .add( Restrictions.eq("age", new Integer(2) ) )
    ) )
    .list();
</code>```

Of course, their approach is a generic SQL solution, your builder could be targeted at precisely one query type that needed dynamic construction at runtime.

Body:
Classic example of needing a Builder pattern

Try to build up a SQL query as the result of a fluent interface. Hibernate for Java does it like this for their Criteria API:

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.in( "name", new String[] { "Fritz", "Izi", "Pk" } ) )
    .add( Restrictions.disjunction()
        .add( Restrictions.isNull("age") )
        .add( Restrictions.eq("age", new Integer(0) ) )
        .add( Restrictions.eq("age", new Integer(1) ) )
        .add( Restrictions.eq("age", new Integer(2) ) )
    ) )
    .list();

Of course, their approach is a generic SQL solution, your builder could be targeted at precisely one query type that needed dynamic construction at runtime.


答:
Imagine how this would be tested: you need to have some real world project developed independently both repeatedly with the same language (to take away the variability of programmer experience and knowledge) and with different languages (to get some data to compare the languages).  Seems to me that the experiment quickly grows to an unmanageable size.

I'd love to hear about ways to "shrink" the experiment, or about attempts to actually perform the experiment as stated.

Title: A measure of development speed

Body:
I've seen a lot of tests measuring execution speed of programming languages, but I've never found tests measuring development speed.

I've heard development speed is increased when working with dynamic languages, but is there any proof of that ? I'm not trying to say dynamic languages aren't efficient, but I'd kind of like to see the results of a scientific study, if such a thing exists.

Even better would be informations on maintenance facility. Are some languages easier to debug than others ?

EDIT : I'm mostly interested in the differences between two languages that are close in syntax. For example, I guess programming in C will usually be slower than programming in Java; but is programming in Java faster than programming in C# ?


答:
For practical implementation, here are what you may concern:

Benifits:

All file contents are definitely synchronized with your table. As comments above said, backing up data is totally convenient as you don't need to keep data synchronized with the file system.

From coding, you can get file content directly from a SQL select.

From a query, you can even filter file content or its size explicitly from SQL statement.

Downsides:

Compared to a databased of which structure is semantically the same but does not store file content, you database tends to consume radically more memory when doing query.

Auto backup can cause performance problem but not much. Let's imagine your database server is backing up things every 6 hours and those databases you have are storing 10-MB file per record. That scenario is not what you want.

Title: Is it a bad practice to store large files (10 MB) in a database?

Body:
I am currently creating a web application that allows users to store and share files, 1 MB - 10 MB in size.

It seems to me that storing the files in a database will significantly slow down database access.

Is this a valid concern? Is it better to store the files in the file system and save the file name and path in the database? Are there any best practices related to storing files when working with a database?

I am working in PHP and MySQL for this project, but is the issue the same for most environments (Ruby on Rails, PHP, .NET) and databases (MySQL, PostgreSQL).


答:
I've actually built queries like that myself in the past when SomeCondition is not something that SQL server could/should possibly know

For example, if SomeCondition is a check to see if a CheckBox is checked or not, then there is no way SQL server could or should know that

It was also because I wasn't comfortable creating stored procedures in SQL, however since then I've gotten much more comfortable with SQL Server and would now create a stored procedure that accepts an IsChecked parameter. It's much easier to maintain and debug, and the risks of a sql injection attack are lower.

There are many developers who are not comfortable with building stored procedures in SQL, and to them, its faster/easier to use the programming language to build in their conditions instead of building a stored procedure in SQL Server.


问:
What is your strategy for converting RC builds into retail?
We're trying to implement a strategy for how we transition our builds from RC to released retail code.

When we label a build as a release candidate, we send it to QA for regression. If they approve it, that RC then becomes our released retail code.

I liked the idea of "obvious" labeling of versions so that a user knows whether they have a beta or an RC or retail code... where you would have some obvious watermark in non-retail code (think Windows 7 where the RC or non-genuine builds watermark in the bottom right).

... but it seemed strange to us to manipulate the project (to remove the watermark) once it passed regression. If QA certified version a.b.c.d then our retail code should be that same version, not a.b.c.d+1

what strategies have you employed to clearly label non-release software versions without incrementing your build to disable the watermarks in your retail code? One idea I've considered is writing your build to look for a signed file in the installer archive... non-release code wouldn't include this file and so the app would know to display a watermark.

But even this seems like QA is then working with non-release code.

Ideas?

EDIT: What about a process that QA themselves can run to remove the "RC" indicator? That might be an interesting way to handle it.

答:
Follow your instinct. It'd be nice if you could make the release candidate look one way before release and another way afterward, but you're right: it's important that the released version be exactly what QA approved. In my experience, the usual MO is:

Produce test (alpha, beta) versions that are clearly marked. Send them to QA for testing.

As you get closer to release, produce release candidate versions that are again clearly marked. Send them to QA for testing.

Once a release candidate gets the seal of approval, produce a final "golden master" build that is exactly what you intend to ship. No "golden master" or "release candidate" markings. Send that to QA one more time.

When QA approves the golden master, ship it. Or better, have them ship it so that there's no question that the version they approved is the shipping version.

It's still a good idea to come up with some technical means for turning the "test" markings on and off. That'll help you minimize the steps that you have to perform between approval of the final candidate and the shipping version. My point here is just that you should have QA review the product after you've performed those steps, whatever they are.


答:
You have a couple simple options.

First, you could use software, and use a flat panel on the wall to display it.  You lose the quick ability to edit at a physical board, but gain instant updates at all ends of the distributed team.

Second, depending how many distributed people exist, if it's only 1 of the team, you could have a physical board at the main location, and just point a webcam at it for the distributed member(s).  However for them to make updates, they would need to contact a person near the board to make the update for them.

Title: Scrum Board for a distributed team

Body:
I am looking for recommendations on a digital Scrum Board which can be shared over the internet. I imagine something like a big tablet on which you can draw and which remote users can access, too.

I dislike Scrum software because I think one major benefit of a Scrum Board is its physical presence. It should be hard to ignore.

The best solution would be two big tablets on which you can draw and which can be synchronized.

Has anyone got product recommendations for something like this? Or would you rather use a software?

Kind regards,
Falcon


答:
Scrumy is by far the best software that I've found. It's just the board, it's lightweight, easy to use and easy to handle. Just what you want.

Most of the other things we evaluated were bloatware. It's like the spirit of agile manifested itself in this software.

Why does Scrumy exist?

We were attempting to use Scrum to manage our
  projects, but the generic sticky notes we bought kept falling off the
  wall. We looked for online solutions to scrum, but all of them were
  too complicated and expensive. All we really wanted was an online
  version of our wall sticky notes. So we made one.

Title: Scrum Board for a distributed team


问:
Initialized variables vs named constants
I'm working on a fundamental programming class in college and our textbook is "programming logic and design" by joyce farrell(spelling?)

Anyhow, I'm struggling conceptually when it comes to initialized variables and named constants.

Our class is focusing on pseudo-code for the time being and not one particular language so let me illustrate what I'm talking about.

Let's say I am declaring a variable named "myVar" and the data type is numeric:

num myVar

now I want to initialize it (I don't understand this concept) starting with the number 5

num myVar = 5

how is that any different than creating a named constant?

答:
The initialization process may look the same, but a constant cannot be changed once it is set.  Depending on the type of variable (private, protected, public), other things, such as the current class, subclasses, or other classes, can act on and may have the ability to change the value of that variable.  A constant stays the same for all things using it.

So lets say you initialize a variable to say:

```<code>var normalVariable = 10;
</code>```

Later in your code you could change it to 20, or something, if you wanted.  With a constant (which is usually named in all caps LIKE_THIS), you couldn't change the value to something else, you would most likely get an error if you tried.

For the most part, a variable is what it claims to be.  It is something that may not always be a certain value.  A constant on the other hand would be something that you want to signify as something that will not change.  Think gravity or Pi in the real world.

Body:
The initialization process may look the same, but a constant cannot be changed once it is set.  Depending on the type of variable (private, protected, public), other things, such as the current class, subclasses, or other classes, can act on and may have the ability to change the value of that variable.  A constant stays the same for all things using it.

So lets say you initialize a variable to say:

var normalVariable = 10;

Later in your code you could change it to 20, or something, if you wanted.  With a constant (which is usually named in all caps LIKE_THIS), you couldn't change the value to something else, you would most likely get an error if you tried.

For the most part, a variable is what it claims to be.  It is something that may not always be a certain value.  A constant on the other hand would be something that you want to signify as something that will not change.  Think gravity or Pi in the real world.


答:
The difference is that a named constant is immutable.  With a variable you could write:

```<code>myVar = 10
</code>```

And the variable would store the change.  If it were a constant though, an error would be thrown.

Title: Initialized variables vs named constants

Body:
I'm working on a fundamental programming class in college and our textbook is "programming logic and design" by joyce farrell(spelling?)

Anyhow, I'm struggling conceptually when it comes to initialized variables and named constants.

Our class is focusing on pseudo-code for the time being and not one particular language so let me illustrate what I'm talking about.

Let's say I am declaring a variable named "myVar" and the data type is numeric:

num myVar

now I want to initialize it (I don't understand this concept) starting with the number 5

num myVar = 5

how is that any different than creating a named constant?

Body:
The difference is that a named constant is immutable.  With a variable you could write:

myVar = 10

And the variable would store the change.  If it were a constant though, an error would be thrown.


答:
A named constant is, as the name states, unable to be modified. In your example, you can set the value of myVar at anytime during your program's execution. Depending on the language, you can create a constant with the const (C/C++) or final (Java) keywords.

```<code>// C/C++
const int CONSTANT = 5;

// java
public static final int CONSTANT = 5;
</code>```

Body:
A named constant is, as the name states, unable to be modified. In your example, you can set the value of myVar at anytime during your program's execution. Depending on the language, you can create a constant with the const (C/C++) or final (Java) keywords.

// C/C++
const int CONSTANT = 5;

// java
public static final int CONSTANT = 5;


答: While it is language dependent, it is common practice when you declare a constant for the program itself to never actually make a variable that hold onto that value.  Instead, you can assume that if you have a numeric constant set to 5 that it will find every place that constant is used at compile time and replace it with 5 (or whatever).  If you create a variable (not constant) and just set it to 5, the compiler can't make that optimization, even if you never change the variable.  This means that when the program runs it will need to create a location in memory for that variable, set it, and then when the program runs it needs to fetch the value of that location in memory rather than using a hard coded value.


问:
when should a database table be broken into multiple tables with relations?
I have an application that needs to store client data, and part of that is some data about their employer as well. Assuming that a client can only have one employer, and that the chance of people having identical employer data is slim to none, which schema would make more sense to use?

Schema 1

```<code>Client Table:
-------------------
id int
name  varchar(255),
email varchar(255),
address varchar(255),
city varchar(255),
state char(2),
zip varchar(16),
employer_name varchar(255),
employer_phone varchar(255),
employer_address varchar(255),
employer_city varchar(255),
employer_state char(2),
employer_zip varchar(16)
</code>```

```<code>**Schema 2**

   Client Table
   ------------------
id int
name  varchar(255),
email varchar(255),
address varchar(255),
city varchar(255),
state char(2),
zip varchar(16),

Employer Table
---------------------
id int
name varchar(255),
phone varchar(255),
address varchar(255),
city varchar(255),
state char(2),
zip varchar(16)
patient_id int
</code>```

Part of me thinks that since are clearly two different 'objects' in the real world, seperating them out into two different tables makes sense. However, since a client will always have an employer, I'm also not seeing any real benefits to seperating them out, and it would make querying data about clients more complex. Is there any benefit / reason for creating two tables in a situation like this one instead of one?

答:
Option 2 is the correct approach. You have your Foreign key backwards though the client table should have an EmployerID field since you said that a client will have only one employer and many clients may have the same employer. This is a database normalization issue, and the goal of database normalization is to reduce insert, update and delete anomalies that can happen, and can be very costly, if tables are not properly normalized. Normalization can slow down select statements though on large tables, in most cases the difference between normalized tables and non normalized tables will be so small its unnoticeable.

it is possible to mitigate the hit to select queries by creating views, but this may not be possible depending on frequency of updates. The general rule of thumb for database design is to normalize as much as possible, and then denormalize as performance dictates.


答:
Number 2 would be recommended by most people, myself included.  Not so much because they are different 'things', but because you are modeling a relationship between the two.

While the first option would also work, it would only work for those cases when a client has one and only one employer, and each client has a different employer.

It would not work in cases where a client has more than one employer.  And if more than one client has the same employer, you'd have the employer listed twice (or more) in the database.  That would lead to repetitive data, and complexities when trying to update their details.  Better to break them into two tables.

Another approach you might also take is to have 3 tables - one for the distinct list of individual clients, one for the distinct list of employers, and then another that connects clients and employers.  That would allow you to model cases where clients have more than one employer, the same employer has more than one client, and cases when a client has no employer.

Title: when should a database table be broken into multiple tables with relations?

Body:
I have an application that needs to store client data, and part of that is some data about their employer as well. Assuming that a client can only have one employer, and that the chance of people having identical employer data is slim to none, which schema would make more sense to use?

Schema 1

```<code>Client Table:
-------------------
id int
name  varchar(255),
email varchar(255),
address varchar(255),
city varchar(255),
state char(2),
zip varchar(16),
employer_name varchar(255),
employer_phone varchar(255),
employer_address varchar(255),
employer_city varchar(255),
employer_state char(2),
employer_zip varchar(16)
</code>```

```<code>**Schema 2**

   Client Table
   ------------------
id int
name  varchar(255),
email varchar(255),
address varchar(255),
city varchar(255),
state char(2),
zip varchar(16),

Employer Table
---------------------
id int
name varchar(255),
phone varchar(255),
address varchar(255),
city varchar(255),
state char(2),
zip varchar(16)
patient_id int
</code>```

Part of me thinks that since are clearly two different 'objects' in the real world, seperating them out into two different tables makes sense. However, since a client will always have an employer, I'm also not seeing any real benefits to seperating them out, and it would make querying data about clients more complex. Is there any benefit / reason for creating two tables in a situation like this one instead of one?


答:
I'd guess that you're thinking of variables the way we think of them in an algebraic expression, i.e. as something with unknown value that depends on the other constraints in the equation:

```<code>x + y = 3
</code>```

In an equation like that, the values of x and y depend on each other. If you know what y is, you can deduce the value of x. They're called variables here because there are many pairs {x, y} that satisfy the equation.

Variables in programming are fundamentally different. In programming, a variable still represents some value, but the value can change over the course of the program. Think of it as a box that can hold a value -- you can always change what's in the box. Some languages might allow an equation like the algebraic one above, but in most languages you don't get to create open-ended constraints like that (at least not without more work). Instead, you'd say something like:

```<code>y = 5;       // assign 5 to y
x = 3 - y;   // y is 5 from the line above, so x becomes -2
x = x - 1;   // it's okay to assign an expression containing a variable
             // to that same variable, so x now becomes (-2 - 1), or -3
</code>```

Constants, on the other hand, are just that -- constant values. They're names for values, and those values can't change. We use them mainly to make code easier to understand:

```<code>secondsPerDay = hoursPerDay * minutesPerHour * secondsPerMinute;
</code>```

is easier to understand than:

```<code>secondsPerDay = 24 * 60 * 60;
</code>```

Body:
I'd guess that you're thinking of variables the way we think of them in an algebraic expression, i.e. as something with unknown value that depends on the other constraints in the equation:

x + y = 3

In an equation like that, the values of x and y depend on each other. If you know what y is, you can deduce the value of x. They're called variables here because there are many pairs {x, y} that satisfy the equation.

Variables in programming are fundamentally different. In programming, a variable still represents some value, but the value can change over the course of the program. Think of it as a box that can hold a value -- you can always change what's in the box. Some languages might allow an equation like the algebraic one above, but in most languages you don't get to create open-ended constraints like that (at least not without more work). Instead, you'd say something like:

y = 5;       // assign 5 to y
x = 3 - y;   // y is 5 from the line above, so x becomes -2
x = x - 1;   // it's okay to assign an expression containing a variable
             // to that same variable, so x now becomes (-2 - 1), or -3

Constants, on the other hand, are just that -- constant values. They're names for values, and those values can't change. We use them mainly to make code easier to understand:

secondsPerDay = hoursPerDay * minutesPerHour * secondsPerMinute;

is easier to understand than:

secondsPerDay = 24 * 60 * 60;


答:
One should always strive in one's designs not to make unwarranted assumptions that may come back to bite one in one's backside.

In this day and age, in the United States at least, the 1-employer-per-employee assumption is VERY unwarranted.  They may very well have ZERO employers, they may well have up to three employers.

With that in mind, schema 2 is far better, as it does not QUITE lock you into a 1-1 assumption.


问:
Motivation and use of move constructors in C++
I recently have been reading about move constructors in C++ (see e.g. here) and I am trying to understand how they work and when
I should use them.

As far as I understand, a move constructor is used to alleviate the performance problems caused by copying large objects. The wikipedia page says: "A chronic performance problem with C++03 is the costly and unnecessary deep copies that can happen implicitly when objects are passed by value."

I normally address such situations

by passing the objects by reference, or

by using smart pointers (e.g. boost::shared_ptr) to pass around the object (the smart pointers get copied instead of the object).

What are the situations in which the above two techniques are not sufficient
and using a move constructor is more convenient?

答: Return values are where I'd most often like to pass by value instead of some kind of reference. Being able to quickly return an object 'on the stack' without a massive performance penalty would be nice. On the other hand, it's not particularly difficult to get around this (shared pointers are just so easy to use...), so I'm not sure it's really worth doing extra work on my objects just to be able to do this.</p>


答:
Consider:

```<code>vector<string> v;
</code>```

When adding strings to v, it will expand as needed, and on each reallocation the strings will have to be copied. With move constructors, this is basically a non-issue.

Of course, you could also do something like:

```<code>vector<unique_ptr<string>> v;
</code>```

But that will work well only because std::unique_ptr implements move constructor.

Using std::shared_ptr makes sense only in (rare) situations when you actually have shared ownership.

Title: Motivation and use of move constructors in C++

Body:
I recently have been reading about move constructors in C++ (see e.g. here) and I am trying to understand how they work and when
I should use them.

As far as I understand, a move constructor is used to alleviate the performance problems caused by copying large objects. The wikipedia page says: "A chronic performance problem with C++03 is the costly and unnecessary deep copies that can happen implicitly when objects are passed by value."

I normally address such situations

by passing the objects by reference, or

by using smart pointers (e.g. boost::shared_ptr) to pass around the object (the smart pointers get copied instead of the object).

What are the situations in which the above two techniques are not sufficient
and using a move constructor is more convenient?

Body:
Consider:

vector<string> v;

When adding strings to v, it will expand as needed, and on each reallocation the strings will have to be copied. With move constructors, this is basically a non-issue.

Of course, you could also do something like:

vector<unique_ptr<string>> v;

But that will work well only because std::unique_ptr implements move constructor.

Using std::shared_ptr makes sense only in (rare) situations when you actually have shared ownership.

ContentLicense: CC BY-SA 4.0


答:
Move semantics introduce a whole dimension to C++ - it isn't just there to let you return values cheaply.

For example, without move-semantics std::unique_ptr doesn't work - look at std::auto_ptr, which was deprecated with the introduction of move-semantics and removed in C++17. Moving a resource is vastly different from copying it. It allows transfer of ownership of a unique item.

For example, let's not look at std::unique_ptr, since it is fairly well discussed. Let's look at, say, a Vertex Buffer Object in OpenGL. A vertex buffer represents memory on the GPU - it needs to be allocated and deallocated using special functions, possibly having tight constraints on how long it can live. It is also important that only one owner use it.

```<code>class vertex_buffer_object
{
    vertex_buffer_object(size_t size)
    {
        this->vbo_handle = create_buffer(..., size);
    }

    ~vertex_buffer_object()
    {
        release_buffer(vbo_handle);
    }
};

void create_and_use()
{
    vertex_buffer_object vbo = vertex_buffer_object(SIZE);

    do_init(vbo); //send reference, do not transfer ownership

    renderer.add(std::move(vbo)); //transfer ownership to renderer
}
</code>```

Now, this could be done with a std::shared_ptr - but this resource is not to be shared. This makes it confusing to use a shared pointer. You could use std::unique_ptr, but that still requires move semantics.

Obviously, I haven't implemented a move constructor, but you get the idea.

The relevant thing here is that some resources aren't copyable. You can pass around pointers instead of moving, but unless you use unique_ptr, there is the issue of ownership. It is worthwhile to be as clear as possible as to what the intent of the code is, so a move-constructor is probably the best approach.

Body:
Move semantics introduce a whole dimension to C++ - it isn't just there to let you return values cheaply.

For example, without move-semantics std::unique_ptr doesn't work - look at std::auto_ptr, which was deprecated with the introduction of move-semantics and removed in C++17. Moving a resource is vastly different from copying it. It allows transfer of ownership of a unique item.

For example, let's not look at std::unique_ptr, since it is fairly well discussed. Let's look at, say, a Vertex Buffer Object in OpenGL. A vertex buffer represents memory on the GPU - it needs to be allocated and deallocated using special functions, possibly having tight constraints on how long it can live. It is also important that only one owner use it.

class vertex_buffer_object
{
    vertex_buffer_object(size_t size)
    {
        this->vbo_handle = create_buffer(..., size);
    }

    ~vertex_buffer_object()
    {
        release_buffer(vbo_handle);
    }
};

void create_and_use()
{
    vertex_buffer_object vbo = vertex_buffer_object(SIZE);

    do_init(vbo); //send reference, do not transfer ownership

    renderer.add(std::move(vbo)); //transfer ownership to renderer
}

Now, this could be done with a std::shared_ptr - but this resource is not to be shared. This makes it confusing to use a shared pointer. You could use std::unique_ptr, but that still requires move semantics.

Obviously, I haven't implemented a move constructor, but you get the idea.

The relevant thing here is that some resources aren't copyable. You can pass around pointers instead of moving, but unless you use unique_ptr, there is the issue of ownership. It is worthwhile to be as clear as possible as to what the intent of the code is, so a move-constructor is probably the best approach.


答:
Why would you be making this decision? Either the client wants/needs the ability to:

Assign multiple employers to each client.

Have consistent data on an employer (i.e. change phone number in one place for all employees)

Track employment over time (similar to multiple employers, but must concept of "current employer").

What if they have a need to expand on the data for employers? At some point it would be better off in its own table

or they don't. How important is address information? What type of reporting/aggregating do they expect?

If you think this is complicated, wait until you findout this really requires a third table to create a many-to-many relationship.


问:
Efficient Bus Loading
This is something I did for a bus travel company a long time ago, and I was never happy with the results. I was thinking about that old project recently and thought I'd revisit that problem.

Problem:

Bus travel company has several buses with different passenger capacities (e.g. 15 50-passenger buses, 25 30-passenger buses ... etc). They specialized in offering transportation to very large groups (300+ passengers per group). Since each group needs to travel together they needed to manage their fleet efficiently to reduce waste.

For instance, 88 passengers are better served by three 30-passenger buses (2 empty seats) than by two 50-passenger buses (12 empty seats). Another example, 75 passengers would be better served by one 50-passenger bus and one 30-passenger bus, a mix of types.

What's a good algorithm to do this?

答:
Here's a quick-and-dirty solution in Python:

```<code>def add50(passengers, buses):
    proposed = buses + [50]
    if sum(proposed) < passengers:
        return add50(passengers, proposed)
    return proposed

def add30(passengers, buses):
    proposed = buses + [30]
    if sum(proposed) < passengers:
        proposed30 = add30(passengers, proposed)
        proposed50 = add50(passengers, proposed)
        return proposed30 if sum(proposed30) < sum(proposed50) else proposed50
    return proposed

print add30(88, [])
print add30(75, [])
print add30(105, [])
</code>```

When I run it, I get:

```<code>[30, 30, 30]
[30, 50]
[30, 30, 50]
</code>```

The code is doing a depth-first search through the possible scenarios. Since order doesn't matter ([30, 50] is the same as [50, 30]), we can make the search space a lot smaller by only adding buses of the same size or larger. That's why add30() can call add50(), but not the other way around.

Title: Efficient Bus Loading

Body:
Here's a quick-and-dirty solution in Python:

def add50(passengers, buses):
    proposed = buses + [50]
    if sum(proposed) < passengers:
        return add50(passengers, proposed)
    return proposed

def add30(passengers, buses):
    proposed = buses + [30]
    if sum(proposed) < passengers:
        proposed30 = add30(passengers, proposed)
        proposed50 = add50(passengers, proposed)
        return proposed30 if sum(proposed30) < sum(proposed50) else proposed50
    return proposed

print add30(88, [])
print add30(75, [])
print add30(105, [])

When I run it, I get:

[30, 30, 30]
[30, 50]
[30, 30, 50]

The code is doing a depth-first search through the possible scenarios. Since order doesn't matter ([30, 50] is the same as [50, 30]), we can make the search space a lot smaller by only adding buses of the same size or larger. That's why add30() can call add50(), but not the other way around.


问:
What happens if we serialize and deserialize two objects which references to each other?
To make it more clear, this is a quick example:

```<code>class A implements Serializable { public B b; }
class B implements Serializable { public A a; }
A a = new A();
B b = new B();
a.b = b;
b.a = a;
</code>```

So what happens if we serialize a and b objects into a file and deserialize from that file?

I thought we get 4 objects, 2 of each. Identical objects but different instances.

But I'm not sure if there's anything else or is it right or wrong.

If any technology needed to answer, please think based on Java.

Thank you.

答:
Java keeps track of the objects that have been written to the stream, and subsequent instances are written as an ID, not an actual serialized object.

So, for your example, if you write instance "a" to the stream, the stream gives that object a unique ID (let's say "1"). As part of the serialization of "a", you have to serialize "b", and the stream gives it another id ("2"). If you then write "b" to the stream, the only thing that is written is the ID, not the actual object.

The input stream does the same thing in reverse: for each object that it reads from the stream, it assigns an ID number using the same algorithm as the output stream, and that ID number references the object instance in a map. When it sees an object that was serialized using an ID, it retrieves the original instance from the map.

This is how the API docs describe it:

Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written

This behavior can cause problems: because the stream holds a hard reference to each object (so that it knows when to substitute the ID), you can run out of memory if you write a lot of transient objects to the stream. You solve that by calling reset().


答:
In Java this is solved by caching the serialized objects and writing the handle of it when it is written again.

See step 5 in http://docs.oracle.com/javase/6/docs/platform/serialization/spec/output.html.

Title: What happens if we serialize and deserialize two objects which references to each other?

Body:
To make it more clear, this is a quick example:

```<code>class A implements Serializable { public B b; }
class B implements Serializable { public A a; }
A a = new A();
B b = new B();
a.b = b;
b.a = a;
</code>```

So what happens if we serialize a and b objects into a file and deserialize from that file?

I thought we get 4 objects, 2 of each. Identical objects but different instances.

But I'm not sure if there's anything else or is it right or wrong.

If any technology needed to answer, please think based on Java.

Thank you.