问:
Patterns for undo in multi-user applications on relational data
I want to build a web application that will allow multiple users to collaboratively populate the contents of a fairly conventional relational database. (The database will have a fixed schema, which is known in advance).

I can see how to define the schema for the necessary object types, relations, and foreign key constraints (items, items as members of categories, links between items, and so on). Basic CRUD operations to instantiate and modify objects are no problem.

But for resilience against vandalism and mistakes, I can foresee that it will be necessary to have undo/rollback functionality, so that moderator-level users can undo changes made by other users. I'm having trouble figuring out a suitable approach to take for two key functional pre-requisites:

Capturing all the database changes that result from an initial user request. For example, there's a many-to-many relationship between items and categories. Therefore, if a category is deleted (triggered by a user submitting an HTML form), all the category-item relation records corresponding to that category will get deleted due to referential integrity constraints on the many-to-many relation. How can I record all the cascading consequences of an initial operation, so that's it's possible to completely undo it later?

How can I isolate undo operations so that a bad action by one user can be undone without also needing to roll back all the beneficial changes which have been made by other users, in between the bad action and the moderator's review?

The Undo patterns I've seen described (e.g. "Command" pattern) all assume that there is a stack of commands and undo operations are always applied in strict reverse order of initial application (no support for out-of-order undos).

Are there any standard patterns for handling undo capability in relational databases which would help meet these two goals? At the moment, I'm looking for generic algorithms and patterns which help solve the problems listed above, rather than platform-specific details.

答:
What you're probably looking for is a schema like this:

```<code>    DOCUMENT
       |
DOCUMENT_VERSION
       |
DOCUMENT_CATEGORY
</code>```

That is, each entity has a VERSION collection associated to it.  When you do an edit, you store the entire new version under a new version record leaving the original untouched.  Then you can implement a diff function to show the user the differences between two versions, and a rollback function to make a previous version the new active version.

These are basic functions in a lot of web applications, particularly Wikis.  If you're using ASP.NET, you could consider downloading and installing ScrewTurn Wiki and look at how it handles versioning.  It's open source.

Body:
What you're probably looking for is a schema like this:

    DOCUMENT
       |
DOCUMENT_VERSION
       |
DOCUMENT_CATEGORY

That is, each entity has a VERSION collection associated to it.  When you do an edit, you store the entire new version under a new version record leaving the original untouched.  Then you can implement a diff function to show the user the differences between two versions, and a rollback function to make a previous version the new active version.

These are basic functions in a lot of web applications, particularly Wikis.  If you're using ASP.NET, you could consider downloading and installing ScrewTurn Wiki and look at how it handles versioning.  It's open source.


问:
Representation of a question mark in variable names
I once in my childhood read a SF story in which it was assumed that the capital letter 'P' would be a good representation for a question mark, if you cannot use that character directly, eg. in variable names. However the story is quite old and things may have changed :)

Is this a good practice?

BTW: The story was called Press Enter by John Varley

Edit

Additional questions that are answered below.

Is this only writer's phantasy or is it based on an actual language's habit?

If yes, which language would that be?

答:
In languages with a malleable syntax such as Lisp or Scala, the question mark is in fact allowed and is frequently used to mark Boolean functions.

Where it isn't, I've never seen a P substituted to mimic a ?. isValidP() doesn't really look very much like a ? to me.

There is in fact a certain tradition of using a suffix of P to mark predicates (i.e. Boolean functions), but there the P stands in for 'predicate', not for the shape of the ?. (Strangely, this is also prevalent in Lisp, so I assume it was from a time or dialect that didn't actually allow ? in identifiers.)

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Quantifying the advantages of a modern version control system
I've worked as a team lead/developer in a large financial enterprise environment for the better part of three years. Our production release process is a nightmare because it revolves around Clearcase. We have a change management group who executes all releases and who will only allow code into production that was taken from it.

One of the first things I did when joining was to set my team up with Git. Everyone agreed that Clearcase was awful and was impractical for handling day-to-day source control matters. So we set up a sort of "unofficial" repository on my local machine and I wrote a script to sync our git and Clearcase repos around release time.

Word of this spread to other teams and several have adopted the same process. Using git in an "unofficial" manner for day-to-day activities and "officially" using Clearcase for releases. I've become sort of the go to guy for any issues with Git.

So I have a meeting this week with the SVP in change of infrastructure who specifically wants me to explain to her the merits of Git. Word apparently got to her of my frequent rants on Clearcase. If she accepts my arguments, I will have a real shot at helping my employer rid themselves of this abomination.

My experience with executives tells me they a) want extremely terse explanations for everything b) are only interested in facts that involve dollar figures

To a developer I can explain the merits of Git over Clearcase (or ANY other version control system over Clearcase for that matter), but I'm drawing a blank on how to do this to a technical executive without a technical background (she has an MBA and did her undergrad in geography).

I feel any argument I make to her is either going to sound like technical gibberish or that I'm evangelizing my personal preferences.

What I'm trying to find are concrete facts demonstrating developers work more effectively with Git, or ANY modern source control system.

I think that the fact the other teams have started using Git internally is a meaningful sign, but it's still not strong enough because it can still be dismissed as personal preference.

What I really need is something powerful enough to break through the "This process has worked for 20 years, why should we change it?" argument.

答:
Specific examples will impress more than abstract advantages. I think you will find most success if you can document particular examples where (a) Clearcase caused problems that took time to solve and (b) Git solves those problems. Remember that you don't need to go into technical details of why this is so (unless asked) simply show that it is; management doesn't need to know the technicalities, that's what you're paid for.

If you can attach specific timescales and dates to these examples so much the better. You might also be able to top this off by showing that task X that you do a lot takes Y minutes in Clearcase and Z minutes in Git.

Remember that time is money so if you can show that working with Git is quicker you can show that it will also make financial sense.


答:
That would not really be universally understood, so I wouldn't recommend it.

Additionally, some languages actually use the ? to check if a variable is defined, so if you named a variable CompletedP and you want to check if that is defined, that would be CompletedP?. This would just give me a headache.

Generally, where I would think this could be appropriate, I would just change the name of the variable into an obvious question. So the following variables could be renamed:

TaskACompleted? -> IsTaskACompleted

ButtonChanged? -> HasButtonChanged

etc.

Title: Representation of a question mark in variable names

Body:
I once in my childhood read a SF story in which it was assumed that the capital letter 'P' would be a good representation for a question mark, if you cannot use that character directly, eg. in variable names. However the story is quite old and things may have changed :)

Is this a good practice?

BTW: The story was called Press Enter by John Varley

Edit

Additional questions that are answered below.

Is this only writer's phantasy or is it based on an actual language's habit?

If yes, which language would that be?


答:
What I really need is something powerful enough to break through the "This process has worked for 20 years, why should we change it?" argument.

This is an invalid argument (horse-drawn carriages have "worked for centuries", but you probably want to buy a car instead).

I have heard the same argument about svn vs. mercurial (I was the one using mercurial on my development system).

This problem is not about replacing what works; Don't try to phrase it as such, and if this is the question you need to "defeat", you should start by pointing out it is not a matter of what works or not - but a matter of what advantages you have with git, when both work (and why git works better).

Good arguments for using git:

git is changeset centric instead of file centric. This means changes are easier to track accross files (trackability accross the project).

git is distributed instead of centralized; This means checking in stuff isn't limited by network speed - saving a lot of time, again. It also means you have no single point of failure in case your ClearCase server goes down.

because of it's branching system, git minimizes the need to merge (i.e. you do not merge files on every check-in, but but on every completed feature). You switch from solving merge conflicts (if any) a few times per day (on every commit) to once or twice per week (on every completed feature). This means more development time for your developers (something managers will want to maximize).

I think that the fact the other teams have started using Git internally is a meaningful sign, but it's still not strong enough because it can still be dismissed as personal preference.

You can point out that the qualitative difference is so big, that developers accross your company prefer the complications of installing, configuring and using git, on top of Clearcase, for it's extra features. It is actually a strong argument (if it didn't provide an alltogether better user experience and feature set, people wouldn't go the extra mile to use it - especially since it is something not required by the company).

So I have a meeting this week with the SVP in change of infrastructure who specifically wants me to explain to her the merits of Git.

Draw a chart representing commits with the two systems, and show the streamlining obtained by developers not comitting publicly (i.e. if you bork a file, the rest of the team is not blocked and unable to complile until you fix it). Also explain the extra quality controls you can make when you can make intermediary commits without affecting anyone else, the fact that you can get clean diffs per feature (essential for code reviews).

Title: Quantifying the advantages of a modern version control system

Body:
I've worked as a team lead/developer in a large financial enterprise environment for the better part of three years. Our production release process is a nightmare because it revolves around Clearcase. We have a change management group who executes all releases and who will only allow code into production that was taken from it.

One of the first things I did when joining was to set my team up with Git. Everyone agreed that Clearcase was awful and was impractical for handling day-to-day source control matters. So we set up a sort of "unofficial" repository on my local machine and I wrote a script to sync our git and Clearcase repos around release time.

Word of this spread to other teams and several have adopted the same process. Using git in an "unofficial" manner for day-to-day activities and "officially" using Clearcase for releases. I've become sort of the go to guy for any issues with Git.

So I have a meeting this week with the SVP in change of infrastructure who specifically wants me to explain to her the merits of Git. Word apparently got to her of my frequent rants on Clearcase. If she accepts my arguments, I will have a real shot at helping my employer rid themselves of this abomination.

