答:
I was on one project where the lead insisted on putting reference data into little tables, and I thought that was silly. But since we already had our persistence infrastructure and connectivity set up, it ended up being a pretty low cost on top of the other persistence operations we were doing.

Now, I still think that was a silly decision, and if we didn't have the infrastructure on hand, I just wouldn't have done it.

But some of the arguments in favor I see are:

If you have a database mindset, then putting reference data into the SQL database allows you join on it for reporting.

If you have an admin utility, or access to the database, then you can tweak the values at runtime. (Although that can be playing with fire.)

Also, sometimes policy gets in the way of coding practices. For example, I've worked at several shops where pushing an .xml file is A-OK, while touching a line in code requires a full regression cycle, and maybe a load test. So there was one team I was on where my .xml files for the project were extremely rich (and maybe -heh- might have contained some code).

I always ask myself if I'm going to enjoy the benefit of pushing data out of the code into an external data store, even if it's just a text file, but I've worked with people who just see it that way as their first impulse.

Title: How did separation of code and data become a practice?

Body:
Please read the question carefully: it asks how, not why.

I recently came across this answer, which suggests using a database to store immutable data:

It sounds like many of the magic numbers you describe - particularly if they are part dependent - are really data, not code. [...]  It may mean an SQL type database, or it may simply mean a formatted text file.

It would seem to me that if you have data that is part of what your program does, then the thing to do is to put it in the program. For example, if your program's function is to count vowels, what's wrong with having vowels = "aeiou" in it? After all, most languages have data structures designed for precisely this use. Why would you bother to separate data by putting it in a "formatted text file", as suggested above? Why not just make that text file formatted in your programming language of choice? Now is it a database? Or is it code?

I'm sure some will think this is a dumb question, but I ask it in all seriousness. I feel like "separate code and data" is emerging culturally as some sort of self-evident truth, along with other obvious things like "don't give your variables misleading names" and "don't avoid using whitespace just because your language considers it insignificant".

Take for example, this article: The Problem with Separating Data from Puppet Code. The Problem? What problem? If Puppet is a language for describing my infrastructure, why can't it also describe that the nameserver is 8.8.8.8? It seems to me that the problem isn't that code and data are mingled,1 but that Puppet lacks sufficiently rich data structures and ways to interface to other things.

I find this shift disturbing. Object oriented programming said "we want arbitrarily rich data structures", and so endowed data structures with powers of code. You get encapsulation and abstraction as a result. Even SQL databases have stored procedures. When you sequester data into YAML or text files or dumb databases as if you are removing a tumor from the code, you lose all of that.

Can anyone explain how this practice of separating data from code came to be, and where it's going? Can anyone cite publications by luminaries, or provide some relevant data that demonstrates "separate code from data" as an emerging commandment, and illustrates its origin?

1: if one can even make such distinctions. I'm looking at you, Lisp programmers.


问:
modelling staged business process
imagine

given a project business object and such (simplified) rules:

it's lifecycle is divided into several stages of evaluation;

stages flow lineary and represent an evaluation chain;

each stage provides its own reward value/algorithm;

promotion of the project is controlled by other user's decision;

the resulting reward is assigned to the project's initiator.

too naive, probably)

The first thought that comes to my mind is using the decorator pattern; because of its structure it looks somewhat applicable. But what if you need to persist additional details provided with the current 'decorated' state of project?

I need an extra behavior on each stage

I've encountered an article about jBPM. I believe it has much in common with WF. It is surely has the most of what is needed and at the same time it has (overkill) large infrastructure.

but can it be designed without incorporating this much complexity?

What would you suggest?

答:
When I see "process" that spans time, I usually think "state machine". However, one of your requirements says the process is linear, so state machine might be overkill.

It definitely sounds like you have a common interface that describes Stage, with functions like reward(), and a top-level Project that "has a" Stage.

I'm assuming the project runs over an extended time, so you need to be able to save the project state in between events in the project. So Project would have to be persist-able, including the Stage that it's in.

Right off the bat, I see a Project class, Stage interface, and concrete implementations of Stage. And then probably a StageId enum to make it easy to persist the stages.

