问:
What is the difference between PHP and ASP.NET Web Forms in page size?
I plan to program web applications for small companies. When I read about ASP.NET Web Forms, I liked its way of building dynamic sites.

However, I have heard from a friend that Web Forms could increase the size of the pages because of ViewState output. Will the difference between the size of PHP pages and the generated HTML of ASP.NET pages be dramatic?

答:
If you use ASP.NET WebForms, there are indeed a couple of aspects that will enlarge your HTML. They can be mitigated to an extent, some more easily than others, and improvements have been made particularly in .NET 4.0.

As you say, there is the hidden __VIEWSTATE element which WebForms uses to maintain the illusion of statefulness. This is turned on by default, and if don't touch it, it can easily add a lot of unnecessary weight to a page with a lot of controls. If you're not actually using it, though, you can turn it off on a page or a control with EnableViewState="False".

If you use the more featureful Web Forms controls, you can do some rather rapid development, but you can also produce a lot of generated HTML which isn't really under your control, and could well be a lot bigger than is necessary for the subset of functionality that you need. In my Web Forms days, I found that a lot of developers (myself included) shied away from the more powerful controls because it always felt like it saved you time in the beginning but ended up costing you more time later on, as you fought with it to get the precise result you needed.

If you architect your pages in an easy-to-maintain fashion, with master pages, pages, and various user controls, you'll find that Web Forms' name-mangling of IDs (to guarantee uniqueness) will lead to some rather long IDs on HTML elements, thing like id="ctl00_AGSMasthead_imgSkipContent". This has been improved in .NET 4.0 - you can use the new ClientIDMode="Static" property to tell Web Forms that it does not need to mangle the ID, you'll maintain uniqueness yourself.

Because Web Forms uses the ID of a control to refer to that control in server-side code and as the ID of the element in the rendered HTML, it often leads to you having a lot of HTML elements with IDs that are never used client-side by CSS or JavaScript, and are just wasted space. This is one of my main dislikes of Web Forms, by the way. You do something like <asp:Label Id="lblName" Runat="Server"/> so you can populate a label in the code-behind, and it gets served up as  - or in the old days, more likely, something like . So unnecessary, personally I wish that instead of the Runat="Server" attribute, they had designed something along the lines of ServerID="lblName" which both identified a control as being server-side and assigned a server-side ID which was separate to the client-side ID (if any).

Ultimately, you can work around most of this to some extent, but if you use Web Forms in the fashion in which it is designed to be used, you will get some weight added to the HTML you serve which is not strictly necessary.

However, I think that the difference in weight between a Web Forms page and a page produced by some other platform and framework is probably less than the difference between a poorly coded page and a well coded one which makes good use of clean semantic markup, minimizes unnecessary tags and attributes, uses clean unobtrusive JavaScript, etc.

Body:
If you use ASP.NET WebForms, there are indeed a couple of aspects that will enlarge your HTML. They can be mitigated to an extent, some more easily than others, and improvements have been made particularly in .NET 4.0.

As you say, there is the hidden __VIEWSTATE element which WebForms uses to maintain the illusion of statefulness. This is turned on by default, and if don't touch it, it can easily add a lot of unnecessary weight to a page with a lot of controls. If you're not actually using it, though, you can turn it off on a page or a control with EnableViewState="False".

If you use the more featureful Web Forms controls, you can do some rather rapid development, but you can also produce a lot of generated HTML which isn't really under your control, and could well be a lot bigger than is necessary for the subset of functionality that you need. In my Web Forms days, I found that a lot of developers (myself included) shied away from the more powerful controls because it always felt like it saved you time in the beginning but ended up costing you more time later on, as you fought with it to get the precise result you needed.

If you architect your pages in an easy-to-maintain fashion, with master pages, pages, and various user controls, you'll find that Web Forms' name-mangling of IDs (to guarantee uniqueness) will lead to some rather long IDs on HTML elements, thing like id="ctl00_AGSMasthead_imgSkipContent". This has been improved in .NET 4.0 - you can use the new ClientIDMode="Static" property to tell Web Forms that it does not need to mangle the ID, you'll maintain uniqueness yourself.

Because Web Forms uses the ID of a control to refer to that control in server-side code and as the ID of the element in the rendered HTML, it often leads to you having a lot of HTML elements with IDs that are never used client-side by CSS or JavaScript, and are just wasted space. This is one of my main dislikes of Web Forms, by the way. You do something like <asp:Label Id="lblName" Runat="Server"/> so you can populate a label in the code-behind, and it gets served up as <span id="lblName"> - or in the old days, more likely, something like <span id="ctl00_ucHeader_lblName">. So unnecessary, personally I wish that instead of the Runat="Server" attribute, they had designed something along the lines of ServerID="lblName" which both identified a control as being server-side and assigned a server-side ID which was separate to the client-side ID (if any).

Ultimately, you can work around most of this to some extent, but if you use Web Forms in the fashion in which it is designed to be used, you will get some weight added to the HTML you serve which is not strictly necessary.

However, I think that the difference in weight between a Web Forms page and a page produced by some other platform and framework is probably less than the difference between a poorly coded page and a well coded one which makes good use of clean semantic markup, minimizes unnecessary tags and attributes, uses clean unobtrusive JavaScript, etc.


问:
What discipline does Computer Science belong to?
Is Computer Science science, applied mathematics, engineering, art, philosophy? "Other"?

To provide background, here is Steven Wartik's blog posting for Scientific American titled "I'm not a real scientist, and that's okay." The article covers some good topics for this question, but it leaves open more than it answers.

If you can think of the discipline, how would computer science fit into its definition? Should the discipline for Computer Science be based on what programmers do, or what academics do? What kind of answers do you get from people who've seemed to think deeply about this? What reasons do they give?

答:
Computer Science is a term which these days cover many, many things:

The master craftsmen doing work for others based on their experiences with their tools (and having apprentices etc).

The tool smiths inventing and creating new tools for the craftsmen

The researchers developing new alloys and other materials - like plastic - for the tool smiths.

The theoretical scientists figuring out how stuff works so the alloymakers know how their tools work.

Note how all the above have distinct naming instead of just "computer scientists".  The difference is just that Computer Science is too new for naming to settle.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


答:
ASP.NET as you have indicated does use the ViewState. First of all I'm going to briefly explain the purpose of the ViewState and why it is there.

What is the ViewState

In a nutshell, the purpose of the ViewState is to preserve the value of form fields between postbacks. From that statement, you can infer then that the more fields you have, the larger your ViewState is going to be.

In addition to preserving the value of form fields between postbacks, you can also store arbitrary data inside of the ViewState, by using ViewState[key] = value.

You can, however, disable the ViewState, either on a page level or element level where it is not appropriate to use. This can also save space in the ViewState.

How

The ViewState is stored as a hidden form element that is posted to the server when you submit the page. The following diagram demonstrates the key points in ViewState processing:

(source: microsoft.com)

The key points here are LoadViewState and SaveViewState. LoadViewState loads the data posted to the server, where SaveViewState serialises it for storage in the ViewState after page events have been processed.

Advantages

The primary advantage of using the ViewState is to persist data between page loads. For example, when the page is first loaded fields may be populated with the results of, for example, a long running database query. Subsequent loads can use the values in the ViewState to save re-executing that query.

Relation to ASP.NET MVC

ViewState is not at all relevant to ASP.NET MVC and is a component of ASP.NET Web Forms.

Equivalent in PHP?

There is no equivalent in PHP. You could manually implement the functionality if you so desired by serialising for example your model and reloading it on POST.

Do you have to use the ViewState

No, you don't. If you turn it off, your page output size will decrease but you will also need to factor in the overhead of reloading data.

TL;DR and to the question

Will the difference between the size of PHP pages and the generated HTML of ASP.NET pages be dramatic?. The answer is it depends on what you are outputting. If you are making massive forms and particularly if you're making use of controls such as Asp:DataTable then yes, your output could be significantly larger. I've seen ViewStates grow to over 1mb. You need to bare in mind that on each submit, the entire ViewState has to be uploaded to the web server. If you're producing small and simple forms, the size difference is going to be negligible. YMMV depending on what it is exactly that you're doing.

The other thing to bare in mind is that in PHP you have a lot more control over the generated markup than what you do with WebForms.

ContentLicense: CC BY-SA 3.0

Title: What is the difference between PHP and ASP.NET Web Forms in page size?

Body:
I plan to program web applications for small companies. When I read about ASP.NET Web Forms, I liked its way of building dynamic sites.

However, I have heard from a friend that Web Forms could increase the size of the pages because of ViewState output. Will the difference between the size of PHP pages and the generated HTML of ASP.NET pages be dramatic?


问:
Why is the usage of string keys generally considered to be a bad idea?
This has been bugging me for a while. Most of the time, when it comes to storing data in structures such as hashtables, programmers, books and articles insist that indexing elements in said structures by String values is considered to be bad practice.
Yet, so far, I have not found a single such source to also explain WHY it is considered to be bad practice.
Does it depend on the programming language? On the underlying framework? On the implementation?

Take two simple examples, if it helps:

An SQL-like table where rows are indexed by a String primary key.

A .NET Dictionary where the keys are Strings.