My experience with executives tells me they a) want extremely terse explanations for everything b) are only interested in facts that involve dollar figures

To a developer I can explain the merits of Git over Clearcase (or ANY other version control system over Clearcase for that matter), but I'm drawing a blank on how to do this to a technical executive without a technical background (she has an MBA and did her undergrad in geography).

I feel any argument I make to her is either going to sound like technical gibberish or that I'm evangelizing my personal preferences.

What I'm trying to find are concrete facts demonstrating developers work more effectively with Git, or ANY modern source control system.

I think that the fact the other teams have started using Git internally is a meaningful sign, but it's still not strong enough because it can still be dismissed as personal preference.

What I really need is something powerful enough to break through the "This process has worked for 20 years, why should we change it?" argument.


答:
The man who taught me to program many many years ago once told me this -

"Any damn fool can write code a computer can understand.  To write code that a human can understand takes skill".

In general, anything which makes your code less human-readable is a really, really bad idea.  Especially selecting arbitrary characters to replace characters which could just as easily be escaped.


问:
Dictionary vs List
So I ran into a Dictionary<int, int> today at work. This just seemed weird to me because I would have probably just used a List<int> instead. Is there a difference and would there be a use case where one structure would be preferred over the other?

答:
Aside: Other programming languages refer to this type of data structure as a Map, rather than a Dictionary.

If your data can meaningfully be defined as key/value pairs, then a Dictionary will provide much faster access if you need to find a value using its key.

For example, suppose you have a list of Customers.  Each Customer includes details such as a name and address, and a unique customer number.  Suppose you also have a list of Orders being processed.  Each Order will contain details of what is being made, and will need to include the customer number of the person who ordered it.

When an order is ready to ship, you need to find the address to ship it to.  If the customers are stored as a plain List, then you need to search the entire list to find the customer with the right customer number.  Instead, you could store the customers in a Dictionary, with the customer number as the key.  The Dictionary will now let you pull out the correct customer in one step without any searching.

Title: Dictionary vs List


问:
Non Existent Keys Returning Null Instead of Exception
I have inherited a project from another developer, and it is riddled through and through with the following type of error:

```<code>echo $data['example'];

Notice: Undefined index: example
</code>```

Obviously, I'm going to refactor this to check for the existence of the key prior to the print statement. However, my question is not related to the code per-se.

Is there a version of PHP, or perhaps a setting within PHP whereby echo $data['example']; would simply return null or 0 in the case of a non-existent key?

I ask because I'm trying to ascertain whether the previous developer had written bad code, or whether their development environment is misconfigured. If it's the latter, we can obviously resolve these issues for that developer's future projects.

答:
An expression accessing non-existent keys evaluates to null, much like using variables that weren't declared or initialized evaluates to null.

These notices, though, are there to let you know your code might not work as expected. Sure, you can hush them up, but really you shouldn't.

Notices, and warnings should be seen as things to notify you of possible buggy code. Don't ignore the issue, fix it.

If the development environment truly ignores these notices, as you say, then that is the first problem that needs fixing: set your error level to E_STRICT|E_ALL when developing, and display the errors.

A notice isn't fatal, but if you run this code in a production environment, it probably will fill up your logs with clutter, and it does impact performance, too.

All in all: adding an isset check isn't too hard. It's just that it is a bit tedious at times...


答:
In Groovy language, the question mark has some functionality.

Imagine that you have a company and it may or may not have a location filled in the system. Same goes for its entire address fields. Now, if I want to get the street name, in similar languages like Java, I'd have to deal with null values. Not in Groovy!

```<code>String streetName = company.getLocation()?.getStreet()?.getStreetName();
</code>```

With that said, I think it's a bad idea to include ? in the variables/methods name. P cannot replace it also, it doesn't look like a readable code to me, I'd choose hasButtonChanged() instead of buttonChangedP() every single time, day and night.

Body:
In Groovy language, the question mark has some functionality.

Imagine that you have a company and it may or may not have a location filled in the system. Same goes for its entire address fields. Now, if I want to get the street name, in similar languages like Java, I'd have to deal with null values. Not in Groovy!

String streetName = company.getLocation()?.getStreet()?.getStreetName();

With that said, I think it's a bad idea to include ? in the variables/methods name. P cannot replace it also, it doesn't look like a readable code to me, I'd choose hasButtonChanged() instead of buttonChangedP() every single time, day and night.


问:
How do you make a service stateless?
When doing Domain Driven Design it is advised that services should be stateless. There are several kinds of services when doing DDD:

Application services.

Domain services.

Infrastructure services.

Factories, Repositories, Specifications,...etc.

How exactly do I make a service stateless?

Does that mean I shouldn't have any instance variables in a class? Is there any guidelines on making a service/class stateless?

I could really use a code sample that illustrate the difference between a stateful and stateless service.

Example: (Is this class stateful or not?)

```<code>Class DataToCsvFileGenerator{

    private String filePath;
    private ResultSet data;

    public String createCsv(ResultSet data){
       this.data=data;

       this.createLocalFile();
       this.loadDataIntoFile();

       return this.filePath;
    }

    private void createLocalFile(){
        this.filePath=//... logic to create file
    }

    private void loadDataIntoFile(){
        //function uses this.filePath to load data
    }
}
</code>```

Notice that any successive calls to createCsv() won't be affected by any prior invocation.

答:
Stateless services don't track information from call to call.  This means they can't have instance variables that are set as a result of calling a method.   They can have instance variables that the service needs, such as a logger or properties required to operate.

A customer service would not track any information about a customer from call to call.  Any information needed to track the customer would be saved externally and retrieved as needed.  Usually a database is used for persistence, but in some cases web services may use cookies or other client side mechanisms.

Your class appears to be stateful, although the state is not  useful. However, additional methods could make your instance variables publicly accessible.  A change as simple as running a generator in an IDE could do that.  The following rewrite is stateless.  Note that the logger variable, would hold a reference to the a logger and would not contain class state.  Initialization and use of the logger has been omitted.

```
Class DataToCsvFileGenerator{

    Static Logger logger;

    public String createCsv(ResultSet data){
       String filePath = createLocalFile();
       this.loadDataIntoFile(filePath, data);

       return filePath;
    }

    private String createLocalFile(){
        string filePath=//... logic to create file
        return filePath;
    }

    private void loadDataIntoFile(String filePath, ResultSet data){
        //function uses filePath to load data
    }
}```

Title: How do you make a service stateless?

Body:
Stateless services don't track information from call to call.  This means they can't have instance variables that are set as a result of calling a method.   They can have instance variables that the service needs, such as a logger or properties required to operate.

A customer service would not track any information about a customer from call to call.  Any information needed to track the customer would be saved externally and retrieved as needed.  Usually a database is used for persistence, but in some cases web services may use cookies or other client side mechanisms.

Your class appears to be stateful, although the state is not  useful. However, additional methods could make your instance variables publicly accessible.  A change as simple as running a generator in an IDE could do that.  The following rewrite is stateless.  Note that the logger variable, would hold a reference to the a logger and would not contain class state.  Initialization and use of the logger has been omitted.

Class DataToCsvFileGenerator{

    Static Logger logger;

    public String createCsv(ResultSet data){
       String filePath = createLocalFile();
       this.loadDataIntoFile(filePath, data);

       return filePath;
    }

    private String createLocalFile(){
        string filePath=//... logic to create file
        return filePath;
    }

    private void loadDataIntoFile(String filePath, ResultSet data){
        //function uses filePath to load data
    }
}


答:
The approach I have used is an audit table which records the before image and change time before each update or deletion.  Each table would have its own audit table, populated by a trigger.  This is usually combined with audit fields listing the change time and user making the change. The audit fields should populated by triggers to prevent spoofing.

Assuming a single userid was used for vandalism, this system should enable you to quickly identify potentially vandalized records.

To be able to back out changes, you would use a history browser, that allows a record to be replaced by a previous version.

Depending on your requirements, you may also want a database backup that allows you to perform point in time recovery.  This would allow you to quickly restore to the point before vandalism started.

Title: Patterns for undo in multi-user applications on relational data

Body:
I want to build a web application that will allow multiple users to collaboratively populate the contents of a fairly conventional relational database. (The database will have a fixed schema, which is known in advance).

I can see how to define the schema for the necessary object types, relations, and foreign key constraints (items, items as members of categories, links between items, and so on). Basic CRUD operations to instantiate and modify objects are no problem.

But for resilience against vandalism and mistakes, I can foresee that it will be necessary to have undo/rollback functionality, so that moderator-level users can undo changes made by other users. I'm having trouble figuring out a suitable approach to take for two key functional pre-requisites:

Capturing all the database changes that result from an initial user request. For example, there's a many-to-many relationship between items and categories. Therefore, if a category is deleted (triggered by a user submitting an HTML form), all the category-item relation records corresponding to that category will get deleted due to referential integrity constraints on the many-to-many relation. How can I record all the cascading consequences of an initial operation, so that's it's possible to completely undo it later?

How can I isolate undo operations so that a bad action by one user can be undone without also needing to roll back all the beneficial changes which have been made by other users, in between the bad action and the moderator's review?

The Undo patterns I've seen described (e.g. "Command" pattern) all assume that there is a stack of commands and undo operations are always applied in strict reverse order of initial application (no support for out-of-order undos).