(Knowing me, I'd probably also define the transitions in a map and implement a really, really simple state machine too. But the simple, linear state machine you have could just be done with if...thens to keep it light.)

ContentLicense: CC BY-SA 3.0

Title: modelling staged business process


问:
How did separation of code and data become a practice?
Please read the question carefully: it asks how, not why.

I recently came across this answer, which suggests using a database to store immutable data:

It sounds like many of the magic numbers you describe - particularly if they are part dependent - are really data, not code. [...]  It may mean an SQL type database, or it may simply mean a formatted text file.

It would seem to me that if you have data that is part of what your program does, then the thing to do is to put it in the program. For example, if your program's function is to count vowels, what's wrong with having vowels = "aeiou" in it? After all, most languages have data structures designed for precisely this use. Why would you bother to separate data by putting it in a "formatted text file", as suggested above? Why not just make that text file formatted in your programming language of choice? Now is it a database? Or is it code?

I'm sure some will think this is a dumb question, but I ask it in all seriousness. I feel like "separate code and data" is emerging culturally as some sort of self-evident truth, along with other obvious things like "don't give your variables misleading names" and "don't avoid using whitespace just because your language considers it insignificant".

Take for example, this article: The Problem with Separating Data from Puppet Code. The Problem? What problem? If Puppet is a language for describing my infrastructure, why can't it also describe that the nameserver is 8.8.8.8? It seems to me that the problem isn't that code and data are mingled,1 but that Puppet lacks sufficiently rich data structures and ways to interface to other things.

I find this shift disturbing. Object oriented programming said "we want arbitrarily rich data structures", and so endowed data structures with powers of code. You get encapsulation and abstraction as a result. Even SQL databases have stored procedures. When you sequester data into YAML or text files or dumb databases as if you are removing a tumor from the code, you lose all of that.

Can anyone explain how this practice of separating data from code came to be, and where it's going? Can anyone cite publications by luminaries, or provide some relevant data that demonstrates "separate code from data" as an emerging commandment, and illustrates its origin?

1: if one can even make such distinctions. I'm looking at you, Lisp programmers.

答:
There are many good reasons to separate data from code, and some reasons not to. The following come to mind.

Timeliness. When is data value known? Is it at the time the code is written, when it is compiled, linked, release, licensed, configure, started execution or while running. For example, the number of days in a week (7) is known early, but the USD/AUD exchange rate will be known quite late.

Structure. Is this a single data time set according to a single consideration, or might it be inherited or part of a larger collection of items? Languages like YAML and JSON enable combining of value from multiple sources. Perhaps some things that initially seem immutable are better made accessible to as properties in a configuration manager.

Locality. If all the data items are stored in a limited number of places it is far easier to manage them, particularly if some might need to be changed to new (immutable) values. Editing source code just to change data values introduces the risk of inadvertent changes and bugs.

Separation of concerns. Getting algorithms to work correctly is best separated from consideration of what data values to use. Data is needed to test algorithms, not to be part of them. See also http://c2.com/cgi/wiki?ZeroOneInfinityRule.

In answer to your question this is not a new thing. The core principles have not changed in more than 30 years, and have been written about repeatedly over that time. I can recall no major publications on the topic as it is generally not considered controversial, just something to explain to newcomers. There is a bit more here: http://c2.com/cgi/wiki?SeparationOfDataAndCode.

My personal experience is that the importance of this separation in a particular piece of software becomes greater over time, not less. Values that were hard-coded are moved into header files, compiled-in values are moved into configuration files, simple values become part of hierarchical and managed structures.

As to trends, I haven't seen any major changes in attitude amongst professional programmers (10+ years), but the industry is increasingly full of youngsters and many things I thought were known and decided keep getting challenged and reinvented, sometimes out of new insights but sometimes out of ignorance.


问:
What are some good ways to represent relationship among three numbers
I'm trying to find a clean, intuitive way to implement this problem. Basically, I have three numbers, and based on relationship (less than, greater than, and equal to) among these numbers would change how I execute the next set of code.

For example, if there are numbers A, B, and C. Here are some examples of relationships among them:

A < B < C

A = B > C

A = B = C

B < A = C

A consumer of my framework would build this kind of relationships between the three numbers and would pass into a class that would process the relationships. So far, I could think of one way to implement that is relatively simple but not clean.

I would represent relationships between the three numbers in flags. So, there would three different flags (A to B, B to C, and A to C). Each flag would have LessThan, EqualTo, and GreaterThan options. I would have to run through many checks to make sure that the 3 given flags are valid. If A < B and B < C, then A cannot be greater than C. If A = B and A < C, then B cannot be greater than C. The list goes on.

Is there a better way to design this?

答:
You have exactly 13 relationships.

6 of them are in the form A>B>C, for various orderings of A,B,C. Let us name them A_B_C and similar.

6 of them are in the form A>B=C or A=B>C, for various orderings of A,B,C. Let us name them A_BC and AB_C and similar.

The final 1 is A=B=C. Let us name that ABC.

These 13 names form an enumeration that identifies all the possible relationships. You can provide synonyms if you believe your users will be more comfortable with LT, LE, GE etc but I would not recommend it. Let them find the right member to describe what they need.

Use that enumeration as an index into a data structure to deliver the various flags you need to drive your code.

OwnerDisplayName: Brian


答:
I think there is some confusion going on. You are mixing two things together: "Separating code and data" and "expressing program's behavior as data".

In your case, you are actually worried about the second and mixing the first one into it. When you express program's behavior as data it makes it easier to extend. In your example with vowels = "aeiou", then adding new vowel is as simple as adding a character. If you have this data externally, you can change this behavior without having to recompile the program.

And when you think about it, OOP is extension of this thinking. Binding data and behavior together will allow you to change program's behavior based on program's data.


问:
Outline for technical software documentation
Say I have a software project for which the technical documentation should include

A license document

A list of used terminology

An introduction about what the software does

A short quick-start guide

Complete documentation of tools covered by the project

Documentation of file formats and protocols

An API Reference

A list of known bugs

A todo list

A set of examples

What is a good order of these points?

How can these points be organized into chapters, sections, subsections, and subsubsections?

One of the tools has an hierarchical configuration structure. Should this structure be represented in the documentation outline (this will result in a really deep outline) or should it be flatted in some way?

答:
For this kind of projects, where software products requires large documentation, you should better not include all the information in one single document.

A good approach to this to have a Workbook for developers which is a set of different documents directly related to the software product.

You may structure your workbook so that it includes

A licence document

An introduction about what the software does,
a short quick-start guide,
complete documentation of tools covered by the project,
documentation of file formats and protocols,
an API Reference, in one separate document

The lists of known bugs and todo list in another document

A set of example

Thus you will have 4 different documents in your workbook. You will have to name them so that developers could easily  understand the content of the document.

Hope this helps


问:
Doing work in vector's push back
I often use the following syntax:

```<code>std::vector<foo> vec;
vec.push_back( someClass.getFoo(...).modifyAndReturn() );
</code>```

Considered about exception safety, I quote the standard on vector's push back behavior (23.3.7.5):

If an exception is thrown other than by the copy constructor, move
  constructor, assignment operator, or move assignment operator of T or
  by any InputIterator operation there are no effects. If an exception
  is thrown by the move constructor of a non-CopyInsertable T, the
  effects are unspecified.

Is it a good practice to use complicated push backs?

Are there any perils exception wise?

答:
The push back is not complicated. Its argument is (somewhat).

If this is a common idiom and consistently used through the code, then it's good practice. I might prefer to evaluate the argument into a helpfully-named local variable to assist readers in understanding the meaning of the value, but then again, I might not. If I knew Class and Foo, I would understand this code.

The perils referred to in this excerpt are related to exceptions that might be raised inside vector as a result of invoking various kinds of constructor or copying operation. Exceptions raised during evaluation of the argument are external to vector, and would be the same if you evaluated the argument separately. Likewise, exceptions raised internal to vector would not be avoided by prior evaluation of the arguments. I see nothing to fear.

Go for it. You're doing fine.

OwnerDisplayName: Nikos Athanasiou

Title: Doing work in vector's push back


答:
Whether using such complicated expressions in a push back (or any other function call) is debatable and it depends on two factors:
1. your local coding conventions, and
2. the comfort level of you and your team with reading such expressions

Regarding exception safety, there is no difference between these three snippets:

```<code>std::vector<foo> vec;
vec.push_back( someClass.getFoo(...).modifyAndReturn(...) );

std::vector<foo> vec;
auto temp = someClass.getFoo(...).modifyAndReturn(...);
vec.push_back( temp );

std::vector<foo> vec;
auto temp = someClass.getFoo(...);
auto temp2 = temp.modifyAndReturn(...);
vec.push_back( temp2 );
</code>```

The exception safety of std::vector<>::push_back does not really enter into the picture, because if getFoo or modifyAndReturn would throw an exception, push_back won't even be called. In C++, arguments to a function are always evaluated before the function gets called.

Title: Doing work in vector's push back

Body:
I often use the following syntax:

```<code>std::vector<foo> vec;
vec.push_back( someClass.getFoo(...).modifyAndReturn() );
</code>```

Considered about exception safety, I quote the standard on vector's push back behavior (23.3.7.5):

If an exception is thrown other than by the copy constructor, move
  constructor, assignment operator, or move assignment operator of T or
  by any InputIterator operation there are no effects. If an exception
  is thrown by the move constructor of a non-CopyInsertable T, the
  effects are unspecified.

Is it a good practice to use complicated push backs?

Are there any perils exception wise?

Body:
Whether using such complicated expressions in a push back (or any other function call) is debatable and it depends on two factors:
1. your local coding conventions, and
2. the comfort level of you and your team with reading such expressions

Regarding exception safety, there is no difference between these three snippets:

std::vector<foo> vec;
vec.push_back( someClass.getFoo(...).modifyAndReturn(...) );

std::vector<foo> vec;
auto temp = someClass.getFoo(...).modifyAndReturn(...);
vec.push_back( temp );

std::vector<foo> vec;
auto temp = someClass.getFoo(...);
auto temp2 = temp.modifyAndReturn(...);
vec.push_back( temp2 );

The exception safety of std::vector<>::push_back does not really enter into the picture, because if getFoo or modifyAndReturn would throw an exception, push_back won't even be called. In C++, arguments to a function are always evaluated before the function gets called.


问:
Are there advantages to declaring stack variables constant in C++
It's not clear to me what benefits there are of declaring your stack variables as constant in C++, I was hoping somebody might explain the benefits and purpose for this technique.

For example:

```<code>void func(const std::string& arg)
{
   if(someCondition)
   {
      const std::string foo ("some string plus " + arg);
      std::out << foo << std::endl;
      someFunction(foo);
      // dozens more lines of code...
   }
   // bla bla bla...
}
</code>```

Thanks!

答:
Yes.

It helps the reader to understand your intent. Clearly foo is given an initial value and never changed thereafter.

It helps the compiler to optimise your code, for both speed and space. The compiler can perform certain optimisations such as hoisting values out of loops if there is a promise that the value cannot change. This is particularly the case if the value has an alias, which would otherwise defeat optimisation.

It occasionally catches bugs, when you accidentally write code to modify something you didn't mean to.

On the down side, you may not be able to pass the value into a function that takes non-const arguments.


问:
How to process large files in NetLogo?
I am running into problems in NetLogo with large *.csv / *.txt files.

The documents can consist of about 1 million data sets and I need to read them (to eventually create a diagram based on the data).

With the most straightforward source code, my program needs about 2 minutes to process these files.

How should I approach reading such large data files faster in NetLogo?  Is NetLogo even suitable for such tasks (as it seems to be designed more for teaching and learning)?

答:
The obvious solution is to extend NetLogo in Java, and take advantage of one of the highly optimised CSV readers or TXT parsers readily available. Take a look at http://commons.apache.org/proper/commons-csv/.

If that doesn't do the trick, you might need to pre-process the data into something that can be read faster. Without knowing the data, it's hard to speculate what.

Title: How to process large files in NetLogo?


问:
Is there any difference learning OOP on different programming languages?
I want to learn OOP. I know Python and I know very little things about OOP.

But when I search for "learn OOP" in forums I saw a guy saying that "Python is so new that's why you can't learn OOP on Python. you should learn Java then understand OOP on Java"

Is it true? Is there any difference understanding OOP on different programming languages?
like learn it on Java, C#, C++, Perl or Python?

答:
When you learn OOP in a language you start to think in this language.
The language influences what you think can be done and how and also adds a flavor to OOP.

Should there be a Garbage Collection?

Can I add methods to integers?

Do I use classes or prototypes?

How do objects reflect on themselves?

Some people can not do OOP without classes. Some must kill their objects with the process.

There is a core of OOP and the original ideas about it. You can have a look also at Smalltalk, Self, Simula, LISP, Newspeak. And also a look at non-OOP language types like dataflow languages bash, APL, J. Logical ones Prolog. Haskell (type classes). They will all teach you a different thinking and you may learn that

OOP is not about imperative languages

OOP is not about classes

And in the end you may see what OOP is good for. At least you will have another idea about it.
I suggest finding talks by Alan Kay.

If you do not look at the languages this post is useless.

As you can see here: We can not agree on what OOP is.


问:
Clarification about Grammars , Lexers and Parsers
Background info (May Skip): I am working on a task we have been set at uni in which we have to design a grammar for a DSL we have been provided with. The grammar must be in BNF or EBNF. As well as other thing we are being evaluated on the Lexical rules in the grammar and the Parsing rules - such as if rules are suitable for the language subset, how comprehensive these rules are, how clear the rules are ect.

What I don't understand is if these rules are covered in a grammar defined in BNF (it's a new topic for us).

The Question: Does a grammar for a given language that has been defined in either BNF or EBNF contain / provide rules for Lexical Analysis   and/or Parsing?  (or do these have to be specified else-where?)

Also what would be considered a lexical rule? And what would be considered a parsing rule?

答:
The answer to your question is certainly Yes, both parsing and lexing rules can be and are specified using an EBNF (which is really just a more compact form of a BNF). However, in production quality compilers the next part of the answer is different.

Most languages have a grammar that is context free, and conforms to a set of rules to do with lookahead and backtracking. The commonest grammars are LL(1) and LR(1). LL(1) grammars allow a simple recursive descent grammar, often hand-coded, while LR(1) usually means a parser generator such as YACC. This part of the grammar goes down to tokens (terminals) but not lower.

The symbols are usually defined separately using an even simpler grammar, such as an operator grammar. [You can look up these terms for better definitions than I can give here.] The lexer that reads these symbols is typically responsible for most of the performance of the compiler so, in my experience, it is always hand-coded. LEX is clunky (and C only) and regex is too slow.

The point is to understand that the parsing rules drive the technology needed for your parser, and the lexing rules ditto for your lexer. The clear distinction between them is whether they apply to the use of tokens (terminals), or the construction of them.

This may not help your academic progress, but it matters if you go beyond toy projects.