答:
There are many tradeoffs here.  Actually I use string keys frequently, but often I include surrogate secondary keys for joins (obviously it would be the other way around if I was using MySQL).  There are cases where I don't however.

First I am a fan of declaring natural keys as the primary key where the db can handle this well (PostgreSQL for example).  This helps with normalization and makes for clearer database design.  Surrogate keys make joining easier.

There are two reasons I usually add surrogate keys:

It isn't always clear what a natural key is.  Sometimes these have to be changed.  Changing a natural, composite key when it is used for joins and referential integrity is complicated and error prone.

Join performance on composite keys is problematic and once you go down the natural key route, you get stuck there.

In cases where a natural key is definitional, single column, and text, however, I usually join on the string key.  My reason for doing so is that this often avoids joins on lookup.  The most common use is providing proper db design around the use case of enum types.  In most cases, these do not require the extra join for routine queries.  So where this is the case, string keys as join keys makes perfect sense.

For example in LedgerSMB, we store account categorizations.   These are identifed by string reference.and some other data is stored with the string reference which is used to enforce rules regarding the combinations of categorizations that can affect an account.  The only time that logic is needed is when saving a set of categorizations, so we join on the string key.

As to why the default would be integer keys, I don't think it's just a question of index size.  A big issue is management of keys.  Since the key is arbitrary and you may be dealing with millions of records, you have to have a way of generating unique strings.  There are cases where people use UUIDs for this, but there is a non-zero chance of UUID collision, and where billions of records are stored, this chance becomes high enough one might actually see while the chance of collision with incremented integer types is zero by definition.


答: There are a number of potential issues with using strings as keys, especially when it comes to sql-like tables.  As mentioned by @bunny, the indexes for your tables are going to be bigger, but I think more significantly, any foreign key relationships to the table will involve BOTH tables to have contain the string as opposed to a lighter-weight (integer) identifier.  If you find that there are even more tables with references to the first, the string keys will be proliferated throughout your database.</p>

Title: Why is the usage of string keys generally considered to be a bad idea?

Body:
This has been bugging me for a while. Most of the time, when it comes to storing data in structures such as hashtables, programmers, books and articles insist that indexing elements in said structures by String values is considered to be bad practice.
Yet, so far, I have not found a single such source to also explain WHY it is considered to be bad practice.
Does it depend on the programming language? On the underlying framework? On the implementation?

Take two simple examples, if it helps:

An SQL-like table where rows are indexed by a String primary key.

A .NET Dictionary where the keys are Strings.


问:
Is it worthwhile to try to write foolproof data structures?

The problem

We need to store data in a table-like way, but we have very strict space constraints (~1Mb per table of 10k+ rows). We store data like this:

```<code>ID | reviews | factor | score | interval | etc.
---+---------+--------+-------+----------+-----
 1 |     244 |    2.4 |    10 |     4268 | ...
</code>```

in a simple binary format (a one-dimensional array of bytes, where the index of each row can be calculated simply by knowing the length of each row, which is fixed).

There is only one function that ever reads this data (gets a row by its index), and only one function that appends a new row (to the end). Removing items from the table will never be required (the table is append-only). Both functions are covered with a decent amount of unit tests.

The problem is the following: we need to be able to quickly go through rows ordered by different columns. In other words, we need the data to be sorted by at least two columns.

A simple solution

To solve this problem, we would implement indexes that, again, would be chunks of binary data. Now I would intuitively do it by creating ordered data structures that only list the index of the row in the original table:

```<code>factor_index        score_index
------------        -----------
          6                  2
          2                  1
          3                  6
          1                  4
          .                  .
</code>```

The function that appends a new row to the table would have to be updated to cause the indexes to be updated as well.

EXAMPLE: To get the first item ordered by score, we just look up the first value in the index table for score (2) and get the corresponding row from the original table (the third row if we agree that the table is zero-indexed).

However, I was suggested to take a different approach.

A more complex but presumably safer version

Instead of of only storing the indexes, we duplicate the ID fields in each index table:

```<code>factor_index | ID        score_index | ID
-------------+---        ------------+---
          6  | 46                  2 |  8
          2  |  8                  1 | 14
          3  | 91                  6 | 46
          1  | 14                  4 | 60
          .  |  .                  . |  .
</code>```

Then keep the original table sorted by ID, and use the indexes only as a starting position for a binary search in the original table.

The function that appends a new record will now have to do a binary search by ID to find where to insert the new row, and cause the indexes to be updated.

EXAMPLE: To get the first item ordered by score, we look up the first row in the index table for score (2, 8), and use the index (2) as a starting position for a binary search in the table. If the data is valid, we don't even need to do a binary search, because at position 2 we will find the row with ID 8. If, however, we find that the record at position 2 has a different index, we continue with a binary search to find the right one, and log the error.

The argument for this approach is that it will work even if the index points to the wrong row in the table.

I find it hard to believe though that this approach is really better, for the following reasons:

It requires a binary search, which can be a new source of bugs.

It requires the table to be kept in order, which implies more complex insert (as opposed to a simple append).

It does not guard against the main table being out of order: if that happens, the index could even fail to find the record via binary search.

It requires writing (and testing) code that is never even meant to be run.

It uses more data than what is necessary.

The question

It is very high priority for our application that the above piece of data is always valid. But does that justify writing more complex data structures and lookup mechanisms to guard against edge cases which may or may not happen? Shouldn't the time and effort instead be put in writing more robust test cases for a simpler version?

答:
If data validity is critical, then any transformation to the data must take the data transformed from a valid state to a valid state.  The transformation mechanisms should ensure validity of output given valid input.  An unsuccessful transformation should fail safely, leaving the data in a valid state.

Unit testing can only ensure that the transformation is valid under each condition you thought of while writing the tests.  Building consistency into all data transformation methods ensures that the data remains valid under all possible conditions.

So, if data validity is a high priority, I suggest you build data modification methods that are always valid, and test them thoroughly.  Don't trust consistency to coincidence.


问:
What is the functional-programming alternative to an interface?
If I want to program in a "functional" style, with what would I replace an interface?

```<code>interface IFace
{
   string Name { get; set; }
   int Id { get; }
}
class Foo : IFace { ... }
</code>```

Maybe a Tuple<>?

```<code>Tuple<Func<string> /*get_Name*/, Action<String> /*set_Name*/, Func<int> /*get_Id*/> Foo;
</code>```

The only reason I'm using an interface in the first place is because I want always want certain properties/methods available.

Edit: Some more detail about what I'm thinking/attempting.

Say, I've got a method which takes three functions:

```<code>static class Blarf
{
   public static void DoSomething(Func<string> getName, Action<string> setName, Func<int> getId);
}
</code>```

With an instance of Bar I can use this method:

```<code>class Bar
{
   public string GetName();
   public void SetName(string value);

   public int GetId();
}
...
var bar = new Bar();
Blarf.DoSomething(bar.GetName, bar.SetName, bar.GetId);
</code>```

But that's a bit of a pain as I have to mention bar three times in a single call.  Plus, I don't really intend for callers to supply functions from different instances

```<code>Blarf.DoSomething(bar1.GetName, bar2.SetName, bar3.GetId); // NO!
</code>```

In C#, an interface is one way to deal with this; but that seems like a very object-oriented approach.  I'm wondering if there's a more functional solution: 1) pass the group of functions together, and 2) ensure the functions are properly related to each other.

答: Haskell and it's derivatives have typeclasses which are similar to interfaces. Though it sounds like you're asking about how to do encapsulation, which is a question regarding type systems. The hindley Milner type system is common in functional languages, and it has data types that do this for you in varying fashion across languages.</p>


问:
What are you thoughts on GWT?
Since I'm learning Java in this period and I just finished with the tutorials I think I'm ready to start contributing to a project (since I know from experience this is the best way to really learn).

I've seen GWT, looks interesting so I thought I should give it a try. I'm thinking however, since GWT deploys Java applications in JavaScript why should I learn GWT when I could learn the actual thing instead (this being JavaScript).
My question: is it worth it? Wouldn't someone be better of learning JavaScript if they want to build JS applications, instead of using Java and GWT? I realize that it might be easier to build certain things with GWT but in the end is it worth it?

Thanks.

答:
GWT is essentially a compiler to native code, much like Visual Studio compiles source to byte codes or machine language.

This allows the programmer to abstract the differences in underlying architecture away, much like Visual Studio users not needing to worry about the differences in word length, the number of registers and exact conventions for calling the operating system when they code for 32-bit or 64-bit.

This is a good thing, as it allows you to move some of the maintainance burden over to others.  As this is Google you know they have more development resources than you have, so you are essentially bringing in extra manpower for free.

OwnerDisplayName: Anonymous Coward

Title: What are you thoughts on GWT?


答:
There are a few ways to allow a function to deal with multiple inputs.

First and most common: Parametric Polymorphism.

This lets a function act on arbitrary types:

--Haskell Example
id :: a -> a --Here 'a' is just some arbitrary type
id myRandomThing = myRandomThing