Are there any standard patterns for handling undo capability in relational databases which would help meet these two goals? At the moment, I'm looking for generic algorithms and patterns which help solve the problems listed above, rather than platform-specific details.


问:
Is it faster to query using linq-to-entities or a data adapter?
I'm creating an MVC application in VS2012 and I reverse-engineered the models from existing Oracle tables. The tables are part of a MASSIVE database. Besides the main tables that I need to insert, update and delete from I also (on a whim) selected a few tables and views that my application only needs to read from. Now I am doubting my decision and considering deleting the less-important models.

It is definitely neater to query using linq-to-entities instead of creating an oracle connection, creating an adapter, filling a dataset and reading what I need, but which is faster?

答:
In general, ADO.NET (OracleConnection, OracleCommand, etc.) is going to be faster.

However, in cases where your LINQ query gets translated directly into a single SQL query, the difference in speed should be pretty minimal. There is a certain amount of additional wrapper logic that still must be applied (and, you're at the mercy of the translation logic), but in the overall scheme of things the difference in speed is usually pretty insignificant.

The real slowdown occurs when you do something in your LINQ query that prevents it from being executed as a single SQL query, e.g. invoking ".ToList()" on one of the collections you're joining together in your "from" clause. Joining to something that's not a database table would also have this effect, but that's not really a fair comparison; ADO.NET can't even run that sort of query (at least, not as a query per se).

In my experience, one can tell whether a LINQ query is getting directly translated to a SQL query by trying to get the actual SQL during a runtime debugging session. If it's there (e.g. when you hover over a variable into which the query is loaded), that's good.


答:
Try it and see!

One thing to note is that if you use Linq, and you do not include a .Select clause, you will be (effectively) running "select * " from the DB, which will be slower and less efficient.

When I last used Oracle with Linq, it generated particularly nasty SQL, running to many pages. I think the provider has been updated since then. You can turn on logging and see what SQL is being run when your LINQ query is executed, and look at the execution plan to see the difference between that and your hand-coded query.

Of course, you could do the best of both worlds: hand-write your queries and expose them as stored procedures. Then use Linq to access these, the fast and efficient query will be executed even though you're calling it from LINQ.

Title: Is it faster to query using linq-to-entities or a data adapter?

Body:
I'm creating an MVC application in VS2012 and I reverse-engineered the models from existing Oracle tables. The tables are part of a MASSIVE database. Besides the main tables that I need to insert, update and delete from I also (on a whim) selected a few tables and views that my application only needs to read from. Now I am doubting my decision and considering deleting the less-important models.

It is definitely neater to query using linq-to-entities instead of creating an oracle connection, creating an adapter, filling a dataset and reading what I need, but which is faster?


问:
How redundant should my tests be?
This is something I often struggle with in testing, yet can never find a canonical or reasonable answer to.

Simple scenario

A function, f(), takes a file, processes it, and returns the processed file.  f() has unit tests to check that it performs as expected.

A command-line interface application (CLI) takes a file path as input and uses f() to process the corresponding file.

How should I test the CLI? Passing it a path and ensuring that it handles that path — whether or not the file exists — is logical, but then passing that file to f() and checking the output is exactly what I'm doing in the unit tests for f(). It is redundant and twice as much work. Further, maintaining the tests when the function changes is twice as much work again.

Note: f() can be anywhere — in a library that someone else has written, for example, or part of the whole program itself. I'm trying to understand best practices in (not) redundantly testing functionality, not just in this small example.

答:
Assuming the CLI is a wrapper that parses the command-line arguments, and passes them to f() and does something with the results, the unit test for the CLI would be that it properly parses the command-line arguments and marshals the function arguments for f(), and that the results are properly 'used' (however that is defined).

If f() does file system or network access, you'd probably want to mock / put in a test stub for f() that verifies the arguments are as expected, that it provides given return values from f().

One benefit of modules / decomposition is that you defer to the module responsibility for meeting its contract. It is your responsibility to wisely choose modules. That the module / function you are deferring to has unit tests is a point in favor of trusting and using it, though, I'd really want to see that the tests are actually GOOD tests. :)

Title: How redundant should my tests be?


答:
Here is an attempt at how I would try that.

That may sound stupid for a developer, but to management, technological changes are seen as risky.

"If the magic thingy already works, why take the risk to break it?"

Thus, you have to turn the table. Make it more risky not to make the switch to git. At all costs, don't make it sound like it's a new toy.

I would start by saying that git is now widely used. Use numbers, like those :  http://ianskerrett.wordpress.com/2014/06/23/eclipse-community-survey-2014-results/

For a manager, this implies that they should be able to find plenty of developers using git. And a whole ecosystem of third party tools (I heard even Microsoft integrates git with visual studio now).

Also a manager can't really be blamed for following the mainstream things, do they? In contrast, who uses $other_cvs here?

Put emphasis on how large projects are using it, because it is simple, fast, flexible, powerful... Find big projects with big names attached to it (GNU/Linux, Google, Microsoft...) that use git.

Having demonstrated that it cannot be a bad move, you could then go on to how it would improve things in your case.

You want the company to stay competitive, and not be outrun by faster, more agile teams, right ?
I would try to find some internal (written) estimations on how the productivity changed by using Clearcase vs Git. You could use some help from you fellow developers there. Then extrapolate for the whole company (ie. all software developers), with numbers and estimated cost of staying with Clearcase.

I would even if appropriate recap the whole thing in a written e-mail after the meeting (include the right persons).


答:
How should I test the CLI?

In general, I leave testing the user interface to the user or some stand-in/advocate for the user (QA people). If there are utility functions to say... parse command line arguments, then I would unit test those.

If the wrapping function is not a user interface, then it probably should take f() as a parameter/strategy. At that point, it's trivial to test that the wrapper calls f(), without actually re-testing f(). For a user interface though, I think that is overkill.

Title: How redundant should my tests be?

Body:
This is something I often struggle with in testing, yet can never find a canonical or reasonable answer to.

Simple scenario

A function, f(), takes a file, processes it, and returns the processed file.  f() has unit tests to check that it performs as expected.

A command-line interface application (CLI) takes a file path as input and uses f() to process the corresponding file.

How should I test the CLI? Passing it a path and ensuring that it handles that path — whether or not the file exists — is logical, but then passing that file to f() and checking the output is exactly what I'm doing in the unit tests for f(). It is redundant and twice as much work. Further, maintaining the tests when the function changes is twice as much work again.

Note: f() can be anywhere — in a library that someone else has written, for example, or part of the whole program itself. I'm trying to understand best practices in (not) redundantly testing functionality, not just in this small example.


答:
What I really need is something powerful enough to break through the "This process has worked for 20 years, why should we change it?" argument.

It's hard to really judge what would be a good argument without being a witness of the scene.  But I'll try to help you frame your arguments so that they may be heard.

I assume your audience to have be a non-expert level of knowledge on the topic, and to have an interest in staying the current course.  They have different concerns and responsibilities, and they may suffer serious consequences if something goes wrong, so you'll have to work from that mindset.  Anticipate some of the questions or worries they might have:

What new capabilities would this bring?  Is there something that we currently cannot do, that we would like to do, and that this new thing would allow us to?  Start on a positive note.

What is the impact on release schedules?  What is the cost of implementing this change towards the immediately next release?  What are the costs and benefits to following releases?

Will this entail a change in process?  As distinct from the release schedule, will this change require that people in the release process change their ways?  Will this be transparent to them, or will they need to adapt?  Will you need to cooperate with other departments?  People are resistant to change.

Are there imminent dangers to sticking with the current system?  Does the current process have software or hardware dependencies that have gone or will go end-of-life soon?  Does it rely on specialised knowledge from individuals that drives up hiring costs?  Does it have a potential security hole that the new system plugs (bonus points if this hole can lead to legal action)?  Don't hand-wave or 'maybe' or 'probably' this: the sense is that it worked well for 20 years, so the burden of proof is on the advocate of change.

Also, be specific about problems and solutions.  If you can't find specific examples, use honest estimates from your position as an expert.  Examples of other companies/departments/entities adopting such a change, preferrably from your industry, and their evaluation of that change, will help you.  (Don't pick examples that had some sort of publicised IT issue in recent years, or the onus will be on you to prove that this change was not the cause.)

You may find this answer to Convince the Company I Work for to Implement Version Control? helpful.


问:
What do you call a problem caused by a design flaw
Is there any terminology for a problem that is caused by a previous wrong decision?

For example you build your own framework, with a flawed MVC design. This in turn leads to weird situations when routing requests. A person then asks how to solve the latter problem, while the actual problem is the wrong design of the framework.

I've tried searching several descriptions but as I'm looking for the word, it's hard to find anything relevant.

It's not one of these Anti-patterns

答: I think this question has no answer because problems aren't categorized by what they're caused by, but by what kind of problem they are. A security vulnerability can be caused by a design flaw or an implementation error, regardless: it's a security vulnerability.</p>


问:
When would you want two references to the same object?
In Java specifically, but likely in other languages as well: when would it be useful to have two references to the same object?

Example:

```<code>Dog a = new Dog();
Dob b = a;
</code>```

Is there a situation where this would be useful? Why would this be a preferred solution to using a whenever you want to interact with the object represented by a?

答:
This method is great when you have several objects that all call back to another object that can be used uncontextually.

For instance, if you have a tabbed interface you may have Tab1, Tab2, and Tab3. You may also want to be able to use a common variable regardless of which tab the user is on to simplify your code and reduce having to figure out on the fly over and over which tab your user is on.

