问:
Should I use a list or an array?
I'm working on a windows form to calculate UPC for item numbers.

I successfully create one that will handle one item number/UPC at a time, now I want to expand and do it for multiple item numbers/UPCs.

I have started and tried using a list, but I keep getting stuck. I created a helper class:

```<code>public class Codes
{
    private string incrementedNumber;
    private string checkDigit;
    private string wholeNumber;
    private string wholeCodeNumber;
    private string itemNumber;

    public Codes(string itemNumber, string incrementedNumber, string checkDigit, string wholeNumber, string wholeCodeNumber)
    {
        this.incrementedNumber = incrementedNumber;
        this.checkDigit = checkDigit;
        this.wholeNumber = wholeNumber;
        this.wholeCodeNumber = wholeCodeNumber;
        this.itemNumber = itemNumber;
    }

    public string ItemNumber
    {
        get { return itemNumber; }
        set { itemNumber = value; }
    }

    public string IncrementedNumber
    {
        get { return incrementedNumber; }
        set { incrementedNumber = value; }
    }

    public string CheckDigit
    {
        get { return checkDigit; }
        set { checkDigit = value; }
    }

    public string WholeNumber
    {
        get { return wholeNumber; }
        set { wholeNumber = value; }
    }

    public string WholeCodeNumber
    {
        get { return wholeCodeNumber; }
        set { wholeCodeNumber = value; }
    }

}
</code>```

Then I got started on my code, but the issue is that the process is incremental, meaning I get the item number from a gridview via checkboxes and put them in the list. Then I get the last UPC from the database, strip the checkdigit, then increment the number by one and put it in the list. Then I calculate the checkdigit for the new number and put that in the list. And here I already get an  Out of Memory Exception.
Here is the code I have so far:

```<code>List<Codes> ItemNumberList = new List<Codes>();

    private void buttonSearch2_Click(object sender, EventArgs e)
    {
        //Fill the datasets
        this.immasterTableAdapter.FillByWildcard(this.alereDataSet.immaster, (textBox5.Text));
        this.upccodeTableAdapter.FillByWildcard(this.hangtagDataSet.upccode, (textBox5.Text));
        this.uPCTableAdapter.Fill(this.uPCDataSet.UPC);
        string searchFor = textBox5.Text;
        int results = 0;
        DataRow[] returnedRows;
        returnedRows = uPCDataSet.Tables["UPC"].Select("ItemNumber = '" + searchFor + "2'");
        results = returnedRows.Length;
        if (results > 0)
        {
            MessageBox.Show("This item number already exists!");
            textBox5.Clear();
            //clearGrids();
        }
        else
        {
            //textBox4.Text = dataGridView1.Rows[0].Cells[1].Value.ToString();
            MessageBox.Show("Item number is unique.");
        }
    }

    public void checkMarks()
    {

        for (int i = 0; i < dataGridView7.Rows.Count; i++)
        {
            if ((bool)dataGridView7.Rows[i].Cells[3].FormattedValue)
            {
                {
                    ItemNumberList.Add(new Codes(dataGridView7.Rows[i].Cells[0].Value.ToString(), "", "", "", ""));
                }
            }
        }
    }

    public void multiValue1()
    {
        _value = uPCDataSet.UPC.Rows[uPCDataSet.UPC.Rows.Count - 1]["UPCNumber"].ToString();//get last UPC from database
        _UPCNumber = _value.Substring(0, 11);//strip out the check-digit
        _UPCNumberInc = Convert.ToInt64(_UPCNumber);//convert the value to a number

        for (int i = 0; i < ItemNumberList.Count; i++)
        {
            _UPCNumberInc = _UPCNumberInc + 1;
            _UPCNumberIncrement = Convert.ToString(_UPCNumberInc);//assign the incremented value to a new variable
            ItemNumberList.Add(new Codes("", _UPCNumberIncrement, "", "", ""));//**here I get the OutOfMemoreyException**
        }

        for (int i = 0; i < ItemNumberList.Count; i++)
        {
            long chkDigitOdd;
            long chkDigitEven;
            long chkDigitSubtotal;
            chkDigitOdd = Convert.ToInt64(_UPCNumberIncrement.Substring(0, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(2, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(4, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(6, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(8, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(10, 1));
            chkDigitOdd = (3 * chkDigitOdd);
            chkDigitEven = Convert.ToInt64(_UPCNumberIncrement.Substring(1, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(3, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(5, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(7, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(9, 1));
            chkDigitSubtotal = (300 - (chkDigitEven + chkDigitOdd));
            _chkDigit = chkDigitSubtotal.ToString();
            _chkDigit = _chkDigit.Substring(_chkDigit.Length - 1, 1);
            ItemNumberList.Add(new Codes("", "",_chkDigit, "", ""));
        }
</code>```

Is this the right way to go about it, using a list, or should I be looking at a different way?

答:
While KChaloux answer is great, I would like to point out another consideration: List<T> is a lot more powerful than an Array. The methods of List<T> are very useful in a lot of circumstances - an Array doesn't have these methods and you may spend a lot of time to implement workarounds.

So, from a development perspective I nearly always use List<T> because when there are additional requirements, they are often far easier to implement when you are using a List<T>.