head :: [a] -> a
head (listItem:list) = listItem
```

<p>Which is nice, but doesn't give you the dynamic dispatch that OO interfaces have. For this Haskell has typeclasses, Scala has implicits, etc</p>

<pre class="lang-hs prettyprint-override"><code>class Addable a where
   (<+>) :: a -> a -> a
instance Addable Int where
   a <+> b = a + b
instance Addable [a] where
   a <+> b = a ++ b

--Now we can get that do something similar to OO (kinda...)
addStuff :: (Addable a) => [a] -> a
-- Notice how we limit 'a' here to be something Addable
addStuff (x:[]) = x
addStuff (x:xs) = x <+> addStuff xs
-- In better Haskell form
addStuff' = foldl1 <+>
</code>```

Between these two mechanisms, You can express all sorts of complex and interesting behaviors on you're types.

Title: What is the functional-programming alternative to an interface?

Body:
If I want to program in a "functional" style, with what would I replace an interface?

```<code>interface IFace
{
   string Name { get; set; }
   int Id { get; }
}
class Foo : IFace { ... }
</code>```

Maybe a Tuple<>?

```<code>Tuple<Func<string> /*get_Name*/, Action<String> /*set_Name*/, Func<int> /*get_Id*/> Foo;
</code>```

The only reason I'm using an interface in the first place is because I want always want certain properties/methods available.

Edit: Some more detail about what I'm thinking/attempting.

Say, I've got a method which takes three functions:

```<code>static class Blarf
{
   public static void DoSomething(Func<string> getName, Action<string> setName, Func<int> getId);
}
</code>```

With an instance of Bar I can use this method:

```<code>class Bar
{
   public string GetName();
   public void SetName(string value);

   public int GetId();
}
...
var bar = new Bar();
Blarf.DoSomething(bar.GetName, bar.SetName, bar.GetId);
</code>```

But that's a bit of a pain as I have to mention bar three times in a single call.  Plus, I don't really intend for callers to supply functions from different instances

```<code>Blarf.DoSomething(bar1.GetName, bar2.SetName, bar3.GetId); // NO!
</code>```

In C#, an interface is one way to deal with this; but that seems like a very object-oriented approach.  I'm wondering if there's a more functional solution: 1) pass the group of functions together, and 2) ensure the functions are properly related to each other.

Body:
There are a few ways to allow a function to deal with multiple inputs.

First and most common: Parametric Polymorphism.

This lets a function act on arbitrary types:

--Haskell Example
id :: a -> a --Here 'a' is just some arbitrary type
id myRandomThing = myRandomThing

head :: [a] -> a
head (listItem:list) = listItem

Which is nice, but doesn't give you the dynamic dispatch that OO interfaces have. For this Haskell has typeclasses, Scala has implicits, etc

class Addable a where
   (<+>) :: a -> a -> a
instance Addable Int where
   a <+> b = a + b
instance Addable [a] where
   a <+> b = a ++ b

--Now we can get that do something similar to OO (kinda...)
addStuff :: (Addable a) => [a] -> a
-- Notice how we limit 'a' here to be something Addable
addStuff (x:[]) = x
addStuff (x:xs) = x <+> addStuff xs
-- In better Haskell form
addStuff' = foldl1 <+>

Between these two mechanisms, You can express all sorts of complex and interesting behaviors on you're types.


答:
If I'm understanding your indexes correctly they aren't the most efficient way to store them.

You can't sort your table on two keys at once anyway, thus I don't think you should try to sort it at all.  Rather, sort your indexes.

10k rows--a two-byte value can refer to any entry in your table.  Thus build two arrays that are initially seeded with 1..10k (or however many entries are in your table).  While these are not pointers in the CPU's sense of the word use them as pointers anyway.  You sort both arrays based on the values in the table.

Insert is handled by simply appending the record and then rebuilding the arrays.  Yes, a fairly expensive operation but since you have specified the arrays aren't all that big and can't grow too much this shouldn't be being done too often.  Anything you do is inherently at least O(n), a full resort is only O(n log n), I would take the latter route.  (And you might even find it's faster as it involves a lot less writing to main memory than moving the records around.)

Note that these arrays are simply two-byte values, NOT key-value pairs like you seem to be indicating.

A couple of other things also come to mind--you seem unusually concerned with the data size.  That says to me that either you are transmitting these blocks (at which point the indexes can be omitted as they can be recreated on the other end) or you have a whole bunch of these in memory at once.  In the latter case if you are using a language that supports weak references you can use them--let the indexes for blocks not being actively used to get garbage collected and then recreated when they are needed.

Title: Is it worthwhile to try to write foolproof data structures?

Body:
The problem

We need to store data in a table-like way, but we have very strict space constraints (~1Mb per table of 10k+ rows). We store data like this:

```<code>ID | reviews | factor | score | interval | etc.
---+---------+--------+-------+----------+-----
 1 |     244 |    2.4 |    10 |     4268 | ...
</code>```

in a simple binary format (a one-dimensional array of bytes, where the index of each row can be calculated simply by knowing the length of each row, which is fixed).

There is only one function that ever reads this data (gets a row by its index), and only one function that appends a new row (to the end). Removing items from the table will never be required (the table is append-only). Both functions are covered with a decent amount of unit tests.

The problem is the following: we need to be able to quickly go through rows ordered by different columns. In other words, we need the data to be sorted by at least two columns.

A simple solution

To solve this problem, we would implement indexes that, again, would be chunks of binary data. Now I would intuitively do it by creating ordered data structures that only list the index of the row in the original table:

```<code>factor_index        score_index
------------        -----------
          6                  2
          2                  1
          3                  6
          1                  4
          .                  .
</code>```

The function that appends a new row to the table would have to be updated to cause the indexes to be updated as well.

EXAMPLE: To get the first item ordered by score, we just look up the first value in the index table for score (2) and get the corresponding row from the original table (the third row if we agree that the table is zero-indexed).

However, I was suggested to take a different approach.

A more complex but presumably safer version

Instead of of only storing the indexes, we duplicate the ID fields in each index table:

```<code>factor_index | ID        score_index | ID
-------------+---        ------------+---
          6  | 46                  2 |  8
          2  |  8                  1 | 14
          3  | 91                  6 | 46
          1  | 14                  4 | 60
          .  |  .                  . |  .
</code>```

Then keep the original table sorted by ID, and use the indexes only as a starting position for a binary search in the original table.

The function that appends a new record will now have to do a binary search by ID to find where to insert the new row, and cause the indexes to be updated.

EXAMPLE: To get the first item ordered by score, we look up the first row in the index table for score (2, 8), and use the index (2) as a starting position for a binary search in the table. If the data is valid, we don't even need to do a binary search, because at position 2 we will find the row with ID 8. If, however, we find that the record at position 2 has a different index, we continue with a binary search to find the right one, and log the error.

The argument for this approach is that it will work even if the index points to the wrong row in the table.

I find it hard to believe though that this approach is really better, for the following reasons:

It requires a binary search, which can be a new source of bugs.

It requires the table to be kept in order, which implies more complex insert (as opposed to a simple append).

It does not guard against the main table being out of order: if that happens, the index could even fail to find the record via binary search.

It requires writing (and testing) code that is never even meant to be run.

It uses more data than what is necessary.

The question

It is very high priority for our application that the above piece of data is always valid. But does that justify writing more complex data structures and lookup mechanisms to guard against edge cases which may or may not happen? Shouldn't the time and effort instead be put in writing more robust test cases for a simpler version?


问:
Space between negative sign and variable name
I tried doing a Google search, as well as searching this Stack Exchange site but could not find a question relating directly to this.

The PEP 8 -- Style Guide for Python Code has lots of good style recommendations, however I don't think they mention anything about whether a space between a minus or negative sign (-) and a variable name would be more or less readable.

Question

It's a (very) minor issue, but which is considered more readable?

false_positive = -true_positive

false_positive = - true_positive

Motivation

I ask not to be trivial, but because in my past math courses I often find myself not noticing the negative sign in important equations, such as the equation for computing entropy:

I often don't notice the - sign before the summation, so making it stand out would be desirable.

答:
I couldn't find anything about it in the Python style guide, as you said, but searching for "unary operator spacing" brought more hits from various languages, such as this for Javascript:

No space should separate a unary operator and its operand except when the operator is a word such as typeof.

Or this for C:

Don't use spaces around unary operators, except sizeof and casts

In the Linux kernel:

Use one space around (on each side of) most binary and ternary operators, [...] but no space after unary operators:

Note that a writing style for code, which is usually written with a fixed-width font and mostly Latin characters, is quite different than that for equations, where you can find both latin and greek letters, topological constructs such as fractions or those marks surrounding that epsilon you have there, and other things that make them a whole lot more complex than code.


答:
First, one thing one can hold against your arguments:

if one wants to use IDs the way you wrote, he surely would first implement an ID-to-row index (so ID lookups don't require the original table in a special order, and you don't have to implement a binary search on that table)

But if you think about this for a moment, you see now you just have moved your original problem to a different level - one has to make sure the ID-to-row index is not out-of-sync. Of course, the advantage now is that you can rebuild this index independently when the row order of the original table changes. This makes sense when you have to expect such changes, you know when they happen and that they happen seldom / at specific points in time.

Nevertheless, is this really worth the hassle? When you are 100% sure that the row number in your original table is a valid and immutable primary key, build the most simple possible solution, based on row numbers, everything else is more error-prone and "premature nonsens". Otherwise use IDs.