```<code>Tab Tab1 = new Tab();
Tab Tab2 = new Tab();
Tab Tab3 = new Tab();
Tab CurrentTab = new Tab();
</code>```

Then, in each of the numbered tabs onClick, you could change CurrentTab to reference that Tab.

```<code>CurrentTab = Tab3;
</code>```

Now in your code you can call "CurrentTab" with impunity without needing to know which Tab you are actually on. You can also update properties of CurrentTab and they will automatically flow down to the referenced Tab.

Body:
This method is great when you have several objects that all call back to another object that can be used uncontextually.

For instance, if you have a tabbed interface you may have Tab1, Tab2, and Tab3. You may also want to be able to use a common variable regardless of which tab the user is on to simplify your code and reduce having to figure out on the fly over and over which tab your user is on.

Tab Tab1 = new Tab();
Tab Tab2 = new Tab();
Tab Tab3 = new Tab();
Tab CurrentTab = new Tab();

Then, in each of the numbered tabs onClick, you could change CurrentTab to reference that Tab.

CurrentTab = Tab3;

Now in your code you can call "CurrentTab" with impunity without needing to know which Tab you are actually on. You can also update properties of CurrentTab and they will automatically flow down to the referenced Tab.


问:
Are bloom filters actually faster than hashes, even taking in account cache?
Bloom filters look really great when you consider you can determine if an Int is in a set with 99% certainty in constant time. But so can hashes, with the only difference that, in a hash, most of the time you are accessing the memory only once. With bloom filters, you need to access them ~7 times per request in completely distant places, so you'd have several cache misses per request.

Am I missing something?

答:
The use-cases for bloom filters and hashes are distinct and mostly disjoint, so direct comparison does not make sense. Besides it will depend on technical details of the implementations as there are many ways to handle hash collisions with different trade-offs.

The bloom filter can answer whether element is in a set for huge sets, with reasonable probability, but not exactly, using modest amount of memory. Huge, like, trillions of elements. But they are never exact. You can only reduce the amount of false positives by using more memory or more hash functions.

On the other hand hash tables are exact, but they need to store the set. So trillions of elements would require terrabytes of memory (and that's only american trillions). They can also store extra data for each element, which bloom filters can't.

So bloom filters are used when you have a slow method of getting data for some member  (that involves querying server, reads from disk and such) of a large set (that won't fit in memory or it is impractical to transfer it to client or such) and want to avoid running the slow operation for objects that are not in the set.


问:
Effective Repository in C# - Where to put methods?
I'm trying to build a new application using the Repository pattern for the first time and I'm a little confused about using a Repository. Suppose I have the following classes:

```<code>public class Ticket
{

}
public class User
{
   public List<Ticket>AssignedTickets { get; set; }
}
public class Group
{
   public List<User> GroupMembers { get;set; }
   public List<Ticket> GroupAssignedTickets { get;set; }
}
</code>```

I need methods that can populate these collections by fetching data from the database.

I'm confused as to which associated Repository class I should put those methods in. Should I design my repositories so that everything returning type T goes in the repository for type T as such?

```<code>public class TicketRepository
{
   public List<Ticket> GetTicketsForGroup(Group g) { }
   public List<Ticket> GetTicketsForUser(User u) { }
}
public class UserRepository
{
  public List<User> GetMembersForGroup(Group g) { }
}
</code>```

The obvious drawback I see here is that I need to start instantiating a lot of repositories. What if my User also has assigned Widgets, Fidgets, and Lidgets? When I populate a User, I need to instantiate a WidgetRepository, a FidgetRepository, and a LidgetRepository all to populate a single user.

Alternatively, do I construct my repository so that everything requesting based on type T is lumped into the repository for type T as listed below?

```<code>public class GroupRepository
{
    public List<Ticket> GetTickets(Group g) { }
    public List<User> GetMembers(Group g) { }
}
public class UserRepository
{
   public List<Ticket> GetTickets(User u) { }
}
</code>```

The advantage I see here is that if I now need my user to have a collection of Widgets, Fidgets, and Lidgets, I just add the necessary methods to the UserRepository pattern and don't need to instantiate a WidgetRepository, FidgetRepository, and LigetRepository class every time I want to create a user, but now I've scattered the concerns for a user across several different repositories.

I'm really not sure which way is right, if any. Any suggestions?

答:
As it turns out, the first option was the more practical option in this case. There were a few reasons for this:

1) When making changes to a type and its associated repository (assume Ticket), it was far easier to modify the Ticket and TicketRepository in one place than to chase down every method in every repository that used a Ticket.

2) When I attempted to use interfaces to dictate the type of queues each repository could pull, I ran into issues where a single repository couldn't implement an generic interface using type T multiple times with the only differentiation in interface method implementation being the parameter type.

3) I access data from SharePoint and a database in my implementation, and created two abstract classes to provide data tools to the concrete repositories for either Sharepoint or SQL Server. Assume that in the example above Users come from Sharepoint while Tickets come from a database. Using my model I would not be able to use these abstract classes, as the group would have to inherit from both my Sharepoint abstract class and my SQL abstract class. C# does not support multiple inheritance of abstract classes. However, if I'm grouping all Ticket-related behaviours into a TicketRepository and all User-related behaviours into a UserRepository, each repository only needs access to one type of underlying data source (SQL or Sharepoint, respectively).


问:
What payoffs have you seen from taking care of technical debt?
This article on technical debt has some good points, including:

Working on the "technical matters" works best when it is driven by stories. The code base is probably in need of work everywhere, but the payoff will be received only where the code is going to be worked on for user-facing reasons. If no stories are going to pass through some crufty area, working on it is largely wasted.

Therefore, I prefer the approach of taking stories as usual (but probably fewer of them), and following the "boy scout rule" of leaving the campground better than you found it. In other words, wherever the stories lead us, let's write more tests, let's refactor more aggressively.

This approach has at least these advantages:

maintains "best sensible" flow of stories;

provides help from all team talent;

provides for whole team to learn how to keep code clean;

focuses improvement exactly where it is needed;

does not waste improvement that "may" be needed;

I've seen code quality have a very big effect on long-term productivity, so I am a believer that technical debt should be taken care of.  I think the post above makes sense, but I'm not so sure about the last two points.  I'm interested in finding out real experiences of benefits from cleaning technical debt, even if it was not related to user stories.

What positive benefits have you seen from cleaning up your code base and ridding yourself of technical debt? What methods did you use to get the work done?

答:
eliminating technical debt yields less technical support and a better foundation for enhancements

always

ContentLicense: CC BY-SA 2.5


答:
I think the term "technical debt" is used often to mean precisely that.

Wikipedia's definition seems to describe what you express in your question:

Technical debt (also known as design debt or code debt) is a
  neologistic metaphor referring to the eventual consequences of poor
  system design, software architecture or software development within a
  codebase. The debt can be thought of as work that needs to be done
  before a particular job can be considered complete or proper. If the
  debt is not repaid, then it will keep on accumulating interest, making
  it hard to implement changes later on. Unaddressed technical debt
  increases software entropy.

The term does not refer though to any given problem but to the sum af all of them.

Title: What do you call a problem caused by a design flaw

Body:
Is there any terminology for a problem that is caused by a previous wrong decision?

For example you build your own framework, with a flawed MVC design. This in turn leads to weird situations when routing requests. A person then asks how to solve the latter problem, while the actual problem is the wrong design of the framework.

I've tried searching several descriptions but as I'm looking for the word, it's hard to find anything relevant.

It's not one of these Anti-patterns


问:
Learning to write DSLs utilities for unit tests and am worried about extensablity
I'm trying to simplify our unit tests with hand written DSL's.  So far I have DSL's that walk developers through processing a service after setting up all preconditions and the construction of an monster object that has a huge constructor and setters that conflict.  The monster is one of the many preconditions of processing the service and they constructed by hand over and over as developers write unit tests for new services in our system.  So it would be worth putting considerable effort into making constructing them easier.  I'm tried of watching people copy and paste the "life support system" from unit test to unit test.

I'm making separate new classes, one who's job it is to build the monster class and one that walks them through the steps to process the service.  These will be used by many developers.  This means once it's used widely changes will be difficult.  That's why I'm worried about extendability.

Rather than a simple fluent interface builder (where every method returns a this and is always available) I've decided to use an internal DSL that returns a different nested class.  This is a very powerful choice.  It lets me limit the methods available at any one step to only the valid ones.  It also lets me change what the return type of a method is based on the "state" previous choices put the DSL into.

Briefly, the way it works is the first method returns the first nested class that has the next valid method that could not have been called before.  This limits the choices intelisense will offer making writing the DSL's calling code easier.

```<code>//Final build() method doesn't exist on PersonBuilder.  Its on a nested class.
public class PersonBuilder {
    public GotRequired doRequired() {
        return new GotRequired();
    }

    //One of many nested classes
    public class GotRequired {
        public GotFirstName addFirstName(String firstName) {
            mFirstName = firstName;
            return new GotFirstName();
        }
    }

    public class GotFirstName {
        public GotMiddleName addMiddleName(String middleName) {
            mMiddleName = middleName;
            return new GotMiddleName();
        }
    }

    ...

}
</code>```

