问:
Refactoring an existing MVC codebase to remove business logic & data access from the Controllers
Product I've inherited has the following composition:

MVC web site where the controllers make calls to Repositories to get, insert and update objects retrieved that are

defined in the:

Data access layer written using Linq2SQL

This means that currently the controller for the action /Account/Add will perform the following pseudo-code:

Get the current user

new() an AccountItem object

Set the UserId, AccountItemTypeId and Value fields on the AccountItem

Get an instance of Repository

Call the repositorys InsertOnSubmit(AccountItem item) method

Call the repositorys SubmitChanges() method

new() an EmailQueue item

Set the appropriate properties on the EmailQueue item (to, subject, body, etc,..) based on the inserted account item

Get an instance of Repository

Call the repositorys InsertOnSubmit(EmailQueue item) method

Call the repositorys SubmitChanges() method

I've already made a first pass through the codebase and injected, using Castle Windsor, the repository's in (actually injecting an instance of a type that implements IRepositoryResolver which has a method called GetRepository<T> so that I can decouple the controllers from the Linq2SQL dependent repositories. I've also started to write unit tests, based on the current behaviour of the controllers (to ensure that when I make further changes I can identify when I get it horribly wrong) but that's tangenital to my actual question.

I've identified lots of places where the controller actions are performing identical actions against various repositories, such as getting a given users total Value for all AccountItem's and am now considering extracting all this common logic into a business/service layer. My question is, would the following structure be considered "best practice":

AccountService: Provides an AddAccountItem method (plus others such as GetAccountValue)

EmailService: Provides an AddEmailToQueue method

Should I be refactoring the controller so it does:

```<code>accountServiceInstance.AddAccountItem(userToCredit, userCrediting, AccountItemType.Bonus, 300);
emailServiceInstance.AddEmailToQueue(userToEmail, EmailType.AccountCreditBonus);
</code>```

Or, should my AccountService take an EmailService as a dependency (that's satisfied by Castle Windsor) and it's the responsibility of the AccountService to call EmailService.AddEmailToQueue?

答:
If the business rule is that AddAccountItem must AddEmailToQueue every time it is successful then I would use the dependency.  Otherwise you will have to make sure you wire it up every time.

I feel that email rules are business logic not presentation logic and would keep it out of the controller.


问:
Why should identifiers not begin with a number?
Most programming languages appear to be designed to not allow one to declare an identifier that starts with a number. I was just curious to know the reason. I have already searched the web, but couldn't find a satisfactory explanation.</p>

答:
In addition to "convenience for the lexer", I think it is also worth considering "convenience for the reader".

When reading code, you need to quickly and repeatedly identify which words are identifiers, and which are numbers.   Looking for a digit at the beginning is easier on our visual pattern-matching; it would be a chore if we had to carefully check all the characters to make sure.

ContentLicense: CC BY-SA 3.0


问:
Real world implementation of functional programming?
I am trying to acquaint myself with different types of languages to understand the areas in which each one of them is extremely good at. So far, I have dabbled into C - a procedural language, C++ & java - static typed Object Oriented languages and groovy - a dynamic typed Object Oriented language.

Every programming language has probably been started to answer a need. And I presume every language is extremely good at at least one thing because of which it becomes a standard in a specific area or field. Like C, C++ have become standard in areas like browser or game development. Python in the Linux world for its easy scripting ability, Java in the enterprise world, etc.

Now I am interested to learn a functional programming language like Clojure or Lisp. So, where are functional programming languages used in real world scenarios? I don't think that one would use Clojure or Lisp for developing applications or UIs. So on what kind of projects should I indulge into after going through the basic tutorials and learning resources to get a brief understanding about the implementation of functional programming? And do you strongly recommend on One language in specific, like say clojure?

答:
Bryan O'Sullivan, founder of mailrank.com (which was acquired by Facebook) built the entire server side of this software in Haskell. He presented on this at Strange Loop 2011, video and slides are available online.

The same guy wrote a book called Real World Haskell. Several people mentioned programming tutorials. This one may be quite appropriate to your interests (I like the Erlang suggestion as well).


问:
Programming with a group of people I've never met
I've been assigned a group project from my AP computer science class, and I am required to work with three other people. I've never talked to them before, I have no idea their skill level, and all I have is their email address. The assignment, summed up, is this:

"As a team you will complete a minimum of three Modules to a Class...."

I going to try and become "Team captain" because none of them have attempted to contact each other but I am curious: how to go about this? I've emailed them and asked them if there are any methods of communication they prefer over emailing each other, but once we actually start the project I'll have to figure out who is doing what.

What should I do? How do I "take charge" and lead three people that I've never met?

Here is an excerpt of the actual assignment:

Therefore you will need to discuss the various roles each team member
  will take in this project early in the week.  You can communicate via
  Pronto (or Blackboard IM), email, a wiki, a google group, blog or any
  other method that you see fit. If a group member does not engage the
  group by the end of week let your instructor know and they will
  provide additional guidance.

  ...

  Also due at the end of a project will be a team evaluation in which you will rate each team members contribution to the completion of this project along with a suggested grade.

Edit: Many people suggested that I meet them in a coffee shop, or something like that. Only problem is, all of us are in different states. I also figured out one of them isn't allowed to use Facebook/Skype/twitter, so I have to resort to messaging them over yahoo messenger and emails.

答:
You haven't told us how much time you have for this, or the language you're working in (I would say a single class is very small, but perhaps in your language it's a good deal more).

First of all, have a working product at any cost.

If the project lasts two weeks or less, assume you will be the only one doing anything and be very happy about any help you get.  Try to schedule things for everyone, but make sure that if nobody does anything, you'll still have a working product.  Even if someone does something, don't rely on them continuing: be prepared for anyone to drop out at any point.

If you have more than one week, consider scheduling a day of the week when the product should be marked as a milestone and stick to that as much as possible.  Make sure you have something you can kick around and check the deficiencies of: if worst comes to worst, this will be what you hand in.  Each one you create, you will see how much you could improve things, which will motivate you to go on.  Don't plan too far forwards: sure, you need to have an idea of what you'll end up with, but keep your most specific plans short-term.

Notice that those two overlap a little: this is intentional, as two weeks is in my opinion a bit of a grey area where getting two iterations done is hard, but only working in one iteration is risky.

I'm assuming the worst case, where you'll be working with people very new to programming.  My general advice would be:

Keep a list of features you want to implement soon, and who will work on them.  Jarrod suggested Trello, and I entirely support that: if your teammates aren't very experienced, it'll help a lot.  You could try keeping the bugs there, too.

In a team of four, you need version control.  It may make others more reluctant to contribute if they don't know how to work it, but it's worth it.

Any external dependencies may scare away newbies.  If you write unit tests, tell people that they shouldn't worry about breaking them.  Tell people that they shouldn't worry about breaking the build, especially at first.  It's much harder to correct people who don't commit any code than those who commit buggy code.

Check whether things suggested here really apply to you.  "Continuous integration" is a fancy term -- for a small program, that might mean "this program runs and all features can be used".  Do you even have sites?  Does splitting into teams help you?

YAGNI, a hundred times over.  If you really have to, write things in advance for features you'll be making yourself.  Make it work, then refactor, or you won't get around to making it work.

Refactor.  Once it's working, spend some time fixing it.  Don't forget your teammates will have to read your code, too: a day spent fixing ugly pieces and replacing simple solutions with better-performing ones is not a day wasted.

Keep an eye on all parts.  Skimming changelogs and occasionally reading others' code helps make sure that everything is up to the quality standards you feel you should enforce and makes sure it isn't as hard to dive in if the person drops out.

Don't hesitate to work on the most important thing, as opposed to your designated thing.  If someone is falling behind schedule, make a written note of that somewhere and do it yourself.  Ask them first, but go ahead if they don't answer, or if you ask once or twice and then feel like they still won't do it.

Focus on making something you're proud of.  Even if it deviates from the assignment.  Even if you have to cut big features in favour of making what you have more smooth.  Every iteration think "Am I proud of this?", and in the next iteration, try to fix those things.

I had a project that failed horribly recently; you can read my thoughts on why it failed if you want to, but this summarises how I'd do something like this if I had another chance to.


答: I know from friends in finance that the quantitative trading firm Jane Street uses OCaml to implement its trading strategies. They have a page where they talk about why, along with links to talks on the subject. </p>

Title: Real world implementation of functional programming?

Body:
I am trying to acquaint myself with different types of languages to understand the areas in which each one of them is extremely good at. So far, I have dabbled into C - a procedural language, C++ & java - static typed Object Oriented languages and groovy - a dynamic typed Object Oriented language.

Every programming language has probably been started to answer a need. And I presume every language is extremely good at at least one thing because of which it becomes a standard in a specific area or field. Like C, C++ have become standard in areas like browser or game development. Python in the Linux world for its easy scripting ability, Java in the enterprise world, etc.

Now I am interested to learn a functional programming language like Clojure or Lisp. So, where are functional programming languages used in real world scenarios? I don't think that one would use Clojure or Lisp for developing applications or UIs. So on what kind of projects should I indulge into after going through the basic tutorials and learning resources to get a brief understanding about the implementation of functional programming? And do you strongly recommend on One language in specific, like say clojure?


答: I'd suggest diving into the compilers (for either general purpose languages or DSLs) - this is where functional programming is in its best. There will be many interesting and useful things to explore, from ADTs and pattern matching on one side of a spectrum to the Lisp macros on the other side.</p>


问:
Should I store False as Null in a boolean database field?
Let's say you have an application that has a boolean field in its User table called Inactive.

Is there anything inherently wrong with just storing false as null? If so can you please explain what the down side should be? I have discussed this with someone a few months ago and we both agreed it shouldn't matter as long as you do it consistently throughout the app/database. Recently, someone I know was emphatic that "true" true or false should be used, but they didn't really give an explanation as to why.

答:
Is there anything inherently wrong with just storing false as null?

Yes.

If so can you please explain what the down side should be?

NULL is not the same as False.

By definition, comparisons (and logic) that involve NULL should return values of NULL (not False).  However, SQL implementations can vary.

True and NULL is NULL (not False).

True and NULL or False is NULL (not False).

http://en.wikipedia.org/wiki/Null_(SQL)#Three-valued_logic_.283VL.29

http://technet.microsoft.com/en-us/library/cc966426.aspx


问:
Is "Code Smell" still a useful metaphor, or has misuse of the term subverted its meaning?
I've come across some
comments
and
answers
on Programmers.SE that decry the use of the phrase "Code Smell" and I've been wondering what the reasoning is for those who dislike it.  I first encountered this term when I read Fowler's
Refactoring
back in 2000, yet it's only in the last year or two that I've heard any
complaint
about
the use of the phrase.

Q: Would it be correct to say that the phrase Code Smell has recently started to fall into disfavor, and if so why does/should this metaphor no longer apply?

I am looking for well defined answers supported by sound reasoning as I realize that this question is borderline subjective.

答:
Code Smell is a great metaphor in my mind.  In this context, "smell" means "stink".  Stink tends to indicate that something is rotten; something is not good; something will make you sick.  Stink refers to something that is inherently unpleasant.

When I say that there is "code smell", I believe that I am unambgiguously indicating that something seems very wrong with the code I am referring to.  However, as in the case of "stink", it may not be immediately apparent what it is.


问:
Implementing oAuth 2 server
Do you have any pointers on how one should go about implementing the oAuth2 protocol itself? That is, the server side or the "provider" facet of OAuth2?

If you have tried to implement (a part of) it, please share the issues and the solutions. Note that this is completely technology and programming language agnostic - except, of course, for the de-facto standard cryptological technologies that might be involved. The IETF draft (v23) for oAuth2 is located here

答:
While I have not yet implemented it I do intend to and have read through both the OAuth 1 RFC and OAuth 2 draft several times. Unlike OAuth 1 RFC the OAuth 2 draft goes into quite a lot of detail as to how to implement the server and you will find all the details you need in the draft.

What you will need to first figure out is your target group of clients since that will help you decide which methods of authorization you need to support.

Web apps? Check out https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-23#section-4.1

JS apps? https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-23#section-4.2

Desktop apps? https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-23#section-4.3 (if the user will trust your app with their credentials)

The protocol basically boils down to generating tokens using adequate crypto functions and encoding and sending parameters properly. For an example of how the communication might look like go to the Google OAuth 2 Playground.

For example, the draft clearly states that when a client requests authorization as per 4.1 (Authorization Code Grant) it supplies the mandatory fields response_type and client_id together with the two optional fields redirect_uri and scope, as well as the recommended state field. In your server implementation you thus extract and validate those parameters (you may define additional required parameters), authorize the user and if all is well redirect to the client specified redirect uri (including an authorization grant).

How you authenticate clients can vary but the spec suggests that using HTTP Authentication would work fine for web apps (but not apps where hiding the client credentials is difficult).

It is very important that all communication is over a secure channel (TLS/SSL). OAuth is not a substitute for TLS/SSL.

Good luck!

Title: Implementing oAuth 2 server


问:
Architecting Challenge: How would you write an opensource script installer to run in a browser?
I currently have an installer that works, but I have to repackage the open source apps and hack things together to get the installer to install them. I want to be able to use the apps installation method without having to hack and repackage. So I am thinking about rewriting it.

It will allow a user with little to no tech experience install open source apps (ie. WordPress, Joomla, Drupal, et.al.). There are a few requirements I want to meet:

The installation should run the scripts install process to make sure
the database is setup correctly and the passwords use the apps
default password encryption processes.

Ability to track the progress and report back any errors.

Ability to run upgrades for future releases.

Ability to remove the application if someone decides they do not want
it any longer.

The only access I will for sure have to the users remote server is
via FTP.

I have thought about using Selenium. However, if you were challenged to hand spin the code in PHP, how would you do it?

UPDATE FOR CLARIFICATION:

The installer will collect the scripts settings from a form in the browser filled out by the end user. The installation process (that runs in the background and connects over FTP to the users server) will then process the installation. (i.e. SimpleScripts, Installatron, Softaculous, Fantastico, WebPub, etc.) I am trying to figure out how you would design the cleanest simplest install process possible. It needs to create databases, install the application using the scripts install method (as if the user was running it manually), etc. I hope that clarifies the challenge.

答:
You're probably thinking about something similar to Installatron. They offer a free and easy way to remotely install the most popular web applications. You just need to fill out the form with DB, FTP and application settings, select the version of the application you want and click install.

NOTE: I'm not affiliated with Installatron in any way. My only association with them is that my hosting provider uses their plugin.

UPDATE:

PHP is a good choice for dynamically building scripts. As GrandmasterB already suggested you can't execute scripts via FTP so the easiest solution is to make an installation script, upload it to the target server and execute.

You're probably want to support a lot of different applications so I would make a system very configurable. Basically every action that needs to be executed to install an application should be written in a configuration. The configuration can be stored as a file or in a database (RDBMS or even NoSQL). That way you can make adjustments to the installation procedure easily without changing the code. This will also allow you to easily support multiple operating systems and allow others to write install procedures for their application.

You can encounter a lot of problems when installing the application on server - e.g. you don't have the sufficient permissions to write/execute or the application you're installing requires a higher version of PHP / MySQL / some library etc.

In case of a failure application should be able to rollback all the changes that are made so the target system remains in the same state before the installation began.

You're targeting users that have minimal or no tech skills so I would make the UI as simpler as I can. But no matter how simple the interface you can't hide some technical details from them i.e. they will need to know their FTP and database credentials. For some users that will also be a problem but the only thing you can do about that is to write some sort of help or wizard that will guide them through the process.


问:
Syntactic sugar regarding function parameters
Are there any modern programming languages where you don't have to specify types for each parameter in a function's definition?

Ex:

```<code>procedure P(a, b, c, d: integer)
</code>```

vs

```<code>void P(int a, int b, int c, int d)
</code>```

Is there a good reason why the latter form is so popular?  Why don't more languages allow you to specify the type of all your parameters at once, like the first form?

答:
Your first example is Pascal code, so unless you don't consider Delphi a modern programming language, that should answer the first part of your question.

As to the second part, I think the second form is preferable, because

you immediately see a parameter's type right next to it, instead of having to scan the parameter list for the next occurence of a type,

changing the type of parameter b in the second form means replacing one word, while in the first you will have to rewrite the defintion by adding types for both a and b.

Remember, that while you write code once, it is read and modified a lot more often. It's therefore more important that code be easy to read and maintain than to write.


问:
When do you know it's time to move on from your current job?
Have you ever reached a point at your job when you just know it's time to move on?

When do you move to the point that you're willing to let go of the demons you know for the ones you don't know?

What was your deciding factor final straw so to speak when you finally faced the decision to find a new job?

答: The final straw was when I was at the hospital with my newborn baby, who was born early and needed to be on oxygen. I was using my own vacation days to be there, I did not get time off for this sort of thing. Then I was getting called and pressured to return back to work early before using up all my vacation days while my child was still in hospital. That was the last of many straws.</p>

ContentLicense: CC BY-SA 2.5


答:
Style-related explanation

While the first form is shorter, it would probably be depreciated by style checkers. It's also more straightforward¹. For example:

```<code>IEnumerable<TResult> LoadEverything<T1, TResult>(
    IEnumerable<T1> baseSet, bool includeChecked, bool useDefaults = false,
    TResult defaultValue = null)
{
}
</code>```

is hard to understand, but still easier than:

```<code>IEnumerable<TResult> LoadEverything<T1, TResult>(
    IEnumerable<T1> baseSet, includeChecked, useDefaults = false: bool,
    TResult defaultValue = null)
{
    // Does bool apply to includeChecked and useDefaults? Or maybe to baseSet too?...
}
</code>```

So you gain a few seconds typing less with your approach in easy cases, but you're sure that such syntactic sugar will cost a lot in terms of time spend reading and understanding code when abused.

Parsing issues

Parsing such source code is more difficult too.

Refactoring issues

Also, changing and refactoring code may be also difficult. Taking the example above, let's ask the IDE to change the order of the parameters, by reverting baseSet and includeChecked. If the IDE is smart enough, it will do it correctly. If it's not, it will produce code which cannot be compiled. The same mistake can be done if you do the refactoring manually.

```<code>IEnumerable<TResult> LoadEverything<T1, TResult>(
    includeChecked, IEnumerable<T1> baseSet, useDefaults = false: bool,
    TResult defaultValue = null)
{
    // What's wrong? Why can't this piece of code compile?
}
</code>```

Typeless parameters case

Finally, if your language accepts typeless parameters, it becomes impossible to implement. The code:

```<code>array<TResult> LoadEverything<T1, TResult>(
    baseSet, bool includeChecked, bool useDefaults = false,
    TResult defaultValue = null)
{
    var set = cast(baseSet to array<T1>);
    // [...]
}
</code>```

will still work, while:

```<code>array<TResult> LoadEverything<T1, TResult>(
    baseSet, includeChecked, useDefaults = false: bool,
    TResult defaultValue = null)
{
    var set = cast(baseSet to array<T1>);
    // [...]
}
</code>```

makes no sense: if baseSet is a boolean, how can it be converted to an array?

¹ By the way, you have a similar case when declaring variables of same types. A shorter form is: int a = 3, b = 5, c = 1;, but in most cases, you would see three lines, one declaration per line, every declaration having its own type.

Title: Syntactic sugar regarding function parameters

Body:
Are there any modern programming languages where you don't have to specify types for each parameter in a function's definition?

Ex:

```<code>procedure P(a, b, c, d: integer)
</code>```

vs

```<code>void P(int a, int b, int c, int d)
</code>```

Is there a good reason why the latter form is so popular?  Why don't more languages allow you to specify the type of all your parameters at once, like the first form?

Body:
Style-related explanation

While the first form is shorter, it would probably be depreciated by style checkers. It's also more straightforward¹. For example:

IEnumerable<TResult> LoadEverything<T1, TResult>(
    IEnumerable<T1> baseSet, bool includeChecked, bool useDefaults = false,
    TResult defaultValue = null)
{
}

is hard to understand, but still easier than:

IEnumerable<TResult> LoadEverything<T1, TResult>(
    IEnumerable<T1> baseSet, includeChecked, useDefaults = false: bool,
    TResult defaultValue = null)
{
    // Does bool apply to includeChecked and useDefaults? Or maybe to baseSet too?...
}

So you gain a few seconds typing less with your approach in easy cases, but you're sure that such syntactic sugar will cost a lot in terms of time spend reading and understanding code when abused.

Parsing issues

Parsing such source code is more difficult too.

Refactoring issues

Also, changing and refactoring code may be also difficult. Taking the example above, let's ask the IDE to change the order of the parameters, by reverting baseSet and includeChecked. If the IDE is smart enough, it will do it correctly. If it's not, it will produce code which cannot be compiled. The same mistake can be done if you do the refactoring manually.

IEnumerable<TResult> LoadEverything<T1, TResult>(
    includeChecked, IEnumerable<T1> baseSet, useDefaults = false: bool,
    TResult defaultValue = null)
{
    // What's wrong? Why can't this piece of code compile?
}

Typeless parameters case

Finally, if your language accepts typeless parameters, it becomes impossible to implement. The code:

array<TResult> LoadEverything<T1, TResult>(
    baseSet, bool includeChecked, bool useDefaults = false,
    TResult defaultValue = null)
{
    var set = cast(baseSet to array<T1>);
    // [...]
}

will still work, while:

array<TResult> LoadEverything<T1, TResult>(
    baseSet, includeChecked, useDefaults = false: bool,
    TResult defaultValue = null)
{
    var set = cast(baseSet to array<T1>);
    // [...]
}

makes no sense: if baseSet is a boolean, how can it be converted to an array?

¹ By the way, you have a similar case when declaring variables of same types. A shorter form is: int a = 3, b = 5, c = 1;, but in most cases, you would see three lines, one declaration per line, every declaration having its own type.


问:
Pro's/Con's to database table layout as it relates to maintenance & extensibility
Basic pseudo class layout below...

```<code>class Location(): # Class containing information about a location.
    id
    address_one

class CustomerLocation(Location):
    customer_id
    account_rep

class VendorLocation(Location):
   vendor_id
   drop_ship_cut_off_time
</code>```

Let's say you have locations which are going to be used to store location info for customers and vendors.

What would be the pro's/cons of the three options in how they relate to application maintenance and extensibility...

One large table containing all fields.

One large table containing all common fields with related tables containing specialized information about the large table records.

Many small tables containing all fields related to specific uses.CustomerLocation table VendorLocation without using a "master table" for common fields.

答:
Good database design implies that you normalize your database adequately. You could generalize the location, assuming that you want to record several locations for a customer or vendor, you could do this:

Customer (0,1,more) Location

Vendor (0,1,more) Location

Location

I don't see why you have 2 separate classes CustomerLocation, VendorLocation.

You could go further in generalizing Vendor and Customer as Party with Vendor and Customer inheriting from the abstract type Party.

The above is valid unless:

A customer may be a vendor or vice verse and/or

The same location is the address for more than one vendor or customer

Edit

You can't use party with inheriance as I suggested above (before your comment) since your comment implies that customers can be vendors and vendors can be customer. So, in fact you only have a party with non-mutually execlusive party type that can be represented by 2 boolean columns: IsCustomer and IsVendor (this may be complicated by creating separate table to record when the status is acquired).

Now, the relationship between a party and location is many-to-many.

The intersection table resulting from the many-to-many relationship can have unused columns.

In designing a database structure don't complicate the design because there may be unused columns. Some ERP applications have 100s of columns in a table and only few are ever used! Just make sure you specify unused columns are Varchars and choose the null-ability wisely.


答:
By allowing nulls in a boolean field, you are turning an intended binary representation (true/false) into a tri-state representation (true, false, null) where your 'null' entries are indeterminate.  The 'null' value is neither appropriately 'true' nor 'false.'  What reason would you have to augment your representation to be inaccurate?

Even if you decide on a pattern such as this and do it consistently throughout your application, that does not make it okay. You'll end up in a situation where it is not clear to fresh eyes why that pattern is in place or, more likely, you'll end up in a situation where that pattern is inadvertently broken.

Title: Should I store False as Null in a boolean database field?

Body:
Let's say you have an application that has a boolean field in its User table called Inactive.

Is there anything inherently wrong with just storing false as null? If so can you please explain what the down side should be? I have discussed this with someone a few months ago and we both agreed it shouldn't matter as long as you do it consistently throughout the app/database. Recently, someone I know was emphatic that "true" true or false should be used, but they didn't really give an explanation as to why.


答:
To answer your question, yes, there are. One example of a relatively modern language that uses a similar syntax is Ada:

```<code>procedure A_Test (A, B: in Integer; C: out Integer) is
begin
    C := A + B;
end A_Test;
</code>```

(this example came from here).

This style was allowed in Algol, so many languages influenced by Algol picked up this syntax:

```<code>proc max = (int i, k)int:
begin
    ....
end
</code>```

Even the early version of C let you write something like this:

```<code>int max(a, b)
int a, b
{
    return a>b ? a : b;
}
</code>```

I think this syntax has gradually died out, because the practice of declaring multiple parameters or locals on a single line has been frowned upon. Eventually, even the languages that allowed it in the past (such as C) stopped allowing this syntax in their less archaic versions.

Body:
To answer your question, yes, there are. One example of a relatively modern language that uses a similar syntax is Ada:

procedure A_Test (A, B: in Integer; C: out Integer) is
begin
    C := A + B;
end A_Test;

(this example came from here).

This style was allowed in Algol, so many languages influenced by Algol picked up this syntax:

proc max = (int i, k)int:
begin
    ....
end

Even the early version of C let you write something like this:

int max(a, b)
int a, b
{
    return a>b ? a : b;
}

I think this syntax has gradually died out, because the practice of declaring multiple parameters or locals on a single line has been frowned upon. Eventually, even the languages that allowed it in the past (such as C) stopped allowing this syntax in their less archaic versions.


问:
Returning an object or false in dynamic languages
Consider the following JavaScript function:

```<code>function Foo() {
  function getPreferences() {
    if ([there is an existing preferences object]) {
      return preferences;
    }
    return false;
  }
}
</code>```

The calling code is:

```<code>var foo = new Foo();
var prefs = foo.getPreferences();
if (prefs) {
  // do something with prefs
}
</code>```

Is the pattern of returning an object if it exists, or false otherwise, seen as a good or bad practice? Other alternatives I can see are to return an empty object {} or null.

Does this pattern have a name?

答: False seems like a strange choice.  null seems more natural.  Best of all, return default preferences and eliminate if (prefs).


答:
I'd much rather see code that returns an object for success and null for not success.  Then, it at least feels like the function is behaving consistently.  It's return either an object or the standard way of saying no object null.  The same code:

```<code>if (prefs) {
    // do something
}
</code>```

works either way, but returning null seems more consistent to me (as the lack of an object) than returning false.

Title: Returning an object or false in dynamic languages

Body:
Consider the following JavaScript function:

```<code>function Foo() {
  function getPreferences() {
    if ([there is an existing preferences object]) {
      return preferences;
    }
    return false;
  }
}
</code>```

The calling code is:

```<code>var foo = new Foo();
var prefs = foo.getPreferences();
if (prefs) {
  // do something with prefs
}
</code>```

Is the pattern of returning an object if it exists, or false otherwise, seen as a good or bad practice? Other alternatives I can see are to return an empty object {} or null.

Does this pattern have a name?

Body:
I'd much rather see code that returns an object for success and null for not success.  Then, it at least feels like the function is behaving consistently.  It's return either an object or the standard way of saying no object null.  The same code:

if (prefs) {
    // do something
}

works either way, but returning null seems more consistent to me (as the lack of an object) than returning false.


答:
This answer differs from others because I've taken your specific use case into account. On any other day, I'd use the null value check.

In this specific case, I probably wouldn't use any of your methods. I'd most likely use an object for preferences with a number of default key/value pairs for any settings that I need. That way, there isn't any special casing needed in any of your code (checks for if(prefs) are not needed).

Consider the following code (how I think I'd go about implementing it anyway):

```<code>function MyClass(o) {
    this.prefs = {
        var1: 0,
        var2: 1,
        var3: 2
    };
    for(key in o) {
        this.prefs[key] = o[key];
    }
}

MyClass.prototype.doFunc = function() {
    console.log(this.prefs.var1);
    console.log(this.prefs.var2);
    console.log(this.prefs.var3);
}

var o = new MyClass();
o.doFunc();

var p = new MyClass({var2: "foo"});
p.doFunc();
</code>```

(http://jsfiddle.net/utkdf/)

Body:
This answer differs from others because I've taken your specific use case into account. On any other day, I'd use the null value check.

In this specific case, I probably wouldn't use any of your methods. I'd most likely use an object for preferences with a number of default key/value pairs for any settings that I need. That way, there isn't any special casing needed in any of your code (checks for if(prefs) are not needed).

Consider the following code (how I think I'd go about implementing it anyway):

function MyClass(o) {
    this.prefs = {
        var1: 0,
        var2: 1,
        var3: 2
    };
    for(key in o) {
        this.prefs[key] = o[key];
    }
}

MyClass.prototype.doFunc = function() {
    console.log(this.prefs.var1);
    console.log(this.prefs.var2);
    console.log(this.prefs.var3);
}

var o = new MyClass();
o.doFunc();

var p = new MyClass({var2: "foo"});
p.doFunc();

(http://jsfiddle.net/utkdf/)


答:
One sees lots of that pattern in javascript because of javascript's 'creative' handling of falsey values.

While it is possible to do nifty stuff in javascript, I'm not sure a language designed in the space of ten days is something you'd want to emulate.


答:
You should either return a default value, or throw an exception . I like throwing exceptions for mandatory things, and delivering default values for optional things. Using null makes debugging a bit more icky, and precludes a key that has null as its value. </p>

```<code> function Foo() {
       function getParameter(name) {
               if ( [name does not exist] ) {
                    throw "no such key";
               }
               return [parameter value]
       }
 }
</code>```

Body:
You should either return a default value, or throw an exception . I like throwing exceptions for mandatory things, and delivering default values for optional things. Using null makes debugging a bit more icky, and precludes a key that has null as its value.

 function Foo() {
       function getParameter(name) {
               if ( [name does not exist] ) {
                    throw "no such key";
               }
               return [parameter value]
       }
 }


答:
Like other people said, it's null which must be returned, instead of false. Even with strongly typed languages, you may expect false from a method, which will have a different meaning than null. It's even more important in languages with no type checking. For example, PHP has a similar problem, perfectly illustrated when using readdir method (below, quote and source code from PHP manual):

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

```<code>/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
    echo "$entry\n";
}

/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle)) {
    echo "$entry\n";
}
</code>```

Body:
Like other people said, it's null which must be returned, instead of false. Even with strongly typed languages, you may expect false from a method, which will have a different meaning than null. It's even more important in languages with no type checking. For example, PHP has a similar problem, perfectly illustrated when using readdir method (below, quote and source code from PHP manual):

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
    echo "$entry\n";
}

/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle)) {
    echo "$entry\n";
}


问:
Need to make my code more readable to the other programers in my team
I am working a project in delphi and I am creating a installer for the application,
there are Three main parts.

PostgreSQL installation/uninstallation

myapplication ( setup of myapplication is created using nsi) installation/uninstallation.

Creating tables in Postgres through script(batch files).

Every thing runs fine and smoothly, but if something fails I have created a LogToFileger which will LogToFile every step of the process,

like this

```<code>LogToFileToFile.LogToFile('[DatabaseInstallation]  :  [ACTION]:Postgres installation started');
</code>```

The function LogToFileToFile.LogToFile() This will write the contents to a file. This is working nicely, but the problem is this has messed up the code as  in it has become difficult to read the code as one ca only see the LogToFileToFile.LogToFile() function call everywhere in the code

an example

```<code> if Not FileExists(SystemDrive+'\FileName.txt') then
 begin
    if CopyFile(PChar(FilePathBase+'FileName.txt'), PChar(SystemDrive+'\FileName.txt'), False) then
       LogToFileToFile.LogToFile('[DatabaseInstallation] :  copying FileName.txt to '+SystemDrive+'\ done')
       else
       LogToFileToFile.LogToFile('[DatabaseInstallation] :  copying FileName.txt to '+SystemDrive+'\ Failed');
 end;
 if Not FileExists(SystemDrive+'\SecondFileName.txt')      then
   begin
     if CopyFile(PChar(FilePathBase+'SecondFileName.txt'), PChar('c:\SecondFileName.txt'), False) then
       LogToFileToFile.LogToFile('[DatabaseInstallation] : copying SecondFileName.txt to '+SystemDrive+'\ done')
   else
       LogToFileToFile.LogToFile('[DatabaseInstallation] :  copying SecondFileName.txt to '+SystemDrive+'\ Failed');
 end;
</code>```

as you can see there are lots of LogToFileToFile.LogToFile() calls,

before it was

```<code> if Not FileExists(SystemDrive+'\FileName.txt') then
    CopyFile(PChar(FilePathBase+'FileName.txt'), PChar(SystemDrive+'\FileName.txt'), False)
 if Not FileExists(SystemDrive+'\SecondFileName.txt')      then
   CopyFile(PChar(FilePathBase+'SecondFileName.txt'), PChar('c:\SecondFileName.txt'), False)
</code>```

this is the case in my whole code now.

its difficult to read.

can any one suggest me a nice way to unclutter the calls to LogToFile?

like

Indenting the ' LogToFileToFile.LogToFile()` call

like this

```<code>   if Not FileExists(SystemDrive+'\FileName.txt') then
     begin
         if CopyFile(PChar(FilePathBase+'FileName.txt'), PChar(SystemDrive+'\FileName.txt'), False) then
        {Far away--->>}                   LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ sucessful')
   else
        {Far away--->>}                   LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ Failed');
   end;
</code>```

Separate unit like LogToFileger

This unit will have all the LogToFile messages in a switch case like this

```<code> Function LogToFilegingMyMessage(LogToFilegMessage : integer)

 begin
case  LogToFilegMessage of

1         :  LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ sucessful');
2         :  LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ Failed');
   150        :  LogToFileToFile.LogToFile(2,'[somthing] :  [ACTION]: somthing important);

end;
</code>```

so I can just call the LogToFilegingMyMessage(1) where ever required.

Can anyone tell me which is a better and cleaner approach to LogToFileging this way?

答:
How about something along this line:

```<code>LogBook.NewEntry( 2,'POSTGRESQL INSTALLATION', 'copying Mapannotation.txt to '+sOSdrive);

if CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False) then
    LogBook.Success()
else
    LogBook.Failed();
</code>```

The NewEntry() method would build the line of text (including adding the [ & ] around the proper entries) and hold that in waiting until the success() or failure() methods are called, which append the line with 'success' or 'failure', and then output the line to the log.  You could also make other methods, such as info() for when the log entry is for something other than success/failure.

Body:
How about something along this line:

LogBook.NewEntry( 2,'POSTGRESQL INSTALLATION', 'copying Mapannotation.txt to '+sOSdrive);

if CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False) then
    LogBook.Success()
else
    LogBook.Failed();

The NewEntry() method would build the line of text (including adding the [ & ] around the proper entries) and hold that in waiting until the success() or failure() methods are called, which append the line with 'success' or 'failure', and then output the line to the log.  You could also make other methods, such as info() for when the log entry is for something other than success/failure.


问:
How does one effectively implement the 80/20 rule for developer time?
I am a developer at a bank where an 80/20 rule is implemented. 80% of the time you work on your assigned project and 20% you work on something that interests you. However, I'm not really sure how to do that. I'm hoping there are others out there who can provide me with advice on how to.

My problem is that when I really get 'in the zone', all I can think about is the task at hand. If this is a 20%'er, the last thing I want to do is stop and go, lose momentum and go back to work on my main project.

Am I suppose to work 4 days on something and 1 day on something else? or 4 weeks and 1 week?

I know this depends on the company, but I'm hoping to get a feel for how this is done industry wide.

答:
My company although not implementing a 80/20 rule as such encourages us to consistently keep up-to date with the latest technology, read other blogs and posts such as programmers etc and basically make sure we are keeping our personal development and interests up-to date.

To achieve this they didn't specify an exact amount of time, but made sure that we work on a project and task deadline rather than a by the hour workload.  This has meant that we consistently talk with our immediate manager to ensure the tasks assigned to us or we take on are manageable and allow us some time outside of the normal to take for ourselves and refresh our mind and interests.  If we are struggling we talk about it to find out why i.e. skill set limitation, too much work, unrealistic deadlines etc

We do keep a rough track of our times spent for billing purposes but this is to the hour on an entire day basis so we are not expected to record what we have done during every minute of the day.

Each of us in the team manages their time themselves so it's up-to them to determine how they do this. Some members of the team work hard at the begging of the week to get their tasks done and any time left over they relax into their own interests.  Others like me tend to mix this in during the week as I quite often hit road blocks in my project / task.  So at this point I jump over to something else which is quite often my own interest.  However as we are task/project driven I still have to make sure I get the job done so it is my responsibility to make sure I don't use all my time on personal tasks at the detriment of the team.

This has in the past lead to some team members rushing their tasks and producing undesirable results.  To help with this we introduced periodic peer reviews and also encourage everyone to read other developers code check ins.  We encourage an open discussion forum where everyone is free to voice their opinion albeit in a respectful manner.

In the end it came down to a bit of trust from the powers that be, taking ownership by the grunts to ensure the work is done and a good manager in the middle to keep the ship running.


问:
How do I make sense of the javascript frameworks explosion ? Should I learn them all?
For a beginner web developer who is still doing web development the conventional way (PHP/J2EE/Struts on server side, HTML/CSS/Javascript on client side), I was bowled over by the recent blog post on Trello technology stack.

I can't help feeling overwhelmed by the list of new technologies and frameworks mentioned in this post and specifically the ubiquitousness of Javascript frameworks.

My question is, is this the future of web development? Are there any articles, websites or resources that can help me make sense of where each of these new frameworks fit in a modern web application ?

答:
Learn enough about each framework to be able to pick and choose technology that suits your current projects, and what kind of projects you envisage you will be working on in the future.

Things do seem to be heading the way of javascript - the direction of browser technology, the expectation for rich web applications etc. I read somewhere a few months ago that javascript is going to be a core language in windows 8 as well, so a good solid knowledge of core javascript is going to be generally useful whether you're working on websites, mobile, or whatever - client side, server side, and desktop apps.

I think that jQuery is a good solid place to start; it's mature, the docs are good, it's got good use of events and callbacks, you'll find your feet with the scoping rules that seem a little odd, and although you have a lot of power available to you, it's not so abstracted that you feel you are relying on magic.

Also, it'll be a good exercise for you to try and build something with a lot of ajax if you haven't before - controlling portions of your page via the dom rather than a full page refresh every time; to really get a feel that you are building a rich javascript web application broken down into client-side modules, rather than being in the mindset of having a back-end application that has a front-end interface with some effects. (I'm saying this because this is where I was not so long ago)

It's when you build something javascript-heavy like that, that you might start to think "I'd like a js framework where I can do MVC" (backbone), or "I'd like a js framework where I can do MVVM" (knockout), and so on. You and your projects flavour what additional frameworks you choose to work with, not the other way round.

node.js could become a major server-side platform down to scalability, I haven't really tried it yet (sorry!) but my feeling is that the biggest things to come out of learning that might be the low(ish)-level network/web tech (if you have been shielded from sending your own headers, listening to ports and so on up until now), and the different approach to concurrency, rather than the language itself.


问:
How to estimate sprint velocity with varying team capacity?
We are a small team of 4 devs rather green in Scrum. Coming from all over the country, we often take odd days off or whole weeks off to go home. Therefore our team capacity changes dramatically from one iteration to another due to annual leaves, which leads to very different velocities from one iteration to another. How do we account for team capacity when estimating velocity at the Planning Meeting? Historical data will reflect very different capacities and we cannot wait one whole year to derive an average for our estimate velocity.</p>

答:
It might be a simple approach, but why don't you calculate your velocity as completed story points * capacity or completed story points / capacity, depending on how measure capacity. If you measure capacity in man-hours, use the second. If you measure capacity as a percentage of a 40-hour week, use the first. When you go to pull off story points, you should have a good idea about your capacity for a given sprint, and use your project's historical data to determine the story points completed for a given load.

However, this makes some potentially dangerous assumptions, such as treating all employees as equal - if your most junior developer takes a week off or the developer with the most experience in the domain and/or technologies takes a week off, your capacity will be the same numeric value, but the impact on velocity would probably be different.

Ultimately, use professional judgement based on historical data when planning a sprint. In this case, use previous velocity as an input into some other estimation scheme, involving the team. I would also err on the side of caution - it's easier to pull more work into a sprint than it is to remove a commitment to do a task.


问:
Abstract methods vs instance variables for reusable objects
I have quite a bit of Java code that I'm re-working to be re-used.  The problem is that there are many pieces that are project specific so there are ends up being a higher level of coupling between the application project and the code base project.

Compare to following situations where we use a class that implements the use of abstract methods to get the resources out of the child class, and one where we simply declare instance variables.

Abstract methods:

```<code>public abstract class SuperBaseClass {

    public abstract int getNumberOne();
    public abstract String getStringOne();
    public abstract String getStringTwo();

    public printStuff() {
        Log.i("IntAndTwoStrings", String.format("%i %s and %s",
                            getNumberOne(), getStringOne(), getStringTwo()));
    }

}

public class ReusedAppClass extends SuperBaseClass {

    public int getNumberOne() {
        return 1;
    }
    public String getStringOne() {
        return "String1";
    }
    public String getStringTwo() {
        return "String2";
    }

    public ReusedAppClass() {
        printStuff();
    }

}
</code>```

Instance variables:

```<code>public class SuperBaseClass {

    protected int numberOne;
    protected String stringOne;
    protected String stringTwo;

    public printStuff() {
        //Possibly throw RuntimeExceptions if the app didnt set these
        Log.i("IntAndTwoStrings", String.format("%i %s and %s",
                            numberOne, stringOne, stringTwo));
    }

}

public class ReusedAppClass extends SuperBaseClass {

    public ReusedAppClass() {
        numberOne = 1;
        stringOne = "String1";
        stringTwo = "String2";
        printStuff();
    }

}
</code>```

Is there a trade-off? Is the abstract method situation overkill, or is this what abstract classes were created for?

答:
If all those variables are properties of the base class and children uniformly depend on them then declaring them in the base is appropriate, and adding abstract get/setters/accessors would be the way to allow children to massage the data as they see fit.  This is not overkill at all and OOP is designed to express these kinds of relationships.

If you find that you're raising way too much of this kind of data to the base class (or this data isn't universally common to all children) then it might be time for a bigger refactorization of the base class into a container for other, more specific base classes to help organize your logic and code.  This would be a little more complex but allow for a cleaner design, and with good naming one easier to follow.

In either of my cases you must first analyze what exactly it is you expect to reuse before changing things up.  Creating a reusable framework from existing code will end up in a very different place than reorganizing data and operations on that data for module reuse, for example.


问:
A decent git branching model for products that should accompany the version of another, third-party product (and pros and cons of one proposal)
Note: My question is focused in my specific problem (which involves Liferay) but I hope it can be useful for anyone who needs to maintain various versions of a same project on git.

I work on a company which writes a lot of plugins for Liferay Portal. These plugins (portlets, themes etc.) are usually reusable and, of course, should be updated for new versions of the portal.

However, it is usual to have to migrate, let us say, a portlet to a new version of Liferay and to maintain its previous version. Also, frequently we have to create very specific customizations for some clients, which does not make sense to be added to the "main version".

These requisites complicate our work but, fortunately, we can assume some simplifications. For example, the plugins are frequently updated by only one programmer at a time. It is very rare to have two or more features being added to a plugin at the same time.

Now, we are migrating to Gitorious. We are trying to conceive a branching model for such a scenario.

My model

What I proposed was:

Each plugin would have its own repository in Gitorious inside a project. For example, a portlet for displaying kittens would have a kittens-portlet repository inside the liferay-portlets project.

When creating a new plugin, create it at a branch named according to the Liferay version (for example, lf5.2).

Each time a update is made on the plugin, the update is approved and deployed in production, tag the plugin with a version (for example, lf5.2v1, lf5.2v2 etc.)*

Every time a plugin should be ported to a new version of Liferay, we branch the most recent version (creating, for example, the branch lf6.0).

Once in production, the head of the new branch will receive a tag such as lf6.0v1.

Every time we have to customize a plugin in a client-specific way, we create a branch with the name of the client (for example, we would create a branch lf5.2clientcorp for our client "ClientCorp Inc.")

This is an unusual model: it would have no master and a lot of not-merging branches. This is how I suppose a repository with such model would look like:

A friend found this system rather complex and error-prone. He suggested the excellent and popular Vincent Driessen model, which I found still harder to manage and discipline-demander. It is great (and tested!) of course but seems too complex to our situation.

My friend's model

Then he suggested another model: we would have a repository for each plugin in a Liferay version (so we would start creating a kittens-lf5.2-portlet and then a kittens-lf6.0-portlet), each one with a master branch and a develop branch. The master would be always ready for deployment. (Or it could be the other way around, master and stable, as suggested by Steve Losh).

This is very simple, but I did not like this system:

it could result in an awful lot of repositories in a project, making Gitorious hard to browse.

The name of the directory of the project is relevant. If someone clone the repository to a kittens-lf6.0-portlet dir and generate the WAR with ant (as usual), the WAR name will be kittens-lf6.0-portlet as well. Old versions of this portlet (named kittens-portlet for example) would be considered as different (and probably missing) portlets in a upgraded portal. A bit of care can avoid it but I would prefer to avoid it.

The different versions of the same plugin would be maintained apart. I break my heart :(

kittens-lf6.0-portlet is a ugly name for a repository, I think.

I suspect the two last points - which are the two more subjective ones, too - are the main reason for my unwillingness. Nonetheless, all four objections stand.

OTOH, my own proposal seems strange to myself and I wonder if there is hidden bugs on it. OT3rdH git is so powerful and flexible that I think I should feel no shame on exploring its possibilities.

So, I ask:

What would be the best model? My proposal? My friend's model? The now traditional Vincent Driessen system?

What other branching model would you suggest?

If you think my model is bad, why do you think so? I would love to learn what are the drawbacks and blind spots.

* Actually, I would prefer to tag the commit with a version such as v1 but apparently a tag in git is not scoped in the branch - that is, I could not have a 1 v1 tag in lf5.2 and another one in lf6.0 - so I have to name the branch. Is it correct BTW?

答:
If I read this properly branches are basically a one-shot deviation from your main line of development, never meant to be merged back into the main line and advances in the main line never get applied to these branches.  The only deviation would be that bug fixes appropriate to the version the branch was based on need to be applied to the branch.

The answer now pivots on your day to day workflow, the number of developers working on any one branch or number of changes are red herrings.  I see your primary need as wanting to know what branches get a bug fix update from a main branch change and for this I think that the combined repository with branches will be more efficient since it's all in one place.  Were there never any need for cross pollination then separate repositories would enforce that, but that scenario doesn't match the reality of your project as I understand it.

The Driessen model would work well if your project needed to merge branches back into the main line of development, but you do not need that.  Even so I think that there is merit in maintaining an InDevelopment and StableRelease concept if you're working on a product that's live.

So to summarize I think that your project would work well with your branching model plus a dash of Driessen for your main line.  Your mileage may vary; I've always worked with a "pending release " branch that turns into a "live" branch and a separate "next release" that all require cross pollination of fixes and changes at various points so my perception may be biased.


答:
Go for option #2. There are no wasted columns just sitting there with null values.  And there is no duplication of columns in multiple tables.  You have exactly what you need. A lot of real systems use option #2.

It's used in a lot of accounting software. You'll have a master Transaction table.  If your transaction is a "special" kind with extra fields it will have a record in a another table (1 to 1 relation) to store the extra fields.

Title: Pro's/Con's to database table layout as it relates to maintenance & extensibility

Body:
Basic pseudo class layout below...

```<code>class Location(): # Class containing information about a location.
    id
    address_one

class CustomerLocation(Location):
    customer_id
    account_rep

class VendorLocation(Location):
   vendor_id
   drop_ship_cut_off_time
</code>```

Let's say you have locations which are going to be used to store location info for customers and vendors.

What would be the pro's/cons of the three options in how they relate to application maintenance and extensibility...

One large table containing all fields.

One large table containing all common fields with related tables containing specialized information about the large table records.

Many small tables containing all fields related to specific uses.CustomerLocation table VendorLocation without using a "master table" for common fields.


答:
What others have said.   3 possible values is not a boolean.

But you may have a legitimate need for 3 values. Such as (true, false, unknown). Even if this is the case, if you are into ultra-normalization you will not allow any null values at all. Instead you'll store a true boolean in another table with a 1 to 1 relation. A null value could be produced in a query by a "failed" outer join, not by a physically stored null value.


答:
I think the abstract methods are the better choice. If the implementation of these properties is not something you want the sub-classes to worry about, you may even want the base class to be responsible for it i.e. use private fields in the base
class with public accessors and protected mutators:

```<code>public class SuperBaseClass {

    private int numberOne;
    private String stringOne;
    private String stringTwo;

    public int getNumberOne() { return numberOne; }
    public String getStringOne() { return stringOne; }
    public String getStringTwo() { return stringTwo; }

    protected void setNumberOne(String numberOne) { this.numberOne = numberOne; }
    protected void setStringOne(String stringOne) { this.stringOne = stringOne; }
    protected void setStringTwo(String stringTwo) { this.stringTwo = stringTwo; }

    public printStuff() {
        Log.i("IntAndTwoStrings", String.format("%i %s and %s", getNumberOne(), getStringOne(), getStringTwo()));
    }
}
</code>```

This kind of approach provides strong encapsulation i.e. the amount of code that can directly modify your fields is minimized.

Title: Abstract methods vs instance variables for reusable objects

Body:
I have quite a bit of Java code that I'm re-working to be re-used.  The problem is that there are many pieces that are project specific so there are ends up being a higher level of coupling between the application project and the code base project.

Compare to following situations where we use a class that implements the use of abstract methods to get the resources out of the child class, and one where we simply declare instance variables.

Abstract methods:

```<code>public abstract class SuperBaseClass {

    public abstract int getNumberOne();
    public abstract String getStringOne();
    public abstract String getStringTwo();

    public printStuff() {
        Log.i("IntAndTwoStrings", String.format("%i %s and %s",
                            getNumberOne(), getStringOne(), getStringTwo()));
    }

}

public class ReusedAppClass extends SuperBaseClass {

    public int getNumberOne() {
        return 1;
    }
    public String getStringOne() {
        return "String1";
    }
    public String getStringTwo() {
        return "String2";
    }

    public ReusedAppClass() {
        printStuff();
    }

}
</code>```

Instance variables:

```<code>public class SuperBaseClass {

    protected int numberOne;
    protected String stringOne;
    protected String stringTwo;

    public printStuff() {
        //Possibly throw RuntimeExceptions if the app didnt set these
        Log.i("IntAndTwoStrings", String.format("%i %s and %s",
                            numberOne, stringOne, stringTwo));
    }

}

public class ReusedAppClass extends SuperBaseClass {

    public ReusedAppClass() {
        numberOne = 1;
        stringOne = "String1";
        stringTwo = "String2";
        printStuff();
    }

}
</code>```

Is there a trade-off? Is the abstract method situation overkill, or is this what abstract classes were created for?

Body:
I think the abstract methods are the better choice. If the implementation of these properties is not something you want the sub-classes to worry about, you may even want the base class to be responsible for it i.e. use private fields in the base
class with public accessors and protected mutators:

public class SuperBaseClass {

    private int numberOne;
    private String stringOne;
    private String stringTwo;

    public int getNumberOne() { return numberOne; }
    public String getStringOne() { return stringOne; }
    public String getStringTwo() { return stringTwo; }

    protected void setNumberOne(String numberOne) { this.numberOne = numberOne; }
    protected void setStringOne(String stringOne) { this.stringOne = stringOne; }
    protected void setStringTwo(String stringTwo) { this.stringTwo = stringTwo; }

    public printStuff() {
        Log.i("IntAndTwoStrings", String.format("%i %s and %s", getNumberOne(), getStringOne(), getStringTwo()));
    }
}

This kind of approach provides strong encapsulation i.e. the amount of code that can directly modify your fields is minimized.


问:
How do I share my jQuery plugin with the world?
I made a plugin for jQuery, which I think is quite useful. It combines an animated colours plugin with an easings plugin, and adds a completely new feature of being able to refer to colours numerically (more useful in hex notation, so 0xff00cc for example) and therefore manipulate them mathematically more easily.

I created a repository on github, and it sits there, nobody looks at it.

Mostly, I would like people to look at it, use it, and improve it, so I can use the improvements and so on. I think this idea of numerically manipulating colors could be interesting. It makes it easy to change the hue without changing the saturation for example. Combined with animated colors, I think something interesting could be done, but I don't know what exactly. How do I let people know it (or any other project) is there..?

I was going to post it on http://plugins.jquery.com which is currently down. Are there any other outlets for this kind of code?

答:
From the blog post that explains what happened to the plugin repository:

We recognize that the old site was still serving as an regular resource for a lot of people, especially newer jQuery users, who simply valued the existence of a central browsing location, despite its flaws. Though many experienced users had moved on to other sites, or relied on relationships with trusted authors and word of mouth, these can take time to develop. Until we’re able to launch the new system, we’re happy to direct you to several other directories and people who can help pick up the slack:

jQuery List

jQuery Style

Mike Alsup

Ben Alman

Matteo Bicocchi

Jörn Zaefferer

If, in the process of searching these or any other directories, you are directed back to the current site at plugins.jquery.com, typically a quick search for the author’s name and the plugin name will yield an alternative site where it was hosted. In addition, DailyJS just did a useful roundup of alternatives that goes into more detail.

The DailyJS article suggests one more alternative for promoting your plugin, The Handpicked jQuery Plugins Repository. Now, all that wasn't very hard to find, was it?

Additionally, you should consider ohloh:

Ohloh is a new kind of software directory, combining community-driven content with a unique source code crawler that monitors up-to-date development activity.

Ohloh generates a set of incredible reports for your project, to get a quick idea check out this Firefox vs Chrome comparison.

Lastly, a very good place for people to look at it, use it, and improve it is Code Review Stack Exchange.


答:
If I had something like that (I wish) I would be inclined to do it like this:

Talk about this with your boss and make sure he/she agrees that it will be the case.

Be very clear to the other people that you work with that when working on assigned projects they are free to interrupt/talk/ask you stuff. But when you are working on your R&D stuff, they cannot bug you will normal work stuff.

I would use Monday-Thursday for work and Friday for R&D. That way, you have a defined time of the week and get a less stressed wind down to the weekend.

Title: How does one effectively implement the 80/20 rule for developer time?

Body:
I am a developer at a bank where an 80/20 rule is implemented. 80% of the time you work on your assigned project and 20% you work on something that interests you. However, I'm not really sure how to do that. I'm hoping there are others out there who can provide me with advice on how to.

My problem is that when I really get 'in the zone', all I can think about is the task at hand. If this is a 20%'er, the last thing I want to do is stop and go, lose momentum and go back to work on my main project.

Am I suppose to work 4 days on something and 1 day on something else? or 4 weeks and 1 week?

I know this depends on the company, but I'm hoping to get a feel for how this is done industry wide.


问:
How to estimate a timeboxed spike using story points?
So my team and I are quite new to Scrum and today moved from estimating in Ideal Hours to Story Points. All seems sound rationale, BUT with timeboxed activities. Here is the case, we have an extremelly complex User Story that needs a spike so to explore underlying technical unknowns. With Ideal Hours it would be easy: timebox it to one ideal day (8 ideal hours). Now we want to account the exploratory work towards our velocity. So, the pressing question is how do we give Story Points to a timeboxed activity? Constraint: we do not know how to translate this 1 ideal day into Story Points because our historical data is badly collected and does not reflect reality.</p>

答:
Personal opinion here, but firstly I prefer to think in terms of complexity rather than story points. I think story points can mean different things to different people so there can be a point (no pun intended!) of confusion when talking about them and estimating based on them.

Secondly, I would not worry about estimating a spike. I would just give it some time (as per your 8 hours) and see what pops out the other end. I don't think you can assign complexity to it because the idea is to find out what the complexity of it is. Otherwise you would not need it.

Thirdly, I would not be including spikes in velocity calculations. Simply because I would expect every spike to be different and I don't necessarily expect a result from a spike. So I think including that time could distort your velocity. I would just write that time off the same way I would write off time if a developer is away sick.


问:
Javascript client - which is likely to be better serverside? WCF or MVC3 controller with restful messages?
I'm looking to write a server side service, which will be accessed from a Javascript/HTML5 client.

The client will likely be sending a bunch of restful messages over HTTPS.

All other things being equal, which is better designed to support this kind of scheme on the serverside - WCF or MVC3 (ie., a controller with only restful messages, no real view or model)?

答:
I recently came up against the same choice: I'm writing a rich web application with MVC3 for server-side and needed to host restful services for those pages to hit.

I ended up going with using MVC3, and so far it has been working very well. With WCF it feels like there is a lot of boilerplate and configuration you have to do just to get started, and very little benefit if you never plan on exposing the services any way other than REST.

All it takes is a controller that returns a JsonResult.  The syntax is also really neat. The Json method takes any plane old object and serializes it to json, which makes it really easy to use Linq to project your data to anonymous types that give a very clear indication of what you are returning:

```<code>return Json(new
{ tasks = _TaskList.Where(t => t.Active)
    .Select(new {name = t.Name, status = t.Status, owner_id = t.Owner.Id})
});
</code>```

Now, you also mention having no model. But your controller must be executing some sort of business logic, correct? You want your controller to still be relatively thin, it should be delagating the real work to the "model", whether this is another class, a library another service, whatever.

Body:
I recently came up against the same choice: I'm writing a rich web application with MVC3 for server-side and needed to host restful services for those pages to hit.

I ended up going with using MVC3, and so far it has been working very well. With WCF it feels like there is a lot of boilerplate and configuration you have to do just to get started, and very little benefit if you never plan on exposing the services any way other than REST.

All it takes is a controller that returns a JsonResult.  The syntax is also really neat. The Json method takes any plane old object and serializes it to json, which makes it really easy to use Linq to project your data to anonymous types that give a very clear indication of what you are returning:

return Json(new
{ tasks = _TaskList.Where(t => t.Active)
    .Select(new {name = t.Name, status = t.Status, owner_id = t.Owner.Id})
});

Now, you also mention having no model. But your controller must be executing some sort of business logic, correct? You want your controller to still be relatively thin, it should be delagating the real work to the "model", whether this is another class, a library another service, whatever.


问:
Designing a web app that will be used from distant geographic locations
I have designed/built a number of small web apps.  Most have been used by clients who operate in a specific geographic area, mostly within the same state/province.  For these I would follow best practices but normally didn't worry too much about issues caused by distance from the server.

I have a potential client whose locations are spread out in several countries around the world.  What specific considerations should I make in designing an app that will be used in locations that are not near each other?

Some of the more obvious ones I've thought about:

i18n/localized strings

Static content delivery via CDN

Reducing instances where the client needs to communicate with the server

Communicating with the server in the background while the client is doing other things

I feel that list should be longer, but I don't have the breadth of experience to be sure.

I am mostly concerned about the marginal issues presented by serving a geographically-distributed userbase that would not otherwise be high-ranking concerns for clients in closer proximity.

答:
I am not  web developer, however can add a few pointers as an end user. Living down under,  I appreciate when developers think about this.  The main things to consider :

Latency. The time it takes an photon to travel halfway around the world is fixed by the laws of physics, and you can't change that. What you can do is design tasks so high latency is not a concern. For instance streaming HD video is not affected by high latency, but text entry processing each key press server side is. Essentially if you are waiting for a response, it should be for a few big tasks, not a large number of small tasks.

Bandwidth - often not fast, sometimes data is expensive (We have data caps on most internet plans).

The best web sites you won't know where the server is, and don't care, the worst ones you just cannot and do not use.


问:
Using XML field Vs. creating a table for unstable organization
I am in the middle of design an application to issue and store invoices for an organization. The problem is the organization is not stable at all. There are many types of invoices and they may increase and change.

First, I tried to use tables in my DAL, one table to store invoices, one for invoice fields, and one for invoice field values. The problem was, this way needs Reflection to detect fields later, and this may slow the application when invoice contains plenty items.

Second, I tried to keep core of invoice data as two tables: invoices and invoice items. Other fields are fully catchable from other tables. I mean, Business Layer should provide different results per invoice type. It should choose the right queries, and process the results according to the type of invoice. Two problems with this solution are:

I still have lots of join between other tables when I want to show
an invoice, for per invoice item. I should recalculate everything
every time for every invoice item.

What if the invoice items table doesn’t support a new type of
invoice? Then I probably should add a new table to store that kind of invoices items.

My client asked me to keep all data related to an invoice, they do
not want me to recalculate it every time. They want something like a
snapshot of related data at the time invoice is creating.

Now, what I’m think can I use the benefit of XML in table? I can save the invoice, with whatever fields as xml.

I can save the different version of their invoices.

On changes, I only update my Business.dll and no DAL change required.

Linq to XML is not slow.

What do you suggest?

答: I would suggest using superset of all the field which can be there in invoices. Say invoice1 has field A,B,C and invoice2 has A,B,D then have a table which has column A,B, C and D(assuming there are only two type of invoices). And depending upon the columns for which data is available you can create invoice1 or invoice 2.</p>


问:
Ideas to get you programming mojo back?
I've been a professional programmer for many many years (20 years) and now I've lost interest, at the moment I have trouble even knocking out a few 100 lines of simple stuff. It will take me 3-4 days rather than 30-40mins

Anyone have any tips how to get your interest back?

Since I was a kid I've pretty much been into programming/coding as long as I was awake. I used to finish work and hit the interwebs for new stuff until bed. Now I am lucky to make LOC counts at work seem reasonable.

EDIT

Thanks everyone - some great suggestions - a lot I didnt think of - although not looking forward to the exercise I probably need it.

答:
Three things can help get your programming mojo back:

Get an SSD.

Get to know your IDE cold. Committing several super-useful shortcut keys to memory can bring back some of the fun that you've lost and make you super-productive in the process.

If you're a .NET developer, buy a Resharper license (even if your employer is petty and refuses to pay for it). Get to know the most useful Resharper shortcut keys cold. These will put you ahead of the pack.

Buy a Pluralsight subscription, and watch the webcasts at 1.5x speed.

Title: Ideas to get you programming mojo back?


答:
Nobody here knows what will inspire you better than you do, but here are a few ideas:

Switch projects. Programming is like writing -- it's a means to an end, not so much an end in itself. If you don't believe in the value of what you're doing, you won't feel that there's much point in doing it. So look for a different project at work that you can switch to, something you can get excited about. If it's not possible to switch completely, look for an additional project that you can spend at least some time on.

Try learning something new. Challenge yourself by trying a project in your own time using a set of tools that are very different from what you've been doing for the last n years. You could try your hand at a functional programming language, or build a web site, or build a project based on Amazon's EC2 or Google's App Engine, or try developing an app for Android or iOS, or pick up an Arduino and try some embedded programming, or corner one of the mainframe guys at work and ask to learn a little COBOL, or...

Take a vacation. When was the last time you took two or three consecutive weeks off? Consider making it a real vacation, where you unplug your computer and don't touch it for the duration. Don't even read about computers. Do some landscaping around your house, finish your basement, do an in-depth study of cupcakes, take up photography, spend some time with your family, travel... anything that doesn't involve typing. Sometimes you need a break from something before you can enjoy it again.

Go back to school. Realize that you don't have to be a programmer forever, especially if you don't find it rewarding. This could be a good time to start thinking about what you want to do for your next act. Or, after a semester of learning about EBITDA and indirect labor costs, you might suddenly realize that you love, love, love programming after all.

Start exercising. It can be hard for desk jockeys like us to believe, but many people swear that exercising gives you more energy, which might help you feel a little more motivated. It can also serve as either a mental break from work, or as a time to think deeply.

Talk to your doctor. Diminished motivation could be a sign of depression or other illness. And even if that's not the problem, your doc might be able to suggest some changes that'll have you feeling a lot better.

Make sure you understand how the work you're doing fits into the bigger picture. Sometimes it's hard to see the forest for the trees, and a talk with your manager about how your work impacts the bottom line could provide some of the motivation that'll help you get back on track.

Title: Ideas to get you programming mojo back?

Body:
I've been a professional programmer for many many years (20 years) and now I've lost interest, at the moment I have trouble even knocking out a few 100 lines of simple stuff. It will take me 3-4 days rather than 30-40mins

Anyone have any tips how to get your interest back?

Since I was a kid I've pretty much been into programming/coding as long as I was awake. I used to finish work and hit the interwebs for new stuff until bed. Now I am lucky to make LOC counts at work seem reasonable.

EDIT

Thanks everyone - some great suggestions - a lot I didnt think of - although not looking forward to the exercise I probably need it.


答:
A change is as good as a rest

Could you take on additional/different responsibilities, such as some business analysis or customer liaison work to give you a "break" from the coal-face?

The best advice I can give though is to understand why you've lost your mojo. This is something only you can answer, but as with programming you can only really begin to solve a problem once you've debugged it to determine the root cause. Anything else is pretty much just going to be the equivalent of putting a plaster on it.

If all else fails, take a holiday (or a sabbatical if your employer offers them and you're eligible); sometimes a rest is better than a change.

Title: Ideas to get you programming mojo back?


答:
Take a break. Do something else. Have a vacation. Watch a movie. Relax.

Things change and your interest will come back, or it won't. Just adjust your situation.

Ask for something else to do at work and be good with yourself.

Title: Ideas to get you programming mojo back?


答:
Share it.

If you have a blog, blog about it. If you don't have a blog, get one and start blogging about it. There are few things more reassuring to someone who's researching a component than finding a project owner who actively discusses their project. It's one of the criteria I use when choosing components. If the developer is actively talking about it then that means there's a fair chance I'll be able to get support for it.

Recommend it.

If you're not already active on stackoverflow, that's a good place to start. Become a participant in questions for relevant tags and then consider recommending your component as a solution, where appropriate. Note: The 'where appropriate' bit is very important. Don't take a scattershot approach of "spamming" questions as the community will not be appreciated and is a very easy way to lose credibility. Always ensure that you adopt a full disclosure approach and explain that you're recommending a component you wrote and WHY it's a good fir for the original question.

Use It.

Look for projects that you can participate in where it might be a good fit and consider recommending it. You'll also gain valuable feedback on your feature-set this way which can be used to improve your component.

Title: How do I share my jQuery plugin with the world?

Body:
I made a plugin for jQuery, which I think is quite useful. It combines an animated colours plugin with an easings plugin, and adds a completely new feature of being able to refer to colours numerically (more useful in hex notation, so 0xff00cc for example) and therefore manipulate them mathematically more easily.

I created a repository on github, and it sits there, nobody looks at it.

Mostly, I would like people to look at it, use it, and improve it, so I can use the improvements and so on. I think this idea of numerically manipulating colors could be interesting. It makes it easy to change the hue without changing the saturation for example. Combined with animated colors, I think something interesting could be done, but I don't know what exactly. How do I let people know it (or any other project) is there..?

I was going to post it on http://plugins.jquery.com which is currently down. Are there any other outlets for this kind of code?


答:
Do something you enjoy. Maybe work is not motivating you enough.

Do something new .. the computer science field is buzzing with new things to do.

20 years ago, you probably did not have Artificial Intelligence, Machine Learning, Data Mining, Distributed computing.. try your hand at some of these.

A good place to start is some Graduate level courses at Stanford or MIT. Some MIT/Stanford courses are open on the web.

Title: Ideas to get you programming mojo back?


答:
Personal Opinion:

I don't think you should assign points to a spike. The reason for a spike is you cannot poker plan stories because of some unknowns.

Timebox it "outside" your sprint.

You realize you need a spike because you cannot estimate something in terms of story points

Try to find out what you can within one day (or 1/2 day).

At end of day (or 1/2 day) determine if you are ready to estimate. If not goto 2.

This will not reflect in your velocity, but you can also have an "average spike time" as a additional measure. This will serve as a future estimator if you need a spike.

Title: How to estimate a timeboxed spike using story points?

Body: So my team and I are quite new to Scrum and today moved from estimating in Ideal Hours to Story Points. All seems sound rationale, BUT with timeboxed activities. Here is the case, we have an extremelly complex User Story that needs a spike so to explore underlying technical unknowns. With Ideal Hours it would be easy: timebox it to one ideal day (8 ideal hours). Now we want to account the exploratory work towards our velocity. So, the pressing question is how do we give Story Points to a timeboxed activity? Constraint: we do not know how to translate this 1 ideal day into Story Points because our historical data is badly collected and does not reflect reality.</p>


答:
My motivation improved greatly by starting to read certain blogs and books, and by listening to podcasts and watching videos of dedicated programmers. Perhaps this is all too familiar to you, but if it isn't, why not treat yourself by widening your horizon professionally?

I found reading Joel on Software highly entertaining and interesting

The early Stack Overflow podcasts were a source of amusement and inspiration

Books like Code Complete and The Pragmatic Programmer taught me to raise my standards

Listening to interviews with people like Kent Beck and Uncle Bob motivated me to investigate unit testing and TDD.

And since no unit testing framework existed for the programming language I do my  daily work in, I wrote my own open source unit testing framework.

Title: Ideas to get you programming mojo back?


问:
Make a big deal out of == true?
There is a colleague of mine who constantly writes:

```<code>if (someBool == true)
</code>```

It drives me up the wall!  Should I make a big deal of it or just drop it?

答: Hopefully, you are using a sensible language, like VB.NET with Option Strict On, which doesn't allow coercion of other types to Boolean inside an If statement. Then there's no need to ever add the "== true" (or "= True" in VB), since the coercion case can't happen.  If you want to check for non-zero then write that explicitly (ie., "If x <> 0").</p>

Title: Make a big deal out of == true?


答:
Well it will depend on details of your client but what I would ask includes the following

What Kind of network connection will the end users have? Both bandwidth and latency

Will they have Modern browsers? If using HTML5's offline options may make sense

Can we put servers near the main places where the clients will be?

Can we put caching proxies in useful locations

I would also do the following

Ensure that all data is sent over the wire compressed

Minimize the amount of sent data.

Title: Designing a web app that will be used from distant geographic locations

Body:
I have designed/built a number of small web apps.  Most have been used by clients who operate in a specific geographic area, mostly within the same state/province.  For these I would follow best practices but normally didn't worry too much about issues caused by distance from the server.

I have a potential client whose locations are spread out in several countries around the world.  What specific considerations should I make in designing an app that will be used in locations that are not near each other?

Some of the more obvious ones I've thought about:

i18n/localized strings

Static content delivery via CDN

Reducing instances where the client needs to communicate with the server

Communicating with the server in the background while the client is doing other things

I feel that list should be longer, but I don't have the breadth of experience to be sure.

I am mostly concerned about the marginal issues presented by serving a geographically-distributed userbase that would not otherwise be high-ranking concerns for clients in closer proximity.


问:
Is there a correlation between some software engineering practices and software engineering success stories?
I've been reading the book "The Drunkard's Walk: How Randomness Rules Our Lives" by Leonard Mlodinow and it's a truly enlightening read. The book deals with probabilities and human reasoning. And let's just say, for the record, that while some things sometimes work, there's a chance that the things you thought made it work, are unrelated to what actually made it work.

Probabilities are unintuitive.

However, it gave me an idea. There ought to be studies on this already, that have attempted to quantify the results of software engineering endeavors (which of course is a hard problem in itself). And these studies should point to what kind of software engineering practices are really important in terms of quantifiable success.

i.e.

A team that employs TDD is this much less likely to have this kind of problem.

A team that employs SOLID principles is this much less likely to have this kind of problem.

etc. etc.

What I'm looking for here is software engineering practices that show strong correlation between implementation and success. I'm confident that these things exist but that they are hard to come by and that's why I pose this question.

What studies or what practices do you know of that have strong correlation between implementation and success (where success is somewhat arbitrary but I think you get the idea)?

If we're gonna sell that idea that software engineering is better than cowboy coding, I think we need proofs.

答:
The problem with this kind of quantification is that it's almost impossible to get good enough data on the effectiveness of software engineering practices to make any meaningful conclusion.

Most importantly, correlation does not imply causation - for example, it could just be that good programmers are quick to jump on and implement new ideas, so you see a general correlation between project success and adoption of new software engineering techniques. But that proves nothing about the effectiveness of the techniques themselves, as the entire effect might be explained by the higher talent level of the programmers who adopt them.

And then it's hard to control the independent variables. How do you ensure a fair experiement unless you are able to control for all the following?

Experience / skill / motivation level of team

Actual extent of adoption of claimed methodology (are they really doing TDD properly?)

Presence / absence of major design mistakes unrelated to the software engineering methodology (e.g. those requiring a major re-architecture during the project)

Difficulty level of projects being compared

Impact of externally imposed problems (e.g. major requirements changes)

Selection bias (e.g. did people tend to share data more often about successful projects?)

Confirmation bias (e.g. did people exaggerate the success of projects which use their favourite methodology?)

Even if you decide to tackle the above by giving multiple carefully selected teams the same problem under the same carefully controlled conditions then your experiment is likely to be prohibitively expensive if you want to create enough data to be statistically significant.

And finally, it's almost impossible to measure success:

A quantity metric like source lines of code (SLOC) is appallingly bad. The incentive on developers is to create million-line monstrosities with copy / paste coding in order to look more "productive"

An on-time / on-budget metric depends mainly on the level of ambition in the estimates used to create the plan / budget

A ROI-type metric depends as much on market situation and the commercial management of the product as it does on the quality of the engineering output (look at the history of Microsoft Windows!)

Story Points are useful to get a feel of velocity in an agile team but aren't really comparable across teams

Functionality based metrics like Function points or Use Case Points are perhaps the best of a bad bunch, but they are bureaucratic to collect and don't reflect the difference in engineering effort required to create each unit of functionality.

Quality metrics like bugs in production / app availability are notoriously difficult to calculate and compare on an equal basis - it depends significantly on things like platform chosen, size of user base and various operational / deployment factors.

In conclusion: trying to quantify the impact of software development tasks is an extremely difficult task, and despite many years following the topic nobody has yet come up with a truly effective approach. As a result, evaluation of software development methodologies remains more of an art than a science, and probably will remain so for many years to come.

Interestingly, there is one approach that I think has promise: application of lean principles. This isn't a panacea and won't directly solve the problem of evaluating software development methodologies, but it does have one key insight: A process with a particular element of waste is unambiguously less efficient than the same process without that element of waste, all other things being equal. So if you focus on eliminating waste in the software development process, you can at least be sure you are moving in the right direction. In addition, waste is often quantifiable so you should also get some idea of how much more efficient you are getting, at least in rough percentage terms.