Here are some scenarios where you cannot be sure your row number is a valid primary key:

rows in a relational database can typically not be expected to have a special order

in a file-based scenario: your amount of data grows and because of your space constraints, you have to split it over several physical tables. Then the ID may be still a valid primary key, but your row number not.

Make sure you are not in such a situation when going for a row-number based approach.


问:
C++ vs Objective-C design principles of setters and getters
In C++ I was told that my classes shouldn't have getters and setters: Doing it wrong... blog post.

On the other hand, in Objective-C, the direct use of ivar is discouraged, because the getters allow to do lazy instantiation, and setters make KVO easy.

Why is that difference?

答: Setters and getters are the technology that came from visual basic properties in 1980's. Since they're often used together with the programming techniques that also come from same place, it's considered bad practise. Problem with getters and setters is that the behaviour of the class gets moved to the user of the class, and class no longer handles it's own behaviour; but supports any behaviour possible. This does not create a good class, since it's not doing the decisions that are normally part of class' responsibility.


答:
I think the best takeaway from the "Doing it wrong..." post is that exposing public accessors without a good reason breaks encapsulation by giving external classes the ability to modify and inspect state that ought not be made public. It's just expressed in an absolutist fashion (I'd argue if you have a Contact object, and want to put that contact's name on a label for an address book application, at some point Contact will probably have to expose its name to another object). Regardless, no matter what the language, making accessors available without thought is going to break encapsulation and lead to tight coupling.

This is orthogonal to the best practice in Objective-C of using accessors for all (at least most) instance variable access. No where does Objective-C recommend making all your accessors publicly visible. Often you will have a class extension visible only to the class's own implementation that defines most of its instance variables and then the class's own implementation uses the accessors. And certainly, external code should always use the accessors - but they still should only be made visible to external code if absolutely necessary.

Title: C++ vs Objective-C design principles of setters and getters

Body:
In C++ I was told that my classes shouldn't have getters and setters: Doing it wrong... blog post.

On the other hand, in Objective-C, the direct use of ivar is discouraged, because the getters allow to do lazy instantiation, and setters make KVO easy.

Why is that difference?


问:
code review with git-flow and github
With regular git and github I can do a code review by simply creating a pull request of the feature branch I'm working on to the master branch. How would I do code reviews with git-flow? With workflow like "git flow feature finish` I'm confused as to where the code review actually happens and how git-flow or git can facilitate that review.</p>

答:
We stumbled on this exact problem recently. We really like git flow, as it use a good level of semantic (using the same level that you use in team discussion : "I'll start feature A" more than "I'll create a branch, checkout it"), while git is very "implementation" level (which is good and useful also, but different).

The problem we have is with git feature finish, as it merge the branch into the develop, while we want a pull request to be sent and (this is important) merged by the reviewer, not the committer, to emphasize team ownership.

Our current solution :

Someone use git flow to create a feature branch

When done, he create a pull request (using github)

The review take place, with potential additional commits

The pull request is merged using GitHub by the reviewer.

There is not git flow feature finish (as the branch is already merged)

This is consistent with our practice, with the downside of requiring to delete the branch ourselves (as we do not git flow finish). Our next step will probably be to reimplement some parts of git flow (as it is mainly about chaining git commands) to take this into account (having the "cleaning" part of the finish, without the merge).

Title: code review with git-flow and github


问:
Can I use MIT license to give some of my previous written code to employer so that I protect myself and don't lose my copyright?
My situation:

I have written a framework before I started my new job. I own the copyright.

It has a bunch of boilerplate logic inside of it, like any piece of software. (duh!)

I don't want to use the whole framework in my new job, but I do need to re-use some parts of it in a similar framework that I am building for my new job.

It is impractical to re-implement / re-think all the logic from scratch. It is a lot of logic and logic is logic, you can't make it much different. For example, how many different versions of a HashMap can you code? I bet they will be very similar and the third version can claim that you violated the copyright of the first version. :(

It is impractical to try to re-invent the API. Can you re-invent the API of a HashMap? Maybe you can change put(k,v) to add(k,v), but not much more than that.

My idea to protect myself and my previous code:

I will tell my employer that I am building the new framework based on a previous one that I have written under the MIT license. So in the future if I use my previous framework someplace else, or even another derived version of it, that has some pieces of code similar with this new framework I am building now for the employer, they won't be able to say I am using their code, the one I wrote for them.

My questions:

I am not distributing my code to anyone. I don't have to distribute my MIT licensed code to anyone, if I own the copyright, correct? I mean, can someone request that I release my code that I now claim it is under MIT license? It would not be the end of the world and I would certainly agree to do that under a legal threat.

Does this strategy make any sense? My final goal is to be able to use a derived version of my previous coded framework without losing the copyright to it. At the same time, i do not want to distribute this code as an open-source project to anyone. I have other open-source projects, that I freely distribute, but this one I would like to keep it to myself so I can use on my jobs (not contractor jobs).

It is like claiming that you have a framework under the MIT license, without actually distributing and/or showing to anyone. If it is out there, free and easily available, my employers don't need me anymore. They can just take the code and give it to someone else to use it.

Notes:

I have listed this framework as a previous invention before I started the job.

I have not released this code anywhere. It is on my private SVN repo I host in my private server.

My idea in a nutshel:

My plan is to keep the previous code to myself, use parts of it in this new framework I am building for the employer and tell the employer it is work derived from a MIT licensed framework I have coded before and have not distributed to anyone". I am not forced to distribute a software I coded under MIT license, am I? If later, some legal claim happens (hopefully not), i can immediately paste the license on all the sources and show/release the code.

答:
Is there a specific reason you cannot ask your employer whether it is possible that you retain copyright on general code you write for your framework (which in turn gives them some free code right now), and give them an you-can-do-everything-you-want-with-it (agreed, this is quite like MIT).

However, if you license your current code MIT, there is no reason why your employer should open source their modified version (modified by you), so I'd say it does not solve much. Even LGPL would not solve this, as long as the code isn't 'distributed'.

All in all your deal doesn't sound unreasonable: you have some framework code, and  you're willing to donate them to the company, as long as you can hold on to the code, and reuse it for other projects later, so why not ask?


问:
Why does automated testing keep failing in my company?
We have tried to introduce developer automated testing several times at my company. Our QA team uses Selenium to automate UI tests, but I always wanted to introduce unit tests and integration tests. In the past, each time we tried it, everyone got excited for the first month or two. Then, several months in, people simply stop doing it.

A few observations and questions:

Does automated testing actually work? Most of of my colleagues who used to work at other companies have tried and failed to implement an automated testing strategy. I still haven't seen a real-life software company that actually uses it and doesn't just talk about it. So many developers see automated testing as something that is great in theory but doesn't work in reality. Our business team would love developers to do it even at a cost of 30% extra time (at least they say so). But developers are skeptics.

No one really knows how to properly do automated testing. Yes we have all read the unit testing examples on the internet, but using them for a big project is something else altogether. The main culprit is mocking/stubbing the database or anything else that is non-trivial. You end up spending more time mocking than writing actual tests. Then when it starts taking longer to write tests than code, that's when you give up.

Are there any good examples of unit tests/system integration tests used in a complex data centric web applications? Any open source projects? Our application is data centric but also has plenty of domain logic. I tried the repository approach at some point and found it pretty good for unit testing, but it came at the price of being able to optimize data access easily and it added another layer of complexity.

We have a big project undertaken by 20 experienced developers. This would seem to be an ideal environment to introduce unit testing/integration testing.

Why doesn't it work for us? How did you make it work at your company?