This can be used to ensure methods are called in some order and ensure that preconditions have been met.  The inner classes can be thought of as states the DSL is in.  More than one state change path can be supported.  Simply being in a state can tell you what states came before so long as no state merges two state paths into one.  This all just means if you're careful you can know every needed method was called before building or returning a result.

Fair warning, what follows is java verbose boiler plate at it's finest.  The full listing is here: Monster builder code.

The monsters DSL code looks something like this:

```<code>public class PersonBuilder {

// -- Required -- //

private String   mFirstName;
private String   mMiddleName;
...

// -- Required Alternatives -- //

//Not both; not neither
private int      mBeersToday;     //One or
private String   mHowDrunk;       //the other

// -- What all the fuss is about -- //

private Person   mPerson;

/** Call each required method in order offered.*/
public GotRequired doRequired() {
    return new GotRequired();
}

public class GotRequired {
    public GotFirstName addFirstName(String firstName) {
        mFirstName = firstName;
        return new GotFirstName();
    }
}

public class GotFirstName {
    public GotMiddleName addMiddleName(String middleName) {
        mMiddleName = middleName;
        return new GotMiddleName();
    }
}

...

/*
   Client code example

    .doRequiredAlternatives()   //Either x or y. a, b, or c. etc.
        .addBeersToday(3)       //Now can't call addHowDrunk("Hammered");
        .addFavoriteBeer("Duff")//Now can’t call addJobTitle("Safety Inspector");
   .addBuild();                 //Calls different constructors based on alternatives

*/
    /** Now the interesting forking bit */
    public class GotRequiredAlternatives {
        public GotPerson addBeersToday(int beersToday){
            mBeersToday = beersToday;

            //Got enough for constructor
            mPerson = new Person(
                    mFirstName,
                    mMiddleName,
                    mLastName,

                    mNickName,
                    mMaidenName,
                    mEyeColor,
                    mHairColor,
                    mDateOfBirth,
                    mBeersToday, //GotBeersToday
                    mAliases);

            return new GotPerson();
        }

        public GotPerson addHowDrunk(String howDrunk){
            mHowDrunk = howDrunk;

            //Got enough for constructor
            mPerson = new Person(
                    mFirstName,
                    mMiddleName,
                    mLastName,

                    mNickName,
                    mMaidenName,
                    mEyeColor,
                    mHairColor,
                    mDateOfBirth,
                    mHowDrunk, //GotHowDrunk
                    mAliases);

            return new GotPerson();
        }
    }

    //Could have created GotHowDrunk and GotBeersToday
    //but we're past the constructor choice so we can
    //forget the path that brought us here.

    public class GotPerson {
        /** Build Person object leaving optional fields set to default values */
        public Person doBuild() {
            return mPerson;
        }
        /** Call any or none of these optional fields */
        public GotOptional doOptional() {
            return new GotOptional();
        }
    }

    //Since person is not immutable the only thing gained here is confidence that these were set according to persons whacky rules
    class GotOptional {

        /** Build Person object */
        public Person doBuild() {
            return mPerson;
        }

        public GotOptionalAlternatives doOptionalAlternatives() {
            return new GotOptionalAlternatives();
        }

        public GotOptional addClothing(String clothing) {
            mPerson.setClothing(clothing);
            return this;
        }

        public GotOptional addTatoo(String tattoo) {
            mPerson.setTattoo(tattoo);
            return this;
        }

        //Add any number of setters that have good default values and do not conflict with each other

    }

    //Ideally person wouldn't allow this anyway but person is set in stone so at least this provides a safer interface
    public class GotOptionalAlternatives {

        /** Build Person object */
        public Person doBuild() {
            return mPerson;
        }

        //Optional but conflicting setters. Might never be called.  Must never be called together.

        public GotFavoriteBeer addFavoriteBeer(String favoriteBeer){
            //mFavoriteBeer = favoriteBeer;  //TODO remove
            mPerson.setFavoriteBeer(favoriteBeer); //GotFavoriteBeer

            return new GotFavoriteBeer();
        }

        public GotJobTitle addJobTitle(String jobTitle){
            //mJobTitle = jobTitle;  //TODO remove
            mPerson.setJobTitle(jobTitle); //GotJobTitle

            return new GotJobTitle();
        }
    }

    //These are not strictly needed.  They are like one-statement {}'s after an 'if'.  Simply there if more gets added.

    public class GotFavoriteBeer {
        /** Build Person object */
        public Person doBuild() {
            return mPerson;
        }
    }

    public class GotJobTitle {
        /** Build Person object */
        public Person doBuild() {
            return mPerson;
        }
    }
}
</code>```

I'll spare you the service code that uses the same nested class technique to mix optional methods and required methods.  It is also able to return different result types based on previous alternate method choices since even though the result() method has the same name and params it's coming off a different inner class.

Despite the unreal amount of typing required to create these DSLs I've found the results to be very powerful.  However, I expect people will want new features added, new preconditions for processing the service.  If I use this style is there any hope of reuse or would it be better to just write a whole new DSL each time something needs to change?

Cause once it's working and being used I do NOT want to dive back into the existing DSL classes and mess with them.

If you can see other issues please let me know.  I'm hoping for a peer review but I appreciate any feedback.

答:
Here's the thing with unit tests. You want them to be really easy to write. Anytime writing a test is made more difficult, it will result in tests not being written, and bugs will be allowed to live. So let's imagine I'm writing a test:

```<code>void testCanDrive() {
    Person person = new PersonBuilder()
        .doRequired()
        .addFirstName("John")
        .addMiddleName("Q")
        .addLastName("Smith")
        .addNickName("Johnny")
        .addMaidenName("Public")
        .addEyeColor("Blue")
        .addHairColor("Blond")
        .addDateOfBirth(new Date(1990, 1, 14))
        .addAliases()
        .doRequiredAlternatives()
        .addBeersToday(1)
        .doBuild();
    assertFalse(person.canDrive());
}
</code>```

Here's the thing, I had to write a crazy amount of code to create the person object, and I didn't really care about most of those details. The only factors that would seem relevant to whether you can drive would be your date of birth and the beers you've had. Forcing the test writer to specify all of that other details makes it harder to follow the test and discourages me from writing further tests.

Now your solution is probably way better than the status quo, but it still sucks. I would suggest that you really want to use a typical builder interface that set default values for everything. Each test will only set those details pertinent to the test itself, for everything else the defaults should be fine.

```<code>void testCanDrive() {
    Person person = new PersonBuilder()
        .setDateOfBirth(new Date(1990, 1, 14))
        .setBeersToday(1)
        .doBuild();
    assertFalse(person.canDrive());
}
</code>```

Body:
Here's the thing with unit tests. You want them to be really easy to write. Anytime writing a test is made more difficult, it will result in tests not being written, and bugs will be allowed to live. So let's imagine I'm writing a test:

void testCanDrive() {
    Person person = new PersonBuilder()
        .doRequired()
        .addFirstName("John")
        .addMiddleName("Q")
        .addLastName("Smith")
        .addNickName("Johnny")
        .addMaidenName("Public")
        .addEyeColor("Blue")
        .addHairColor("Blond")
        .addDateOfBirth(new Date(1990, 1, 14))
        .addAliases()
        .doRequiredAlternatives()
        .addBeersToday(1)
        .doBuild();
    assertFalse(person.canDrive());
}

Here's the thing, I had to write a crazy amount of code to create the person object, and I didn't really care about most of those details. The only factors that would seem relevant to whether you can drive would be your date of birth and the beers you've had. Forcing the test writer to specify all of that other details makes it harder to follow the test and discourages me from writing further tests.

Now your solution is probably way better than the status quo, but it still sucks. I would suggest that you really want to use a typical builder interface that set default values for everything. Each test will only set those details pertinent to the test itself, for everything else the defaults should be fine.

void testCanDrive() {
    Person person = new PersonBuilder()
        .setDateOfBirth(new Date(1990, 1, 14))
        .setBeersToday(1)
        .doBuild();
    assertFalse(person.canDrive());
}


问:
Efficiency of self-education
Do you think being self-educated in software development is good? Please give an example of what you have learnt successfully by yourself.</p>

答:
A couple of random ramblings on the subject...

As all others have said, you are going to have to do a lot of self-study as your career progresses.  One thing that I haven't really seen spelled out here, though, is the reality is that you will find it very difficult to find that first job without some formal education in a related field, especially in a recession.  A lot of resumes pass over the "filtering desk," and if there is nothing on there with related education on it, it is likely to be passed over.  You may squeak by if you have a lot of related experience, but it depends on how closely somebody reads your resume (which, in the first round, is unfortunately not very likely).  It's unclear if this applies to you, but it will apply to somebody, I'm sure.

On a (somewhat) unrelated note, self-study is great, but having the time to do so is even greater (and more rare, I would argue).  We all fit it in somehow, but if you are given the opportunity to take some time each day to work on learning something, grab it and hold on with all your might.

Title: Efficiency of self-education


答:
Of course you can have instance variables in a class but the class-instance does not exist any more on the next call if you have a stateless service.

a classical statefull service is a cart where articles can be added to. with these statefull service-methods:

createCart

addArticleToCart(quantity, articleid)

removeArticleFromCart(quantity, articleid)

....

you can make a service stateless if you provide all necessary infos as parameters of the call:

createCart returns a cartID

addArticleToCart(cartID, quantity, articleid)

removeArticleFromCart(cartID, quantity, articleid)

the statefull cartService is responsible to remeber the cartID.

the stateless cartService gets the cartID on ever servicecall.