问:
Requiring a specific order of compilaiton
When designing a compiled programming language, is it a bad idea to require a specific order of compilation of separate units, according to their dependencies?

To illustrate what I mean, consider C. C is the opposite of what I'm suggesting. There are multiple .c files, that can all depend on each other, but all of these separate units can be compiled on their own, in no particular order - only to be linked together into a final executable later.

This is mostly due to header files. They enable separate units to share information with each other, and thus the units are able to be compiled independently.

If a language were to dispose of header files, and only keep source and object files, then the only option would be to actually include the unit's meta-information in the unit's object file.

However, this would mean that if the unit A depends on the unit B, then the unit B would need to be compiled before unit A, so unit A could "import" the unit B's object file, thus obtaining the information required for its compilation.

Am I missing something here? Is this really the only way to go about removing header files in compiled languages?

答:
Yes, it's a bad idea although it's very common.

For situations where the application is spread across multiple source code files that potentially share cyclical dependencies, there is absolutely nothing preventing a compiler from reading and compiling all the source code together to avoid order sensitivity. Such a compiler should also offer incremental compilation to reduce compile times when small changes are made.

For other situations where there are libraries or components that are not to be recompiled, and are not dependent on client applications, the compiler should read meta data from the binary, generated by a previous compilation. There are dependencies, but they are natural and not a problem.

As it happens the above is not very far from what actually happens in C# and Java. Dependencies do arise at times, and it would be nice if they didn't.

The C++ header arrangement is truly awful, but we're stuck with it. No modern language designer would commit that crime again.


问:
Why develop free, open source programs?
Why would someone use his own time to develop an open-source project for free and without compensation?</p>

答:
There's a variety of reasons.