答:
One thing about automated testing is that it requires you to write code to be testable.  This is not a bad thing in and of itself (in fact it's good because it discourages a lot of practices that as a rule should be avoided), but if you're trying to apply unit testing to existing code then the chances are it's not been written in a testable way.

Things like singletons, static methods, registries, service locators and so on introduce dependencies that are very difficult to mock out.  Violations of the Law of Demeter mean that too many parts of your code base know too much about how other parts of your codebase function, introducing further hidden dependencies that can be difficult to break. All these things make it difficult to isolate a module from the rest of the code base, and if you can't test your modules in isolation then unit tests lose a lot of their value.  If a test fails is it because of a fault in the unit under test, or because of a fault in one of its dependencies, or perhaps it's because the data that's being pulled in through a dependant data source isn't what the test writer expected?  If you can't replace dependencies with mocks then any of those are a possibility.

Most codebases I've seen that weren't built with unit testing in mind tend to be inherently untestable, as coders tend to focus on making the code work as they expect it should rather than doing the work necessary to keep coupling loose and dependencies explicit.  Code that was written with unit testing in mind tends to look very different.

A lot of people take a naive approach to unit testing when they start doing it for the first time, they think they can just write a load of tests for an existing codebase and all will be good, but it never works out that way because of the above mentioned issues.  They start discovering they have to inordinate amounts of setup in unit tests to get them to run at all, and the results are often questionable because the lack of isolation in the code means you can't track down what caused a test failure.  They also tend to start off trying to write "clever" tests that demonstrate some highly abstract aspect of how the system should work.  This tends to fail because a "clever" unit test is a potential source of bugs in itself.  Did the test fail because of a bug in the tested module, or because of a bug in the test?  A test should be so excruciating simple that there's obviously no possibility that a bug could be hiding in it.  In fact the best tests are rarely more than 2 lines long, the first line instructing the unit under test to do something, the second asserting that what it did was what was expected.

If your team is serious about adopting unit testing then it would be unwise to start with an existing project.  Your team's existing projects are probably untestable without major refactoring.  You're better off using a new project as the basis of learning about unit testing, as you have a clean slate to work with.  You can design the new code base to favour dependency injection over singletons, registries and other such hidden dependencies, you can write it to depend on interfaces instead of implementations and so on.  You can also (and should) write the tests along side the code being tested, as writing the tests afterwards results in unit tests that make sure the tested module does what you think it might be meant to do rather than ones that test that it does what the specs say it should do.

Once you've gained some confidence with unit testing, your team will probably begin to realise the flaws in their existing code that are going to be obstacles to unit tests.  This is when you can start working to refactor existing code to make it more testable.  Don't be ambitious and attempt to do this all at once, or attempt to replace a system that works with an entirely new one, simply start by finding the bits of the codebase that can easily be tested (the ones that don't have any dependencies or where the dependencies are obvious) and write tests for those.  I know I said writing a test alongside code is preferable to writing tests after, but even a test written later still has value as a starting point.  Write the tests as if you know nothing about how the class works other than what its specifications say it should do.  When you run the tests and get failures, then either the specs or the implementation is wrong.  Double check both to determine which is wrong and update either the test or the code accordingly.

Once you've picked off the low-hanging fruit, your real work begins.  You need to start finding the hidden dependencies in your codebase and correcting them, one at a time.  Don't get over-ambitious at this point, just stick to doing one module at a time, or even just one single issue in one module, until the obstacles to testing are fixed and you can move on to the next bit.

TL:DR: Most people think testing is easy and you can retrofit tests into existing code easily.  Both of these assumptions are wrong.  If you embark on a project to get unit testing into your projects with both these facts in mind you're more likely to succeed.


答:
IANAL, ask a real lawyer, etc.

First of all, I think you believe that when you have copyright, you can only license the product to yourself under the same terms you license it to everybody else. This is wrong: you can license it to yourself in any license suitable, and license it to somebody else under a different license.

Which means you can create a special license for the company that is about to hire you, and make the software available to them as a separate agreement. Of course, this should be done by a real lawyer.

Have your company sign the separate license, which explicitly states that you have copyright and you are giving certain rights to them, not the copyright.

As to the secondary issue, there are other ways to prove prior date, besides open-sourcing the project. For example, you could host on a publicly available server a file, that says that you indeed wrote this software, at the date specified, containing for example a few different hashes of the current version, or even the encrypted version of the project.

This means that if you're under a legal threat, you can prove prior date of usage to the judge, yet you reveal virtually nothing about the project, besides that you're the author and the date you revealed it. You should consult a lawyer about the possible validity of such an argument, but I believe it would be accepted at most courts.

Title: Can I use MIT license to give some of my previous written code to employer so that I protect myself and don't lose my copyright?

Body:
My situation:

I have written a framework before I started my new job. I own the copyright.

It has a bunch of boilerplate logic inside of it, like any piece of software. (duh!)

I don't want to use the whole framework in my new job, but I do need to re-use some parts of it in a similar framework that I am building for my new job.

It is impractical to re-implement / re-think all the logic from scratch. It is a lot of logic and logic is logic, you can't make it much different. For example, how many different versions of a HashMap can you code? I bet they will be very similar and the third version can claim that you violated the copyright of the first version. :(

It is impractical to try to re-invent the API. Can you re-invent the API of a HashMap? Maybe you can change put(k,v) to add(k,v), but not much more than that.

My idea to protect myself and my previous code:

I will tell my employer that I am building the new framework based on a previous one that I have written under the MIT license. So in the future if I use my previous framework someplace else, or even another derived version of it, that has some pieces of code similar with this new framework I am building now for the employer, they won't be able to say I am using their code, the one I wrote for them.

My questions:

I am not distributing my code to anyone. I don't have to distribute my MIT licensed code to anyone, if I own the copyright, correct? I mean, can someone request that I release my code that I now claim it is under MIT license? It would not be the end of the world and I would certainly agree to do that under a legal threat.

Does this strategy make any sense? My final goal is to be able to use a derived version of my previous coded framework without losing the copyright to it. At the same time, i do not want to distribute this code as an open-source project to anyone. I have other open-source projects, that I freely distribute, but this one I would like to keep it to myself so I can use on my jobs (not contractor jobs).

It is like claiming that you have a framework under the MIT license, without actually distributing and/or showing to anyone. If it is out there, free and easily available, my employers don't need me anymore. They can just take the code and give it to someone else to use it.

Notes:

I have listed this framework as a previous invention before I started the job.

I have not released this code anywhere. It is on my private SVN repo I host in my private server.

My idea in a nutshel:

My plan is to keep the previous code to myself, use parts of it in this new framework I am building for the employer and tell the employer it is work derived from a MIT licensed framework I have coded before and have not distributed to anyone". I am not forced to distribute a software I coded under MIT license, am I? If later, some legal claim happens (hopefully not), i can immediately paste the license on all the sources and show/release the code.


问:
Should a method's parameter list contain objects or object identifiers?
Our teams is having the following discussion:

Let's say we have the following two methods:

```<code>public Response Withdraw(int clubId, int terminalId,int cardId, string invoice, decimal amount);

public Response Withdraw(Club club, Terminal terminal,Card card, string invoice, decimal amount);
</code>```

whats sent over-the-wire are just the ids.

one side says that the first method is correct, because we only have the ids of terminal and club, and it should be clear that we have nothing else, this is my approach.

the other side says that the second method is correct because it's more flexible.

We are familiar with object parameter idea, the other side also thinks that the object parameter should have the objects as properties.

Which is the correct approach?

Maybe there is a third even better approach?

答:
The first approach is indicative of Primitive Obsession. Because you are passing ints and strings around, it's very easy for the programmer to make a mistake (eg passing a clubId to the terminalId parameter). This will result in difficult to find bugs.

In the second example, it's impossible to pass a club when a terminal is expected - this would give you a compile time error.

Even so, I would still look at string invoice. Is an invoice really a string? What does amount mean? This is more likely a monetary value.

You mentioned in your question "whats sent over-the-wire are just the ids.". This is correct, but don't let this requirement muddy your domain.

The best explanation I've seen in favour of this approach was in rule 3 of Object Calisthenics:

An int on its own is just a scalar, so it has no meaning.   When a method takes an int as a parameter, the method name needs to do all of the work of expressing the intent.  If the same method takes an Hour as a parameter, it’s much easier to see what’s going on.  Small objects like this can make programs more maintainable, since it isn’t possible to pass a Year to a method that takes an Hour parameter. With a primitive variable the compiler can’t help you write semantically correct programs. With an object, even a small one, you are giving both the compiler and the programmer additional info about what the value is and why it is being used.


答:
The answer is context dependent.

If the client is expected to have all those objects already available, I'd use the object parameters. Otherwise, their code will look more convoluted than it needs to be. (E.g. they will have calls like club.getId(), for example.)

If the client will only have the ids available easily, then maybe the second approach is better, as you might not want the client to have to assemble/load all those objects if you really only need the ids.

An option is to provide both methods, so the client can choose which one to use (given that this does not clutter your API)

In general the object parameters are more extensible, since if in the future you need another piece of data to do the work, you do not need to introduce another method that takes that extra info.

Lastly, your method signatures should not be dictated by the specifics of what the method does (in your case, what exactly goes over the wire). The API should abstractly make sense so if implementation changes, you are not screwed.

Title: Should a method's parameter list contain objects or object identifiers?

Body:
Our teams is having the following discussion:

Let's say we have the following two methods:

```<code>public Response Withdraw(int clubId, int terminalId,int cardId, string invoice, decimal amount);

public Response Withdraw(Club club, Terminal terminal,Card card, string invoice, decimal amount);
</code>```

whats sent over-the-wire are just the ids.

one side says that the first method is correct, because we only have the ids of terminal and club, and it should be clear that we have nothing else, this is my approach.

the other side says that the second method is correct because it's more flexible.

We are familiar with object parameter idea, the other side also thinks that the object parameter should have the objects as properties.

Which is the correct approach?

Maybe there is a third even better approach?


答:
I dislike it

Everything you can do with it you can do cleaner without it.

Title: What are you thoughts on GWT?

Body:
Since I'm learning Java in this period and I just finished with the tutorials I think I'm ready to start contributing to a project (since I know from experience this is the best way to really learn).

I've seen GWT, looks interesting so I thought I should give it a try. I'm thinking however, since GWT deploys Java applications in JavaScript why should I learn GWT when I could learn the actual thing instead (this being JavaScript).
My question: is it worth it? Wouldn't someone be better of learning JavaScript if they want to build JS applications, instead of using Java and GWT? I realize that it might be easier to build certain things with GWT but in the end is it worth it?

Thanks.


问:
No programmer will build my semi-adult website. Why?
I've been looking for get this website done for a long time.

I thought with a well organized write-up of what I wanted, as well as having clear examples done in photoshop of faux pages to give an idea of the vision, and no hidden surprises, I would be a programmer's dream job.

Unfortunately, no company will touch the website. There is nothing illegal about it or even remotely offensive. It's an adult listing for professional Dominatrices. I don't see what the big deal is, when there are way worse and more hard-core sites out there, and this is just a listing. Pro Domination is a legal occupation in the USA and most of the world. People just don't want to touch the site. It's really strange. I have all of the information and details of the site laid out perfectly and clearly. I just either get no response or people who tell me they won't touch anything remotely adult.

Is there a reason for this?

答:
Basically, lots of professional programmers don't want pornography on their resumes.  The "adult industry" drives lots of innovation on the web, but they get no credit for it.  For many years they were the only companies making actual money on the Internet - they pioneered many of the small-payment systems everyone else uses today.  For years they were some of the network hardware manufacturers' largest customers.

I won't say nobody wants to do this stuff.  But most folks don't want it to be their full time job.  It taints everything it touches in some peoples' eyes.  As a hiring manager, I've received resumes that had vague descriptions of technical work that, when I asked, proved to be from that industry.  I personally couldn't care less, I wanted to know the technical details.  But the candidates were genuinely embarrassed to have done that work


问:
Communication between a C# application and C++ DLL
I am currently building an audio streamer and I have a CPP .dll that I use functions of inside the WPF C# GUI.

The program needs to deal with sorts of events such as

Lower/Increase Volume

Manipulate Equalizer Bands

To this point I have used named events to deal with this issue. What would be a better way of handling all those events from the GUI to the .dll?  The events system I use (.dll spawns a thread which while-s on a WaitForMultipleObjects), or would it be better/smarter/more-beneficial or just better-practice to use a named pipe instead?

答:
You can call from C# to C/C++ directly using a technology known as P/Invoke.  With P/Invoke, a C++ function can be made to look just like a C# function.

Here's a simple example from this article in MSDN Magazine:

C Method Definition

```<code>BOOL MessageBeep(
  UINT uType   // beep type
);
</code>```

P/Invoke Definition in C# of method in C

```<code>[DllImport("User32.dll")]
static extern Boolean MessageBeep(UInt32 beepType);
</code>```

Calling the C method from C#

```<code>MessageBeep(0);
</code>```

Now, isn't that simple & clean?  Much of the .NET Base Class Library is implemented as C/C++ code with a P/Invoke wrapper and a C# facade.  The .NET team itself uses P/Invoke rather than COM for this type of interop, it's simpler and more efficient.

A great resource for finding how to write P/Invoke method definitions is pinvoke.net.

Body:
You can call from C# to C/C++ directly using a technology known as P/Invoke.  With P/Invoke, a C++ function can be made to look just like a C# function.

Here's a simple example from this article in MSDN Magazine:

C Method Definition

BOOL MessageBeep(
  UINT uType   // beep type
);

P/Invoke Definition in C# of method in C

[DllImport("User32.dll")]
static extern Boolean MessageBeep(UInt32 beepType);

Calling the C method from C#

MessageBeep(0);

Now, isn't that simple & clean?  Much of the .NET Base Class Library is implemented as C/C++ code with a P/Invoke wrapper and a C# facade.  The .NET team itself uses P/Invoke rather than COM for this type of interop, it's simpler and more efficient.

A great resource for finding how to write P/Invoke method definitions is pinvoke.net.


问:
How Do Computers Process Conditional/Input/ Event Based Code?
I understand that computers are basically a complex system of electrical signatures that can calculate based on logic boards, and some sort of gate mechanism, but how do computers process something like if the number produced by the keyboard is less than 10, or if a mouse is clicked two times in a certain amount of time it equals a double click?</p>

答:
Not totally sure where you are going with this, and it depends on the hardware
The way it all started was.

There's special register in the CPU called Flags
Less than is done by a Subtraction.
Subtraction is done by addition with two's complement representation.
In two's complement negative numbers (bearing in mind overflow) the most significant bit is always 1

So a less than test is Just a - b.
The most significant bit of the result is copied to the N bit of the flags register
and then that is tested.

There's usually a zero bit to test if A = B and an Overflow bit.
A few others as well Carry for istance.

Overflow would be say your number is a signed byte that gives you -128 to + 127 (256 different numbers). so -128 - 1 won't fit and the overflow bit gets set.

There's a load more to this in modern processors, but the basics are still true.

This sort of stuff is a lot easier to pick up in far more basic CPUs than we use now. I learnt it on the Z80 back in 76...

The mouse click one
Is store the "time" of the last click.
Then on next click subtract the above and then compare it with the interval you stored for how fast you had to click for it to be a double click.


问:
How can you write tests for Selenium (or similar) which don't fail because of minor or cosmetic changes?
I've been spending the last week or so learning selenium and building a series of web tests for a website we're about to launch. it's been great to learn, and I've picked up some xpath and css location techniques.

the problem for me though, is seeing little changes break the tests - any change to a div, an id, or some autoid number that helps identify widgets breaks any number of tests - it just seems to be very brittle.

so have you written selenium (or other similar) tests, and how do you deal with the brittle nature of the tests (or how do you stop them being brittle), and what sort of tests do you use selenium for?

答:
The purpose of Selenium is to create UI-driven integration tests.

Integration tests verify that all components of your system work correctly when deployed together.  Integration tests are not a sufficient test strategy and complement other test strategies having a different focus, for example unit-testing and acceptance testing.

UI-driven tests are inherently brittle, although Selenium and Watir are a step up from the early days of record-and-playback tools.  There are several ways to deal with this problem - here's is a compilation of advice from some world-class experts:

Don't try to get all your test coverage from this type of tests.  Robert C. Martin  argues that your code coverage by integration tests should be about 20%.  It is simply impractical to test all paths of execution when the input is several application layers away.

Get most of the test coverage from unit- and acceptance tests.  Look for links to Gojko Adzic's articles in FinnNk's answer.  Adzic argued repeatedly about testing business logic through acceptance tests and bypassing UI.

But some amount of UI-driven tests still needs to be written.  This is where you need some practical advice in addition to "don't test your business logic via UI."  I'd recommend Patrick Wilson-Welsh's blog as the starting point.


问:
How to deal with too much pragmatism in the project?
My team and I took over a medium sized codebase over a year ago when the previous tech lead left the company. Originating from the lack of man power I fear we favored pragmatic solutions over best practices a little too much.

Now, I have to deal with a constant decline in code quality and some kind of organic growth of day-to-day processes. I regret that when asked for code conventions a year ago I basically gave common sense as the only rule. Soon I had programmers using different syntactic styles and failing to see the difficulties this induces in a merge process. Another example is my push for database migration scripts. I tried to incorporate Flyway into our process but after only a week I was quickly overruled by my boss. Even despite me warning them about the upcoming mandatory use of database migration scripts and providing them with as many clues, hints and tools to mitigate the problem of not starting applications because of missing or failing migrations they decided that it would be best do complain to my boss about them not being able to do their work. I forcefully disabled Flyway again and we now live with migration steps in arbitrary named SQL files on a network share that you have to remember to apply to the respective database at the right time.

One problem in our process was that we never did formal code reviews. So a lot of hacks went under the radar and into the code base without someone noticing on time. Nowadays I tend to read checkins of my team mates when there is time (that's not often the case) but there is no automatic process to prevent unwanted changes. It is up to me to go to the developer in question and try to ease them into acknowledging why their code is bad. I thought to introduce lint-like tools like FindBugs and Checkstyle but I fear I would face the same psychological problems like I did with the database migrations. After all I would make their jobs harder for them and I can understand why this might lead to misunderstandings.

So my question is: How can I go about improving our process and our code quality in an environment where getting the job done is valued much higher than doing it right?

答:
You are never going to get around technical debt, it's a commercial necessity. Even if you are lucky enough to have bosses who get it, they'll still say I need it yesterday, or that the risk of reworking the legacy code to improve it for what they consider to be weird arcane propeller head aesthetics, isn't acceptable.

Even if you were CIO, you'd have a herculean task to impose best practices on your colleagues, and that's even if you could agree that they were "best"

The best approach, especially if you are low down in the food chain, is self defense.

Get the idea across if they do that like this, it will make their job easier not yours.
Don't go all esoteric on them, good naming practice (not some Hungarian notation thing) and common architecture can alleviate all sorts of comprehension issues.
Something as simple as the routine that displays the entity on the form is always called DisplaySomeEntityName
Start simple don't try to build and an entire hierarchy of good practice before you do anything. Build it together organically.

It might be just an impression I'm getting, but a key point is to make Code Reviews are time where you can help each other not criticize each other.
It's not you've done it wrong.
It's I don't understand what you've done.

So instead of you reviewing their code, get them to review yours.
If it's a good habit and it makes things easier, they'll start doing it.
Never know you might be doing it wrong, I'm a bit of a nut about this sort of thing, but I've been pulled up more than a few times by my code only being comprehensible to me, just after I wrote it....


问:
Azure Storage Table design with multiple query points
I have the following Azure Storage Table.

PositionData table:

```<code>PartitionKey: ClientID + VehicleID
RowKey: GUID
Properties:  ClientID, VehicleID, DriverID, Date, GPSPosition
</code>```

Each vehicle will log up to 1,000,000 entities per year per client. Each client could have thousands of vehicles.  So, I decided to partition by ClientID + VehicleID so to have small, manageable partitions.  When querying by ClientID and VehicleID, the operation performs quickly because we are narrowing the search down to one partition.

PROBLEM:

The problem here is that sometimes I need to query on only ClientID and DriverID.  Because it's not possible to perform partial PartitionKey comparisons, every single partition will need to be scanned.  This will kill performance.

I can't have a PartitionKey with all ClientID, VehicleID and DriverID because queries will only ever query on VehicleID OR DriverID, never both.

SOLUTION 1:

I considered having a value stored elsewhere which represented a VehicleID and DriverID pair, and then having a ClientID + VehicleDriverPairID PartitionKey, but that would result in hundreds of thousands of partitions and there will be much unioning of data between partitions in my code.

SOLUTION 2:

Have a partition for Client + VehicleID and another partition for Client + DriverID.  This means that updating the table is twice as much work (two updates) but both queries will be fast.  Also there will be redundant data.

Do any of these solutions sound viable?  Other solutions?

答:
I think you have several viable programming solutions that could work - your original solutions as well as those that were posted on SO.  As you say, the problem becomes deciding which design is optimal for your case - and also which will be easily understood by other programmers modifying your code in the future.

You didn't really say if vehicles are owned and operated by the clients or by the drivers. I expect it would be rare for clients that own and operate their vehicles to trade vehicles over a year. If vehicles are owned and operated exclusively by drivers I expect they would drive that vehicle most of the time.

When I read your question I thought of partitioning the table by VehicleID + DriverID if the vehicles are owned and operated exclusively by clients. And if the vehicles are owned and operated exclusively by drivers, a partition by ClientID + DriverID would be more efficient.

This approach would be fast, but it would become less accurate or less efficient as more driver-owners or client-owners traded vehicles.


问:
Managing Alerts in Web Application Using RESTful API
I have designed a RESTful API and I am now working on creating a web application to use the service.

One thing I am struggling with is how to manage alerts in the web application (similar to the alerts stackoverflow gives in your profile for a new answer, response etc).

Basically the web application is a workflow between a user and his clients. Certain tasks have to be completed in order, and the web application alerts both the user and his clients of any actions. The user also gets alerted to any client actions that are outstanding.

The way I have my architecture setup at the moment is that the API has no knowledge of alerts. It simply stores the resources that are retrieved by the web application. To work out if an alert needs to be displayed, the web application looks at all the resources, and based on a set of rules, decides what alerts need to be displayed.

The problem I have is that I'm not sure this is a very efficient way to do things. There are a number of different alerts that can be displayed, and they depend on different API resources which will all need to be retrieved when a user or client logs in.

My question: Is this the best way to achieve what I want, or are there other methods which are better to use and will help decrease web application load time and api calls?

答:
So one thing you could do is to make the checking of rules asynchronous.  Once the resource is created (maybe as an aspect) you put a reference to the posting in Rabbit MQ, Active MQ or even a database table that's periodically swept by another process.  Using aspects means your API need not know anything about alerts.  (Although you should be careful about what verbs you use with these side effects - i.e. POST is your friend but GET would be inappropriate).

Can you be a little more specific? Maybe disclose the frameworks or language?  There might be a more better way to do this than AOP.


答:
There's no right answer to this one. Either option could be right for the job.
Well nearly any way, the invoice argument raised a furrow on my brow, I don't have a clue what that is from reading the code.

If you send an id, then both systems need to be tightly coupled at to what that represents. ClubID is key in the clubs table. More to the point both caller and callee need to agree what the Clubs table is called and which database it's in.
If you don't want to or can't impose that constraint, then you'd pass the object using some common description, native, serialized, xml, name = value whatever, an ini file:)

That as you identified will cost you "over the wire". Avoiding that by just sending the identifier costs you elsewhere.
So which one hurts you the least, now (or may be later...) is the indicator of good vs bad.


问:
What are the disadvantages of automated testing?
There are a number of questions on this site that give plenty of information about the benefits that can be gained from automated testing.  But I didn't see anything that represented the other side of the coin: what are the disadvantages?  Everything in life is a tradeoff and there are no silver bullets, so surely there must be some valid reasons not to do automated testing.  What are they?

Here's a few that I've come up with:

Requires more initial developer time for a given feature

Requires a higher skill level of team members

Increase tooling needs (test runners, frameworks, etc.)

Complex analysis required when a failed test in encountered - is this test obsolete due to my change or is it telling me I made a mistake?

Edit

I should say that I am a huge proponent of automated testing, and I'm not looking to be convinced to do it.  I'm looking to understand what the disadvantages are so when I go to my company to make a case for it I don't look like I'm throwing around the next imaginary silver bullet.

Also, I'm explicity not looking for someone to dispute my examples above.  I am taking as true that there must be some disadvantages (everything has trade-offs) and I want to understand what those are.

答: One of the main disadvantages can be overcome by using self-learning tests. In this situation the expected results are all stored as data and updateable with minimal review by test suite user in self-learning mode (show diffs between old expected result and new actual result - update expected if press y). This testsuite learning mode needs to be used with caution so buggy behaviour is not learned as being acceptable. </p>


答:
The CPU is composed of a set of registers.  Some are general purpose registers (can be used for computation) and some have dedicated uses (like the instruction pointer which contains the address of the next instruction to fetch).  There's a status register (usually) which has several bits such as "overflow."  Certain errors are captured by status register flags but its up to the machine code generated or produced from the language you are executing to read the status register and initiate exceptional processing.

Interactive input events are usually handled through interrupts.  There's usually an set of interrupt lines into the CPU and when there's a signal on one of those lines that causes the CPU to jump to a new block of code that's called an interrupt handler.  Without talking about a particular O/S, the interrupt handler is written as part of the operating system and isn't part of the CPU, although the CPU calls the address provided by the O/S as the interrupt handler.  For example, a prototypical O/S, moving the mouse could cause an interrupt, which invokes a serial interrupt handler, which reads the value from the serial port, which then triggers the GUI to redraw, which reads the mouse position and draws the mouse arrow in the right place.

Still other IO is handled through a combination of IO ports and registers and the values are polled periodically for changes.

Title: How Do Computers Process Conditional/Input/ Event Based Code?

Body: I understand that computers are basically a complex system of electrical signatures that can calculate based on logic boards, and some sort of gate mechanism, but how do computers process something like if the number produced by the keyboard is less than 10, or if a mouse is clicked two times in a certain amount of time it equals a double click?</p>


答:
Let me guess...now you have a team of developers mired in daily production support because the stream of issues coming in is endless and no one gets to work on more strategic things?

I'll be curious to see what kinds of answers you get, but without being too pessimistic here I think you're in for a heck of an uphill battle, mainly because my first bit of advice would be to get management on your side, and these quotes make me think that's going to be difficult:

I was quickly overruled by my boss

and

an environment where getting the job done is valued much higher than
  doing it right

I like to refer to this as the decision-consequence gap. The people making the decisions do not have to suffer the consequences of the decision. If the decision is bad, the fallout is often someone else's problem. If the decision is good, or was bad and the hard work of others made it look good, then of course the decision maker takes credit.

I'm not busting on you here, these problems are a sadly systemic issue I see in most corporate IT shops and the corporate world at large. It's what causes them to narrowly put delivery date before quality in every project. And of course they'll do that because they are judged by their superiors on date first; as none of them have to live with the software's deficiencies, quality doesn't really matter to them.

Ideal Solution

Anyway, the "happy path" scenario is that you get management to agree to:

Halt new feature development while you make a focused effort to repair and refactor major deficiencies in the code.

While they're at it, they empower you to release anyone from the team that isn't smart enough to recognize the value of best practices and doesn't want to change their hack-style of coding. Getting rid of crappy developers is probably even more valuable to the team than the refactoring itself; good developers will find ways to refactor as they go, naturally improving things over time.

Management in this scenario recognizes that the leaks in the boat must be repaired or much time and money will be lost in paying for a team that is stuck churning through tactical issues (user hand-holding, data fixes, rote tasks, and other assorted diaper changes) rather than strategic (new features to enable user efficiency, improve quality of customer-facing output, and make possible new streams of revenue).

Pragmatic Solution

Look, we know the above theoretical ideal is unlikely to happen based on what you've already told us. That leaves you and your team to find ways to handle this on your own.

Establish the standards you need. You mentioned it in your post; get them published and get the team to understand the value and begin implementing for all future work. If you can keep the issues load stable even as the code grows because the new features don't add more problems, then that's a small but laudable victory against tough circumstances.

Refactoring is likely one of your best approaches. Every time you have to go in for a fix, take advantage of the opportunity to also clean up that script and improve it some. If you can't get management to support a directed repair effort then evolve the code slowly; you might have to engage some overtime but some improvement is better than none. The problem here is that it works for individual scripts, but less well for system-wide changes that need to happen simultaneously in large numbers. But you may be able to blend in some larger changes if you do get some new feature request; you must be tactful though. I once got my hand slapped by a project manager that thought I was actually greenlighting unapproved work (I was not, I was implementing changes that would fix a part of the system and in turn enable the new requested feature and was thus a material part of the project).

Make staffing changes? I don't want to speak out of turn because I don't know the full story behind your team, but it sounds like they are quite comfortable with sloppy quick fixes and don't appreciate best practices like code review. If you've identified people that are creating more problems than they solve, perhaps they can be put somewhere else. This is a tough one because these days management doesn't like firing people for incompetence because that's politically incorrect; they only fire people for hurting someone's feelings. But I mention this because it is a factor; poor developers compromise the rest of the team's efforts. You will waste many hours trying to convince them to improve, and any work they manage to get into production will create more support.

Really Pragmatic Solution

A lot of the folks on the stackexchange sites are smart people that are also impatient and are quick to say, "Just leave, it's obvious your shop isn't going to get any better."

I'd agree with them if you really feel it's not going to get better. But obviously you have to be careful because at least in my experience, you have a chance of ending up somewhere that has the same problems.

Also, this site's sidebar lists several similar questions you could look into for advice.

Title: How to deal with too much pragmatism in the project?

Body:
My team and I took over a medium sized codebase over a year ago when the previous tech lead left the company. Originating from the lack of man power I fear we favored pragmatic solutions over best practices a little too much.

Now, I have to deal with a constant decline in code quality and some kind of organic growth of day-to-day processes. I regret that when asked for code conventions a year ago I basically gave common sense as the only rule. Soon I had programmers using different syntactic styles and failing to see the difficulties this induces in a merge process. Another example is my push for database migration scripts. I tried to incorporate Flyway into our process but after only a week I was quickly overruled by my boss. Even despite me warning them about the upcoming mandatory use of database migration scripts and providing them with as many clues, hints and tools to mitigate the problem of not starting applications because of missing or failing migrations they decided that it would be best do complain to my boss about them not being able to do their work. I forcefully disabled Flyway again and we now live with migration steps in arbitrary named SQL files on a network share that you have to remember to apply to the respective database at the right time.

One problem in our process was that we never did formal code reviews. So a lot of hacks went under the radar and into the code base without someone noticing on time. Nowadays I tend to read checkins of my team mates when there is time (that's not often the case) but there is no automatic process to prevent unwanted changes. It is up to me to go to the developer in question and try to ease them into acknowledging why their code is bad. I thought to introduce lint-like tools like FindBugs and Checkstyle but I fear I would face the same psychological problems like I did with the database migrations. After all I would make their jobs harder for them and I can understand why this might lead to misunderstandings.

So my question is: How can I go about improving our process and our code quality in an environment where getting the job done is valued much higher than doing it right?


答:
I think it's going to be language specific.  I come from a lispy background.  In many cases interfaces with state break the functional model to a degree.  So CLOS, for example, is where LISP is less functional and closer to an imperative language.  Generally, required function parameters combined with higher level methods are probably what you're looking for.</p>

```<code>;; returns a function of the type #'(lambda (x y z &optional a b c)

(defun get-higher-level-method-impl (some-type-of-qualifier)
    (cond ((eq 'foo) #'the-foo-version)
          ((eq 'bar) #'the-bar-version)))
</code>```

Body:
I think it's going to be language specific.  I come from a lispy background.  In many cases interfaces with state break the functional model to a degree.  So CLOS, for example, is where LISP is less functional and closer to an imperative language.  Generally, required function parameters combined with higher level methods are probably what you're looking for.

;; returns a function of the type #'(lambda (x y z &optional a b c)

(defun get-higher-level-method-impl (some-type-of-qualifier)
    (cond ((eq 'foo) #'the-foo-version)
          ((eq 'bar) #'the-bar-version)))


问:
Why is the usage of string keys generally considered to be a bad idea?
This has been bugging me for a while. Most of the time, when it comes to storing data in structures such as hashtables, programmers, books and articles insist that indexing elements in said structures by String values is considered to be bad practice.
Yet, so far, I have not found a single such source to also explain WHY it is considered to be bad practice.
Does it depend on the programming language? On the underlying framework? On the implementation?

Take two simple examples, if it helps:

An SQL-like table where rows are indexed by a String primary key.

A .NET Dictionary where the keys are Strings.

答:
It' not a bad idea in and of itself, it's usually with 20/20 hindsight a poor design compromise.
The flexibility and range of string versus the additional cost and complexity.

If integer does the job range wise and the bulk of the expensive processing doesn't need to know what the integer represents, use one.


问:
Understanding high cohesion principle for methods in object oriented design
I know the idea of strong cohesion applies to methods as much it applies to classes. Just to be clear when I say strong cohesion of a method I mean a method which does only one task and does it well. This idea really works for simple getters and setters. But sometimes we usually come across methods that does more than one task internally , although it seems to be doing a single task if you look at a higher level of abstraction. An example of such a method can be :

```<code> public void startUp() {
        List<SubSystem> subSystems = getSubSystems();
        sychronized(subSystems) {
            for (SubSystem subSystem : subSystems) {
                subSystem.initialize();
            }
        }
    }
</code>```

And inside those subSystem#initialize() methods  a lot is going on. So is this a violation of the high/strong cohesion principle ?

答:
No.  It looks like it's a cohesive method.  You might rename the method "initializeAllSubsystemsOnStartup" and that's probably more descriptive than "startUp".  Here's a non-cohesive example:

```<code>public void updateCustomerOrders(Customer customer, Orders newOrders) {
    if(!customer.isPersisted()) { customer.save(); }
    else if(customer.inGoodStanding() {
        customer.setOrders();
        for(Order order in Orders) { order.setCustomer(); }
        customer.save();
    } else {
        updateUi("Invalid customer");
    }
}
</code>```

It's not cohesive because the method claims to be about updating customer orders (the lines in the else if block, but does many things, including possibly updating the UI which doesn't feel like it should a concern at this layer.

Body:
No.  It looks like it's a cohesive method.  You might rename the method "initializeAllSubsystemsOnStartup" and that's probably more descriptive than "startUp".  Here's a non-cohesive example:

public void updateCustomerOrders(Customer customer, Orders newOrders) {
    if(!customer.isPersisted()) { customer.save(); }
    else if(customer.inGoodStanding() {
        customer.setOrders();
        for(Order order in Orders) { order.setCustomer(); }
        customer.save();
    } else {
        updateUi("Invalid customer");
    }
}

It's not cohesive because the method claims to be about updating customer orders (the lines in the else if block, but does many things, including possibly updating the UI which doesn't feel like it should a concern at this layer.


问:
Why sequential cohesion for operations in a method is not a good idea?
I read from the seminal  Code Complete book that method statements that require to be executed in order passing parameter from one to the next is a code smell and is an example of a sequential cohesion. Why is this not a good idea?

A contrived example of a sequential cohesion:

```<code>public Part createPart(input) {
        PartOne partOne = computePartOne(input);
        PartTwo partTwo = computePartTwo(partOne);
        PartThree partThree = computePartThree(partTwo);
        PartsBuilder partsBuilder = new PartsBuilder();
        return partsBuilder.add(partOne).add(partTwo).add(partThree).build();
    }
</code>```

Here is the exert:

Several other kinds of cohesion are normally considered to be less than ideal:

Sequential cohesion exists when a routine contains operations that
  must be performed in a specific order, that share data from step to
  step, and that don't make up a complete function when done together.

An example of sequential cohesion is a routine that, given a birth
  date, calculates an employee's age and time to retirement. If the
  routine calculates the age and then uses that result to calculate the
  employee's time to retirement, it has sequential cohesion. If the
  routine calculates the age and then calculates the time to retirement
  in a completely separate computation that happens to use the same
  birth-date data, it has only communicational cohesion.

How would you make the routine functionally cohesive? You'd create
  separate routines to compute an employee's age given a birth date and
  compute time to retirement given a birth date. The time-to-retirement
  routine could call the age routine. They'd both have functional
  cohesion. Other routines could call either routine or both routines.

答:
I think the example is actually Functionally Cohesive not Sequentially Cohesive. The inputs and outputs just happened to be related, but the methods could have been used independently. "Other routines could call either routine or both routines." - other routines could call any of the computePart methods.

Here is an example that I think better demonstrates the sequential cohesion.

```<code>public Part createPart(input) {
        setInput(input);
        computePartOne();
        computePartTwo();
        computePartThree();
        PartsBuilder partsBuilder = new PartsBuilder();
        return partsBuilder.add(this.PartOne).add(this.PartTwo).add(this.PartThree).build();
    }
</code>```

Where as the above example has coupling between the stages here as the parts are inside the object and you can't really use them independently. They are tightly coupled - they actually "share data from step to step".

Body:
I think the example is actually Functionally Cohesive not Sequentially Cohesive. The inputs and outputs just happened to be related, but the methods could have been used independently. "Other routines could call either routine or both routines." - other routines could call any of the computePart methods.

Here is an example that I think better demonstrates the sequential cohesion.

public Part createPart(input) {
        setInput(input);
        computePartOne();
        computePartTwo();
        computePartThree();
        PartsBuilder partsBuilder = new PartsBuilder();
        return partsBuilder.add(this.PartOne).add(this.PartTwo).add(this.PartThree).build();
    }

Where as the above example has coupling between the stages here as the parts are inside the object and you can't really use them independently. They are tightly coupled - they actually "share data from step to step".