Title: How do you make a service stateless?

Body:
When doing Domain Driven Design it is advised that services should be stateless. There are several kinds of services when doing DDD:

Application services.

Domain services.

Infrastructure services.

Factories, Repositories, Specifications,...etc.

How exactly do I make a service stateless?

Does that mean I shouldn't have any instance variables in a class? Is there any guidelines on making a service/class stateless?

I could really use a code sample that illustrate the difference between a stateful and stateless service.

Example: (Is this class stateful or not?)

```<code>Class DataToCsvFileGenerator{

    private String filePath;
    private ResultSet data;

    public String createCsv(ResultSet data){
       this.data=data;

       this.createLocalFile();
       this.loadDataIntoFile();

       return this.filePath;
    }

    private void createLocalFile(){
        this.filePath=//... logic to create file
    }

    private void loadDataIntoFile(){
        //function uses this.filePath to load data
    }
}
</code>```

Notice that any successive calls to createCsv() won't be affected by any prior invocation.


问:
When using Visual Studio 2012 do you have to use the drag and drop system?
I am fluent in most of Java and have thought about moving on to a .Net language. Obviously C# and Java are very similar so I have chosen to learn C#. When programming in Java I would always use Eclipse as my IDE, which doesn't have a Drag and Drop system for creating the UI. I noticed, however, that Visual Studio does for all .Net languages. I love to keep my code clean and format it in my own away and do not like how Visual Studio formats it. I have looked for tutorials on how to program the GUI instead of using Drag and drop but cannot find any tutorials. Any help? Do I have to use the Drag and Drop system. (By "the Drag and Drop System" I meant he form creator.)</p>

答:
Code generators increase productivity...

Code generators available in Visual Studio are here to make your life easier. This includes the one which generates code for Windows Forms.

A graphical tool like that is particularly useful when you need to communicate that this button is large and is positioned here, while that one is small and is just in this corner, but not too close to the border: having to position the elements through code would be much harder. If you're not convinced, try to do both techniques while sitting near a stakeholder or a designer who actually takes decisions about the look of a form; what would be more productive: to have an immediate visual feedback after every change, or to have to recompile and rerun the app every time, trying to guess whether "close enough to the border" should be 11, 12, 13, 14 or 15 pixels?

... so be productive

As a programmer or a developer, you're expected to write clean code when it is beneficial for the project. Following the clean code dogma in every case makes you unproductive: in other words, you become a burden for the project.

It's your job to determine right where clean code matters, and where anybody couldn't care less.

A piece of business-critical code which will be read thousands of times by you and your colleagues over ten years period and frequently modified has every reason to be as clean as possible. On the other hand, boilerplate code nobody will read doesn't have to be well commented or nicely indented.

Code generators also have a benefit compared to a human: machines have less chances to introduce a subtle bug. Guess how much bugs I've found in code produced by code generators for the last five years? Zero. On the other hand, when repetitive and monotonous tasks are performed by humans, errors have a great risk of being introduced. A bug at this level would only decrease your productivity.

Side note: as a recruiter, I'll probably reject a candidature of a .NET WinForms programmer who claims that he don't use WinForms code generator because he prefers writing clean code by hand. While I favor persons who are able to write clean code, I don't need a person who is wasting my money typing by hand boilerplate code.

Code generators don't necessarily produce ugly code...

Talking about clean code, Windows Forms code is not the ugliest one. It could certainly be better (and at least be compliant with the official style guidelines enforced through StyleCop and official recommendations enforced through Code analysis), but in all cases, the usage of partial classes with two SuppressMessage and a GeneratedCode similarly to this example makes it possible to abstract completely this part of the code and prevent it from spawning useless warnings during static checking.

... but not all code generators are equal

Code generator for ASP.NET (WebForms) is a very different beast. It's not particularly useful: unless a programmer doesn't know HTML, he'll be as efficient (if not more) writing code directly. My recommendation is to never use this code generator.

Code generator for WPF is quite useful when you don't know the exact names. On the other hand, it often produces code which is much more complicated than it should be. My recommendation is to use this code generator selectively, and try to write most XAML code by hand¹.

Code generator for LINQ to SQL and for Entity Framework is a must-have. There is no need to write boilerplate code by hand. T4 is an excellent feature which reduces even more the necessity to write repetitive code.

Conclusion

This being said, nothing forces you to use those code generators. You can create a form directly in code, including through Visual Studio.

¹ I have used WPF in Visual Studio 2010 only. Things may have changed since then, and if I remember well, next versions of Visual Studio were advertised for having a much better WPF editor.


问:
Entity-Attribute-Value table vs single table for storage of posts, events and pages
I am trying to decide whether to just use individual tables with more fields for storing posts, pages and events or using tables with basic fields plus having EAV tables as well for fields that are optional. Also EAV would allow to add more 'attributes' to each entity without actually changing the database at all (just changing the application code slightly).

However, what I am worried about is performance. Would EAV decrease performance in such scenario (storing data like events)?

Also, is it worth adding an EAV table like event_meta to the database just in case I will need to add extra fields/attributes to the model later on (when specs change and the system has to be expanded)?

Currently I can think of two options:

Not using EAV tables and just having single tables for each entity type (posts, pages and events) and having all data (about 15 fields) in the entity table.

Use EAV tables to store optional data that is not usually entered by users (this would prevent the entity tables from having many empty fields) but store all required and crucial data in the entity tables.

Also, for option two I might actually be able to just have one generic table 'posts' to instead of 3 tables posts, pages and events and just use more attribute-value rows in the EAV table (and have a type field in the posts table). However that would probably reduce the performance even more.

Option 1 is much easier to implement. However option 2 might make it easier to extend the entities in the future as database would not have to ever be adjusted.

Another important thing to consider is performance. What happens when we have millions of rows in the events_meta. Every time someone would view an event the application would have to perform queries on both tables which would be quite big and I am afraid that would reduce performance.

So which option should I use for my situation?

答:
Do not build a database in your database.  The performance will suck and so will the code to manage it.  Attributes that drive application logic should be real columns in the database on the appropriate table with a name matching their purpose.  Use an EAV when you need to support an arbitrary number of user-defined attributes that are transparent to your application.

Schema changes are a part of database application maintenance.  Attempting to avoid it leads to madness.


问:
How to implement await in Android
This is a general question to understand how await in C# works, and particularly I am interested in implementing it in Android.

So C# await allows you to go in to waiting mode in the middle of the method until the the task you are waiting for is complete, then you will continue the method execution.

How ever the interesting part is while you are waiting inside the method, the thread that you are working on is not getting locked(or at list it does not looks like it got locked) and the code will continue running from where you called that method.

I want to understand what is happening there in C# and how can I implement it in Android?

答:
How it works is fully explained here. Unfortunately, it's mostly implemented in the compiler. You might be able to do it by implementing a state machine and some lambda expressions, but by the time you do all that, callbacks are almost going to be simpler.

There is a non-compiler implementation/replacement for Async/Await in this Code Project article that you might be able to translate into Java.  It works by spinning off background threads in a process he calls "cooperative threading," rather than reordering method calls as the C# compiler does.

References

Code Project: Async/Await could be better

Stack Overflow: How to Await without Async CTP