Some people get paid for writing it, because their employer thinks it worthwhile (and there's plenty of potential reasons for that).  Some people start companies based on F/OSS because they can make money from it.

Some people use F/OSS and want to give back.

Some people treat it as a reputation game, like academic research or answering questions here.

Some people want a certain piece of software for their own purposes, and just release it because what they want is to use it, and they can sometimes get useful suggestions if other people can use it also.

Title: Why develop free, open source programs?

ContentLicense: CC BY-SA 2.5


问:
Advantage of monitoring file change using Windows API rather than manually
I developed a Windows software about an year ago. Part of it was to monitor few configuration files for manual changes by user and if any of these change restart a particular service.

So, I used the simplest approach. I load them as a string in memory and after few seconds, I read the latest file and compare it with the one in memory. Since, the files are very small (less than 500KB), the program doesn't consume much memory.

I am using that application since it is developed and have not experienced any performance problem due to that. But, few days ago I noticed that the program ranks at highest for I/O Read Bytes in task manager. After few hours of uptime of PC, the I/O Read Bytes by this program become significant higher than the rest of processes.

So, My question is should I worry about high value of I/O Read Bytes. Is this have some downside effect (maybe on Hard Disk) that I am missing. Is implementing the functionality of monitoring file changes using Windows API have some benefits that are worth the effort required to implement it?

答:
If you only worry about your program being the greatest I/O user: don't. If you changed it, then by definition, something else would become the greatest I/O user on the system, so you gain nothing.

If you have something else to point to a problem with resource usage - users complaining, jobs delayed, etc. then you could check out whether rewriting is worthwhile. But occasionally reading a small file, and always the same at that, is unlikely to put a large strain on a full-fledged Windows installation.


答:
I'm not surprised, every few seconds you open a file, and read the contents. Repeat forever keeping your disk from sleeping.

The file notification APIs are very easy to use, make the call to set things up and then simply wait for your callback to be called. When you get the callback, you know something has modified the file, so then you read the contents as you do now. The only thing you have to lose is the busy-polling!

Title: Advantage of monitoring file change using Windows API rather than manually

Body:
I developed a Windows software about an year ago. Part of it was to monitor few configuration files for manual changes by user and if any of these change restart a particular service.

So, I used the simplest approach. I load them as a string in memory and after few seconds, I read the latest file and compare it with the one in memory. Since, the files are very small (less than 500KB), the program doesn't consume much memory.

I am using that application since it is developed and have not experienced any performance problem due to that. But, few days ago I noticed that the program ranks at highest for I/O Read Bytes in task manager. After few hours of uptime of PC, the I/O Read Bytes by this program become significant higher than the rest of processes.

So, My question is should I worry about high value of I/O Read Bytes. Is this have some downside effect (maybe on Hard Disk) that I am missing. Is implementing the functionality of monitoring file changes using Windows API have some benefits that are worth the effort required to implement it?


问:
How to integrate and Program Avatar customization in HTML(5)?
I am making a Game in HTML5. In one part of it, I want the users to be able to customize the avatar they get by default.

For sample, let me share a screenshot from Zombie Lane on Facebook (now this game may not be in HTML5 but that's not the point):

My question is as to how do I include the images in the HTML5 page and in which format?

Whenever a clothing is different shirt is selected, the change is applied immediately. Is it a whole new photo that we see, or is the photo changed somehow by programming? How is it done?

答:
As you've already guessed, this can be done in several ways.  There is no reason why this couldn't be done with a single image for every possible combination, however, it quickly becomes very impractical to do it this way.  More likely the individual components are thrown on top of the person in the correct location to make it look like the person is wearing that component.

If action poses are used throughout the game, then you must create an image for each action pose for each type of component.  In other words, if in the game the character can be seen aiming a gun, you'd have to have a "white shirt relaxed" image as well as a "white shirt aiming gun pose" image.

Another approach is to physically render the component.  By this I mean, using some sort of algorithm to calculate how the component is rendered.  This could be a svg whose fill gets replaced by an image pattern according to how the user personalized the character.  This is more flexible in that you don't need to add a new image for each pose when adding a new personalization.  You can simply add the new pattern and only the fill changes.

If you're performing actual 2d/3d rendering, you can go even farther and do without the poses.  You'd have a model that you'd transform into new positions smoothly, which allows for the most potential for animation, but it also requires the most amount of work.


问:
How do I manage a very large set of rules and magic numbers in my program?
I'm somewhat new to programming (I'm a mechanical engineer by trade), and I'm developing a small program during my downtime that generates a (solidworks) part based on input from various people from around the plant.

Based on only a few inputs (6 to be exact), I need to make hundreds of API calls that can take up to a dozen parameters each; all generated by a set of rules I've gathered after interviewing everyone that handles the part. The rules and parameters section of my code is 250 lines and growing.

So, what is the best way to keep my code readable and manageable? How do I compartmentalize all my magic numbers, all the rules, algorithms, and procedural parts of the code? How do I deal with a very verbose and granular API?

My main goal is to be able to hand someone my source and have them understand what I was doing, without my input.

答:
I'm surprised that no one else has mentioned this...

You said:

My main goal is to be able to hand someone my source and have them
  understand what I was doing, without my input.

So let me say this, most of the other answers are on the right track. I definitely think databases could help you out. But another thing that will help you out is commenting, good variable names, and proper organization / separation of concerns.

All the other answers are heavily technical based, but they're ignoring the fundamentals that most programmers learn. Since you're a mech engie by trade, my guess is you're not used to this style of documentation.

Commenting and choosing good, succinct variable names helps immensely with readability. Which is easier to understand?

```<code>var x = y + z;
</code>```

Or:

```<code>//Where bandwidth, which was previously defined is (1000 * Info Rate) / FEC Rate / Modulation * carrier spacing / 1000000
float endFrequency = centerFrequency + (1/2 bandwidth);
</code>```

This is pretty language independent. No matter what platform, IDE, language, etc. you're working with, proper documentation is the cleanest, easiest way to make sure someone can understand your code.

Next it's on to managing those magic numbers and tons of concerns, but I think GrandmasterB's comment handled that pretty well.

Body:
I'm surprised that no one else has mentioned this...

You said:

My main goal is to be able to hand someone my source and have them
  understand what I was doing, without my input.

So let me say this, most of the other answers are on the right track. I definitely think databases could help you out. But another thing that will help you out is commenting, good variable names, and proper organization / separation of concerns.

All the other answers are heavily technical based, but they're ignoring the fundamentals that most programmers learn. Since you're a mech engie by trade, my guess is you're not used to this style of documentation.

Commenting and choosing good, succinct variable names helps immensely with readability. Which is easier to understand?

var x = y + z;

Or:

//Where bandwidth, which was previously defined is (1000 * Info Rate) / FEC Rate / Modulation * carrier spacing / 1000000
float endFrequency = centerFrequency + (1/2 bandwidth);

This is pretty language independent. No matter what platform, IDE, language, etc. you're working with, proper documentation is the cleanest, easiest way to make sure someone can understand your code.

Next it's on to managing those magic numbers and tons of concerns, but I think GrandmasterB's comment handled that pretty well.


问:
Measuring "novelty" of data
I have a heuristic in mind that should allow me to "score" data based on "novelty" that I would like to work in real-ish time.

In this case, I mean novelty in the sense that the data source is something like a video and I want to know when there is a statistically significant change in the stream.

For example, consider a video of a scene where the camera is turning to the right. As long as the velocity of the turn is constant, the data should be considered to be not-novel, or uninteresting. If a bird flies past in the opposite direction, then the parts of frame where the bird is flying past would be considered novel, and would be assigned a high score. If the scores were assigned per 16x16 block of pixels, when the bird reached center frame it might look like:

```<code>0 0 0 0 0 0 0
0 0 0 3 1 0 0
0 0 0 0 1 0 0
0 0 0 0 0 0 0
</code>```

As I understand it, there are algorithms that can do part of this for video compression, block Motion compensation and Global motion compensation, but the result of these algorithms seems to be a difference image that I would then need to digest further (average of differences), when all I want  is a simple hash. That is, given the above 7x4 matrix:

```<code>0x00003200
</code>```

The very first frame of the video, having no history, would be maximally novel:

```<code>0xFFFFFFFF
</code>```

The cool thing would be to assign a score to the whole frame, and then for interesting frames break that up into smaller blocks, and for the interesting blocks another set, and so on, like a quadtree.

So to summarise, is there a short-cut to get from a series of frames to a single hash value for each frame, based on the most recent frames? Or is there a better way to do this that I'm not aware of?

Further refinements

Reusing the example matrix above, where there is a 3 the sample is more novel because the block where the bird is in this frame didn't have a bird there before, whereas the samples with a 1 are still somewhat novel because there is no longer a bird there, but not as much because that block has returned to what would be expected in the background.

This leads me to believe that there should be some kind of accumulating effect in the solution, because more than the very last frame needs to be taken into account.

答:
I would proceed like this:

Acquire the new frame

Compare every pixel color with the same pixel, but from n previous frames

Assign a "novelty index" to that pixel (for example, the quadratic mean of the differences from every past n frames, maybe weighted with the frame temporal difference)

Count the number of pixel whose "novelty index" overcome a "novelty threshold"

If that number is above a certain "overall novelty threshold", that frame is novel

You can adapt this to a recursive approach, so that you decompose your frame in 4 areas, and so on, apply the algorithm and then backtrack to the top frame.

N.B.: I'm not a computer scientist neither a mathematician, so that's probably not the best approach!

Title: Measuring "novelty" of data


答:
It might keep your disk from sleeping, which is especially bad on a laptop.  However, I don't know how good the file caching is on Windows.  On Linux, those files would be cached in memory if unchanged, and your reads would most likely come from memory, not the disk itself.  I assume Windows is similar.

The advantages are that you consume practically zero memory and CPU time when the files aren't changing, which is most of the time, and when it does change, there's a very short latency before your program finds out about it.  You know in milliseconds instead of seconds.  You don't have to worry about how long you wait in between checks, in order to balance latency with resource usage.

The file monitoring APIs are not that difficult.  I almost never program for Windows, and I once implemented a feature using them in a couple hours.  Just stop thinking about it and give it a try.  If you don't like the result, that's what version control is for.  Just make sure to try it with different editors, because some do a rename from a temporary file rather than modifying the file in place.

Also something you may not have considered, is reading config files this way makes it difficult for users to control when their changes are applied.  If they have a large config edit to do, they can't save it when they are partially through, unless they use a different file name.  That's why most services only read the config on a restart or signal.


问:
"All software has an expiration date by which time it must be rewritten from scratch."
I stumbled upon a discussion between senior engineers and people from non-technical backgrounds and this seems to be a strongly held belief in some places.

I'm of the opinion that such a situation is purely down to incompetence on the side of the developers and project managers, those involved in creating the original system and those struggling to modify it now. Especial those who intersect both these groups.

Am I wrong? If so why?

If not, how can I convince developers twice my age that they need to change their approach to software development to overcome this problem and that rewriting the system from scratch every 2-3 years is not just an unavoidable fact of life.

Are there books or influential programmers I can quote on this issue?

答: Here's an influential programmer's opinion on the subject : "the single worst strategic mistake that any software company can make: They decided to rewrite the code from scratch."[1] -- Joel Spolsky


答:
Consider just how many things can change over a short timescale: New OSs appear. Existing OSs get rebuilt. 3rd party packages appear, develop, drop off support or go obsolete. New hardware appears, including completely new devices and paradigms (eg. touch-screens becoming the norm).

Existing paradigms are exposed as having exploitable flaws and are abandoned, or just fade away from the market. All of these require your application to change, and none are down to incompetence of your seniors.

I wouldn't agree that software always has to be rewritten from scratch, but the only (and superior) alternative to rewrites is regular ongoing refactoring. The idea that you can write a whole application and it's done for all time is just plain wrong.

Title: "All software has an expiration date by which time it must be rewritten from scratch."

Body:
I stumbled upon a discussion between senior engineers and people from non-technical backgrounds and this seems to be a strongly held belief in some places.

I'm of the opinion that such a situation is purely down to incompetence on the side of the developers and project managers, those involved in creating the original system and those struggling to modify it now. Especial those who intersect both these groups.

Am I wrong? If so why?

If not, how can I convince developers twice my age that they need to change their approach to software development to overcome this problem and that rewriting the system from scratch every 2-3 years is not just an unavoidable fact of life.

Are there books or influential programmers I can quote on this issue?


答:
I used to work for a company that had source code that had "copyright 1984" at the top of the file. It was still in the codebase because it worked, and it hadn't been removed or replaced because it still worked.

There's a lot that does get rewritten eventually, but its so rare that it might as well be never. eg. TCP/IP is still with us even though we're attempting to get the rewrite of IP implemented. HTTP is still here even though it got a little refactored in HTTP 1.1, its still pretty much the same as it always was. There's plenty more examples.

The rewrite all the time crowd just don't know how to design software right first time.


答: Rewriting from scratch every 2-3 years seems extreme to me. But a reason one might decide to rewrite from scratch is because the requirements of the current system have changed so much they bear no resemblance to the original specs. Which means that the underlying architecture might not be the right one for the current requirements. So instead of a properly designed and coded system, you have a system that consists of patches and weird design changes that only make sense when you look at the progression of the requirements from day one.


答:
You are explicitly asking what the easiest language is to learn OOP concepts. I think the answer is clear: python.

To show why this is the case, let's look at the typical beginner program in Java vs Python. Let's make a simple higher-lower guessing game.

Java

In Java, you will write a Game class.

```<code>public class Game {
    public int secretNumber;
    public int tries;

    public Game(int tries, int secretNumber) {
        this.tries = tries;
        this.secretNumber = secretNumber;
    }

    public void guess(int myNumber) {
        if(myNumber > secretNumber)
            System.out.println("Your guess is too high!");
        else if (myNumber < secretNumber)
            System.out.println("Your guess is too low!");
        else
            System.out.println("You win!!");
        tries = tries - 1;
        if(tries == 0) {
            System.out.println("No more tries: you lose :(");
        }
    }

    public static void main(String[] args) {
        Game game = new Game(10, 47);
        while(true) {
            // how do I read a newline again? Something with BufferedInputStreamReader?
            // how do I convert a String to a number?
        }
    }
}
</code>```

I am an experienced programmer, and even I am having difficulties. Furthermore, look at what you need to explain to a prospective pupil for this simple program:

Static methods

Visibility (public vs private). You should always mark fields as private.

this. notation for referring to variables when they are masked by others

The constructor resembles a method, but is not a method.

System.out is an outputStream. And yes, it is a field, but it's a static field.

Sometimes, you can omit the curly brackets if there is only one statement

String[] is an array. It is a special type of object, but then again, not really.

int is a primitive type. It is special.

You need a lot of framework methods

Python

Python is a lot 'purer'. There are no primitive types. A constructor does not exist, there is only a special method that is called at initialization.

You do not need to interact with the console, as you have a REPL. You can simply play the game using g.guess(35) and returning a string.

This makes the language easier to learn and grasp the basic OOP concepts.

Title: Is there any difference learning OOP on different programming languages?

Body:
I want to learn OOP. I know Python and I know very little things about OOP.

But when I search for "learn OOP" in forums I saw a guy saying that "Python is so new that's why you can't learn OOP on Python. you should learn Java then understand OOP on Java"

Is it true? Is there any difference understanding OOP on different programming languages?
like learn it on Java, C#, C++, Perl or Python?

Body:
You are explicitly asking what the easiest language is to learn OOP concepts. I think the answer is clear: python.

To show why this is the case, let's look at the typical beginner program in Java vs Python. Let's make a simple higher-lower guessing game.

Java

In Java, you will write a Game class.

public class Game {
    public int secretNumber;
    public int tries;

    public Game(int tries, int secretNumber) {
        this.tries = tries;
        this.secretNumber = secretNumber;
    }

    public void guess(int myNumber) {
        if(myNumber > secretNumber)
            System.out.println("Your guess is too high!");
        else if (myNumber < secretNumber)
            System.out.println("Your guess is too low!");
        else
            System.out.println("You win!!");
        tries = tries - 1;
        if(tries == 0) {
            System.out.println("No more tries: you lose :(");
        }
    }

    public static void main(String[] args) {
        Game game = new Game(10, 47);
        while(true) {
            // how do I read a newline again? Something with BufferedInputStreamReader?
            // how do I convert a String to a number?
        }
    }
}

I am an experienced programmer, and even I am having difficulties. Furthermore, look at what you need to explain to a prospective pupil for this simple program:

Static methods

Visibility (public vs private). You should always mark fields as private.

this. notation for referring to variables when they are masked by others

The constructor resembles a method, but is not a method.

System.out is an outputStream. And yes, it is a field, but it's a static field.

Sometimes, you can omit the curly brackets if there is only one statement

String[] is an array. It is a special type of object, but then again, not really.

int is a primitive type. It is special.

You need a lot of framework methods

Python

Python is a lot 'purer'. There are no primitive types. A constructor does not exist, there is only a special method that is called at initialization.

You do not need to interact with the console, as you have a REPL. You can simply play the game using g.guess(35) and returning a string.

This makes the language easier to learn and grasp the basic OOP concepts.


问:
What is the advantage of wrapping exceptions
It's very common in .NET for an exception to be wrapped in several layers of "outer exceptions" which give marginally more contextual data.  For example, in EF if your update fails, you get exceptions wrapped similar to this:

EntityException

DbUpdateException

SqlException

The data I need to understand what failed is almost always in the SqlException, so what's the advantage to the other two?  What if I was using EF inside a custom library, should I wrap this exception with one of my own?  Like MyCustomLibraryException: Could not update the data. See inner exception for details.

答:
to hide what the core cause was in places where it doesn't matter

the top level only needs to know that a storage exception occurred instead of an SQLException, which may not happen if you decide to migrate to a non-sql data store

not wrapping also leaks the abstraction and requires reimplementation of the top level when doing a migration of a lower level which will then use different exceptions


答:
A compelling principle behind error handling is to handle the error at the layer best suited to deal with the error.  Handling an error can involve retrying the operation, signaling the user, or just plain rolling over and dying.

Frequently, this means that error handling is taken care of fairly high up in the application stack as you don't want to have duplicate error handling code scattered all over your application.  Likewise, lower layers won't have the necessary information in order to figure out what sort of corrective action is appropriate.

But this presents a problem when your error handling is fairly high up in the stack and the error occurs at a fairly low point in the stack.  What you call "marginally more contextual data" is information that the lower level is providing to the calling level in order to give the calling level a better shot at taking corrective action instead of rolling over and dying.

In your specific case, it sounds like you need additional error handling closer to the database call so that you can take more appropriate corrective action.

Title: What is the advantage of wrapping exceptions

Body:
It's very common in .NET for an exception to be wrapped in several layers of "outer exceptions" which give marginally more contextual data.  For example, in EF if your update fails, you get exceptions wrapped similar to this:

EntityException

DbUpdateException

SqlException

The data I need to understand what failed is almost always in the SqlException, so what's the advantage to the other two?  What if I was using EF inside a custom library, should I wrap this exception with one of my own?  Like MyCustomLibraryException: Could not update the data. See inner exception for details.


答:
Depends on the code, what it does, and who wrote it.

The right answer, of course, is to design and implement your software in such a way that it can be easily updated without having to be completely scrapped and rewritten every few years.  Factor aggressively, deploy incrementally, test test test, and think ahead.

But...

There are some data centers that still run on '80s-vintage hardware and software because the risk of moving over to a new platform is unreasonably high; these are very high volume online transaction processing systems, such as an investment bank or an order management system for a multi-billion dollar coporation, where downtime is measured in millions of dollars per minute.  Any switchover to a new platform1 would have to be effectively instantaneous (less than a few minutes of downtime), and the new system would have to perform at least as well and as reliably as the existing system; from the end user's POV, the transition would have to be invisible.

That code isn't going to be scrapped anytime soon.  Where possible, migrations are being done in a piecemeal fashion, but a lot of these systems are monolithic COBOL apps and not easily refactored; it simply wasn't a consideration back then.

1.  Hardware, OS, database engine, application code, etc.; do you feel lucky?


问:
Handling login errors with User Class
We have a User class which handles all things related to users within a Content Management System. As you'd expect, the class contains a function login(). This function accepts three arguments: $username, $password and $remember (the latter defaulting to true).

My question is: what is the best way to handle login errors so that they can be displayed to the user? We're using a custom MVC model here, so we have controllers and views that need to remain abstract from the class itself. I have identified the following possible solutions:

Return signed integers from the login() function that can be interpreted inside the controller.

Add a variable to the User object containing the error message in plain text

Output the error directly from within the function call

Point 3 is moot, since we won't be doing that (coupling output with a class == bad).

Point 2 seems to be the most logical, but will make multi-language (a feature that may well be added later) difficult. For example, we might do something like this:

```<code>class User
{
    public $loginError;

    public function login($username, $password, $remember = true)
    {
        if($password !== $ourStoredPassword)
        {
            $this->loginError = 'Password does not match';
            return false;
        }
    }
}
</code>```

I think the best option is #1. For example, we could do this inside the Class:

```<code>class User
{
    public function login($username, $password, $remember = true)
    {
        if($password !== $ourStoredPassword)
        {
            return -1;
        }
    }
}
</code>```

Then inside our controller, just look at the return value from login(), and handle it therein. What are people's thoughts? Is there a better way to tackle this?

答:
Why not create a series of Exception objects for Login Errors such as UserNotFoundException and PasswordIncorrectException.

You can then throw the exceptions within your login method when something fails.

You should then catch this Exception within your Controller and show the output to the user as appropriate. This approach removes the coupling between the error and the message you wish to display.

http://en.wikipedia.org/wiki/Exception_handling

Title: Handling login errors with User Class


问:
How do purely functional programming languages deal with fast changing data?
What data structures can you use so you can get O(1) removal and replacement? Or how can you avoid situations when you need said structures?</p>

答:
One cheap mutable structure is argument stack.

Take a look at the typical SICP-style factorial calculation:

```<code>(defn fac (n accum)
    (if (= n 1)
        accum
        (fac (- n 1) (* accum n)))

(defn factorial (n) (fac n 1))
</code>```

As you can see, the second argument to fac is used as a mutable accumulator to contain the fast-changing product n * (n-1) * (n-2) * .... There is no mutable variable is in sight, though, and there is no way to inadvertently alter the accumulator e.g. from another thread.

This is, of course, a limited example.

You can get immutable linked lists with cheap replacement of the head node (and by extension any part beginning from the head): you just make the new head point to the same next node as the old head did. This works well with many list-processing algorithms (anything fold-based).

You can get pretty good performance from associative arrays based e.g. on HAMTs. Logically you receive a new associative array with some key-value pair(s) changed. The implementation can share most of the common data between the old and the newly created objects. This is not O(1) though; usually you get something logarithmic, at least at worst case. Immutable trees, on the other hand, don't usually suffer any performance penalty compared to mutable trees. Of course, this requires some memory overhead, usually far from prohibitive.

Another approach is based on the idea that if a tree falls in a forest and no one hears it, it needs not produce sound. That is, if you can prove that a bit of mutated state never ever leaves some local scope, you can mutate data within it safely.

Clojure has transients that are mutable 'shadows' of immutable data structures that don't leak outside local scope. Clean uses Uniques to achieve something similar (if I remember correctly). Rust helps doing similar things with statically checked unique pointers.

Body:
One cheap mutable structure is argument stack.

Take a look at the typical SICP-style factorial calculation:

(defn fac (n accum)
    (if (= n 1)
        accum
        (fac (- n 1) (* accum n)))

(defn factorial (n) (fac n 1))

As you can see, the second argument to fac is used as a mutable accumulator to contain the fast-changing product n * (n-1) * (n-2) * .... There is no mutable variable is in sight, though, and there is no way to inadvertently alter the accumulator e.g. from another thread.

This is, of course, a limited example.

You can get immutable linked lists with cheap replacement of the head node (and by extension any part beginning from the head): you just make the new head point to the same next node as the old head did. This works well with many list-processing algorithms (anything fold-based).

You can get pretty good performance from associative arrays based e.g. on HAMTs. Logically you receive a new associative array with some key-value pair(s) changed. The implementation can share most of the common data between the old and the newly created objects. This is not O(1) though; usually you get something logarithmic, at least at worst case. Immutable trees, on the other hand, don't usually suffer any performance penalty compared to mutable trees. Of course, this requires some memory overhead, usually far from prohibitive.

Another approach is based on the idea that if a tree falls in a forest and no one hears it, it needs not produce sound. That is, if you can prove that a bit of mutated state never ever leaves some local scope, you can mutate data within it safely.

Clojure has transients that are mutable 'shadows' of immutable data structures that don't leak outside local scope. Clean uses Uniques to achieve something similar (if I remember correctly). Rust helps doing similar things with statically checked unique pointers.


答:
What you're asking is a bit too broad. O(1) removal and replacement from which position? The head of a sequence? The tail? An arbitrary position? The data structure to use depends on those details. That said, 2-3 Finger Trees seem like one of the most versatile persistent data structures out there:

We present 2-3 finger trees, a functional representation of persistent sequences
      supporting access to the ends in amortized constant time, and concatenation and
      splitting in time logarithmic in the size of the smaller piece.

(...)

Further, by defining the split operation in a general form, we obtain a general
      purpose data structure that can serve as a sequence, priority queue, search tree,
      priority search queue and more.

Generally persistent data structures have logarithmic performance when altering arbitrary positions. This may or may not be a problem, since the constant in an O(1) algorithm may be high, and the logarithmic slowdown might be "absorbed" into a slower overall algorithm.

More importantly, persistent data structures make reasoning about your program easier, and that should always be your default mode of operation. You should favor persistent data structures whenever possible, and only use a mutable data structure once you've profiled and determined that the persistent data structure is a performance bottleneck. Anything else is premature optimization.

Title: How do purely functional programming languages deal with fast changing data?

Body: What data structures can you use so you can get O(1) removal and replacement? Or how can you avoid situations when you need said structures?</p>


答:
There is a vast array of data structures exploiting laziness and other tricks to achieve amortized constant time or even (for some limited cases, such as queues) constant time updates for many kinds of problems. Chris Okasaki's PhD thesis "Purely Functional Data Structures" and book of the same name is a prime example (perhaps the first major one), but the field has advanced since. These data structures are typically not only purely functional in interface, but can also be implemented in pure Haskell and similar languages, and are fully persistent.

Even without any of these advanced tools, simple balanced binary search trees give logarithmic-time updates, so mutable memory can be simulated with at worst a logarithmic slow down.

There are other options, which may be considered cheating, but are very effective with regard to implementation effort and real-world performance. For example, linear types or uniqueness types allow in-place updating as implementation strategy for a conceptually pure language, by preventing the program from holding on to the previous value (the memory that would be mutated). This is less general than persistent data structures: For example, you can't easily build an undo log by storing all previous versions of the state. It's still a powerful tool, though AFAIK not yet available in the major functional languages.

Another option for safely introducing mutable state into a functional setting is the ST monad in Haskell. It can be implemented without mutation, and barring unsafe* functions, it behaves as if it was just a fancy wrapper around passing a persistent data structure implicitly (cf. State). But due to some type system trickery that enforces order of evaluation and prevents escaping, it can safely be implemented with in-place mutation, with all the performance benefits.


答:
I can't imagine designing a system that would have to be scrapped, redesigned and rewritten after just 2 to 3 years, but I also don't want to make a blanket statement that it isn't a possibility. As there are many application domains in software development all with different needs and practices that are required to keep a company competitive. I suppose those companies where "time to market" is of utmost importance would fall in that category. Unfortunately, I bet 99% of the companies that make that claim, really aren't as "time to market" as important as they believe they are. A more robust application a few months later would likely serve their interests far better, but then building robust applications takes skill and patience, so it is easier to just make the blanket claim that time to market is why we aren't doing it right.

Anyways, I have worked with a fair number of "Senior" developers that I have ticked off immensely because I have made them redo work (sometimes many times over) that would have resulted in the 2-3 year easier to scrap than fix system if I let their work make it into the product. So being "Senior" doesn't necessarily mean that the person knows how to effectively develop software.

I don't believe there is a "right" answer to your question without knowing details about the application domain you are working in. Are the "rebuilt" systems essentially the same system with enhancements or are they really new applications? If they are essentially the same then your "senior" guys are dead wrong. They obviously are lacking in skills in many areas. On the other hand, if the new application is really a "new" application that only shares some similar traits as the previous application then maybe the "senior" guys are taking the more efficient approach.


答:
“All software has an expiration date by which time it must be rewritten from scratch.”

That is true only for improperly designed and implemented software. For properly designed software it is true that:

"All sofware is completely replaced every so often."

But this is same as "Cells in human body are completely replaced every 7-10 years". That doesn't mean that person is completely reborn after time period passes, but bits and pieces are continuously replaced so there are no cells older than 10 years. Properly designed software should have same property. Especially if it is complex and big system. When platforms, frameworks and languages change, then it becomes much more expensive to develop for the previous ones. But replacing the whole system in one big rewrite is terrible idea, just like Joel Spolsky says. Instead, rewriting pieces that are too expensive to maintain is much more realistic idea. So over course of few years, you could replace practically whole codebase while minimizing the impact of not having working software for prolonged period of time.


问:
How do you work out timings for larger projects?
I work for a small company that hasn't done much work in bespoke development. It's something we're growing into. With all our projects, whether a bespoke development piece of work, or a simple brochure website, we plan out how long we expect the job to take us and then multiply that by our daily fee to give us a quote for the customer.

That has always worked well for us with the smaller projects, the CMS sites, the eCommerce sites, where we know the systems well and don't come across many issues. We have timings down well and can predict costs accurately.

However with these larger bespoke projects we're starting to find that no matter how much we plan ahead, no matter how much we nail the specifications of the system, our timings are always out. We've started adding in a considerable buffer for bespoke pieces of software, but even then a couple of nasty bugs can really set things back and push us beyond what we expect by quite a long way.

How do you quote for these larger projects? Is it simply a case of keep going and eventually we'll get it right? Or are we missing something here as it seems almost impossible to nail pricing down for bespoke websites that fall outside our standard CMS or eCommerce site.

Update

As @Zeroth pointed out there's probably a few things missing out about the team. We don't run sprints. We have one large project on the go and have milestones and just set goals based on our estimates of how long things should take.

As for the team, currently it's made up of 4 people, although 2 new people are being trained up at the moment. The 4 people make up a salesman and designer (he's also the office manager), a designer and website builder, a website builder who also deals with content for the sites and day to day customer facing issues, and me, the developer. I deal with development of custom projects and improving / fixing our CMS and eCommerce platforms. The two people being trained up are another designer and website builder, and a junior developer.

Once a project reaches certain milestones, everyone pitches in to test it as thoroughly as we can. I always put in as much logging and debugging information as I can think of to help track down the inevitable bugs as quickly as possible, but no matter how much we do, we can't test every situation.

I understand this is a complex and widely varying answer, I guess I'm mostly after some advice and also some pointers to resources (thank you @MichaelT for the link to the book) that can help us improve. We need to be able to pull a profit from custom work as we're currently fully booked until June for development work and we need to make this work for us. Over the last year, it just seems no matter how much we learn from each project we work on, we still get it wrong with our estimates.

答:
The elephant in the room is the large bugs you mention that set you back. Your estimation could be spot on until you encounter a few of these. That however is a separate question.

Perfect estimation is based on knowing precisely the amount of work ahead of you. However, the more time you spend on this, the more you'll be looking at increasing levels of detail and the longer you'll spend estimating instead of getting started.

Start at a very high level and then iteratively look at each deliverable until you get down to the level where work needs to be done e.g. coding, specification etc. Then estimate for each of the leaf nodes. Then add a contigency (we use 20%).

Use experts in the area to estimate the effort required. It is pointless having a BA look at DBA tasks if they don't understand what is involved. The closer to the action you can do the estimation, the more reliable they'll be.

This will give you the effort (man hours, man days etc) which can be used to quote for the work. Note that effort doesn't give you a delivery date. This would be decided on by your resource allocation (other projects, holidays etc). Depending on how your company is set up, you may bill the same for all man effort or you might have a split structure depending on grade. At a former company we charged £1000 a day for DBAs, £500 for Analyst Programmers etc. You'll need to factor all this in.

For each project of a given size you complete, review it once it has been delivered. Which areas overran? Also (and this is critical) fully understand why each major issue came about otherwise you risk coming across the same problems again and again.

If a few people are doing the estimations, you'll get a feel for which people's estimates are reliable and which are way off. This isn't a stick to beat the staff with, the important thing is to understand why. Was a piece of work missed off the plan? Was a piece of work poorly understood? Did the requirements change? etc etc etc


问:
Combining version numbers of app components
I have an app that is made up of multiple different components, each with their own version number and history. I would like to create a version number of the entire application, preferably somehow based on the version numbers of the components. I am not sure if this is possible at all, but I would like:

The version number be unique for each version of the components, so that when I upgrade the version number of one of the components, the version number of the whole app will change as well, and the number must not be ambigous so that it could refer to some other constellation of components.

It would be nice if there was a way to reverse the process to go from a combined version number to see what versions of components it consists of.

It is also nice if the combined version number is not too long to remember

It's a plus if the combined version number always increases with the increase of a component version number.

I am aware that some of these desires are not possible to accomodate together (such as short AND reversable since you would lose information when shortening)

The easiest approach is of course to just add the version number together in a long row, but that would be too long to be practical. Another is to create some kind of hash, but it would not be very readable.

Is there a standard way of doing this? Or will I have to name the major version manually and take note of what component versions it consists of?

答:
That's what version control systems are for. Properly set up and used, they allow you to keep track of the released versions along with all of their dependencies used.

To get a short cut from "official" version number to source code revision, the CVS revision number(s) can be compiled into the binaries through different ways. Most CVS offer also some built-in support for this. For example, we put that info into the version resources of our Windows binaries and use SubWCRev for some special cases.

If you need/want all the information about the components used as human readable information in your programs, add it to the "Info/About" box or whatever the equivalent of it is. If do it cleverly, like using a readonly edit field, anyone will be able to copy+paste the info, if such is needed.


问:
Aspect Oriented Programming: When to start using a framework?
I just watched this talk by Greg Young warning people to KISS: Keep It Simple Stupid.

One of the things he suggested is that to do aspect-oriented programming, one does not need a framework.

He starts by making a strong constraint: that all methods take one, and only one, parameter (though he relaxes this a little later by using partial application).

The example he gives is to define an interface:

```<code>public interface IConsumes<T>
{
    void Consume(T message);
}
</code>```

If we want to issue a command:

```<code>public class Command
{
    public string SomeInformation;
    public int ID;

    public override string ToString()
    {
       return ID + " : " + SomeInformation + Environment.NewLine;
    }
}
</code>```

The command is implemented as:

```<code>public class CommandService : IConsumes<Command>
{
    private IConsumes<Command> _next;

    public CommandService(IConsumes<Command> cmd = null)
    {
        _next = cmd;
    }
    public void Consume(Command message)
    {
       Console.WriteLine("Command complete!");
        if (_next != null)
            _next.Consume(message);
    }
}
</code>```

To do logging to console, one then just implements:

```<code>public class Logger<T> : IConsumes<T>
{
    private readonly IConsumes<T> _next;

    public Logger(IConsumes<T> next)
    {
        _next = next;
    }
    public void Consume(T message)
    {
        Log(message);
        if (_next != null)
            _next.Consume(message);
    }

    private void Log(T message)
    {
        Console.WriteLine(message);
    }
}
</code>```

Then, the pre-command logging, command service, and post-command logging are then just:

```<code>var log1 = new Logger<Command>(null);
var svr  = new CommandService(log);
var startOfChain = new Logger<Command>(svr);
</code>```

and the command is executed by:

```<code>var cmd = new Command();
startOfChain.Consume(cmd);
</code>```

To do this in, for example, PostSharp, one would annotate the CommandService this way:

```<code>public class CommandService : IConsumes<Command>
{
    [Trace]
    public void Consume(Command message)
    {
       Console.WriteLine("Command complete!");
    }
}
</code>```

And then have to implement the logging in an attribute class something like:

```<code>[Serializable]
public class TraceAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry( MethodExecutionArgs args )
    {
        Console.WriteLine(args.Method.Name + " : Entered!" );
    }

    public override void OnSuccess( MethodExecutionArgs args )
    {
        Console.WriteLine(args.Method.Name + " : Exited!" );
    }

    public override void OnException( MethodExecutionArgs args )
    {
        Console.WriteLine(args.Method.Name + " : EX : " + args.Exception.Message );
    }
}
</code>```

The argument Greg uses is that the connection from the attribute to the implementation of the attribute is "too much magic" to be able to explain what's happening to a junior developer. The initial example is all "just code" and easily explained.

So, after that rather longwinded build-up, the question is: when do you make the switch from Greg's non-framework approach to using something like PostSharp for AOP?

答:
What Greg describes is absolutely reasonable. And there is beauty in it as well. The concept is applicable in a different paradigm than pure object orientation. It's more a procedural approach or a flow oriented design approach. So if you are working with legacy code it will be quite difficult to apply this concept because a lot of refactoring might be needed.

I will try to give another example. Maybe not perfect but I hope it makes the point more clear.

So we have a product service which uses a repository (in this case we will use a stub). The service will get a list of products.

```<code>public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public override string ToString() { return String.Format("{0}, {1}", Name, Price); }
}

public static class ProductService
{
    public static IEnumerable<Product> GetAllProducts(ProductRepositoryStub repository)
    {
        return repository.GetAll();
    }
}

public class ProductRepositoryStub
{
    public ProductRepositoryStub(string connStr) {}

    public IEnumerable<Product> GetAll()
    {
        return new List<Product>
        {
            new Product {Name = "Cd Player", Price = 49.99m},
            new Product {Name = "Yacht", Price = 2999999m }
        };
    }
}
</code>```

Off course you could also pass an interface to the service.

Next we want to show a list of products in a view. Therefore we need an interface

```<code>public interface Handles<T>
{
    void Handle(T message);
}
</code>```

and a command which holds the list of products

```<code>public class ShowProductsCommand
{
    public IEnumerable<Product> Products { get; set; }
}
</code>```

and the view

```<code>public class View : Handles<ShowProductsCommand>
{
    public void Handle(ShowProductsCommand cmd)
    {
        cmd.Products.ToList().ForEach(x => Console.WriteLine(x.ToString()));
    }
}
</code>```

Now we need some code that executes all this. This we will do in a class called Application. The Run() method is the integrating method that contains no or at least very little business logic. The dependencies are injected into the constructor as methods.

```<code>public class Application
{
    private readonly Func<IEnumerable<Product>> _getAllProducts;
    private readonly Action<ShowProductsCommand> _showProducts;

    public Application(Func<IEnumerable<Product>> getAllProducts, Action<ShowProductsCommand> showProducts)
    {
        _getAllProducts = getAllProducts;
        _showProducts = showProducts;
    }

    public void Run()
    {
        var products = _getAllProducts();
        var cmd = new ShowProductsCommand { Products = products };
        _showProducts(cmd);
    }
}
</code>```

Finally we compose the application in the main method.

```<code>static void Main(string[] args)
{
    // composition
    Func<IEnumerable<Product>> getAllProducts = () => ProductService.GetAllProducts(new ProductRepositoryStub(""));
    Action<ShowProductsCommand> showProducts = (x) => new View().Handle(x);
    var app = new Application(getAllProducts, showProducts);

    app.Run();
}
</code>```

Now the cool thing is that we can add aspects like logging or exception handling without touching the existing code and without a framework or annotations. For exception handling e.g. we just add a new class:

```<code>public class ExceptionHandler<T> : Handles<T>
{
    private readonly Handles<T> _next;

    public ExceptionHandler(Handles<T> next) { _next = next; }

    public void Handle(T message)
    {
        try
        {
            _next.Handle(message);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
</code>```

And then we plug it together during the composition at the entry point of the application. we don't even have to touch the code in the Application class. We just replace one line:

```<code>Action<ShowProductsCommand> showProducts = (x) => new ExceptionHandler<ShowProductsCommand>(new View()).Handle(x);
</code>```

So to resume: When we have a flow oriented design we can add aspects by adding the functionality inside a new class. Then we have to change one line in the composition method and that's it.

So I think an answer to your question is that you cannot easily switch from one approach to the other but you have to decide on what kind of architectural approach you will go for in your project.

edit:
Actually I just realized that the partial application pattern used with the product service makes things a little more complicated. We need to wrap another class around the product service method to be able to add aspects here as well. It could be something like this:

```<code>public class ProductQueries : Queries<IEnumerable<Product>>
{
    private readonly Func<IEnumerable<Product>> _query;

    public ProductQueries(Func<IEnumerable<Product>> query)
    {
        _query = query;
    }

    public IEnumerable<Product> Query()
    {
        return _query();
    }
}

public interface Queries<TResult>
{
    TResult Query();
}
</code>```

The composition then has to be changed like this:

```<code>Func<IEnumerable<Product>> getAllProducts = () => ProductService.GetAllProducts(new ProductRepositoryStub(""));
Func<IEnumerable<Product>> queryAllProducts = new ProductQueries(getAllProducts).Query;
Action<ShowProductsCommand> showProducts = (x) => new ExceptionHandler<ShowProductsCommand>(new View()).Handle(x);
var app = new Application(queryAllProducts, showProducts);
</code>```

Body:
What Greg describes is absolutely reasonable. And there is beauty in it as well. The concept is applicable in a different paradigm than pure object orientation. It's more a procedural approach or a flow oriented design approach. So if you are working with legacy code it will be quite difficult to apply this concept because a lot of refactoring might be needed.

I will try to give another example. Maybe not perfect but I hope it makes the point more clear.

So we have a product service which uses a repository (in this case we will use a stub). The service will get a list of products.

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public override string ToString() { return String.Format("{0}, {1}", Name, Price); }
}