This leads to a final problem: My code (I don't know about yours) contains 90% List<T>, so Arrays are not really fitting in. When I pass them around, I have to call their .toList() method and convert them to a List - this is annoying and is so slow that any performance  gain from using an Array is lost.

Title: Should I use a list or an array?


问:
What are common code review processes and what is considered bad?
My company recently started doing formalized code reviews. The process goes like this: you submit into a github, request a pull request, code gets reviewed by approximately three people, then if all passes, your code goes in.

The process seems fair, however the three people who do the code reviews don't seem to be fair. I notice that when I put my code in for review, I get anywhere between 100-200 comments. The top number for me was 300 comments once. Of course you'd think it is big changes, but this can be very small changes as well with less than 50 lines of code (which includes unit tests). All comments are considered "must do" and without argument.

With that in mind, my main problem here is that it seems a bit excessive. I talked to the group and they told me basically that just because I had so many years of development in php doesn't mean I am an "developer." Of course this seems more hurtful than not. Also I notice that within the group, they don't appear to produce as much comments and most of the time they ignore or otherwise disregard other comments or suggestions rarely accepting it as a valid point even if something is broken.

So my question is if this is fair? Or common?

答:
For 50 LOC 300 comments seems to be a bit excessive and - wow - 3 reviewers for every pull request? Your company must have a lot of resources.

From my experience for a useful code review process there must be some rules and/or guidelines:

Priority of comments

Classification of comments (Bug, Code Style, etc.)

Agreed architecture / design to follow

Agreed code style

If you don't get a priority from the reviewers ask your responsible project manager / team leader; the responsible person for the costs should have an opinion about priorities.

If you have a defined architecture, a common understanding what design patterns you use in your project and an agreed code style, then the review comments should be only about "real issues" like security issues, unintentional bugs, corner cases not covered by the specified architecture, etc.

If your development team has not agreed on "taste issues" (e.g. should a member variable start with "m_"), then every reviewer will force you to follow his style, which is just a waste of time/money.

ContentLicense: CC BY-SA 3.0


问:
Legitimate use of the Windows "Documents" folder in programs
Anyone who likes their Documents folder to contain only things they place there knows that the standard Documents folder is completely unsuitable for this task. Every program seems to want to put its settings, data, or something equally irrelevant into the Documents folder, despite the fact that there are folders specifically for this job1.

So that this doesn't sound empty, take my personal "Documents" folder as an example. I don't ever use it, in that I never, under any circumstances, save anything into this folder myself. And yet, it contains 46 folders and 3 files at the top level, for a total of 800 files in 500 folders. That's 190 MB of "documents" I didn't create. Obviously any actual documents would immediately get lost in this mess.

My question is: can anything be done to improve the situation sufficiently to make "Documents" useful again, say over the next 5 years? Can programmers be somehow educated en-masse not to use it as a dumping ground? Could the OS start reporting some "fake" location hidden under AppData through the existing APIs, while only allowing Explorer and the various Open/Save dialogs to know where the "real" Documents folder resides? Or are any attempts completely futile or even unnecessary?

1For the record, here's a quick summary of the various standard directories that should be used instead of "Documents":

RoamingAppData for user-specific data and settings. This is the directory to use for user-specific non-temporary data. Anything placed here will be available on any machine that a given user logs on to in networks where this is configured. Do not place large files here though, because they slow down login/logout in such environments.

LocalAppData for user-and-machine-specific data and settings. This data differs for every user and every machine. This is also where very large user-specific data should be placed.

ProgramData for machine-specific data and settings. These are the same regardless of which user is logged on, and will not roam to other machines in a network.

GetTempPath for all files that may be wiped without loss of data when not in use. This is also the place for things like caches, because like temporary data, a cache does not need to be backed up. Place your huge cache here and you'll save your user some backup trouble.

"Documents" itself should only ever be used if the user specified it manually by entering a path or selecting it in a Save dialog. That is the only time it is ever appropriate to save stuff in "Documents".

答:
Solution:

 1. Right Click 'Documents' folder and select the 'location' tab.

 2. Change the 'Documents' location to some other place I choose 'C:\Admin\Configs'
 (once this is done, all applications, writing to 'documents' should be sent off to C:\Admin\Configs instead.

But this solves only half the problem, the next step should be pretty obvious.

Create a new folder in 'C:\User\\Documentation'

You should be able then to add that directory to the libraries and delete the old one, I deliberately set a different folder name in 'C:\User\**Documentation**' because I wanted to ensure nothing could just hard path to that folder.

Should the folder 'documents' appear again in your C:\User\ because of the above fact, simply right click the folder and make it an invisible folder.

OwnerDisplayName: romkyns


问:
How to abstract transition between Views?
Our team is developing an application using WPF with MVVM.

We want to make ViewModels reusable. With this intention we want to abstract the transition logic between Views (ViewModels, we use ViewModel-first approach with Caliburn.Micro) so the other application can override it.

For instance, we have App1 and App2. Firstly, we developed App1 and it has FooViewModel which creates FunViewModel when user clicks a Next button.

But, developing App2 we want to get to NotFunViewModel instead of FunViewModel when user makes a click on a Next button.

How to accomplish such a task? The solution has to be universal and safe in accordance to types (in compile-time).

答:
If you share a ViewModel in two Views and it shall behave differently, it certainly has some kind of switchable 'operation mode'.

You could just introduce a bool/enum property in your ViewModel and let the individual Views set its value to Mode1 or Mode2 respectively (in MVVM the View knows its ViewModel, but not vice versa => value could be set e.g. in View XAML).

Then the button click event or associated command can evaluate this mode-Property to choose the right action.


问:
How did Strassen come up with his matrix multiplication method?
The famous Strassen's matrix multiplication algorithm is a real treat for us, as it reduces the time complexity from the traditional O(n3) to O(n2.8).

But of all the resources I have gone through, even Cormen and Steven Skienna's book, they clearly do not state of how Strassen thought about it.

What is the rationale of Strassen's matrix multiplication algorithm?  Is this a lucky accident or is there something deeper in it?

答:
Apart from Strassen, nobody is able to tell you how Strassen has got
his idea.  Howeber¹, I can tell you, how you could have found that
formula yourself—provided that you are interested in algebraic
geometry and representation theory. This also gives you the tools to show that Strassen's formula is as good as it can, or more precisely, that there is no formula computing the product of two 2×2 matrices that uses fewer than 7 multiplications.

Since you are interested by matrices I assume you know basic linear
algebra and will be a bit blurry for the more advanced details.

First let be E the set of all linear maps from a plane to a
plane. This is basically the set of all 2×2 matrices, but we forget
about a particular coordinate system—because, if there were a better
coordinate system than the “default one” we could have interest in
using it for matrix multiplication.  We also denote by E† the dual
space of E and by X = P(E⊗E†⊗E†) the projective space associated
to the tensor product E⊗E†⊗E†.

An element of X = P(E⊗E†⊗E†) of the special form [c⊗α⊗β] can be
interpreted as an elementary operation on matrices, which, in some
appopriate coordinate systems, reads a coefficient of a matrix A and
a coefficient of a matrix B and writes the product of these
coefficients in some matrix C. A general element of X is a combination of
these elementary operations, so the product π of two matrices,
understood as a map from P(E)×P(E) to P(E), is a point in X.

The usual matrix product formula and Strassen's formula can be
expressed as combinations of these linear operations, so let me denote
by W₁ the set of these elementary operations [c⊗α⊗β] and let me describe
geometrically their combinations.

Let W₂ be the variety of secants of W₁ in X. It is obtained by
taking the (closure of the) union of all lines going through two
(generic) points of W₁.  We can think of a it as of the set of all
combinations of two elemetary operations.

Let W₃ be the variety of secant planes of W₁ in X. It is obtained by
taking the (closure of the) union of all planes going through three
(generic) points of W₁.  We can think of a it as of the set of all
combinations of three elemetary operations.

Similarly, we define secant varieties for greater indices. Note that
these varieties grow larger and larger, that is W₁⊂W₂⊂W₃⊂⋯ Hence
the classical matrix product formula shows that the product of
matrices is a point of W₈. Actually

PROPOSITION(Strassen) — The product of matrices π lies in W₇.

As far as I know, Strassen did not put things that way, however this
is a geometric point of view on this question. This point of view is
very useful, because it also lets you prove that Strassen's formula is
the best, that is, that π does not lie in W₆. Geometric methods
developped here can also be used for a broader range of problems.

I hope, I caught your curiosity. You can go further by reading this
article by Landsberg and Manivel:

http://arxiv.org/abs/math/0601097

¹ I will not fix this typo, because I caught a cold.


问:
How do MySQL joins really work?
In my case joining table inside subquery or outside subquery gives very few difference with COUNT

CASE 1: about 6202 rows.

In this case table_c is joined inside subquery, but is only joined (No other actions for the table, not selecting any data or filtering whole query with that table).

CASE 2: about 6235 rows.

In this case that table is joined outside of subquery but joining key (groupCol) is the same.

Here is my self-explanatory MySQL query:

```<code>SELECT
    COUNT(*)
FROM (
    SELECT
          a.*
        , b.some
        # no c columns
    # main table
    FROM table_a      AS a

    # no mention this
    LEFT JOIN table_b AS b
    ON a.col = b.bcol

    #### CASE 1 ###
    # this is left joined, this is matter
    # this is only joined, does nothing more
    LEFT JOIN table_c AS c
    ON c.col = a.groupCol
    #### CASE 1 ###

 WHERE
    *** SOME statements ***
    # c table not participating in WHERE, or GROUP-ing clause
 GROUP BY a.groupCol
 ORDER BY a.dateCol
) AS subSelect

#### CASE 2 : table_c is joined outside of subquery ###
LEFT JOIN table_c AS c
ON c.col = subSelect.groupCol
#### CASE 2 ###

WHERE
    *** SOME statements ***
    # table_c still not participating of course
</code>```

I also know how does MySQL LEFT JOIN works: if data not found on second table, row corresponding fields from that table are set to null.

What what actually happens here I can't figure out.

Also case 1 is faster than case 2.

Why? Also for sure, that joining in case 1, contains least double amount of rows. In case 2 it's first filtered and then joined.

I thought this should be faster way...

答:
I performed two queries in MySQL while using EXPLAIN.

The first one being the following:

```<code>select count(*) from parent
left outer join child on child.parent_id = id;
</code>```

The second being the following:

```<code>select count(*) from (
    select * from parent p
    left outer join child c on c.parent_id = p.id
) count;
</code>```

They both returned 68 records, which implies if you're getting something different, it is because of a filter you're using, not the way in which the query is being performed.

When I run explain on the first query I get the following:

```<code>'1', 'SIMPLE', 'parent', 'index', NULL, 'FK8338B25AD02D715A', '9', NULL, '15', 'Using index'
'1', 'SIMPLE', 'child', 'ref', 'PRIMARY,FKAFAB561391AEEB78', 'FKAFAB561391AEEB78', '8', 'db.parent.id', '2', 'Using index'
</code>```

And when I run the second query I get the following:

```<code>'1', 'PRIMARY', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'Select tables optimized away'
'2', 'DERIVED', 'p', 'ALL', NULL, NULL, NULL, NULL, '15', ''
'2', 'DERIVED', 'c', 'ref', 'PRIMARY,FKAFAB561391AEEB78', 'FKAFAB561391AEEB78', '8', 'db.p.id', '2', 'Using index'
</code>```

The DERIVED merely means that I used aliases for the tables which were necessary in the second query in order to work properly.  Otherwise, you'll notice they're very similar.  You'll notice the only other major difference is an additional line "Select tables optimized away".  This is an optimization which MySQL performs in order to reduce the queries and make it simpler.

In other words, the second query is only requiring MySQL to optimize in addition to the actual query, so it can only be slower and provide the same results as the first.  If your count is not consistent between these two queries, it is likely because something else is going on which is probably a filter of some sort.

Hope that helps!

Title: How do MySQL joins really work?

Body:
I performed two queries in MySQL while using EXPLAIN.

The first one being the following:

select count(*) from parent
left outer join child on child.parent_id = id;

The second being the following:

select count(*) from (
    select * from parent p
    left outer join child c on c.parent_id = p.id
) count;

They both returned 68 records, which implies if you're getting something different, it is because of a filter you're using, not the way in which the query is being performed.

When I run explain on the first query I get the following:

'1', 'SIMPLE', 'parent', 'index', NULL, 'FK8338B25AD02D715A', '9', NULL, '15', 'Using index'
'1', 'SIMPLE', 'child', 'ref', 'PRIMARY,FKAFAB561391AEEB78', 'FKAFAB561391AEEB78', '8', 'db.parent.id', '2', 'Using index'

And when I run the second query I get the following:

'1', 'PRIMARY', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'Select tables optimized away'
'2', 'DERIVED', 'p', 'ALL', NULL, NULL, NULL, NULL, '15', ''
'2', 'DERIVED', 'c', 'ref', 'PRIMARY,FKAFAB561391AEEB78', 'FKAFAB561391AEEB78', '8', 'db.p.id', '2', 'Using index'

The DERIVED merely means that I used aliases for the tables which were necessary in the second query in order to work properly.  Otherwise, you'll notice they're very similar.  You'll notice the only other major difference is an additional line "Select tables optimized away".  This is an optimization which MySQL performs in order to reduce the queries and make it simpler.

In other words, the second query is only requiring MySQL to optimize in addition to the actual query, so it can only be slower and provide the same results as the first.  If your count is not consistent between these two queries, it is likely because something else is going on which is probably a filter of some sort.

Hope that helps!


问:
Should I pass an object or values?
Let's say I have a model that has 'purchase' method. The purchase method should take care of purchasing a product.

Signature of purchase

```<code>public function purchase($token, Model_Member $member, Model_Product $product, Model_Recipient $recipient);
</code>```

To call this method, I need to make $member, $product, and $recipient in my controller. Is it considered a better approach to pass an array of values to the purchase so that purchase can make those required objects like below?

```<code>public function purchase($token, $member_id, $product_id, array $recipient);
</code>```

in this case, purchase should pull up a member record from the database and make a model of it.

What's the better approach?

答:
Well the way I do it is like this:
The Controller:

Should be responsible for interacting with the view and choosing the
appropriate Application service.

So read the input from the request object and create the appropriate
Application service.

The application service:

Should be responsible for modeling your use case (i.e. your application logic), but holds no business logic. It orchestrates the application, but does no work itself.

The raw input passed from the controller is mapped to objects in this layer. Any domain service required is created in this layer and the appropriate method is invoked on this service.

The Domain Service, Entities and Value Objects:

Should be responsible for modelling your domain logic and doing the actual work.

So in your case create the objects in the application service then pass them to the appropriate Domain service/entity/value object.

OwnerDisplayName: Moon

Title: Should I pass an object or values?


问:
How to share a file over multiple projects
I'm using Visual Studio 2010 to amend a C# project.

Part of the application requires the user to be able to save and read a settings file (1 Project reads them in (as read only) from a file. The other project reads them in from the file to be shown in the GUI and when saved, the file is to be overwritten).

If both of these files were in 1 project, I could share it easily (using Resources.resx for example or any other approach). The issue I have is the project that reads the settings file is different to the project that writes/amends the settings file.

The 2 projects are not allowed to be referenced to each other (they apparently have to remain oblivious to each other existence) so I can't share a CONST STRING between them.

Now, I may be taking the DRY principal too far, but I am worried about writing code reference the a single file in multiple projects (next OS change may break this logic etc).

I'm going to assume that this decision isn't uncommon and that an approach(es) already exist to overcome this issue?

Is it just a question of having the same file referenced in 2 locations (and if that file changes, having to update each reference (this seems undesired)) or is there a better way?

答:
You've a couple of options.

Create a third project that contains the shared functionality. Both
existing projects reference this new DLL, problem solved.

Put the functionality that you'd put in a shared DLL in a .cs file
in one of the projects. Then add the file to the second project, but
hit the drop down on the "Add" button on the "Add existing item"
dialog, and choose "Add as link". The file only exists in one place,
but appears in both projects as if it existed in both projects.

Hope this helps


答:
After taking 20 min break I've found out what's going on:

In first case when joining inside the subquery, GROUP-ing done the job, but when joining outside it would be GROUP-ed again, sure that would be stupid but...

Seems I've got duplicate entries to table_c that is multiplying some of rows.

Also thank you @Neil

Title: How do MySQL joins really work?

Body:
In my case joining table inside subquery or outside subquery gives very few difference with COUNT

CASE 1: about 6202 rows.

In this case table_c is joined inside subquery, but is only joined (No other actions for the table, not selecting any data or filtering whole query with that table).

CASE 2: about 6235 rows.

In this case that table is joined outside of subquery but joining key (groupCol) is the same.

Here is my self-explanatory MySQL query:

```<code>SELECT
    COUNT(*)
FROM (
    SELECT
          a.*
        , b.some
        # no c columns
    # main table
    FROM table_a      AS a

    # no mention this
    LEFT JOIN table_b AS b
    ON a.col = b.bcol

    #### CASE 1 ###
    # this is left joined, this is matter
    # this is only joined, does nothing more
    LEFT JOIN table_c AS c
    ON c.col = a.groupCol
    #### CASE 1 ###

 WHERE
    *** SOME statements ***
    # c table not participating in WHERE, or GROUP-ing clause
 GROUP BY a.groupCol
 ORDER BY a.dateCol
) AS subSelect

#### CASE 2 : table_c is joined outside of subquery ###
LEFT JOIN table_c AS c
ON c.col = subSelect.groupCol
#### CASE 2 ###

WHERE
    *** SOME statements ***
    # table_c still not participating of course
</code>```

I also know how does MySQL LEFT JOIN works: if data not found on second table, row corresponding fields from that table are set to null.

What what actually happens here I can't figure out.

Also case 1 is faster than case 2.

Why? Also for sure, that joining in case 1, contains least double amount of rows. In case 2 it's first filtered and then joined.

I thought this should be faster way...


问:
Providing an agnostic authorization system
I'm trying to design a small web platform that would host several "applications", with a common user pool. My reflection is now focused on the authorization system.

I define an application as an interface that allows users to perform CRUD and more custom operations on a set of resources. I tend to prefer to model an application as a collection of RESTful webservices to be consumed from various front ends.

I really would like to generalize the authorization system and to make it application agnostic; I'm thinking of implementing it as a webservice, leveraging unstructured document databases.

Assuming that:

A users and groups management service is available to the application developer;

The scope of any application would be limited to perform CRUD and more custom operations on resources, as stated previously;

My idea is to provide to developers read/write access to a structure like this:

```<code>[{
    "Application":"Application1",
    "Ressource":"ResourceType1",
    "id":"123",
    "read":{
        "whitelist_group_ids":[ 2 ],
        "whitelist_user_ids":[ 1 ],
        "blacklist_users_ids":[ 2 ]
    },
    "CustomOperation1":{
        "whitelist_group_ids":[ * ],
        "whitelist_user_ids":[ 1, 2 ],
        "blacklist_users_ids":[ 3 ]
    }
},{
    "Application":"Application1",
    "Ressource":"ResourceType2",
    "id":"13",
    "read":{
        "whitelist_group_ids":[ * ],
        "whitelist_user_ids":[ 1 ],
        "blacklist_users_ids":[ 2 ]
    },
    "CustomOperation2":{
        "whitelist_group_ids":[ 2 ],
        "whitelist_user_ids":[ 1, 2 ],
        "blacklist_users_ids":[ 3 ]
    }
}]
</code>```

They would then be able to store, check and update their access restrictions on demand;

What would be the flaws of such an approach? Is there any standard strategy to achieve something close to what I described?

答:
Look into Apache Shiro.  Going with a canned solution is usually a better move than starting from scratch.  They have a solution for your problem that, I can attest, is very easy to implement.  It can automatically tie into the user's session and provide authentication and authorization on varying levels.

The most powerful portion of our implementation consisted of a hierarchy of groups such that each group would inherit basic authorizations from its parent, and then override, or add to the authorizations.  We decided to use true/false for all our permissions so that each permission would boil down to a yes/no answer.  We avoided negatives in the names of permissions so that the code would read more cleanly.

To give you an idea, here's some groups and their permissions:

```<code>WebUser
     advanced_tools: false
     admin_tools:false
     tree_navigation:true
     enhanced_panel:false
     search_limit_to_25:true
PaidUser
     advanced_tools:true
     tree_nagivation:false
     search_limit_to_25:false
TrialUser
     advanced_tools:true
AdminUser
     tree_navigation:false
     admin_tools:true
</code>```

An admin user was also a paid user (as stored in the database), so that first it would apply all the web user authorizations, then the paid user values would overwrite, and finally, the admin user would be applied.  We also had authorizations that were assigned to individual users, but it remained unused.

In the server-side source code, we would use Shiro to see if a user was authorized to do tree_navigation or admin_tools before including the code.  On every call to the server to perform an action, we verified the user was allowed to do what they were doing.  The trick was to not trust any session data - we would recheck all authorizations on every server call.  If the session expired, or the user wasn't logged in via Shiro, then the permission check would fail and we would protect our data / information.

The fact that this was all in the database meant that admin users could edit or modify the permissions on the fly, and then trigger a cache update for the user module on server-side.

Body:
Look into Apache Shiro.  Going with a canned solution is usually a better move than starting from scratch.  They have a solution for your problem that, I can attest, is very easy to implement.  It can automatically tie into the user's session and provide authentication and authorization on varying levels.

The most powerful portion of our implementation consisted of a hierarchy of groups such that each group would inherit basic authorizations from its parent, and then override, or add to the authorizations.  We decided to use true/false for all our permissions so that each permission would boil down to a yes/no answer.  We avoided negatives in the names of permissions so that the code would read more cleanly.

To give you an idea, here's some groups and their permissions:

WebUser
     advanced_tools: false
     admin_tools:false
     tree_navigation:true
     enhanced_panel:false
     search_limit_to_25:true
PaidUser
     advanced_tools:true
     tree_nagivation:false
     search_limit_to_25:false
TrialUser
     advanced_tools:true
AdminUser
     tree_navigation:false
     admin_tools:true

An admin user was also a paid user (as stored in the database), so that first it would apply all the web user authorizations, then the paid user values would overwrite, and finally, the admin user would be applied.  We also had authorizations that were assigned to individual users, but it remained unused.

In the server-side source code, we would use Shiro to see if a user was authorized to do tree_navigation or admin_tools before including the code.  On every call to the server to perform an action, we verified the user was allowed to do what they were doing.  The trick was to not trust any session data - we would recheck all authorizations on every server call.  If the session expired, or the user wasn't logged in via Shiro, then the permission check would fail and we would protect our data / information.

The fact that this was all in the database meant that admin users could edit or modify the permissions on the fly, and then trigger a cache update for the user module on server-side.


问:
Loading data for ShoppingCart item
I'm currently trying to cover our shopping cart with unit tests.

Class ShoppingCartItem has property Term. It also loads available terms for this item upon object creation. Currently this is done using call to static class in constructor.

Current state:

```<code>public class ShoppingCartItem
{
    private Dictionary<Guid, ShoppingCartTerm> terms;
    public ShoppingCartItem(int productID)
    {
        terms = SKUInfoGopasProvider.LoadAllTerms(productID);
    }
 }
</code>```

My question is. How to make data source interchangeable?  Should I introduce factory class?

Obvious answer is use constructor injection but that doesn't seem somewhat right to me.

I am thinking about making something along these lines.

```<code>public class ShoppingCartData
{
    private readonly ShoppingCartItemFactory _factory;

    public ShoppingCartData(ShoppingCartItemFactory factory)
    {
        _factory = factory;
    }

    public void AddItem(int productId)
    {
        var item = _factory.CreateCartItem(productId);
        _items.Add(item);
    }
}
</code>```

答:
I think you're on the right path.  The code you posted, however, doesn't fully reflect that, so I'm going to talk it through here.

The list of Terms seems to be a dependency of the ShoppingCartItem class.  As such, I'd be tempted to inject it in via the constructor.

The difficulty here is that now any code that used to simply instantiate a ShoppingCartItem now needs to source the explicit dependencies... meh.

A convenient way to get around this is to use a Factory.  The factory (as you've shown above) will be responsible for resolving the dependency, passing it into the ShoppingCartItem constructor, and returning the new ShoppingCartItem.  Done, right?

Well, how does the Factory get a handle of the list of Terms?  This is where I think IoC containers really shine.  Your factory can use an IoC container to resolve this dependency on the fly.

This setup should make the ShoppingCartItem testable, as well as the Factory.

Title: Loading data for ShoppingCart item


问:
Typed search over complex model. Possible CQRS / NoSQL solution
Given the following relational model:

I need to implement a typed search for hotels, which should be able to query on name, city, country, category, hoteltype, roomprice, customtype, room custom type and roomtype or any combination of these criteria.

At the moment I'm doing this though Entity Framework, dynamically constructing a query over the Hotel-entity (IQueryable). This is fine as currently there is very little data. However, this isn't very scalable and when there is a lot of data this will become very slow as it's a query over 10 tables. Note that I only need to load the hotel-data, not the entire graph.

I'm thinking of ways to improve the scalability of this part. I have been looking into CQRS and maybe NoSQL solutions.

One approach I had in mind is having this model on the write side (to enforce consistency) and having a different model on the read side. On write, I would then update the read-model (viewmodel).

However, since this is already a more or less complex model in terms of relations, I see a few problems with that:

Updating metadata (such as category, roomtype, hoteltype) would require me to update all of the hotels or rooms in the read-model. This could be quite slow or impossible once there's a lot of data.

Suppose I use a document database such as MongoDB and save a hotel with all the related items denormalized, won't the query over that table still be slow as it has to search inside each document, or is still still quite fast in NoSQL?

To summarize a few questions:

Is denormalizing this model the right approach and what would be the best way?

Will NoSQL be faster?

Are there any better approaches I can follow or ways to break up the relationship and flatten the hierarchy while still being able to do a typed search?

Ideally some fields should also support fuzzy search, what would be the best way to achieve that?

答:
What I have done for complex queries over large datasets is this:

Perform a simple query which includes only one or two tables

Truncate the number of results to a reasonable amount (500k?)

Perform a more complicated query to narrow down options based on the truncated records

This is a scalable solution to your problem.  Once you start joining many tables with millions of records, you multiply the size of your temporary table used in the join.  By truncating the results to a manageable amount, the queries will still run quickly, and in a majority of cases, you will get 100% of the results.  In the case where your truncate removes valid hotels, you will find that you'll still get tens of thousands of results.  It's a matter of being okay with not getting a perfectly complete solution in order to get results in a timely manner.

As far as fuzzy searching goes, you may be talking about Semantic Web implementations.  This is a difficult task, but your refined results may well be superior to another competing site.  Take a look into Gate for an idea (it's Java).  Essentially, it generates annotations on text blocks that will let you do additional term searches.  Once you add stemming and a comprehensive ontology to your annotator, it becomes a very powerful search tool.

I haven't tried switching to NoSQL.  I find relational models have more tools and more developers that are comfortable with them.  Flattening and distributing data isn't always the best choice, but if you have 10+ systems that can participate in a distributed data model, you may find the searches running faster.  That's only if you have the resources to make this happen.  Certainly flattening the database with a single server as the data source would be a mistake.

Hope this helps!


问:
Inheritance in test classes
I have an interface Serializer with methods serialize and isSerializerFor. I created a first implementation of this using TDD, and ended up with a nice clean test case fully covering a nice clean implementation. To get a more concrete idea, here is one relevant commit.

Now someone else (who is not used to doing TDD) started with writing the second implementation of this Serializer interface. This person figured the test needed for the second implementation would have some overlap with my initial test. So an abstract base class for serializer tests was created, holding the methods that are suspected to be common to all serializer test cases.

I'm not happy with this for two main reasons. First of all, the only reason inheritance is used here is for code reuse, which is a big code smell. Secondly, this breaks the TDD cycle. If I now want to create another implementation of Serializer, and create a derivative of the base test class, I end up having to implement all production code in one step.

On the other hand, simply duplicating the common code in the test classes seems rather odd as well. I'm hoping composition can be used here in a sane way to avoid these problems.

This seems like a reasonably common situation. How would you solve this? What would you do differently?

答:
First of all, the only reason inheritance is used here is for code reuse, which is a big code smell.

Different serializer implementations (like SerializerA, SerializerB, SerializerC) lead to different SerializerTest classes (SerializerTestA, SerializerTestB, SerializerTestC), which are all "Serializer testers", giving your a "is-a" relationship to the common SerializerTester base class, so inheritance is probably the right tool here.

If I now want to create another implementation of Serializer, and create a derivative of the base test class, I end up having to implement all production code in one step.

I don't think so. You start TDD by creating a test class SerializerTestA (derived from SerializerTester, with nothing more than creating a SerializerA object. This won't compile - test is RED. Then you implement SerializerA with nothing more than a constructor and empty method implementations for the Serializer interface  - test is GREEN. Next, you add your first test method to SerializerTestA, which may just delegate a test call to a corresponding method in SerializerTester. Because of the missing implementations in SerializerA, your test fails - RED again. Then, you implement the first empty method in SerializerA, until your first does not fail any more - test status is GREEN again.

So, as long as you don't call any test methods from SerializerTester needing the full implementation of the Serializer class you can still do this step-by-step, staying on the classic TDD path.

Title: Inheritance in test classes


答:
I usually use a ParentViewModel to control the application flow

The simplified version of it typically looks something along these lines:

```<code>App1ViewModel
{
    BaseViewModel CurrentView { get; set; }
    ICommand NextCommand { get; } <!-- will set CurrentView to FunViewModel -->
}

App2ViewModel
{
    BaseViewModel CurrentView { get; set; }
    ICommand NextCommand { get; } <!-- will set CurrentView to NotFunViewModel -->
}
</code>```

```<code><ContentControl Content="{Binding CurrentView}" />
<Button Command="{Binding NextCommand}" />
</code>```

Title: How to abstract transition between Views?

Body:
Our team is developing an application using WPF with MVVM.

We want to make ViewModels reusable. With this intention we want to abstract the transition logic between Views (ViewModels, we use ViewModel-first approach with Caliburn.Micro) so the other application can override it.

For instance, we have App1 and App2. Firstly, we developed App1 and it has FooViewModel which creates FunViewModel when user clicks a Next button.

But, developing App2 we want to get to NotFunViewModel instead of FunViewModel when user makes a click on a Next button.

How to accomplish such a task? The solution has to be universal and safe in accordance to types (in compile-time).

Body:
I usually use a ParentViewModel to control the application flow

The simplified version of it typically looks something along these lines:

App1ViewModel
{
    BaseViewModel CurrentView { get; set; }
    ICommand NextCommand { get; } <!-- will set CurrentView to FunViewModel -->
}

App2ViewModel
{
    BaseViewModel CurrentView { get; set; }
    ICommand NextCommand { get; } <!-- will set CurrentView to NotFunViewModel -->
}

<ContentControl Content="{Binding CurrentView}" />
<Button Command="{Binding NextCommand}" />


答: Have a look at Solr. It can do all the things that you want and much more, out of the box. One possible downside is that you have to push your data into the server every time you have an update (or do it in batches at specific intervals) but since Solr supports delta imports, it shouldn't be that much of a hassle.</p>

Title: Typed search over complex model. Possible CQRS / NoSQL solution

Body:
Given the following relational model:

I need to implement a typed search for hotels, which should be able to query on name, city, country, category, hoteltype, roomprice, customtype, room custom type and roomtype or any combination of these criteria.

At the moment I'm doing this though Entity Framework, dynamically constructing a query over the Hotel-entity (IQueryable). This is fine as currently there is very little data. However, this isn't very scalable and when there is a lot of data this will become very slow as it's a query over 10 tables. Note that I only need to load the hotel-data, not the entire graph.

I'm thinking of ways to improve the scalability of this part. I have been looking into CQRS and maybe NoSQL solutions.

One approach I had in mind is having this model on the write side (to enforce consistency) and having a different model on the read side. On write, I would then update the read-model (viewmodel).

However, since this is already a more or less complex model in terms of relations, I see a few problems with that:

Updating metadata (such as category, roomtype, hoteltype) would require me to update all of the hotels or rooms in the read-model. This could be quite slow or impossible once there's a lot of data.

Suppose I use a document database such as MongoDB and save a hotel with all the related items denormalized, won't the query over that table still be slow as it has to search inside each document, or is still still quite fast in NoSQL?

To summarize a few questions:

Is denormalizing this model the right approach and what would be the best way?

Will NoSQL be faster?

Are there any better approaches I can follow or ways to break up the relationship and flatten the hierarchy while still being able to do a typed search?

Ideally some fields should also support fuzzy search, what would be the best way to achieve that?


答:
If your complex queries are always based on Hotel Rooms, I'd say that you need in order to escalate is to denormalize (or otherwise build an index).

If you denormalize on SQL, I'd go for an OLAP approach. A simple denormalized, indexed table seems should be enough to escalate to millions of rows.

NoSQL (ie MongoDB) can also be used for this. The design principle is similar to an OLAP approach, but backed by a NoSQL database.

In any case, I'd suggest to use such an OLAP/denormalized backend only for the indexed search part, while maintaining your SQL structure for the transactional processing part (exactly as you mention, using a "read-model").

You can use a search engine like Solr (or Lucene in your case) as suggested, which can perhaps be seen as a way of denormalizing too. I tend to dislike this approach when I don't need fuzzy/score-based/text-based search. Depending on which kind of fuzzy search you need, you can avoid Lucene and resolve fuzzy search with a custom (ie using string-distance algorithms). As a concrete example: I'd consider a seach engine like Lucene if I need to do fuzzy search based on "City" or other text fields, but I'd perhaps go with something custom based on "Levenshtein distance" if I only need to do simple fuzzy searches on "Country". If you, however, need score-based search (like: some room attribute is not really important and doesn't disqualify the room from being listed) then go with some search engine like Lucene.

Finally, note that when querying your database the number of tables is not really a big concern as long as you are using indexed columns to join tables and their cardinality is not too big (ie, a "country" table can be contained in memory, and joining it on its primary key doesn't normally impact performance). Such joins are very common in Relational-OLAP systems.


问:
Quickest way to split a delimited String in Java
I am building a Comparator that provides multi-column sort capability on a delimited String.
I am currently using the split method from String class as my preferred choice for splitting the raw String into tokens.

Is this the best performing way to convert the raw String into a String array? I will be sorting millions of rows so I think approach matters.

It seems to run fine and is very easy, but unsure if there's a faster way in java.

Here is how the sort works in my Comparator:

```<code>public int compare(String a, String b) {

    String[] aValues = a.split(_delimiter, _columnComparators.length);
    String[] bValues = b.split(_delimiter, _columnComparators.length);
    int result = 0;

    for( int index : _sortColumnIndices ) {
        result = _columnComparators[index].compare(aValues[index], bValues[index]);
        if(result != 0){
            break;
        }
    }
    return result;
}
</code>```

After benchmarking the various approaches, believe it or not, the split method was the quickest using the latest version of java. You can download my completed comparator here: https://sourceforge.net/projects/multicolumnrowcomparator/

答:
According to this benchmarks, StringTokenizer is faster for splitting strings but it doesn't return an array which makes it less convenient.

If you need to sort millions of rows I'd recommend using a RDBMS.


答:
I've written a quick and dirty benchmark test for this.  It compares 7 different methods, some of which require specific knowledge of the data being split.

For basic general purpose splitting, Guava Splitter is 3.5x faster than String#split() and I'd recommend using that.  Stringtokenizer is slightly faster than that and splitting yourself with indexOf is twice as fast as again.

For the code and more info see http://demeranville.com/battle-of-the-tokenizers-delimited-text-parser-performance/

Title: Quickest way to split a delimited String in Java

Body:
I am building a Comparator that provides multi-column sort capability on a delimited String.
I am currently using the split method from String class as my preferred choice for splitting the raw String into tokens.

Is this the best performing way to convert the raw String into a String array? I will be sorting millions of rows so I think approach matters.

It seems to run fine and is very easy, but unsure if there's a faster way in java.

Here is how the sort works in my Comparator:

```<code>public int compare(String a, String b) {

    String[] aValues = a.split(_delimiter, _columnComparators.length);
    String[] bValues = b.split(_delimiter, _columnComparators.length);
    int result = 0;

    for( int index : _sortColumnIndices ) {
        result = _columnComparators[index].compare(aValues[index], bValues[index]);
        if(result != 0){
            break;
        }
    }
    return result;
}
</code>```

After benchmarking the various approaches, believe it or not, the split method was the quickest using the latest version of java. You can download my completed comparator here: https://sourceforge.net/projects/multicolumnrowcomparator/


问:
Can a pure-functional solution to this problem be as clean as the imperative?
I have an exercise in Python as follows:

a polynomial is given as a tuple of coefficients such that the powers are determined by the indexes, e.g.: (9,7,5) means 9 + 7*x + 5*x^2

write a function to compute its value for given x

Since I am into functional programming lately, I wrote

```<code>def evaluate1(poly, x):
  coeff = 0
  power = 1
  return reduce(lambda accu,pair : accu + pair[coeff] * x**pair[power],
                map(lambda x,y:(x,y), poly, range(len(poly))),
                0)
</code>```

which I deem unreadable, so I wrote

```<code>def evaluate2(poly, x):
  power = 0
  result = 1
  return reduce(lambda accu,coeff : (accu[power]+1, accu[result] + coeff * x**accu[power]),
                poly,
                (0,0)
               )[result]
</code>```

which is at least as unreadable, so I wrote

```<code>def evaluate3(poly, x):
  return poly[0]+x*evaluate(poly[1:],x) if len(poly)>0 else 0
</code>```

which might be less efficient (edit: I was wrong!) since it uses many multiplications instead of exponentiation, in principle, I do not care about measurements here (edit: How silly of me! Measuring would have pointed out my misconception!) and still not as readable (arguably) as the iterative solution:

```<code>def evaluate4(poly, x):
  result = 0
  for i in range(0,len(poly)):
      result += poly[i] * x**i
  return result
</code>```

Is there a pure-functional solution as readable as the imperative and close to it in efficiency?

Admittedly, a representation change would help, but this was given by the exercise.

Can be Haskell or Lisp aswell, not just Python.

答:
If you just have a (fixed) tuple, why not do this (in Haskell):

```<code>evalPolyTuple (c, b, a) x = c + b*x + a*x^2
</code>```

If instead you have a list of coefficients, you can use:

```<code>evalPolyList coefs x = sum $ zipWith (\c p -> c*x^p) coefs [0..]
</code>```

or with a reduce as you had it:

```<code>evalPolyList' coefs x = foldl' (\sum (c, p) -> sum + c*x^p) 0 $ zip coefs [0..]
</code>```

Body:
If you just have a (fixed) tuple, why not do this (in Haskell):

evalPolyTuple (c, b, a) x = c + b*x + a*x^2

If instead you have a list of coefficients, you can use:

evalPolyList coefs x = sum $ zipWith (\c p -> c*x^p) coefs [0..]

or with a reduce as you had it:

evalPolyList' coefs x = foldl' (\sum (c, p) -> sum + c*x^p) 0 $ zip coefs [0..]


答:
This really sounds to me like a communication problem.  You have an expectation that your code isn't bad enough to deserve 300 comments.  The reviewers seem to think you need a lot of feedback.  Arguing back and forth in an asynchronous fashion is going to waste a lot of time.  Heck, writing 300 comments is a TREMENDOUS waste of time.  If these are not all defects then it's possible as a new team member that you don't know the team's style yet. That's normal and something that should be learned to accelerate the whole team.

My suggestion is to save time.  Accelerate the feedback.  I would:

Do more interim reviews to avoid making the same mistake and generating the same comment 50 times

Sit with a reviewer as they review your code so you can talk about the issues as they come up, thus avoiding documenting 300 "issues" that will be wiped away in the next commit

Pair with one of these "real" developers for some time as you write the code to see what they would do differently

People may argue against pairing because "it will take longer" but that's obviously not an issue here.

Title: What are common code review processes and what is considered bad?

Body:
My company recently started doing formalized code reviews. The process goes like this: you submit into a github, request a pull request, code gets reviewed by approximately three people, then if all passes, your code goes in.

The process seems fair, however the three people who do the code reviews don't seem to be fair. I notice that when I put my code in for review, I get anywhere between 100-200 comments. The top number for me was 300 comments once. Of course you'd think it is big changes, but this can be very small changes as well with less than 50 lines of code (which includes unit tests). All comments are considered "must do" and without argument.

With that in mind, my main problem here is that it seems a bit excessive. I talked to the group and they told me basically that just because I had so many years of development in php doesn't mean I am an "developer." Of course this seems more hurtful than not. Also I notice that within the group, they don't appear to produce as much comments and most of the time they ignore or otherwise disregard other comments or suggestions rarely accepting it as a valid point even if something is broken.

So my question is if this is fair? Or common?


问:
Selecting the (right?) application design
While working to build software products for early stage startups, I have seen two very common schools of thought that define an approach to application design.

Those 2 paradigms typically include designing an application predicated on an "extendible codebase” or a "throw away codebase".

What factors should one consider/measure to identify their approach to application design?  What are alternatively ways to think about application design?

Some factors suggested to date include:

the amount of time available to build the product.

the total amount of budget available.

the level of quality.

答:
For a startup, what are the pros and cons of building a software product predicated on "Throw away code" vs "an extendible codebase"?

In reality, if you phrase the question as "either one or the other", it might reduce your options significantly. I feel like you kind of answered already the pros and cons in the question, so I'll try to exercise the real question:

I don't know of a single startup success story where people take their time to build a good system. Time to market is king, and like you said, going against it can increase significantly the risk of going out of business.

"Doing right" has serious problems in the first moments of a startup. One, it requires experienced engineers (which requires money); two, it requires unbounded time (depends on the complexity of the product and the experience of the engineers with this kind of system). Finally, we all know you don't need good design to be in business, you need something that runs, and whose problems are hidden from your customers.

Pretty much any startup experience I know of (and probably every single famous one) took big advantage of this fact: if part of your product is poor quality, but that part is invisible to the customer (or their potential desire is not significantly affected by it), don't waste time on improving it, just ship it.

But that is "time 0" in the time scale. In time t > 0 you begin to learn what most startups learn the hard way: the poor quality of those invisible parts is constraining your current opportunities. That is, the team is requiring much more time to implement new features, these are being shipped half baked, bugs are bugging the customers and making them angry, etc.

tangent: at this point, hopefully the manager knows the capital sin of software engineering and would not fall into the myth of the man-month.

The difference that makes the difference here is to know at which time t you should pause, hold the horses, and put some effort into cleaning the house before you sink (and how much time dedicated to and how much cleaning should be done).

In other words, this is not solved by selecting either  "Throw away code" vs "an extendible codebase" once at the beginning, closing your eyes and running in the chosen direction. You can solve it by putting the "time" in the equation and acknowledging there is a question you should make from time to time, and from time to time, it might require opposing answers.

In summary, instead of having a static "time vs. cost vs. quality" pick-two-triangle, put these in a time scale:

(source: metareload.com)

Now, take into consideration that, at any t, cost and time for developing a feature depends on the resulting quality of the product at t-1. In other words, how much quality of design you chose to invest right now is telling how cheap or onerous the future developments will be (so, quality is the variable that tells you the cost of your future).

If you are a manager, this point of view can give you more clues about how to manage the tension between design quality and time to market. And that is something to be managed constantly.

Finally, experienced engineers are optimized for design. And if you have very good ones, you can push time constraints on them and they will make a significant effort into selecting critical parts of the system to dedicate to design and testing, and will let less-critical parts to be of lesser quality -- they know these have messes that are more easily manageable and the trade-off for quick delivery pays off. You can also count on them to put some breaks at the incoming demands and tell you that this is the t moment they should stop and work on the code base to make room for new maneuvers. In other words, what you're doing is  "amortizing" the total cost of good design (and risks) by spreading it through prioritized parts of the system and through time.

ContentLicense: CC BY-SA 4.0


答:
Many functional languages have mapi implementations that allow to you have an index weaved through a map. Combine that with a sum and you have the following in F#:</p>

```<code>let compute coefficients x =
    coefficients
        |> Seq.mapi (fun i c -> c * Math.Pow(x, (float)i))
        |> Seq.sum
</code>```

Title: Can a pure-functional solution to this problem be as clean as the imperative?

Body:
I have an exercise in Python as follows:

a polynomial is given as a tuple of coefficients such that the powers are determined by the indexes, e.g.: (9,7,5) means 9 + 7*x + 5*x^2

write a function to compute its value for given x

Since I am into functional programming lately, I wrote

```<code>def evaluate1(poly, x):
  coeff = 0
  power = 1
  return reduce(lambda accu,pair : accu + pair[coeff] * x**pair[power],
                map(lambda x,y:(x,y), poly, range(len(poly))),
                0)
</code>```

which I deem unreadable, so I wrote

```<code>def evaluate2(poly, x):
  power = 0
  result = 1
  return reduce(lambda accu,coeff : (accu[power]+1, accu[result] + coeff * x**accu[power]),
                poly,
                (0,0)
               )[result]
</code>```

which is at least as unreadable, so I wrote

```<code>def evaluate3(poly, x):
  return poly[0]+x*evaluate(poly[1:],x) if len(poly)>0 else 0
</code>```

which might be less efficient (edit: I was wrong!) since it uses many multiplications instead of exponentiation, in principle, I do not care about measurements here (edit: How silly of me! Measuring would have pointed out my misconception!) and still not as readable (arguably) as the iterative solution:

```<code>def evaluate4(poly, x):
  result = 0
  for i in range(0,len(poly)):
      result += poly[i] * x**i
  return result
</code>```

Is there a pure-functional solution as readable as the imperative and close to it in efficiency?

Admittedly, a representation change would help, but this was given by the exercise.

Can be Haskell or Lisp aswell, not just Python.

Body:
Many functional languages have mapi implementations that allow to you have an index weaved through a map. Combine that with a sum and you have the following in F#:

let compute coefficients x =
    coefficients
        |> Seq.mapi (fun i c -> c * Math.Pow(x, (float)i))
        |> Seq.sum


问:
What is the standard practice for extracting an auto-incrementing primary key?
I have some objects that will be created an entered into the database. There is no guarantee that any of their fields will be unique except for the auto-incrementing primary key. I would like to be able to access these objects later in the program using their primary key.

What is the best way to get this key out of the database? I can think of two methods to obtain the primary key after adding the object's data to the database:

Find the maximum primary key as this was the one most recently added.

Delete the current object, compare the data in the database with the data in the program, and then create a new object based on the row that is not contained in the program.

Both of these seem error-prone and hacky and I am wondering if there was a more standard way do to this.

答:
Most databases have a way to access the last generated ID, take SQL server for example.

```<code>CREATE TABLE [SomeTable] (
    ID INT NOT NULL IDENTITY(1,1),
    FieldOne VARCHAR(MAX) NOT NULL,
    PRIMARY KEY(ID)
)

INSERT INTO [SomeTable](FieldOne) VALUES('a')

SELECT scope_identity() -- returns 1

INSERT INTO [SomeTable](FieldOne) VALUES('b')

SELECT scope_identity() -- returns 2
</code>```

This has the advantage of being safe for multiple users / transactions.

The first suggestion about guessing what the next ID would be is not safe in that regard.

Your second suggestion will wreck havoc if you have any referential integrity or if there are any triggers.

Body:
Most databases have a way to access the last generated ID, take SQL server for example.

CREATE TABLE [SomeTable] (
    ID INT NOT NULL IDENTITY(1,1),
    FieldOne VARCHAR(MAX) NOT NULL,
    PRIMARY KEY(ID)
)

INSERT INTO [SomeTable](FieldOne) VALUES('a')

SELECT scope_identity() -- returns 1

INSERT INTO [SomeTable](FieldOne) VALUES('b')

SELECT scope_identity() -- returns 2

This has the advantage of being safe for multiple users / transactions.

The first suggestion about guessing what the next ID would be is not safe in that regard.

Your second suggestion will wreck havoc if you have any referential integrity or if there are any triggers.


答:
Are you confident that you will deliver "extendible solution" - that will not turn into the "prototype" due to time constraints and unexpected requirements?

I believe what happens most often is that the "prototype" becomes the product - with all its shortcomings and imperfectness it still actually works. Startups that go for ultimate solution most often run out of funding and never deliver.

Title: Selecting the (right?) application design

Body:
While working to build software products for early stage startups, I have seen two very common schools of thought that define an approach to application design.

Those 2 paradigms typically include designing an application predicated on an "extendible codebase” or a "throw away codebase".

What factors should one consider/measure to identify their approach to application design?  What are alternatively ways to think about application design?

Some factors suggested to date include:

the amount of time available to build the product.

the total amount of budget available.

the level of quality.


问:
eCommerce use case: removing a product
I am starting to design the database schema for the eCommerce element of a web service I am creating.

The thing I'm trying to get my head around is how to deal with the use case of a seller (user of my web service) deleting a product.

The issue I have is that this product could be referenced in a customers basket, to be paid orders, pending orders, deliveries, past orders etc...

This problem is surely one that everyone developing such a system has come across. I'm just wondering if there is a best practice way to address it?

Can it be addressed at the database schema level? Or maybe it just requires certain validation checks on database data before allowing a product to be deleted, or to stop an error if a customer is trying to pay for an order that had a reference to a product, but that reference has been deleted (i.e. product was deleted).

答:
Don't delete; mark it discontinued or unavailable, like Mike pointed out in the comments. If the product is discontinued, you simply don't show it on sales pages any more, but your database references are left intact. If there is a pending order for that product, then the business side (not the database) has to figure out how to handle it: do we still ship (assuming any is in stock) or just issue a refund?

That said, if the item is not used in any shopping carts, orders, etc. -- for example, it's just being used for training someone or was somehow created inadvertently -- then, sure, delete away. But you need to do lots of integrity checking even in this scenario to be sure a deletion is safe; you're still probably better off marking it discontinued.

Title: eCommerce use case: removing a product


答:
We would not allow our system to physically delete the product. We simply turned the Active flag to "No". This allowed the archived invoices to produce correctly.

Updated 12-26-2013: There is a bigger issue at stake here

After re-reading the OP's question it seems that this web service will be used by more than one seller. If that is the case then there is a many to many relationship between Seller and Product. So not only should the Product table contain an Active boolean flag the Product table needs a ForeingKey that identifies the SellerId.

Title: eCommerce use case: removing a product

Body:
I am starting to design the database schema for the eCommerce element of a web service I am creating.

The thing I'm trying to get my head around is how to deal with the use case of a seller (user of my web service) deleting a product.

The issue I have is that this product could be referenced in a customers basket, to be paid orders, pending orders, deliveries, past orders etc...

This problem is surely one that everyone developing such a system has come across. I'm just wondering if there is a best practice way to address it?

Can it be addressed at the database schema level? Or maybe it just requires certain validation checks on database data before allowing a product to be deleted, or to stop an error if a customer is trying to pay for an order that had a reference to a product, but that reference has been deleted (i.e. product was deleted).


答:
I don't understand how your code relates to the problem scope you defined, so I'll give my version of what your code does ignoring the problem scope (based on the imperative code you wrote).

Pretty readable haskell (this approach can be easily translated to any FP language that has list destructuring and come out pure and readable):

```<code>eval acc exp val [] = acc
eval acc exp val (x:xs) = eval (acc + execPoly) (exp+1) xs
  where execPoly = x * (val^exp)
</code>```

Sometimes the naive simple approach in haskell like that is cleaner than the more concise approach to people less accustomed to FP.

A more clearly imperative approach that's still completely pure is:

```<code>steval val poly = runST $ do
  accAndExp <- newSTRef (0,1)
  forM_ poly $ \x -> do
    modifySTRef accAndExp (updateAccAndExp x)
  readSTRef accAndExp
  where updateAccAndExp x (acc, exp) = (acc + x*(val^exp), exp + 1)
</code>```

bonus to the second approach is being in the ST monad it will perform very well.

Though to be certain, the most likely real implementation from a Haskeller would be the zipwith mentioned in another answer above. zipWith is a very typical approach and I believe Python can mimic the zipping approach of combining functions and an indexer which can be mapped.

Body:
I don't understand how your code relates to the problem scope you defined, so I'll give my version of what your code does ignoring the problem scope (based on the imperative code you wrote).

Pretty readable haskell (this approach can be easily translated to any FP language that has list destructuring and come out pure and readable):

eval acc exp val [] = acc
eval acc exp val (x:xs) = eval (acc + execPoly) (exp+1) xs
  where execPoly = x * (val^exp)

Sometimes the naive simple approach in haskell like that is cleaner than the more concise approach to people less accustomed to FP.

A more clearly imperative approach that's still completely pure is:

steval val poly = runST $ do
  accAndExp <- newSTRef (0,1)
  forM_ poly $ \x -> do
    modifySTRef accAndExp (updateAccAndExp x)
  readSTRef accAndExp
  where updateAccAndExp x (acc, exp) = (acc + x*(val^exp), exp + 1)

bonus to the second approach is being in the ST monad it will perform very well.

Though to be certain, the most likely real implementation from a Haskeller would be the zipwith mentioned in another answer above. zipWith is a very typical approach and I believe Python can mimic the zipping approach of combining functions and an indexer which can be mapped.


答:
First off, if that's your actual schema, it appears to be over-normalized.

Hotel_Category | Categories

Hotel_HotelType | HotelTypes

Room_RoomType | RoomTypes

Hotel_Room | Room

are all candidates for being merged together by the pairing.  So instead of 8 tables you would have 4.  The double prefix on some of your tables is a hint that the normalization has been taken too far.

Practical or pragmatic normalization is always a balancing act.  In this case, I think you've gone too far down the normalization route.

Next up, performance on the relational DB side:

I need to implement a typed search for hotels, which should be able to query on name, city, country, category, hoteltype, roomprice, customtype, room custom type and roomtype or any combination of these criteria.

Apologies if this sounds pedantic, but you do have indexes in place for all of those elements, right?  If sharding is the secret sauce of web scale1, indexes are a critical first step in making sure your relational DB can scale.

1 The phrase is from a viral video parodying certain reasons in selecting database.  Just google the term, but know that it's an NSFW video.

After that, we need to look at write models & read models.

With as small as this schema is, I think that approach is overkill, especially if you don't de-normalize the schema you provided in the question.  Taking this route is just adding gasoline to an already hot fire - all that you'll have accomplished is bringing your application down more quickly due to the complexity.

That's not to say read-only views wouldn't be worth considering after you reduce the schema.  Thinking through the ways people are likely to query for rooms, you can build views by location + name, location + price, location + type, etc...

Ideally, you'll have metrics from existing use to drive which views you should build.  But it sounds like you understand the domain well enough that you can take a reasonable guess at which ones to start with.

Finally, consider a noSQL approach.  And there's a reason why I bring it up last.

If you don't attempt any of the above first, your noSQL implementation will perform significantly worse than your existing relational DB solution.  The biggest challenge will be the number of joins that you have in your queries.  While you aren't likely to have a lot of complex joins, noSQL systems run best with little to no joins in the queries.

If you reduce your schema as suggested in the first segment, then you may have a decent chance at migrating to noSQL.  I would probably collapse Hotel, Country, Room, and Room_Type into one table though.  That would leave simple joins from there against Hotel_Category and Hotel_Type, but I'm assuming that those two tables are used less often when finding rooms.

Along with collapsing the schema, you'll need to index against the major elements that you want to search against.  Perhaps even more so than relational DBs, the noSQL approach relies heavily upon the prebuilt index in order to find the information you need quickly.

Bootnotes:

As far as which would be faster (relational vs. noSQL), I really don't know and I don't think anyone could know until you've spent some time building and tuning both.  Work on one doesn't apply to the other, so you have to double your effort in order to truly answer that part of your question.  If you're already invested on the relational side, I don't see anything compelling within your question to switch to noSQL.

Fuzzy search can be a challenge regardless of underlying database type.  The best thing you can do here is look at the options provided by the platform you pick and start trying to implement fuzzy search.  Profile that; keep revising; and see where your iterations take you.


问:
How to mock method with hard coded object?
I am working on an application which have multiple layers. Data access layer to retrieve and save data from data source, business logic to manipulate data, user interface to show the data on screen.

I also doing unit testing of the business logic layer. The only requirement is to test the flow of business layer logic. So I use Moq framework to mock the data access layer and unit test the business logic layer with MS Unit.

I am using interface programming to make the design decouple as much as possible so that unit test can be done. Business layer call data access layer through interface.

I am facing a problem when I am trying to test one of the business logic method. That method does some work and create an object and pass it to data access layer. When I am trying to mock that data access layer method then it can not successfully mock.

Here I am trying to create a demo code to show my problem.

Model:

```<code>public class Employee
{
    public string Name { get; set; }
}
</code>```

Data access layer:

```<code>public interface IDal
{
    string GetMessage(Employee emp);
}

public class Dal : IDal
{
    public string GetMessage(Employee emp)
    {
        // Doing some data source access work...

        return string.Format("Hello {0}", emp.Name);
    }
}
</code>```

Business logic layer:

```<code>public interface IBll
{
    string GetMessage();
}

public class Bll : IBll
{
    private readonly IDal _dal;

    public Bll(IDal dal)
    {
        _dal = dal;
    }

    public string GetMessage()
    {
        // Object creating inside business logic method.
        Employee emp = new Employee();

        string msg = _dal.GetMessage(emp);
        return msg;
    }
}
</code>```

Unit test:

```<code>[TestMethod]
    public void Is_GetMessage_Return_Proper_Result()
    {
        // Arrange.
        Employee emp = new Employee; // New object.

        Mock<IDal> mockDal = new Mock<IDal>();
        mockDal.Setup(d => d.GetMessage(emp)).Returns("Hello " + emp.Name);

        IBll bll = new Bll(mockDal.Object);

        // Act.

        // This will create another employee object inside the
        // business logic method, which is different from the
        // object which I have sent at the time of mocking.
        string msg = bll.GetMessage();

        // Assert.
        Assert.AreEqual("Hello arnab", msg);
    }
</code>```

In unit test case at the time of mocking I am sending an Employee object but when invoking the business logic method, it is creating different Employee object inside the method. That is why I can not mock the object.

In that case how to design so that I can solve the problem?

答:
Its a failing of some testing tools, you must always use interfaces and everything must be created in a way that allows you to swap out the interface-based object for another one.

However, there are better tools - take Microsoft Fakes (was called Moles) that allows you to swap out any object, even static and global ones. It takes a more low-level approach to replacing objects so you don't have to use interfaces everywhere whilst still keeping the way of writing tests that you're used to.


答:
We handle it via a status field.  Products can be active, inactive, backordered, advance_sale, superseded, or discontinued. Only active, advance_sale and backordered products are displayed to the user.

What to do if the state changes during a transaction is a business requirement.  Some sellers might want the customer notified and the item removed from the cart.  Some might allow customers with the item in their cart to check out, but the item can't appear on new orders. We have a per-store product eligibility verifier that checks the products in a customer's cart whenever a cart activity occurs (add/remove item, change quantity, start checkout). If you support wish lists or recurring orders, be sure your solution takes those into account as well.

Title: eCommerce use case: removing a product


问:
To load or not to load data for unit tests from external files
When unit testing I often find myself debating how much of the data I feed to, and expect back from my units under test, I should include in the actual test files.

The tradeoff I constantly struggling with is:

If a large portion of the test (in code volume) consists of input and output data, it seems difficult to actually read the test, but I can easily see the actual in-and outputs.

If I load the test data from files, I can easily test a bunch of variations on possible data input, easily reuse test data for multiple tests, but I have to leave the source code to look at another file to see what exactly the inputs are.

Is either one of these an anti-pattern?

答:
To answer your question directly - no, I don't believe either is an anti-pattern when used correctly.

--- More verbose answer ---

From my experience, I think this depends heavily on the goal of your test. Here's the rule of thumb I've used in the past and it's helped me decide:

Are you actually testing a small unit of code? (A true unit test)

If yes, then I've found it's much easier to create the data inside the test itself exactly because I can see what is being passed in. In these cases, I will usually look for a Jasmine-like library to use because I find that it makes creating and maintaining the test data easier. That's a personal preference though - use whatever makes your job easier.

If no, then you're probably actually testing the system itself. In these cases, I often do load data from an external source, the reasons here being:

This test isn't about code clarity for programmers (although that is still important - someone has to maintain this), it's about running enough different types of data through the entire chunk of the system to be reasonably sure it works.

Often I will write the plumbing code to load and use the test data, but the data itself is created by someone else (usually a QA staff member in my case). These people aren't usually programmers so I can't expect them to be editing code.

So long answer short, it depends on what you're testing and why. Both approaches are useful and have their place - choose what works best for your situation.


问:
Why is the following naming guideline different between OO and non-OO languages?
I am working with a non-OO language and I'm trying to name my routines consistently. I came acrross the following guideline from Steve McConnell's Code Complete:

To name a procedure, use a strong verb followed by an object

McConnell gives the following good and bad examples:

good, non-OO --> PrintDocument(doc)

good, OO -->       doc.Print()

bad, OO -->          doc.PrintDocument()

For an OO language, doc.PrintDocument() is non-recommended on the basis that it is redundant.

I'm having a hard time wrapping my head around this guideline. Why is PrintDocument(doc)recommended, and doc.PrintDocument() non-recommended?

Also, what would be the problem with the simpler name Print(doc) in a non-OO language?

Am I missing something very basic here?

答:
If I read "Print(doc)" my first instinct would be to assume that the function that called prints the contents of doc to the console.

PrintDocument on the other hand gives the impression that the document gets actually printed by the printer.


问:
How to Name Different Branches with Identical Functionality in Semantic Versioning
For a software, I have two different branches, that only differ in using different library versions of a package, that my software uses. The API of this library has changed between the versions in a non-compatible way.

I am currently developping using both versions with the identical functionality in different branches, the only difference exists during building and loading of shared libraries.

Should I release these packages with different version names using Semantic Versioning? In my opinion, yes, but what about the naming of these different versions?

Currently I am using the "normal" numbering using the new version of the third-party library, e.g. 1.0.0, and a suffix for the version using the older third-party library, e.g. 1.0.0-json-c-0.10, see https://github.com/residuum/PuRestJson/releases

答:
There are two cases:

If you are sure that you will never release a backwards-incompatible version of the older dependency library, and if the implied reduced visibility of the older dependency version does not bother you => use 1.x for the older, 2.x for the newer;

All other cases: use a different package name, do not disambiguate by version;

However, if I was confronted with such an issue, I would refactor the code to a "provider-based" model, where the client code calls into an abstract provider, and I would provide "provider implementations" both for the old, and the new versions of the dependencies. That is the model that is used by JDBC or ADO.NET for example, in order to support any kind of SQL database. Of course, it is more work, but if you have both customers that need the older dependency and other customers that need the newer dependency, that is in my opinion the more rational way to handle and support that.


答:
Horner's method is probably more computationally efficient as @delnan points out, but I would call this pretty readable in Python for the exponentiation solution:</p>

```<code>def eval_poly(poly, x):
    return sum( [a * x**i for i,a in enumerate(poly)] )
</code>```

Body:
Horner's method is probably more computationally efficient as @delnan points out, but I would call this pretty readable in Python for the exponentiation solution:

def eval_poly(poly, x):
    return sum( [a * x**i for i,a in enumerate(poly)] )


问:
Design for migrating to Multitenant architecture
We are in a process of redesigning our product code in such a way so as to support multitenancy.

Currently the implementation is such that one product deployment caters to only one customer.

Thus the application data corresponds to only one customer. This data (which is global  wrt the application) is in the form of hashtables, lists and DB. Multiple threads make use of this data. The complete code is written in C.

Now, since we want to migrate to multitenant architecture, the application code would need to store data for multiple customers. Since data stored in the application should be segregated wrt customers, I want to figure out what kind of architecture would best suit this requirement. I am thinking of adopting some OOP concepts here since I can use C++ also. But not sure how good this idea would be. Modularity is a prime advantage that OOP offers over C and hence thinking on those lines. But at the same time it is going to have a humongous on the current implementation requiring lots of changes. Hence, minimizing this is also important.

What would be the best approach to attain all the objectives mentioned above? Is there any other way to do this?

答:
Bubble bursting: Moving to a multitenant architecture is an orthogonal aspect to utilizing OOP within your code.  Yes, you'll need to update your application code, but you don't necessarily need to change the overall style of your programming.

And now, for an actual answer:

There are three broad approaches to moving to a multi-tenant environment.  I think you want the blended approach to solve your problem.  It represents the best balance between system administrative overhead; additional code to be written; and database maintenance.

The blended approach is to use a single, shared schema that has authorization checks to control access to the data.

The easiest way to get this blended multitenancy is to add a column representing ownership to the various database tables that need access control.  You'll also need to create a permissions table if you don't already have one that links users or groups to database owner IDs that they are allowed to access.

Within your application, your queries will need to be updated to reflect access restrictions.  If you already have a security / authorization layer this should be fairly easy to add in.  If not, try to find the point within your application that's closest to querying the database and add the checks there.  This is where having a data access layer of some sort will really make your life a lot easier.

If you were smart enough to use stored procedures, then it's even easier for you to modify the queries.  Your application is already treating the stored procs as an abstract interface, so adding authorization controls will be transparent to the application.

Another option is to create views based upon the clients.  It gets a bit trickier to make this work, but you could have a similar permissions table that indicates what views a user or group is allowed to access.  At run time, or perhaps through some sort of configuration that you control, queries are told which views they are allowed to go against.

When you write data to the database, you need to make sure that ownership is recorded along with the data.  It's a similar programmatic challenge as the querying, but I would encourage you to assign ownership to a client group ID instead of to an individual user.  The exception would be if you have a generic user representing the client's business.

If you don't have constructs within your database schema to organize the data within objects that can be assigned to a client, consider creating that.  Instead of having a bazillion rows of data that ClientA can access, there are a bazillion rows of data belonging to ObjectA that ClientA happens to own.  Abstracting out the ownership to an object can simplify some of the access queries when you have a complex number of objects within the system.

Surprisingly, that's about it for moving to a multi-tenant environment.  Obviously, the pain is in the details.  I recommend having unit and integration tests in place to validate that the security mechanisms are operating as you expect.

Regarding OOP & modularity - your general thoughts are on track.  But keep in mind that you can use OO principles within a structured language like C.  It takes more governance to maintain that code style, but you can gain some of the benefits of modularity that you are looking for.

If you don't already have a data access layer, now is the time to consider putting one into place.  Having a DAL will help promote Encapsulating that logic within one area and decoupling DB access from the rest of the application.  Implementing those principles will make future changes easier to accomplish.

There are other approaches to multi-tenancy such as having a full DB schema per client within a single the DBMS.  Having multiple schemas bypasses some of the authorization / ownership changes that you would have to make.  But the downside is this approach can require a much bigger DBMS server.

Another option is that you can have a full DBMS per client in order to segregate the data.  Again, you bypass some of the security changes but you have to maintain more servers.  Referential integrity between the schemas becomes an issue with this option.

However, the context of your question implied you were looking for a multi-tenant with a shared DB so I didn't go into those approaches.


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
Control structures as functions.

I want for, if, else, while, etc to be functions, not special structures.

I want return, try/except and goto to be derivatives of continuations.

This of course has less to do with a particular control structure and more to do with how you see control structures in general, the meta of control structures.

ContentLicense: CC BY-SA 2.5


问:
Programming beginner: Options for small program interfaces?
I have been a Rails developer for a year now, and I really want to start diving in to Ruby and pure programming without using a framework. However I am having trouble conceptualizing little programs I can build on my own. I guess it's because I'm so used to having a GUI (the web browser) to interact with the classes that I write that I don't really get how I would interact with classes without clicking, going to different pages, etc.

In terms of pure Ruby (without Rails), I've only built a blackjack game you play through the console through typing Y/N for hitting and staying. I would like to know what types of interfaces you guys use for your small programs? Are they all just ran once from your console using something like ruby myclass.rb? I have the motivation but I don't know what I would do after writing a few classes. All I do is have a separate file that requires all my other classes, instantiate my classes like so:

```<code>myclass = MyClass.new
myclass.part = ClassPart.new(1,2,3)
myclass.do_something # puts "value of instance_variable = #{@instance_variable}"
</code>```

And then what? The program finishes. It's not interactive. It doesn't do much. I don't see myself building anything cool/powerful like that. Can anyone enlighten me?

答:
There are many ways you can run a program and do 'something'(obviously). Since you come from Rails one simple alternative would be to write a web service that takes a few params and returns simple json. That way you could somehow stop thinking about minor details of rendering and displaying results.

Next option would be to read some text from the commandline and simply output text as result. There have been many Basic games of this kind around back in the 80s. That's still a nice way to learn those simple things.

Or just solve some of the Project Euler problems. Those normally require a script with no special input (some read data from files) and get a single number as result that you just print on the screen. Many Code Katas and similar small code challenges work this way.

Btw: even in real live you often write such scripts. A large part of my current Rails project are various scripts for importing/exporting and processing data. (Not your average Rails project)

And then there is of course the option to go 'full GUI'. There are several toolkits and libraries for that. Maybe write a simple game or whatever you like.


问:
Frontend vs Backend data handling
Firstly I would like an answer from an experienced person (not a one man band), someone whom has worked in a medium/large team and had to battle with this burning question before.

The problem:
I am constantly being asked to not submit empty rows

by rows = I mean a list of items and properties.

A good example would be, multiple file uploads.

```<code><form>
    <input type="text" name="pic[0][label]" />
    <input type="file" name="pic[0][file]" />

    <input type="text" name="pic[1][label]" />
    <input type="file" name="pic[1][file]" />

    <input type="text" name="pic[2][label]" />
    <input type="file" name="pic[2][file]" />
    <input type="submit" value="Upload" />
</form>
</code>```

The requirement states:

As a user I should be presented with fields 3 (three) upload fields.

For each field there should be a corresponding title/name/label

There should be a "Add more" button, to allow me (the user) to add more images.

The reason for the requirement above is user experience. (Less clicks are required)

The Backend argument

Submitting empty rows (to the server) is "error prone" or is seen as a "validation corner"

The Front-end argument

Backend should not dictate what the FE can/cannot do.

JavaScript is very volatile and should not manage/validate whether empty rows should be sent or not

The question

if the user:

Enters 1 (one) title/label

Selects 1 (one) image from his/her local PC

Clicks Upload

Leaves the last 2 (two) upload fields empty.

So in your opinion/experience with this kind of problem. Should the front end send empty rows or data to the server or not?

答:
We did something similar several times. We ended up using javascript to add the rows dynamically at to the browser.

The HTML for a row is defined in a javascript variable. When clicking on your "Add new row" button you simply add the html to the dom (by replacing the IDs of the controls).

Then we used AJAX to send the rows to the server. You can simply select all rows when collecting the data to send, by applying a class on them.

You can view a version of this (which I coded) here:

http://carbocount.wikidot.com/project:products:visualization

You can dynamically add new sensors on the fly by clicking on the "+"

Advantages of adding the rows on the frontEnd:

No postback needed

Faster performance

No empty rows get commited

Advantages of adding the rows on the BackEnd:

Easier coding as you can add it right to the HTML code

Javascript independent solution

OwnerDisplayName: Val

Title: Frontend vs Backend data handling

OwnerDisplayName: RononDex