MSDN: Asynchronous Programming with Async and Await (C# and Visual Basic)

Title: How to implement await in Android


答:
(Is this class stateful or not?)

Yes, it is stateful.

Now it's not...

```<code>    Class DataToCsvFileGenerator{

      public string createCsv(ResultSet data, string filePath){
         string fullFilePath = string.Empty;

         fullFilePath = this.createLocalFile(filePath);
         this.loadDataIntoFile(data, fullFilePath);

         return fullFilePath;
      }

      private string createLocalFile(string filePath){
          filePath=//... logic to create file
      }

      private void loadDataIntoFile(ResultSet data, string filePath){
          //function uses filePath to load data
      }
    }
</code>```

Title: How do you make a service stateless?

Body:
(Is this class stateful or not?)

Yes, it is stateful.

Now it's not...

    Class DataToCsvFileGenerator{

      public string createCsv(ResultSet data, string filePath){
         string fullFilePath = string.Empty;

         fullFilePath = this.createLocalFile(filePath);
         this.loadDataIntoFile(data, fullFilePath);

         return fullFilePath;
      }

      private string createLocalFile(string filePath){
          filePath=//... logic to create file
      }

      private void loadDataIntoFile(ResultSet data, string filePath){
          //function uses filePath to load data
      }
    }


问:
If your workmate is quitting his job, would you notify your boss?
If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>

答:
Generally speaking, no. I don't think it is anyone else's business if someone wants to quit, and it is not my place to tell work. In my mind, that would be the equivalent of telling a man's wife that her husband doesn't find her attractive any more. Not my business nor my call.

Now, as stated above, if there were prevailing circumstances... if the employee planned to somehow attack the company on departure (delete existing code and wipe out the backups) or plan the timing in such a way as to hurt the company (make a big scene on the day a multi-million dollar client is visiting) or maybe just leaving under high pressure stakes (we have a week to get this done and don't know how we're gonna make it with the few people we have in the first place) then maybe I might drop a hint that my boss needs to talk to this co-worker about their attitude or intentions.


问:
Should the check correctness of a time constrained puzzle game application be done on the server side?
I am working on an application where a user has to complete a puzzle and check  within a given time limit.

This is an HTML5 based game, I can't keep the solution on the client side.
but I also want to avoid the latency that will be caused when we check for the correctness of the player's attempt.

Is there a way I can check the correctness of the solution on the client side safely ?

One implementation I was considering was to take the hash of the solution and compare it with hash of user's solution  at the client side and once he finally submits it, recheck it on the server side.

Any potential flaws here or are their cleaner ways to accomplish the same ?

答: Depending on the puzzle you could use a rule based solution check. So for a sudoku puzzle you wouldn't explicitly list the value of each square just check that each column, row, and 3 by 3 section each have exactly one instance each number one through nine.</p>


问:
Knowing the range of variable types needed
So, if I (as the programmer) know that my value will never exceed a small number (say 100) because it is really just a counter-controlled loop or whatever, may I use short or char instead of int for the minute memory savings?

答: I suppose you could. Of course, if you do that you should also include code that validates your variable so that if an input is greater than 100, you get a sensible error message. And it's also a good idea to add comments to explain why you're using char instead of int (if that's what you end up doing). It might not be obvious to everyone. Are you working in an environment where memory is so tight that this will make a significant difference to your program? Are you doing this for educational reasons?


问:
What can REST API do that a API using HTTP URL query strings cannot do?
I'm learning about REST and had the chance to build a basic REST API.  After doing so, most of the material I read was internalized and I now have a better understanding of it.

However, I do not see any real difference yet as to the tangible benefits of using REST over the old way I was doing things, which was simple URL query strings.  It seems they both do the exact same things.  But with REST, it's cleaner, and standardized.

I thought REST had additional technical benefits.  If they do, what are they?  Or is REST simply that - an agreed way to implement and API?

答:
REST has many technical benefits, and it's not just about "style". It's an architecture, a way of thinking, that has many benefits over an rpc-style architecture. REST is also MUCH more than just a URI scheme.

REST provides 5 "constraints" that help guide toward a good API:

1. Client–server

Self-explanatory and already the nature of web apps.

2. Stateless

Statelessness means that state is maintained on the client. This makes every request/response transaction independent. Benefits are:

Stateless communications enable clients to recover from network errors.
Clients and servers can come and go without corrupting state.
New processing nodes can be attached without complex state management.

3. Cacheable

Cache control at multiple levels (client, server, intermediary) – because state exists in only one place. For obvious reasons caching at multiple levels decreases latency, bandwidth, and cost.

4. Layered system

Limits complexity at each layer. Also improves security because security can be implemented at multiple levels.

5. Uniform interface

Resources are identified by URIs. These URI's serve as an abstraction and should not change often. Representations are representations of a resource to the client based on a  negotiation. Control Data is what negotiates the representations and actions. Hypermedia protects the server from being locked into a uri scheme.

All of these are part of REST. It's much more than a URI scheme.


答:
You can, and this will likely work. As FrustratedWithFormsDesigner mentioned you will need to be sure of bounds checking.

Another important factor is that as delnan said registers are fixed size. But using them as a smaller type may mean using different, less-efficient instructions if the variable's size is not the computer's word size.

Most of the time there is not much to be gained from using variable sizes smaller than the machine's word size. Embedded systems may benefit, and if a file format specifies specific field sizes then of course use those. Another thing to keep in mind is memory alignment, a 16 bit variable may be aligned on a 32 or 64 bit memory boundary with unused space between variables. Or it may not. Or it may be a compiler flag.

Edit: the comments brought up a good point. Even with a 64 bit word size, int is still likely 32 bits (C/C++, desktop platforms). The reasons are historical and out of context here. However, a modern 64 bit CPU such as the Intel Core i7 is heavily optimized for 32 and 64 bit arithmetic. Any CPU should be fast when using ints the same size as its native word size. However, there is a lot of 32 bit software out there that these CPUs need to be able to run and run well. Working with ints smaller than 32 bits may or may take a performance hit, as you are now outside the realm of what the CPU is optimized for. In practice I would expect any performance hit to be minimal, and the memory difference would be negligible as well. File this one under "premature optimization."

Title: Knowing the range of variable types needed

Body: So, if I (as the programmer) know that my value will never exceed a small number (say 100) because it is really just a counter-controlled loop or whatever, may I use short or char instead of int for the minute memory savings?


答:
Yes This is especially useful in for loops. People often just use int, or allow var to determine what the variable type should be. This is inefficient (but not terribly so), but for people like me who like to get every ounce of performance and are just tickled pink by using the most perfect datatype for a situation, this is awesome.

```<code>for(SByte i = 0; i <= 10; i++)
{
...code
}
</code>```

SByte allows -128 to 127. I love this little datatype because it saves on memory and is the most appropriate datatype for the situation where warranted.

However, integer, in some languages, is the fastest datatype for arithmetic operations, even when it is way to large of a container for what you need.

Arithmetic operations are faster with integral types than with other
  data types. They are fastest with the Integer and UInteger types in
  Visual Basic. 1 (msdn.com)

So in loops, yes, use this. When doing arithmetic, however, air on the side of caution and use an int unless you research the language you are using first to see what the fastest type is.

--Adding another example I gave in the comments--

You have a class that has a 100 ints in it, but none of the ints will ever go above a value of 10. Every time you create an object of that class you are blocking off 32 bits per int creating 32*100=3200 bits. If you replaced those ints with sBytes you are now blocking off 8*100=800. You are saving 2400 bits for use anywhere else.

Body:
Yes This is especially useful in for loops. People often just use int, or allow var to determine what the variable type should be. This is inefficient (but not terribly so), but for people like me who like to get every ounce of performance and are just tickled pink by using the most perfect datatype for a situation, this is awesome.

for(SByte i = 0; i <= 10; i++)
{
...code
}

SByte allows -128 to 127. I love this little datatype because it saves on memory and is the most appropriate datatype for the situation where warranted.

However, integer, in some languages, is the fastest datatype for arithmetic operations, even when it is way to large of a container for what you need.

Arithmetic operations are faster with integral types than with other
  data types. They are fastest with the Integer and UInteger types in
  Visual Basic. 1 (msdn.com)

So in loops, yes, use this. When doing arithmetic, however, air on the side of caution and use an int unless you research the language you are using first to see what the fastest type is.

--Adding another example I gave in the comments--

You have a class that has a 100 ints in it, but none of the ints will ever go above a value of 10. Every time you create an object of that class you are blocking off 32 bits per int creating 32*100=3200 bits. If you replaced those ints with sBytes you are now blocking off 8*100=800. You are saving 2400 bits for use anywhere else.


问:
Representation of a question mark in variable names
I once in my childhood read a SF story in which it was assumed that the capital letter 'P' would be a good representation for a question mark, if you cannot use that character directly, eg. in variable names. However the story is quite old and things may have changed :)

Is this a good practice?

BTW: The story was called Press Enter by John Varley

Edit

Additional questions that are answered below.

Is this only writer's phantasy or is it based on an actual language's habit?

If yes, which language would that be?

答:
Many communities have naming conventions for making predicates stick out. In Java, they are prefixed with has or is (isEven), in Ruby and Scheme, they are suffixed with ? (even?) and in some other languages, they are suffixed with p or _p (evenp, even_p). At first glance, it has a bit of a "Bad Hungarian" smell, but actually I find it makes code more fluent.

Haskell doesn't use any markers, they trust the types (anything which returns a Bool is a predicate, e.g. even :: Integral a ⇒ a → Bool).

If your community uses and understands that convention, you should follow it.

Naming predicates ending with p is indeed somewhat common, but that has nothing to do with the looks of the letter p, it is simply an abbreviation of "predicate". Here's an example of some functions from the CommonLISP ANSI spec:

adjustable-array-p

alpha-char-p

alphanumericp

array-has-fill-pointer-p

array-in-bounds-p

arrayp

bit-vector-p

both-case-p

boundp

char-greaterp

char-lessp

char-not-greaterp

char-not-lessp

characterp

compiled-function-p

complexp

consp

constantp

digit-char-p

endp

equalp

evenp

fboundp

floatp

functionp

graphic-char-p

hash-table-p

input-stream-p

integerp

interactive-stream-p

keywordp

listp

logbitp

lower-case-p

minusp

next-method-p

numberp

oddp

open-stream-p

output-stream-p

packagep

pathname-match-p

pathnamep

plusp

random-state-p

rationalp

readtablep

realp

simple-bit-vector-p

simple-string-p

simple-vector-p

slot-boundp

slot-exists-p

special-operator-p

standard-char-p

streamp

string-greaterp

string-lessp

string-not-greaterp

string-not-lessp

stringp

subsetp

subtypep

symbolp

tailp

typep

upper-case-p

vectorp

wild-pathname-p

y-or-n-p

yes-or-no-p

zerop


答:
If you decide to go with a client-side solution you must be prepared for the fact that someone will crack the hash or whatever else you decide to do. If this puzzle victory/loss isn't being recorded into a greater scoreboard that is retained across games then you might as well do that since it'll have no impact on you if they cheat.

If you are going to record these onto a leaderboard or something similar than integrity of score is paramount. You'll want to postback the page to the server and check it there. I wouldn't even attempt this with ajax since the user could capture what data you are sending back and, based on what variables you are sending, alter them to be a winner.

You could also do a clientside check, and only if they win post the page back and double check that they actually did win. If they lose then no need to postback since there is nothing to double check.

Title: Should the check correctness of a time constrained puzzle game application be done on the server side?

Body:
I am working on an application where a user has to complete a puzzle and check  within a given time limit.

This is an HTML5 based game, I can't keep the solution on the client side.
but I also want to avoid the latency that will be caused when we check for the correctness of the player's attempt.

Is there a way I can check the correctness of the solution on the client side safely ?

One implementation I was considering was to take the hash of the solution and compare it with hash of user's solution  at the client side and once he finally submits it, recheck it on the server side.

Any potential flaws here or are their cleaner ways to accomplish the same ?


问:
I have generally read that having many (>4) arguments to a function/constructor is a bad practice. Is this still considered a bad practice?
I have generally read that having many (>4) arguments to a function/constructor is a bad practice.

Is this still considered a bad practice? And is there a non-obvious reason?

In something like a Scala Case Class where there may be many fields what can be done to avoid such a construction?

(Not sure if this is best fit for here, SO, or CodeReview)

答:
I've never heard this.

What are you expected to do if you need to pass in both a username and a specific security permission? Should you create a new class that can hold both, populate it, and then send it through to maintain "less is better" in regards to parameters? I can't imagine that this can be true.

Even libraries that are obsessed with performance (jQuery, php, .NET) have multiple arguments in their functions.

I think my answer made more sense before the OP edited their question to only encompass >4 parameters. My answer stands if there are only 2 parameters or so.

If there are >4 parameters...yes, you should reevaluate what you're doing and consider if all of the parameters are actually needed or if a more encompassing object can be passed in.


答:
Yes. The number of possible permutations for n arguments scales rather quickly. It's easy to forget the order of the arguments to a function of arity 5. Moreover, there's a good chance some of those arguments are always used together. Wrapping them up makes passing them around easier (and is necessary for returning them from functions.)

Not too familiar with Scala, but anonymous classes would help since the order of the fields isn't important.

Body:
I have generally read that having many (>4) arguments to a function/constructor is a bad practice.

Is this still considered a bad practice? And is there a non-obvious reason?

In something like a Scala Case Class where there may be many fields what can be done to avoid such a construction?

(Not sure if this is best fit for here, SO, or CodeReview)


答:
The issue is twofold.

In case of functions/methods:

Having to pass many parameters is an indication of a non-cohesive design.

The method doesn't use the state of the class.

If it's a static method in a static utility class, it's OK. Otherwise it's a possible indicator that the method doesn't belong to that class.

Even in case of a static method, you can avoid a lot of parameters creating a "parameter object" that is a class with all values needed to pass to the method.

In case of constructor:

You can use the "parameter object" I mentioned above

Or you could populate the object with setter methods. In this case you should provide "inteligent defaults" so object has a default state to begin with, or throw an invalid state exception if you call a method that requires the object to be fully initialized.

Title: I have generally read that having many (>4) arguments to a function/constructor is a bad practice. Is this still considered a bad practice?


问:
Is having some logic in source code in order to perform some tests a good practice?
The question is not about changing the method/function visibility or extract local variable into instance variable in order to perform unit tests.

There are cases where we could include some logic in the source code in order to help us performing some functional tests or end-to-end tests. Generally speaking, these code interact with main logic directly and if the test code is defective, the business logic is affected.

One example could be that we have some test code around date/time logic so that if the testers make server and client time different, this code could help them to perform some tests.

So how bad you think having this is, if there is no other easy(ish) way to test this part of business logic?

Please comment if this plain explanation is too vague and you need more examples.

答:
The question seems a little vague so I will try to answer it the best that I can. If the answer does not help feel free to add more info and I can add an edit to focus on the new info.

Typically it is a good idea to test data that is passed into a function or method. One of the more popular tests would be a null or none test. These types of tests can ensure that the data passed in will not break the function/method. Additionally the function/method has the option of handling or passing back an error to the user without having a null pointer exception, or similar, being thrown causing the program to crash.

Additionally it is a good idea to check for other things too. If you are supposed to get a datetime but only receive a date this could be a problem. You may want to throw an exception or simply add in a default time so that code further down the function/method will not break.

I would not want to supply code that preforms the same type of tests that a unit test would provide. Meaning that you should not have code that checks to see if a function/method can handle a certain type of data. This can be pulled out into a test that is run in a non-production environment.

It sounds like you are trying to add in code to check a passed in parameter. For example, if a call to an API returns the time of the server and the client machine checks to see if that time matches or is close to its own internal time. Assuming the same time zone or both machines are comparing using UTC (its good to have a common base to compare to) you would almost certainly want to check that time sensitive data has a correct timestamp in your code. From there you could either let the user know that their data may be out of date or that their system time is off.


答:
Scala case classes are a lot like immutable tuples (plus other stuff irrelevant for this question). I don't find a tuple with more than 4 elements strange, though there is certainly a limit where it starts to become unreadable.

Also, because a case class such as Person(name: String, age: Int) is immutable, some of Java's patterns for building complex objects such as the Builder pattern become difficult to apply. See What is the Scala equivalent to a Java builder pattern? and Type-safe Builder Pattern in Scala.


答:
On logic in tests

There are cases where we could include some logic in the source code in order to help us performing some functional tests or end-to-end tests

Unit testing is an area of software engineering where people seem to become very dogmatic.  "Do it this way or it isn't unit testing" - this can get in the way of actually doing tests.  People have argued it each way and will continue to argue about it for quite some time.

One of my favorite documents on testing is The Way of Testivus - its a good (and humorous) read.

The thing is to write the test that needs to be written.  If this means putting logic in there, then there's logic in there.

The danger of the this is who tests the logic in the tests (Test-Driven Hypocrisy? Who tests the test?).  The issue being if your test logic and your business logic are both broke, you may miss an actual failed test.

On code with test logic

Another aspect to this question is the "we stuck some code in the build that goes to QA (and presumably to production - because you don't switch out the build after giving it to QA...) to make their job easier.

There's a real danger here.

When you put test code into the build it is possible that it will get tickled in production.  "But that will never happen" has happened far too often.  The code allows you to set the time stamp, or get into a certain state that allows you to do set some data without going through some other process.

These are bad things.  Don't do them.

One example could be that we have some test code around date/time logic so that if the testers make server and client time different, this code could help them to perform some tests.

Don't do that.  And here I'm being rather dogmatic.  There's a difference between having the unit test code which never gets bundled into a production build where its important to do the testing... and code that is going to production.

Having test code in there that lets you bypass the normal flow of the code that a user would need to do has several issues with it:

The full process isn't being tested.  The QA tester is jumping around the code in a way a normal user can't.  This means that the actual workflow isn't being tested.  You've stuck data in some place through an admin/test interface that initializes the structure before using it... but your normal code doesn't and you've got a bug that QA won't find.

There's a hook in there that someone else can use. We know all the users are nice and don't go poking into places they shouldn't be looking.  Sure you've got it hidden needing to hold down the shift-control-alt and 'cat' at the same time... but you've never had a cat actually step on your keyboard to do this in a way that only a cat can.  And cats aren't the most nefarious of the keyboard users - people with less than honorable intentions will find this hook too.

If you need an environment that makes a particular thing easier to test, set up that environment.  You want the testers to have the ability to do some test with the client and server out of sync? Create a VM that recreates this environment easily rather than inserting some code that makes the client interpret its timestamps as 30 seconds in the past (or future).

Don't put test code in the production build.  Make sure you test the production build.  This may necessitate having longer testing processes, but the alternatives can be very bad (missing a bug or letting someone use the software improperly).

Title: Is having some logic in source code in order to perform some tests a good practice?

Body:
The question is not about changing the method/function visibility or extract local variable into instance variable in order to perform unit tests.

There are cases where we could include some logic in the source code in order to help us performing some functional tests or end-to-end tests. Generally speaking, these code interact with main logic directly and if the test code is defective, the business logic is affected.

One example could be that we have some test code around date/time logic so that if the testers make server and client time different, this code could help them to perform some tests.

So how bad you think having this is, if there is no other easy(ish) way to test this part of business logic?

Please comment if this plain explanation is too vague and you need more examples.


答:
Code that is added to, say, a class, for testing purposes, is symptomatic of code that hasn't been written to be testable.

I'll give you an example.  In one of my current applications, there is a parser which reads a data file containing Key/Value pairs, and creates a representative recursive data structure. The specification is here, if you're at all interested.

To speed up the testing process, I overrode the ToString() method in the Node class (a recursive data structure containing the current data node, and a list of descendant nodes), and put some code in there that recursively walks the nodes and builds a string containing a human-readable representation of the content of that part of the tree.  I then parse a bit of the data file, examine the output I get from ToString(), and if it looks good, I paste the output into a unit test and assert against it.

You can build a test suite relatively quickly this way. The problem, of course, is that if you change anything, especially the ToString() method, it breaks all of your tests.  Also, because the tests don't test specific functionalities (preferring to cast a wide net instead, and hoping that adequate code coverage is achieved), they are essentially "go, no-go" tests.  If the test fails, you have to analyze the output to determine why (a process made easier with the use of diff methods).

So the tradeoff is that such tests are relatively easy to fabricate and save a ton of time, but the downside is that the degree of code coverage is uncertain, the tests are brittle, and a failed test doesn't tell you anything without additional analysis.

An ugly test is better than no test

When the code is ugly, the tests may be ugly.

You don’t like to write ugly tests,   but ugly code needs testing the most.

Don’t let
ugly code stop you from writing tests,    but let ugly code stop you
from writing more of it.

-- The Way of Testivus