public static class ProductService
{
    public static IEnumerable<Product> GetAllProducts(ProductRepositoryStub repository)
    {
        return repository.GetAll();
    }
}

public class ProductRepositoryStub
{
    public ProductRepositoryStub(string connStr) {}

    public IEnumerable<Product> GetAll()
    {
        return new List<Product>
        {
            new Product {Name = "Cd Player", Price = 49.99m},
            new Product {Name = "Yacht", Price = 2999999m }
        };
    }
}

Off course you could also pass an interface to the service.

Next we want to show a list of products in a view. Therefore we need an interface

public interface Handles<T>
{
    void Handle(T message);
}

and a command which holds the list of products

public class ShowProductsCommand
{
    public IEnumerable<Product> Products { get; set; }
}

and the view

public class View : Handles<ShowProductsCommand>
{
    public void Handle(ShowProductsCommand cmd)
    {
        cmd.Products.ToList().ForEach(x => Console.WriteLine(x.ToString()));
    }
}

Now we need some code that executes all this. This we will do in a class called Application. The Run() method is the integrating method that contains no or at least very little business logic. The dependencies are injected into the constructor as methods.

public class Application
{
    private readonly Func<IEnumerable<Product>> _getAllProducts;
    private readonly Action<ShowProductsCommand> _showProducts;

    public Application(Func<IEnumerable<Product>> getAllProducts, Action<ShowProductsCommand> showProducts)
    {
        _getAllProducts = getAllProducts;
        _showProducts = showProducts;
    }

    public void Run()
    {
        var products = _getAllProducts();
        var cmd = new ShowProductsCommand { Products = products };
        _showProducts(cmd);
    }
}

Finally we compose the application in the main method.

static void Main(string[] args)
{
    // composition
    Func<IEnumerable<Product>> getAllProducts = () => ProductService.GetAllProducts(new ProductRepositoryStub(""));
    Action<ShowProductsCommand> showProducts = (x) => new View().Handle(x);
    var app = new Application(getAllProducts, showProducts);

    app.Run();
}

Now the cool thing is that we can add aspects like logging or exception handling without touching the existing code and without a framework or annotations. For exception handling e.g. we just add a new class:

public class ExceptionHandler<T> : Handles<T>
{
    private readonly Handles<T> _next;

    public ExceptionHandler(Handles<T> next) { _next = next; }

    public void Handle(T message)
    {
        try
        {
            _next.Handle(message);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

And then we plug it together during the composition at the entry point of the application. we don't even have to touch the code in the Application class. We just replace one line:

Action<ShowProductsCommand> showProducts = (x) => new ExceptionHandler<ShowProductsCommand>(new View()).Handle(x);

So to resume: When we have a flow oriented design we can add aspects by adding the functionality inside a new class. Then we have to change one line in the composition method and that's it.

So I think an answer to your question is that you cannot easily switch from one approach to the other but you have to decide on what kind of architectural approach you will go for in your project.

edit:
Actually I just realized that the partial application pattern used with the product service makes things a little more complicated. We need to wrap another class around the product service method to be able to add aspects here as well. It could be something like this:

public class ProductQueries : Queries<IEnumerable<Product>>
{
    private readonly Func<IEnumerable<Product>> _query;

    public ProductQueries(Func<IEnumerable<Product>> query)
    {
        _query = query;
    }

    public IEnumerable<Product> Query()
    {
        return _query();
    }
}

public interface Queries<TResult>
{
    TResult Query();
}

The composition then has to be changed like this:

Func<IEnumerable<Product>> getAllProducts = () => ProductService.GetAllProducts(new ProductRepositoryStub(""));
Func<IEnumerable<Product>> queryAllProducts = new ProductQueries(getAllProducts).Query;
Action<ShowProductsCommand> showProducts = (x) => new ExceptionHandler<ShowProductsCommand>(new View()).Handle(x);
var app = new Application(queryAllProducts, showProducts);


问:
Is a lambda expression something more than an anonymous inner class with a single method?
There is a new hype with the long awaited lambda expressions in Java 8; every 3 day another article appears with them about how cool they are.

As far as I have understood a lambda expression is nothing more than an anonymous inner class with a single method (at least at the byte-code level). Besides this it comes with another nice feature - type inference but I believe the equivalent of this can be achieved with generics on some level (of course not in such a neat way as with lambda expressions).

Knowing this, are lambda expressions going to bring something more than just a syntactic sugaring in Java? Can I create more powerful and flexible classes or other object-oriented constructs with lambda expressions that aren't possible to be built with current language features?

答:
No. They are not.

Another way to put it is lambdas are an un-object-oriented, however concise, way to achieve the same thing that an anonymous class or, my preference, inner class would achieve in an object-oriented way.


问:
Do any package managers provide select-one dependencies
With jquery very slowly being phased out you get into more and more situations where library X will run with either jquery or zepto.js (but at least one is required).

No package managers that I can think of however allow you to express dependencies like this. If I was to propose this feature to - say - bower, is there precedent for how it might look?

答:
dpkg / APT has supported this for ages.

There are two mechanisms for this. One is alternate dependencies by simply declaring the dependency like this:

```<code>Depends: jquery | zeptojs
</code>```

You will declare that the package depends on either jquery or zepto.js.

The other mechanism is Virtual Packages. A package can declare that it Provides a virtual package and then other packages can depend on that virtual package.

For example, both the jquery package and the zeptojs package can declare that they provide the jquery-api virtual package, and then your app can depend on jquery-api. This has the added advantage that if in the future a third new JQuery-compatible library appears in the market, only the author of that package has to put a Provides: jquery-api line in his package description. You don't have to change your app and it will just work with the new library.

In your app:

```<code>Depends: jquery-api
</code>```

In JQuery:

```<code>Provides: jquery-api
</code>```

In Zepto.JS:

```<code>Provides: jquery-api
</code>```

In the brand-new yet-to-be-written awesome new JQuery replacement:

```<code>Provides: jquery-api
</code>```

Body:
dpkg / APT has supported this for ages.

There are two mechanisms for this. One is alternate dependencies by simply declaring the dependency like this:

Depends: jquery | zeptojs

You will declare that the package depends on either jquery or zepto.js.

The other mechanism is Virtual Packages. A package can declare that it Provides a virtual package and then other packages can depend on that virtual package.

For example, both the jquery package and the zeptojs package can declare that they provide the jquery-api virtual package, and then your app can depend on jquery-api. This has the added advantage that if in the future a third new JQuery-compatible library appears in the market, only the author of that package has to put a Provides: jquery-api line in his package description. You don't have to change your app and it will just work with the new library.

In your app:

Depends: jquery-api

In JQuery:

Provides: jquery-api

In Zepto.JS:

Provides: jquery-api

In the brand-new yet-to-be-written awesome new JQuery replacement:

Provides: jquery-api


问:
Is this a monad in Java? (part 2)
My first try was on stackoverflow. I'm picking up on the answer there to improve my monad: StackOverflow - Is this a monad in Java?

My goal is to write an example of a monad. I'm not trying to solve the general case, just come up with one to see how it works. If I'm right, then I really like this pattern. I've already used it to rework some code I'm working on. So I hope it's right.

I was pretty strict about the signatures & not taking shortcuts that OO allows.

The (contrived) example is to provide semantics to represent a Friend relationship between two users. If there's an error, or the friendship is blocked, then processing stops. I have sample code that "lifts" Boolean, String and a custom Friend class into the monadic space, so I think that' a sign I'm on the right track. I've included the sample code lifting String into the monadic space.

My question is, did I get the monad implementation right? Please call out the places where I jumped the rails!

```<code>public class FriendSpace<A> {

    public boolean rejected = false;
    public String errors = "";
    public A original;

    public interface Function<B, MA> {
        MA apply(B b, MA a);
    }

    public FriendSpace<A> unit(A a) {
        FriendSpace<A> that = new FriendSpace<A>();
        that.original = a;
        return that;
    }

    public <B> FriendSpace<A> bind(B b, Function<B, FriendSpace<A>> f) {
        if (! errors.isEmpty()) {
            // we have errors; skip the rest
            return this;
        }

        if (rejected) {
            // No means no
            return this;
        }

        FriendSpace<A> next = f.apply(b, this);

        return next;
    }

    @SuppressWarnings("unchecked")
    public <B> FriendSpace<A> pipeline(B value,
           FriendSpace.Function<B, FriendSpace<A>>... functions) {
        FriendSpace<A> space = this;
        for (FriendSpace.Function<B, FriendSpace<A>> f : functions) {
            space = space.bind(value, f);
        }
        return space;
    }

    // toString omitted to save space
}
</code>```

And here's an example where the (arbitrary) input is a People class, and the (arbitrary) class representing the friendship state is String

```<code>public class People {

    public People(String from, String to) {
        this.from = from;
        this.to = to;
    }

    public String from;
    public String to;
}

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        FriendSpace<String> proto = new FriendSpace<String>();

        People people0 = new People("Bob", "Fred");
        FriendSpace<String> space0 = proto.unit("");
        FriendSpace<String> friends0 = space0.pipeline(people0, VERIFY, INVITE, ACCEPT);
        System.err.println(friends0);

        People people1 = new People("Bob", "Jenny");
        FriendSpace<String> space1 = proto.unit("");
        FriendSpace<String> friends1 = space1.pipeline(people1, VERIFY, INVITE, ACCEPT);
        System.err.println(friends1);

        People people2 = new People("Fred", "Jenny");
        FriendSpace<String> space2 = proto.unit("");
        FriendSpace<String> friends2 = space2.pipeline(people2, VERIFY, INVITE, BLOCK);
        System.err.println(friends2);

        People people3 = new People("Bob", "Tom");
        FriendSpace<String> space3 = proto.unit("");
        FriendSpace<String> friends3 = space3.pipeline(people3, VERIFY, INVITE, ACCEPT);
        System.err.println(friends3);
    }

    public interface StringFunction extends FriendSpace.Function<People, FriendSpace<String>> {
    }

    static StringFunction VERIFY = new StringFunction() {
        public FriendSpace<String> apply(People from, FriendSpace<String> to) {
            String KNOWN_USERS = "Bob Fred Jenny";

            if (! KNOWN_USERS.contains(from.from)) {
                to.errors += "Unknown from: " + from.from;
            }

            if (! KNOWN_USERS.contains(from.to)) {
                to.errors += "Unknown to: " + from.to;
            }

            return to;
        }
    };

    static StringFunction INVITE = new StringFunction() {
        public FriendSpace<String> apply(People from, FriendSpace<String> to) {
            // Jenny has blocked Bob
            if ("Jenny".equals(from.to) && "Bob".equals(from.from)) {
                to.errors = "Jenny blocked Bob";
            }
            return to;
        }
    };

    static StringFunction ACCEPT = new StringFunction() {
        public FriendSpace<String> apply(People from, FriendSpace<String> to) {
            // Good to go!
            to.original = "YES";
            return to;
        }
    };

    static StringFunction BLOCK = new StringFunction() {
        public FriendSpace<String> apply(People from, FriendSpace<String> to) {
            to.original = "BLOCK";
            to.rejected = true;
            return to;
        }
    };
</code>```

答:
The place Java and C# fall down in implementing monads is if you bind a function a -> m b where a != b you can't return this - you need to construct a default b to create the m b where in Haskell Nothing is a valid m b construction as well as Left anything can supplant Right anything.

You have an Either monad here which is what we OO folks prefer over Maybe because it allows us to trap some information with the issue explicitly (FP folks tend to prefer the implicit and more concise Nothing from the Maybe monad).

Fix your return this to meet the requisite polymorphism so it can take an a -> m b and return an m b even in the failure case. You'll need to return new FriendState(something else) because this may be a FriendState but your bind needs to return a FriendState, right now failure only allows returning FriendState which only works when you bind functions that go from a -> FriendState.

I know that's the tricky part as a C# guy who's done variations on monads in C# myself, it's hard to get the amount of polymorphism ADTs give you. This is a very good first crack!

Title: Is this a monad in Java? (part 2)

Body:
The place Java and C# fall down in implementing monads is if you bind a function a -> m b where a != b you can't return this - you need to construct a default b to create the m b where in Haskell Nothing is a valid m b construction as well as Left anything can supplant Right anything.

You have an Either monad here which is what we OO folks prefer over Maybe because it allows us to trap some information with the issue explicitly (FP folks tend to prefer the implicit and more concise Nothing from the Maybe monad).

Fix your return this to meet the requisite polymorphism so it can take an a -> m b and return an m b even in the failure case. You'll need to return new FriendState(something else) because this may be a FriendState<a> but your bind needs to return a FriendState<b>, right now failure only allows returning FriendState<a> which only works when you bind functions that go from a -> FriendState<a>.

I know that's the tricky part as a C# guy who's done variations on monads in C# myself, it's hard to get the amount of polymorphism ADTs give you. This is a very good first crack!