答:
The Way of Testivus says thus on the matter of when to write unit tests:

The best time to test is when the code is fresh

Your code is like clay.

  When it’s fresh, it’s soft and malleable.

  As it ages, it becomes hard and brittle.

If you write tests when the code is fresh

  and easy to change, testing will be easy

  and both the code and the tests will be strong.

The key thing to take away form this is that you write code early in the process when you can still think about what the code is doing.  When doing this, you think about what is testable and what isn't.  Another bit from the Way of Testvius...

Think of code and test as one

When writing the code, think of the test.

  When writing the test, think of the code.

  When you think of code and test as one,

  testing is easy and code is beautiful.

One thing that I like about The Way of Testivus rather than more dogmatic statements is it specifiably calls out dogma and says don't get stuck on it.  Writing the test is more important than following rules set in stone.

Write tests.

Write tests early.

A poor written test is better than no test.

Title: When to write Unit Tests : Is there any or list of terms to take right decision

Body:
To write Unit Tests we have to write extra bits of code.
For several projects we do Unit Tests and for several projects we do not.

As a Team Leader I face trouble to make the right decision.

Is there any or list of terms by which I can take the right decision whether we will do Unit tests or not?

EDIT: Please provide a comment while down voting the question. It will help me to improve my question.


问:
Declaring functions as final... except when it is me who does the deriving
I have a class in which I want to disallow other programmers from overriding one of it's methods, since it requires special knowledge of the inner workings of the class. Since I personally know how the class works, I would like to be able to make an exception and actually DO override the function in one derived class. Is this a common problem to which there is a standard solution, or does the fact that I feel like I have to make an exception like this mean I should rethink my approach?

Edit: I didn't mention languages, since I was looking for a general answer, but since it was requested, this came up using PHP.

答:
You should rethink your approach. Put yourself in the shoes of the future maintainer of your class, be it future you (who has forgotten some stuff) or someone else.

You want as few "special" commentaries or magic behaviour in the code as possible. This is especially true for special inheritance, where base class codes makes undocumented assumptions on the derived classes. And in your case, the sentence "requires special knowledge of the inner workings of the class" means that knowledge about the base class is encoded in the derived class, and the derived class makes a lot of assumptions on the base class. If you have the desire to make the base class final-but-not-for-me, you seem to have the gut feeling that not all assumptions are readily understood. This is a nightmare for a maintainer.

If you need to derive, do so and derive openly, with all the associated costs. If it isn't worth the cost, don't derive. Intermediate solutions incur all the costs in maintenance, but none of the gains.

ContentLicense: CC BY-SA 3.0


问:
Should the variable be named Id or ID?
This is a bit pedantic, but I've seen some people use Id as in:

private int userId;
public int getUserId();
```

<p>and others use:</p>

<pre class="lang-cs prettyprint-override"><code>private int userID;
public int getUserID();
</code>```

Is one of these a better name than the other? Why? I've seen this done very inconsistently in large projects. If I were to set a standard which would most people be familiar with? Which is the conventional standard?

答:
TL;DR: In the context of .NET class libraries, Microsoft recommends that you use Id.  This is slightly counter-intuitive, since it's a rare example of an abbreviation that is allowed / recommended (abbreviations are generally frowned upon).

If we're talking about C# or .NET class library conventions, Microsoft has some fairly well defined naming guidelines available.  They are well thought out, with many explanations on a variety of issues - actually, every developer should take some time to read the entire Design Guidelines section.

When it comes to acronyms, the rule of thumb is: for two letter acronyms, you tend to keep them upper case (where Pascal case is applicable), so e.g. IOStream might be the name of a class.  For a longer acronym, you lower case the rest of the acronym, e.g. XmlDocument or HtmlParser.  This is actually a mostly unambiguous rule (there's no confusion as to where the one word ends and the next begins, unless you're chaining two-letter acronyms), and you get used to it very quickly.

So, is it ID, or Id?  Well, according to Microsoft, it might not be what you think:

Acronyms differ from abbreviations in that an abbreviation shortens a single word. For example, ID is an abbreviation for identifier. In general, library names should not use abbreviations.

The two abbreviations that can be used in identifiers are ID and OK. In Pascal-cased identifiers they should appear as Id, and Ok. If used as the first word in a camel-cased identifier, they should appear as id and ok, respectively.

Anecdotally, I'm not actually sure when this distinction started appearing in the guidelines, but a few years back (around 3.0 / 3.5) the general naming trend in class libraries went from ID to Id.

Title: Should the variable be named Id or ID?

ContentLicense: CC BY-SA 4.0


问:
What should junior developer expect from their senior team lead
Disclaimer: Opinions expressed are solely my own and do not express the views or opinions of my employer.

I work for a small company, in which few people are  developers, others are QA/Test and 1 is a Manager. I joined this company 1.5 years ago. 3 senior developers have 8+ years of experience.

These are the observations which I made about the team lead. (considering me as a fresher with less experience compared to them in all aspects )

They never discuss 1:1 or they never consider the junior suggestion (I agree that it's up to them, whether they accept it or not, at least they should consider an opinion).

As senior team leader they can try to refactor the codebase with new technologies ( including the factor of rolling out new technologies is possible and other developer and infrastructure also ready), but these team leader feel less in-secure to work with new technologies, as they are not up to date. (reason I am telling, they don't know what current programming trend, *(such as popular open source projects like modernizr, bootstrap and many others).

In our codebase more than 10000+ lines are repeated, so I told them  about DRY: Don't Repeat yourself.  Their reply was : "It is a fascinating article, but never works in practice".  I just told them if we do not make it 100% DRY, we can at least use interfaces, but that also was not considered. *(interfaces can be added for new features, not touching the previous codebase, if they are not ready to refactor)

All senior developers do maintenance and hot fixing of patches. The rest of the time they just spend on entertainment sites. They are just happy to finish the task.

Introducing new technology is bad? *(including factor of feasibility can be done).

Manager also least concerned about the things which I am talking about.

Junior expects they can learn many things from team lead. *(not by asking help or senior coding for them).

My questions are:

Am I too aggressive about the changes which I am proposing?

What should I expect from senior dev leads who have 8+ years experience?

Am I wrong to expect to learn and gain experience from a company?

Update :

Why they feel DRY is impractical: because they don't want get involved with OOP concepts. They are happy with repeating tasks.

New technologies I am proposing:

Usage of Minification of CSS, JS, SPrite images

Usage of Interfaces and .net framework 4, generics and many others.

Client side libraries such as modernizr, knockout js, bootstrap for responsive,

答:
I think you need to get creative. Start asking around for some side project requests that your seniors have been putting off. By working on something independently (or better yet, get another junior dev in on it) and from the beginning, you can apply a lot of the new stuff. Don't be surprised if you find out it's not all for the better.

Another approach would be to do your own code branch and go through a refactor process. I may never make its way into production based on what you've said, but at least you get to improve your skill set.

Who knows, they may see how you're able to make everyone's job easier and they'll embrace the true use of 'laziness' in programming.

If all else fails, put the new skill-set on your CV and start looking for another job.


问:
Why are actual parameters called "arguments"?
Where does the word "argument" (in the programming sense) come from?

i.e. Why are actual parameters called "arguments"?

The meanings don't seem related, and I haven't found any explanation of it anywhere.

Note on the terminology:

"Formal" parameters (also known simply as "parameters") are the "placeholder" names (say, x) -- the declared parameters of a function.

"Actual" parameters (also known as "arguments") are the actual values which are passed to a function (say, 5), hence I used this term above to prevent any confusion.

答:
According to Wiktionary, the originating Latin word was argumentum, which also means "token". So you can see pretty easily how that term got used in mathematics, most of the texts of which were written in Latin for a long time.

A lot of terms used in mathematics, particularly around functions, naturally spread to programming.


问:
What are the criteria for evaluating an ORM for.NET?
I'm looking at evaluating ORMs.

I've used SubSonic, Linq-to-SQL and Entity Framework. I've got a team of developers ranging from juniors to seniors.

What are the criterias for evaluating an ORM for.NET?

答: We've had good luck with Entity Framework.  Our situation is somewhat unusual, though -- we do data collection for the reporting team, so they actually design the database.  We get the DB and then just use EF to generate the data access classes from it.  Works great for us, but we just do bulk data loads, so I can't vouch for how well it does in a more transactional environment.</p>

ContentLicense: CC BY-SA 2.5


问:
Is there a license for selling a software with the sources so buyer can make modifications without claiming ownership of the code or distributing it?
I would like to sell a software that has some open source competitors. Therefore I would like to include the source code with the binaries so that the company buying it can modify it as it wishes. The only catch is that the source code will NOT belong to the company, in other words, I would like to maintain the copyright and ownership over the code so I can sell to other companies, etc.

Is there a license name for this kind of model? The buyer can see the code, modify it for its needs, but it cannot take ownership over the code, in other words, it is licensed for a particular use/need and he cannot give or show the code to anyone else.

Buyers are more likely to be companies in that model, in other words, they will be able to take control of the product by modifying the source code, but they will not be able to take ownership of the original code or do anything with it besides the initial purpose they bought it for. It is still closed source. Only the companies that buy the product are entitled to see and modify the code but never to distribute it.

答:
I am not a lawyer, and I would always recommend discussing changes to licences with one.

With that out of the way:

The buyer could never under any copyright scheme take ownership of the code. Even lenient licenses like Apache 2.0 and GPL both keep the ownership of the code to the original copyright holder.

So you don't have to worry about ownership, instead you are worried about showing the source code and the license that applies to the modified forms of the code that they create.

I don't know offhand how licenses can control sharing of source code. You can say that you cannot redistribute, but I don't know offhand the distinctions in that verbiage between binaries and source.

Assuming you already have a license that sufficiently restricts their use of the original form, that same can apply to all of the derived forms as well. So they don't gain or lose any rights in modified forms from a licensing standpoint.


答:
Like most of us here, I am not a lawyer, and questions of law are better suited for lawyers than programmers.

But what you are describing sounds like a fairly common non-exclusive, non-transferable, non-redistributable license.

"Non-exclusive" indicating that you are or may be licensing the same code to other customers. "Non-transferable" indicating that they can't sell their license to someone else. "Non-redistributable" indicating that they can't distribute your code in any fashion.

A quick Google came across this license from Intel. It's actually more liberal than what you're describing in that it allows the licensee to use the code in their own products and distribute them, as long as they are distributed in executable form only, which you probably don't want to allow. But the main thrust of it is very clear: you can use our source code, you can't give it to anyone else.

Title: Is there a license for selling a software with the sources so buyer can make modifications without claiming ownership of the code or distributing it?

Body:
I would like to sell a software that has some open source competitors. Therefore I would like to include the source code with the binaries so that the company buying it can modify it as it wishes. The only catch is that the source code will NOT belong to the company, in other words, I would like to maintain the copyright and ownership over the code so I can sell to other companies, etc.

Is there a license name for this kind of model? The buyer can see the code, modify it for its needs, but it cannot take ownership over the code, in other words, it is licensed for a particular use/need and he cannot give or show the code to anyone else.

Buyers are more likely to be companies in that model, in other words, they will be able to take control of the product by modifying the source code, but they will not be able to take ownership of the original code or do anything with it besides the initial purpose they bought it for. It is still closed source. Only the companies that buy the product are entitled to see and modify the code but never to distribute it.


答: I read a very good explanation in some coding conventions' document. CamelCase should always be used for acronyms and abbreviations, because it is easier to distinguish word boundaries (compare XmlIdWriter to XMLIDWriter).

Title: Should the variable be named Id or ID?

Body:
This is a bit pedantic, but I've seen some people use Id as in:

private int userId;
public int getUserId();
```

<p>and others use:</p>

<pre class="lang-cs prettyprint-override"><code>private int userID;
public int getUserID();
</code>```

Is one of these a better name than the other? Why? I've seen this done very inconsistently in large projects. If I were to set a standard which would most people be familiar with? Which is the conventional standard?


答:
Think of this as a huge opportunity.

Promotions often don't (and shouldn't) come from the number of years you've put into a company anymore. You've got what you think are some really good ideas, and your superiors/peers don't want to listen.

Here is a strategy:

Do something awesome

Collect hard metrics for how awesome it is (this step is key)

Demonstrate it, with your metrics to everyone at your company (owner/lead/seniors/sales guys - everyone you can get your hands on)

Profit

And I don't mean profit to be some vague "I win" step. Step 4 is where you get one, or all of the following:

Promoted

A raise

A bonus

Either with your company, or a new one that can appreciate your talents and the amazing metrics that you've got on your resume.

I call it "being awesome" - and it works.

Anecdote: I'm not consistently awesome, but I try to be and I've performed the steps given 5 distinct times (2 promotions, 3 new jobs; all with substantial pay increases).

With that in mind, I should probably answer your questions directly:

Am I too aggressive about the changes which I am proposing?

Have you done something awesome yet, with metrics and examples for how awesome it is? There's an old saying (crass, as it may be)...

Ideas are like assholes; everyone's got one, and they all stink

Go do something.

What should I expect from senior dev leads who have 8+ years experience?

Seriously? You should expect nothing. But try to learn everything they know. Ask questions, privately review their work, listen when they talk and critically think about what they say. They're experience in a box... err... body. Try to open them up and learn. My best friend is a brilliant developer, and I actively tell him that I'm always trying to learn as much as I can from him.

Am I wrong to expect to learn and gain experience from a company?

Absolutely not. That doesn't mean that you can't be learning what not to do. People will make mistakes, learn from your company's mistakes as well as yours.

Title: What should junior developer expect from their senior team lead

Body:
Disclaimer: Opinions expressed are solely my own and do not express the views or opinions of my employer.

I work for a small company, in which few people are  developers, others are QA/Test and 1 is a Manager. I joined this company 1.5 years ago. 3 senior developers have 8+ years of experience.

These are the observations which I made about the team lead. (considering me as a fresher with less experience compared to them in all aspects )

They never discuss 1:1 or they never consider the junior suggestion (I agree that it's up to them, whether they accept it or not, at least they should consider an opinion).

As senior team leader they can try to refactor the codebase with new technologies ( including the factor of rolling out new technologies is possible and other developer and infrastructure also ready), but these team leader feel less in-secure to work with new technologies, as they are not up to date. (reason I am telling, they don't know what current programming trend, *(such as popular open source projects like modernizr, bootstrap and many others).

In our codebase more than 10000+ lines are repeated, so I told them  about DRY: Don't Repeat yourself.  Their reply was : "It is a fascinating article, but never works in practice".  I just told them if we do not make it 100% DRY, we can at least use interfaces, but that also was not considered. *(interfaces can be added for new features, not touching the previous codebase, if they are not ready to refactor)

All senior developers do maintenance and hot fixing of patches. The rest of the time they just spend on entertainment sites. They are just happy to finish the task.

Introducing new technology is bad? *(including factor of feasibility can be done).

Manager also least concerned about the things which I am talking about.

Junior expects they can learn many things from team lead. *(not by asking help or senior coding for them).

My questions are:

Am I too aggressive about the changes which I am proposing?

What should I expect from senior dev leads who have 8+ years experience?

Am I wrong to expect to learn and gain experience from a company?

Update :

Why they feel DRY is impractical: because they don't want get involved with OOP concepts. They are happy with repeating tasks.

New technologies I am proposing:

Usage of Minification of CSS, JS, SPrite images

Usage of Interfaces and .net framework 4, generics and many others.

Client side libraries such as modernizr, knockout js, bootstrap for responsive,


问:
Design Pattern for enterprise application
I read few articles about composite pattern and I want to know whether its applicable in following situation,

I found that "A Composite Entity object can represent a coarse-grained
object and all its related dependent objects"

```<code>public class PatientRegistrationDTO
{
    public string RegistrationNo;
    public string ID;
    public DateTime AdmitDate;
}

public class PersonDTO
{
     public string ID{ get; set; }
     public string FullName { get; set; }
     public string FirstName { get; set; }
}
</code>```

by using these two objects I need to create

```<code>public class Patient
  {
        public string ID{ get; set; }
        public string FullName { get; set; }
        public DateTime AdmitDate;
  }
</code>```

Can I use Composite pattern for enterprise applications in here?

Is it possible for me to add some class like below?

```<code>public class PatientDTO
{
    public static Patient ConvertToEntity(PatientRegistrationDTO pregDTO, PersonDTO person)
    {
        Patient p = new Patient();
        p.ID= pregDTO.ID;
        p.FullName = person.FullName;
        p.AdmitDate = pregDTO.AdmitDate;

        return p;
    }
}
</code>```

答:
The composite pattern implies that when you call a method perform() on a composite (perform() being part of the interface contract of IComponent), the call is redirected to all its sub-components, until they are leaf elements that do an actual thing.

In your case I see absolutely no difference between the coarse and the fine grain, and which entity group/represent others as a composite.

So I would say no, the composite pattern really doesn't apply here.

the wikipedia class diagram may explicit my point of view: ( in this diagram perform = operation)


问:
Lowercase in Linux file names
As I find that UpperCase are really readable for first letter word separation in long complex names, I tend to give some of my Linux files names with some UpperCase. Mostly executables, some directories too.

But it's been a few weeks I have remarked that the huge majority off all file names in my linux distrib are lowercase...

So I made some googling a moment ago, and I found this article: Linux File Names, that states one should always use lowercase in the unix world,

...It's best to always use lowercase in Linux unless you can think of a good reason to use uppercase or mixed case. Most Unix people use lowercase almost exclusively, but aside from this "cultural" point, there's another good reason to use lowercase. If you're sharing or accessing a DOS file system with Linux, DOS will not be able to see the files that have uppercase or mixed-case file names...

Is that really the case?

答:
Programmers abhor the use of the shift key (and caps lock is something many try to do away with).  Continuing on from the spot that says "always use lower case"...

It's best to always use lowercase in Linux unless you can think of a
  good reason to use uppercase or mixed case. Most Unix people use
  lowercase almost exclusively, but aside from this "cultural" point,
  there's another good reason to use lowercase. If you're sharing or
  accessing a DOS file system with Linux, DOS will not be able to see
  the files that have uppercase or mixed-case file names.

The main reason for this is that if you are transferring two files that are separated by only case to a case-insensitive system, confusing things can happen on the insensitive machine.

The files on your linux machine are yours.  Do with them as you like in a way that makes sense to you.

I have found that a convention of using upper case for the leading letter of a directory makes it easier for me to navigate them.  Doing an 'ls' in the directory automatically puts all of the directories at the top of the list and separates the directories from the files making both easier to see and navigate to.  But again that is for me - do what works for you.

Title: Lowercase in Linux file names


答:
"Consumer-oriented" (whatever that may mean) usages tend to use Title Case, even in the Unix world. This is more often the case when the organization in question has people whose whole job is to think about user experience.

For example, my Ubuntu desktop has folders in the home directory called Downloads, Pictures, Documents, etc. Same goes for my OSX laptop (yes, it counts; it's BSD). Though it's worth pointing out that Apple goes as far as to name its own system directories with titlecase (e.g. /Library/Audio/Apple Loops/), while keeping the "classic" base filesystem all lowercase (e.g. /usr/libexec/dtrace/). But no Linux distribution I'm aware of uses titlecase anywhere outside the user's home directory.

Presumably the distinction is that directories you expect people to actually look at are titlecase, while places you expect people to not go exploring are all lowercase. A similar distinction appears to be at play with Ubuntu; only the directories that are expected to show up as a list of folders in an Nautilus window are titlecase, while folder names that are expected to be typed (not browsed) are all lower.

And that's the crux of it; titlecase or uppercase is more difficult to type. But titlecase looks better in a list or set of tiled folders. So, choose accordingly. Linux people frequently deal in the command line even for mundane tasks, so lowercase makes more sense.

Title: Lowercase in Linux file names

Body:
As I find that UpperCase are really readable for first letter word separation in long complex names, I tend to give some of my Linux files names with some UpperCase. Mostly executables, some directories too.

But it's been a few weeks I have remarked that the huge majority off all file names in my linux distrib are lowercase...

So I made some googling a moment ago, and I found this article: Linux File Names, that states one should always use lowercase in the unix world,

...It's best to always use lowercase in Linux unless you can think of a good reason to use uppercase or mixed case. Most Unix people use lowercase almost exclusively, but aside from this "cultural" point, there's another good reason to use lowercase. If you're sharing or accessing a DOS file system with Linux, DOS will not be able to see the files that have uppercase or mixed-case file names...

Is that really the case?


答:
The term was adopted by computer scientists when they applied mathematical reasoning to programming in the mid 20th century.

The word argument has the general sense of something from which another thing may be deduced. It comes ‘from the L. arguere “make clear, make known, prove, declare, demonstrate,” from PIE *argu-yo-, from root *arg- “to shine, be white, bright, clear” ’, which root is also preserved in the words argent (“silvery white”) and Argentina (“[river] of silver”).¹

Its use in English to mean a “mathematical quantity from which another … quantity may be deduced, or on which its calculation depends” is attested as early as 1386:

 Argument (ā·ɹgiuměnt). [a. F. argument (13th c.), ad. L. argūment-um, f. arguěre (or refashioning, after this, of OF. arguement, f. arguer): see ARGUE. For use of the L. form, see 3 c.]

   2. Astr. and Math. The angle, arc, or other mathematical quantity, from which another required quantity may deduced, or on which its calculation depends.

   c 1386 CHAUCER Frankl. T. 549 Hise othere geeris, As been his centris and hise Argumentz.

   c 1391 — Astrol. xliv. 54 To knowe the mene mote and the argumentis of any planete.

   1796 HUTTON Math. Dict. I. 141/2 Annual argument of the moon’s apogee . . is the distance of the sun’s place from the place of the moon’s apogee.

   1879 THOMPSON & TAIT Nat. Phil. I. 1. § 54 An arc of the circle referred to . . is the Argument of the harmonic motion.²

Body:
Where does the word "argument" (in the programming sense) come from?

i.e. Why are actual parameters called "arguments"?

The meanings don't seem related, and I haven't found any explanation of it anywhere.

Note on the terminology:

"Formal" parameters (also known simply as "parameters") are the "placeholder" names (say, x) -- the declared parameters of a function.

"Actual" parameters (also known as "arguments") are the actual values which are passed to a function (say, 5), hence I used this term above to prevent any confusion.


问:
Frustration with Java Swing layout managers
I have been trying for years to master Swing layout managers with no success.  Every time I need to do something with Swing, it is like pulling nails to get the visual components to line up the way I want them to.  I am familiar with frameworks like Matisse but that's not the point.

My question is:  Why does Swing even need layout managers?  It seems like an overcomlicated paradigm.  What I would like to be able to do is jave a simple JFrame and then for each component (like JLabel) simply specify X and Y coordinates where I want it to be situated -- done deal.  Can anybody explain what is wrong with this simple approach that would work predictably 100% of times?  Or is there an actual layout manager that does things exactly like this?

答:
Consider using MigLayout.  It's a comprehensive layout manager that I haven't had any issues with.  To get an initial taste of what it's capable of and how easy it is to use, look at the sample application linked to from the home page.  Make sure you try resizing the window to see how the user interface is able to adapt to the size of the screen.

The core reason behind the layout managers is to allow your application to scale elegantly to what your user wants or needs.  MigLayout makes this easy by providing a huge number of easily tweakable constraints and rules, some of which make it more powerful than HTML+CSS in some areas (though that's finally changing).  It also includes a debug mode which shows you exactly what it's trying to do, and has the ability to arrange buttons according to a user's operating system.

A few examples of absolute positioning:

```<code>// adds item at 100, 100
panel.add(item, "pos 100, 100");
// adds item 10% + 5 "logical pixels" + 1 inch from left side of parent
// and centers itself 75% of the way down parent component
panel.add(item, "pos (10% + 5lp + 1in) .75al");
</code>```

Details can be found on the tutorial, sample application, and cheat sheet linked to from the main page.

Body:
Consider using MigLayout.  It's a comprehensive layout manager that I haven't had any issues with.  To get an initial taste of what it's capable of and how easy it is to use, look at the sample application linked to from the home page.  Make sure you try resizing the window to see how the user interface is able to adapt to the size of the screen.

The core reason behind the layout managers is to allow your application to scale elegantly to what your user wants or needs.  MigLayout makes this easy by providing a huge number of easily tweakable constraints and rules, some of which make it more powerful than HTML+CSS in some areas (though that's finally changing).  It also includes a debug mode which shows you exactly what it's trying to do, and has the ability to arrange buttons according to a user's operating system.

A few examples of absolute positioning:

// adds item at 100, 100
panel.add(item, "pos 100, 100");
// adds item 10% + 5 "logical pixels" + 1 inch from left side of parent
// and centers itself 75% of the way down parent component
panel.add(item, "pos (10% + 5lp + 1in) .75al");

Details can be found on the tutorial, sample application, and cheat sheet linked to from the main page.


问:
Can a function be too short?
Whenever I find myself writing the same logic more than once, I usually stick it in a function so there is only one place in my application I have to maintain that logic. A side effect is that I sometimes end up with one or two line functions such as:

```<code>function conditionMet(){
   return x == condition;
}
</code>```

OR

```<code>function runCallback(callback){
   if($.isFunction(callback))
     callback();
}
</code>```

Is this lazy or a bad practice? I only ask because this results in a greater number of function calls for very tiny pieces of logic.

答:
No, but it can be too terse.

Remember: Code is written once, but read many times.

Don't write code for the compiler. Write it for future developers who will have to maintain your code.

Title: Can a function be too short?


问:
Good practices to implement mappers in a multi-tier application
When you are working with a multi-tier application very often you run into task of converting objects in one layer to objects in another layer. This could be converting database objects into domain objects, service objects into domain objects, domain object into view models, etc.

I've seen it being done in multiple ways, those include:

In-line conversion

Creating a translator class with static helper methods

Using extension methods to simplify conversion

Overriding cast operators

Creating sepearate mapper classes for every possible translation

Utilizing solutions such as automapper

What would be the "proper" way to handle it. The application I currently work with utilizes separate mapper class for every possible translation, and although it has benefits of testability we are using dependency injection and we have to pass all those mappers as dependencies in the constructor.

Has anybody figured out a better way to do it?

UPDATE

I am using .NET stack here (EF +Business Layer + MVC)

答:
AutoMapper is a common solution for this, however I prefer to hand-code the mappings. I usually have a static class with extension methods which maps to and from DTOs.

```<code>[DataContract]
class UserDto
{
 [DataMember]
 public string Name { get; set; }

 [DataMember]
 public DateTime BirthDay { get; set; }
}

class User
{
  public string Name { get; private set; }
  public DateTime BirthDay { get; private set; }
}

static class ContractMappings
{
   public static UserDto ToDto(this User user)
   {
     return new UserDto
     {
       Name = user.Name,
       BirthDay = user.BirthDay
     };
   }
}
</code>```

Each project at application boundaries will have a ContractMappings class which contains mappings for all contracts associated with that project. If this class gets too big it may be a sign that the project boundaries are invalid.

Hand-coded mappings allow a greater degree of flexibility, which may be both an advantage and a disadvantage.

In case of ViewModels, I usually have the ViewModel accept a DTO or domain object in its constructor. If the ViewModel is used for creating a DTO or updating a domain object, I put the update method directly in the ViewModel to maintain the highest degree of cohesion.

Body:
AutoMapper is a common solution for this, however I prefer to hand-code the mappings. I usually have a static class with extension methods which maps to and from DTOs.

[DataContract]
class UserDto
{
 [DataMember]
 public string Name { get; set; }

 [DataMember]
 public DateTime BirthDay { get; set; }
}

class User
{
  public string Name { get; private set; }
  public DateTime BirthDay { get; private set; }
}

static class ContractMappings
{
   public static UserDto ToDto(this User user)
   {
     return new UserDto
     {
       Name = user.Name,
       BirthDay = user.BirthDay
     };
   }
}

Each project at application boundaries will have a ContractMappings class which contains mappings for all contracts associated with that project. If this class gets too big it may be a sign that the project boundaries are invalid.

Hand-coded mappings allow a greater degree of flexibility, which may be both an advantage and a disadvantage.

In case of ViewModels, I usually have the ViewModel accept a DTO or domain object in its constructor. If the ViewModel is used for creating a DTO or updating a domain object, I put the update method directly in the ViewModel to maintain the highest degree of cohesion.


问:
When to use weak references in .Net?
I have not personally come across a situation where I've needed to use WeakReference type in .Net, but the popular belief seems to be that it should be used in caches. Dr Jon Harrop gave a very good case against the use of WeakReferences in caches in his answer to this question.

I've also often heard AS3 developers talk about using weak references to save on memory footprint but based on the conversations I've had it seems to add complexity without necessarily accomplishing the intended goal, and the runtime behaviour is rather unpredictable. So much so that many simply give up on it and instead manage the memory usage more carefully/optimize their code to be less memory intensive (or making the trade-off of more CPU-cycles and smaller memory footprint).

Dr Jon Harrop also pointed out in his answer that the .Net weak references are not soft, and there's an aggressive collection of weak references at gen0. According to MSDN, long weak references gives you the potential to recreate an object, but the state of the object remains unpredictable.!

Given these characteristics, I can't think of a situation where weak references would be useful, perhaps someone could enlighten me?

答:
I've found legitimate practical applications of weak references in the following three real-world scenarios that actually happened to me personally:

Application 1: Event handlers

You're an entrepreneur. Your company sells a spark lines control for WPF. Sales are great but support costs are killing you. Too many customers are complaining of CPU hogging and memory leaks when they scroll through screens full of spark lines. The problem is their app is creating new spark lines as they come into view but data binding is preventing the old ones from being garbage collected. What do you do?

Introduce a weak reference between the data binding and your control so that data binding alone will no longer prevent your control from being garbage collected. Then add a finalizer to your control that tears down the data binding when it gets collected.

Application 2: Mutable graphs

You're the next John Carmack. You've invented an ingenius new graph-based representation of hierarchical subdivision surfaces that makes Tim Sweeney's games look like a Nintendo Wii. Obviously I'm not going to tell you exactly how it works but it all centers on this mutable graph where the neighbors of a vertex can be found in a Dictionary<Vertex, SortedSet<Vertex>>. The graph's topology keep changing as the player runs around. There's only one problem: your data structure is shedding unreachable subgraphs as it runs and you need to remove them or you'll leak memory. Luckily you're a genius so you know there is a class of algorithms specifically designed to locate and collect unreachable subgraphs: garbage collectors! You read Richard Jones' excellent monograph on the subject but it leaves you perplexed and concerned about your imminent deadline. What do you do?

Simply by replacing your Dictionary with a weak hash table you can piggyback the existing GC and have it automatically collect your unreachable subgraphs for you! Back to leafing through Ferrari adverts.

Application 3: Decorating trees

You're hanging from the ceiling of a cyclindrical room at a keyboard. You've got 60 seconds to sift through some BIG DATA before someone finds you. You came prepared with a beautiful stream-based parser that relies upon the GC to collect fragments of AST after they've been analyzed. But you realise you need extra metadata on each AST Node and you need it fast. What do you do?

You could use a Dictionary<Node, Metadata> to associate metadata with each node but, unless you clear it out, the strong references from the dictionary to old AST nodes will keep them alive and leak memory. The solution is a weak hash table which keeps only weak references to keys and garbage collects key-value bindings when the key becomes unreachable. Then, as AST nodes become unreachable they are garbage collected and their key-value binding is removed from the dictionary leaving the corresponding metadata unreachable so it too gets collected. Then all you have to do after your main loop has terminated is slide up back through the air vent remembering to replace it just as the security guard comes in.

Note that in all three of these real-world applications that actually happened to me I wanted the GC to collect as aggressively as possible. That's why these are legitimate applications. Everybody else is wrong.

OwnerDisplayName: theburningmonk

Title: When to use weak references in .Net?


问:
Which HTTP status codes are really OK?
I am writing an application to report to the user(devs) when their website fails. And what I mean by fails which is unfunctional or needs to report the problem to devs.
 I do understand that status code 2XX means 'Success' according to wiki. But does that really do? I have access my website once and returned 204 'No-Content', which is unfunctional to me. So the question is, what are the list of status codes return should It be considered "website is functional"?

答:
It depends on what exactly you are checking.  Depending on what you check a 204 may be acceptable or it may be an error.

If you are checking a website, it is likely that 200 OK is the only acceptable response.  (After following redirects).  If you are checking an API or something that isn't intended to display in a browser, any 2xx code may be acceptable.

Title: Which HTTP status codes are really OK?


问:
lightweight document indexing to handle less than 250k potential records
Recently I've found myself chafing at the limitations of document indexing engines. I was developing a small website that needed some fairly robust searching capabilities but due to their hardware constraints I couldn't deploy a Lucene-ish solution (such as Solr or ElasticSearch, like I normally would) to handle this need.

And even then, while I needed to serve up some complex data and calculations that were database-intensive, I didn't need to handle more than 250k potential records. Deploying an entire Solr or ES instance just to handle this seemed like a waste.

After I thought about it, it seems like a fairly large problem. Most people handle search requirements solely with SQL. They just run SQL queries for their data and that's that. Their search capabilities also end up being terrible.

Doing a blanket full-text wildcard search can be painfully slow on some systems (shared hosts in particular) and bog down your database, especially if you have complicated queries and lots of joins.

You end up doing multiple queries on a single request from the user. You might get around this with ever-more-complicated queries, but see the previous point.

Lack of features typically present in full-text engines.

Databases had the same problem of needing to be deployed as a server and then SQLite came along and suddenly we could deploy a database that is self-contained in a single file. My Googling has produced nothing - wonder if something exist like this for full-text indexing/searching.

What factors to take into account when deciding whether to implement lightweight document indexing (eg as explained in answers to another question) or keep using SQL for these situations?

答:
You know, I've got to say consider using redis.

Use the idea of context. It would be hard to go in depth without knowing more about the documents. Often you can discern many things from the headings of documents. Profiling each document is the basic first step, just like web crawling.

Do a count on each document of words in a dictionary of keywords. Keep track of each word's popularity count for total project. Add more weight to the iterator for this count if you happen to be able to detect high relevance in a document or set.

The first thing this does is give you an all-inclusive list of words in your whole set. Anything NOT found in that list, automatic return of 'no results'. I'd suggest results ranking of lower than the bottom 5-20% of popularity (when running search query on index) also simply say no results'.

If you do go with something like redis, or even just make your own memory structure you can pair documents with descriptor files or mini-db file and page objects that describe each specific document back and forth to memory. Keep the common searches in memory by maybe having them compete for slots or giving them a time to live that grows on each search.

To go further, start saving reference data that groups a link/ref/pointer/index/whatever of two or more documents and a pool of keywords or phrases. Basically you get a pumped up tag cloud.

Further still, make phrase detection by tracking when a word in your dictionary is followed or preceeded by an exact string commonly in documents of similar metadata/title. This is intensive but requires only one pass to render the data.

The more ways you can segregate your data and keep the groups related to each other in actual usage, the better.

Connect the likelihood of correctness by tracking every time a user clicks a result that is not the top three. Gain improving phrase detection by watching user searches that didn't deliver perfect results. Force your queries to become relative to the clients' searches.

Do you have to watch for document updates? Chronjobs/shell script or scheduled tasks/batch script can help. There are various options for scheduling and scripting though obviously.

Waste disk, gain speed, lose complexity. Save multiple trees of your documents and/or trees of links to the documents. Only search the trees for whom criteria have been met, or at least prefer them to get result quicker in most cases.

Make your own lightweight permutation engine or find one that uses quick character detection and no regex. Or just make one using regex in a few hours but the performance difference will be noticeable here for sufficient searches.

So many things.

These are meant as possible solutions to implementing robust document indexing and searching. It isn't all inclusive. And at that you'ld probably do better to grab a spare box, throw a neural net on it and spend a couple days making a nice web interface to that neural net.


答:
Every code is acceptable in some circumstances, but indicate a problem in other circumstances.

Take 404. It may indicate:

that a link on your website is broken (which is actually a problem you may want to fix),

that the client is trying deliberately to break the website (which is a problem too, but should be included in security reports instead),

that somewhere, some website has a broken link or that a person misspelled an address (which doesn't matter, since you can't do anything with it),

or that the page is not intended to exist (which is an expected situation and should not worry anybody). Example: /wpad.dat.

Take 200. It may indicate:

a success,

or that your security system is not working any longer, and is not forbidding the access to some very confidential web page to guests (the only acceptable response being 401 Unauthorized).

If you want to report problems to developers, do it the right way: through logging and exception handling, not through something which was never intended for that, like HTTP status codes.

Title: Which HTTP status codes are really OK?

Body:
I am writing an application to report to the user(devs) when their website fails. And what I mean by fails which is unfunctional or needs to report the problem to devs.
 I do understand that status code 2XX means 'Success' according to wiki. But does that really do? I have access my website once and returned 204 'No-Content', which is unfunctional to me. So the question is, what are the list of status codes return should It be considered "website is functional"?


答:
I will write this from my perspective as a Senior Developer (or insert any other fancy title you like here) that works with Junior developers frequently.

This is probably a shortage on both your front, and the Senior Developers' front.

One thing a lot of Junior developers don't understand is that whilst you (as a junior) are pushing to use new technologies, new ways to do things, telling the team they're doing it wrong, etc. - the Seniors in the team are reporting to the management on delivery and are being pushed by management to deliver new things as quickly as possible to make the company as much money as possible (or deliver the best outcomes for the client/customer).

Sometimes the tried and proven ways of delivering just outweigh the risk of implementing [insert cool technology here]. Tight deadlines, too much work and a truckload of pressure to boot means that the way we've done it for 8+ years is the way we're doing it this time too.

You need to be able to demonstrate to the team that what you're proposing will actually have some benefit to them and to the company in the long run. Otherwise you will not get buy-in from your colleagues and they will not be able to sell it to the management team to get approval to run with it.

Am I too aggressive about the changes which I am proposing?

Without knowing the full circumstances, you might be. Just telling people A is better than B so we should be using A doesn't hold much ground. You need to go and do something to show why it is better. It doesn't have to be big, even just a small component or application that shows your suggested way of doing it should be more than enough. You then need to present it and be ready to stand your ground against criticism from your team.

Even as a Senior Developer I have to do this before I can convince my colleagues that the new way of doing things is better.

What should I expect from senior dev leads who have 8+ years experience?

As others have said, 8+ years experience doesn't necessarily mean you're fantastic. But in general, you should be able to learn a lot from someone who has been around the traps for a while; you may also be able to teach them something too.

People are people and everyone has an ego (some bigger than others) and there's nothing worse than the new guy coming in and telling you that you've been doing your job wrong for the past 8+ years. At the same time, a Senior developer (a good one) should be able to take constructive criticism and be able to articulate the reasons for their decisions.

Am I wrong to expect to learn and gain experience from a company?

Not using the latest and greatest technology and features doesn't mean you're not learning and gaining experience within your company. Experience is experience, sometimes knowing the old way of doing something can give you a greater appreciation of why the new way is better. This also helps you demonstrate why the new way is better, because you understand both and can articulate a more convincing argument when you're trying to sell it. I personally don't use the latest and greatest things where I work at the moment - but I still learn new things every day and it still looks good on my resume too.

Having said all that - if the company is really not a good fit and all else fails, you might want to look for a new place to work.


答:
This goes back to celestial mechanics in the pre-calculus days.  Orbits, arcs, chords, sinus, periapsis, and so on.

The term "argument" was used since I don't know how long ago, but it is described in the book "A philosophical and mathematical dictionary, containing an explanation of the terms, and an account of the several subjects, comprised under the heads mathemetics, astronomy, and philosophy both natural and experimental ... also memoirs of the lives and writings of the most eminent authors, both ancient and modern" (that's not the entire title) published in 1815 by Charles Hutton, 1737-1823.

(excerpt taken from Google Books)

The "argument" was an angle of some sort. Exactly how that term came to be, I haven't found yet.  At some point in science history, the astronomers realized that the sinus and cosinus, being thus far known only as geometric constructs associated with lines and ellipses, could be thought of as functions of the argument.  "Function" was a new concept back in those days.  The notation f(x) had been invented around the early 1700s.

Naturally, astronomers were thinking "sinus of the argument of the periapsis" == "sin(ω)" and later as more functions were found to be useful, any "f(x)" came to be thought of as "function f of argument x".  Even if x wasn't an angle.  Mathematicians of all flavors and stripes came to use such terminology in general.

In the mid 20th Century, it was only natural for computer scientists to borrow the same terminology for their different but similar idea of a function as a subroutine taking any number of input values.

(This is one of those unusual topics that is easier to dig up answers for in a musty university library, than on the internet.)

Title: Why are actual parameters called "arguments"?


问:
Naming convention for a method that both sets and gets
Let's say we have a method setFoo that sets a flag in a Bar object e.g.

```<code>class Baz {
    public void setFoo(String foo)(
       ...
    }
}
</code>```

inside setFoo, the method is doing some expensive load of the Bar object from the database.

```<code>class Baz {
    public void setFoo(String foo)(
       Bar bar = expensiveGetBar();
       ...
    }
}
</code>```

To avoid the need to get the Bar object again, the developer changes the method to return it.

```<code>class Baz {
    public Bar setFoo(String foo)(
       Bar bar = expensiveGetBar();
       ...
       return bar;
    }
}
</code>```

Questions are:

Is this discouraged?

If yes, why and what is the alternative

Should the solution be adding some sort of cache instead?

How would you prefix the method? set? get? seget? geset?

答:
A function should serve one purpose. That’s part of the reason it’s called a function. If you find a method hard to name because it’s doing more than one thing, then split it into more than one method. Readable method names can often be made from just one verb and one noun.

In your example, you could change setFoo() to take a Bar explicitly. As a setter, it shouldn’t really need to return anything. Then either expose expensiveGetBar(), or expose getBar() and have it cache the result of expensiveGetBar().


问:
About classes and their valid states
I get stuck each time I need to write a constructor for any class I design. The reason is that I am not sure what should go into a constructor and what should not.

On googling for this, I got the answer that the constructor need to do only as much as to make sure that the opbect created is valid. But my query is

How do you know if an object is in the valid state?

My class represents a chess board:

```<code>public class ChessBoard
{
    List<ICellRow> lstRow;
    int cellOffset;

    //Other function

    public ChessBoard()
    {
        //What should go in here?
    }
}
</code>```

How do you decide when a class has the minimum information to be in the valid state? In this specific example, makes the board class valid?

答:
Think of an object as a value, just like a number or a string. That value represents a concept in the problem you’re trying to solve. For example, you might use an int to denote a distance in miles, or a number of points, or a set of Boolean flags. The value has no meaning on its own, but it does have an interpretation.

Whenever you create a value, you want to make sure its interpretation makes sense. It should be valid by construction—3 is a valid number, and “hello” is a valid string. In particular, there is no way to construct a string with a value that isn’t a string.

In addition, operations on values should be designed in such a way that every operation leads to a valid internal state, or else reports an error—whether at compile time through static typing, or at runtime through exceptions. Division by zero, for example, is not allowed on integers.

What this means for you is that the constructor of your ChessBoard class should produce a legal board state according to the game rules. For example, you could use the constructor to set the initial configuration of pieces for the start of a game. Operations on the board should then only allow you to move to other legal game states. By thinking along these lines, you can ensure that your ChessBoard accurately represents how a game of chess works in real life.

Title: About classes and their valid states


问:
Pushing a new version of a live web application in a Git based workflow
I have a question regarding workflow in web development. I'm building my project in Symfony, and it's in Git.

Right now, I have three environments, dev (local), staging and prod. The project itself is hosted on GitHub in a private repo.

I'm wondering what a good way is to update the staging & production environments. Should I somehow setup a push based system so I can push the prod/staging branch directly to my server, and use Git hooks to regenerate cache files and run database migrations?

Right now on similar projects I use a manual pull system, where I SSH to the server, pull down changes from the prod Git branch and manually run cache/migrations. This obviously is not ideal.

答:
I'm now deploying server to staging/production by using command:

git push stating master

git push production master

And finished, I don't have to go to the servers to pull the code.

This is might be the thing you want. Please read on this link
https://stackoverflow.com/questions/279169/deploy-a-project-using-git-push


答:
I think your current situation is most ideal, provided that you are not (a) load balancing, and (b) you have automated the regen-refresh-restart cycle once you do the git operation.  Too much more automation, and you run the risk of accidental deployments.

There are various complexities related to real-life deployments, such as database modifications, cache-regeneration, minification, etc, web server configurations, etc...  What about when you need a new rewrite rule added?  Is that automated?  It is for us, and I would never do it differently.

If load balancing, then deploy to a "push" server, and rsync from there.

Title: Pushing a new version of a live web application in a Git based workflow

Body:
I have a question regarding workflow in web development. I'm building my project in Symfony, and it's in Git.

Right now, I have three environments, dev (local), staging and prod. The project itself is hosted on GitHub in a private repo.

I'm wondering what a good way is to update the staging & production environments. Should I somehow setup a push based system so I can push the prod/staging branch directly to my server, and use Git hooks to regenerate cache files and run database migrations?

Right now on similar projects I use a manual pull system, where I SSH to the server, pull down changes from the prod Git branch and manually run cache/migrations. This obviously is not ideal.


问:
I have a previous invention (software / framework) that I plan to use on my new job. What happens to my copyright if I improve it during the job?
I have filled that standard form where you list your previous inventions before starting your new job so the employer is legally aware you have the copyright over them. But if I want to use this invention (software code / framework) in my new job, would they have any copyright claims on it if for example I change / improve something on my code while working for them?

I have heard something like a shared ownership. Something like: you would own what was done before and employer would own any improvements you did on it while employed. That kind of sucks and take away any incentive you would have to do improvements on your product since once improved, the improvement is gone. :(

Has anyone gone through this situation before and could share some ideas so I can protect my code?

答:
This is a simple problem.  You need to make sure there is an intersection between your interests and your employer's interests in this matter.

Does your new employer even care about using your code?  Do they want it?  If so, then add it to your agreement that any modifications to that code:

you retain copyright to

they retain full, unlimited, permanent, transferable, sublicensable, etc... licence to use, reuse, etc...

If they are too big to do that, then simply don't take your software there.


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答: While I can't officially vouch for it, I have always been impressed with Chris Sawyer developing Rollercoaster Tycoon almost entirely in assembly language.</p>


问:
Should the variable be named Id or ID?
This is a bit pedantic, but I've seen some people use Id as in:

private int userId;
public int getUserId();
```

<p>and others use:</p>

<pre class="lang-cs prettyprint-override"><code>private int userID;
public int getUserID();
</code>```

Is one of these a better name than the other? Why? I've seen this done very inconsistently in large projects. If I were to set a standard which would most people be familiar with? Which is the conventional standard?

答:
As we can see in JavaScript's default function getElementById();
Id is written in Camel case...

Use 'id' if using with an underscore.  Example:  user_id

Use 'Id' if naming a var without any Underscore to differentiate the different words. Example: userId

If its a single word variable it should be in complete lowercase, if multiple word var then use lower Camel case. Example:  thisIsExample

But I highly would not recommend 'ID' all in CAPS because we generally use all caps for defining CONSTANTS.

Title: Should the variable be named Id or ID?


问:
Multi-platform design with Delphi, Java, MySQL and CouchDB
What are the most obvious drawbacks to this idea for an enterprise(ish) model using the following technologies.

Browser based and native developed GUI using Delphi to connect to

Datasnap server (Delphi, obviously) via Rest which stores documents in

A CouchDB Server

But gets the structure for those documents from a centralized tree of

JBoss servers connecting to

MySQL databases which have information about all kinds of domain specific things

Which connects to another JBoss server, all the way up to a centralized hosted repository to maintain some sort of control over licensing and structure of the program.

I know that's kind of vague, but bear with me.  I'm really asking:

Whether it's sensible to use a mixture of NoSQL and SQL DB's and

Whether it's easier to mix them if they're not connected to the same backend service.

If this is just crazy.

I thought of it on the drive to work and it seems to solve all the problems that we have.  I'm not sure that datasnap is robust enough, but we could use node.js or another jboss server instead. I just wanted to go with Delphi since we've got it and know it.

I think this is a fairly normal model, the difference being the web server (or datasnap server) being the thing that has a database attached to it as well as the data server.  I think it's better that way, and it would probably make sense if I said this is for medical records primarily and it's better that documents stay separated from things that need to be updated, but it's meant as a general purpose solution for storing info in a structured way.

答:
You ask 3 questions - and you are talking about medical records being separate:

1: Whether it's sensible to use a mixture of NoSQL and SQL DB's and - My answer is YES

2: Whether it's easier to mix them if they're not connected to the same backed service - My answer is YES, if I have understood what you are asking correctly.

3: If it is crazy - NO, it is not crazy.

4: You later ask if this had been done successfully - and the answer is yes. I have done this already, if I understand what you are doing correctly.


问:
Abstracting out a module or using the Module Singleton directly?
I am working on a module which is dependent on other module for some functionality. Now the dependent module provides a lot of functionality and I need only few of them, hence got the idea to create an abstraction of the same in my module which is again be a singleton only.

My question is when to abstract out and when to use the modules singleton class directly? Is there any guidelines for the same? Or its depend upon project to project?

答:
There is a golden rule in programming and refactoring: couplage faible et un haut degre de cohesion. (Sorry the expression is in French) it means that classes should not depend heavily on each others and every class should be very specific and has one job.
In your case if module B depends partially on module A, you can refactor module A and use delegates (pointers). Abstraction is a solution only if 'is instance of' is semantically correct. In java for example multiple inheritance is not allowed. So what if a module depends partially on two different modules? That's why consider using delegates rather than abstraction.</p>


问:
Is LINQ to SQL dead?
Is there any reason to keep using Linq to SQL, or is it better to move to ORM techniques like EF, NHibernate etc.

We are using Linq to SQL in a new large enterprise application that will exist for a long time. The motivation for this new enterprise application is that the application was ordinary written in Visual Basic and since Microsoft stopped the support we where forced to rewrite the application. It’s seems that we are already there but this time with our DAL (Data Access Layer).

I have already read this article, but it only compare to EF's weakness.

答:
It is weird but I have seen this phrasing a lot (“LINQ2SQL is dead”) and I’m not sure where it stems from*. It is just as dead Windows XP. Microsoft has discontinued support and has created something new (and in my eyes better) yet people are still free to use XP just as they are free to use Linq2SQL. Admittedly, I use Linq2SQL when creating custom DotNetNuke modules. However, with new features in EF4 such as code-first-development (http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx) it is hard to find reasons to stick with Linq2SQL. I don’t see a reason to go through and update code but for new code I don’t know why you wouldn’t want to use EF4.

*In all honesty though, I’m very…obsessive over semantics! I apologize if it is annoying to others :)

Title: Is LINQ to SQL dead?


答:
About the DOS argument: DOS/Windows filesystems do see your files regardless of case, and they can handle them fine. Very old DOS filesystems do not support anything beyond 8.3 filenames, but even FAT32 can handle long filenames. The only problem is that while DOS/Windows filesystems preserve case (in most cases; some flavors discard case for filenames that fit in the 8.3 format), they are not case sensitive when it comes to comparing filenames; Windows considers "foobar", "Foobar", "FOOBAR" and "fOObAr" to be the same filename.

That said, it is mostly a culture thing, but there is some background to it. The reason why this particular convention stuck in the UNIX world is usability. There are two main arguments here:

Separating words using non-letter characters is better for reading comfort than using casing to mark word boundaries. IfYouDonTBelieveMe, CompareThisSentenceWithThePreviousOneAndTellMeWhichIsEasierToRead. (And of course, novisualseparationatallistheworst).

Lower-case letters have more varied shapes than upper-case, which in turn leads to more diverse word shapes. THIS MAKES TEXT WRITTEN IN LOWERCASE EASIER TO READ THAN TEXT WRITTEN IN UPPERCASE.

These observations are easy to verify, and they have even been confirmed by scientific research.

In addition, UNIX culture prefers conventions that are not only easy to read, but also easy to write; UNIX hackers are typically people who spend a lot of time using their keyboard, and many use either the official touch-typing system or some personal derivative tweaked for programming. The concept of staying on the home row is important either way, so people like to avoid using keys that cannot be reached from the home row, especially the shift keys.

If you combine these three constraints, there is only really one sensible convention, which is all-lowercase-with-dashes.

Title: Lowercase in Linux file names


答:
Getters and Setters are a means to expose properties of classes.  They are one-way functions.  They either get (return a value) or they set (accept a value), but they don't do both in the same function.  Even C# properties which do away the extra get and set functions maintains the one-way operation.

So if I have

GetFoo()

SetFoo()

Then there is an implied operation upon a property called Foo.  Due to the magic of encapsulation, I don't really care if the internal object is called Foo.  I just know that if I SetFoo() and then GetFoo() then there should be some degree of logical linkage between my operations.

So you don't have getters | setters in your example.  Yes, I know they are named that way, but that's not what they're doing.  The third snippet really shows the deviation from the concept of properties.  public Bar setFoo(String foo) means I set a Foo but I get a Bar back?  What?!

You need to pick a different verb than 'Set' to use in this case, because the function is not performing a set operation.  Something like public Bar AnalyzeFoo(String foo) may be a more appropriate description of what the function is doing and still hides the fact that there is a really expensive operation on Bar as part of the function.

A more concrete example may help.

This next example is bad, for the reasons explained above:

public ProfitMargin SetInvoice(Invoice inv)

But this example makes more sense:

public ProfitMargin AnalyzeInvoice(Invoice inv)

I don't know or need to know how expensive of an operation it is to break apart the Invoice and identify the profit margin; the AnalyzeInvoice() function takes care of that for me.

A quick note on what I meant with C# properties...

Yes, I still have to define the get & set routines but they are expressed as part of the Property and don't require additional functions like Java used to require.

So in C#, I have:

```
private ____ xyz
public ____ MyProp {
   get { .... return xyz; }
   set { .... xyz = value; }
}
```

Whereas old-school Java required explicit functions:

```
private ____ xyz;
public ____ GetMyPrep() { ... return xyz; }
public void SetMyPrep(____ value) { ... xyz = value; }
```

Both work well, and modern IDEs simplify the getter | setter creation.  The point is that both approaches are still one-way operations.

Title: Naming convention for a method that both sets and gets

Body:
Let's say we have a method setFoo that sets a flag in a Bar object e.g.

```<code>class Baz {
    public void setFoo(String foo)(
       ...
    }
}
</code>```

inside setFoo, the method is doing some expensive load of the Bar object from the database.

```<code>class Baz {
    public void setFoo(String foo)(
       Bar bar = expensiveGetBar();
       ...
    }
}
</code>```

To avoid the need to get the Bar object again, the developer changes the method to return it.

```<code>class Baz {
    public Bar setFoo(String foo)(
       Bar bar = expensiveGetBar();
       ...
       return bar;
    }
}
</code>```

Questions are:

Is this discouraged?

If yes, why and what is the alternative

Should the solution be adding some sort of cache instead?

How would you prefix the method? set? get? seget? geset?

Body:
Getters and Setters are a means to expose properties of classes.  They are one-way functions.  They either get (return a value) or they set (accept a value), but they don't do both in the same function.  Even C# properties which do away the extra get and set functions maintains the one-way operation.

So if I have

GetFoo()

SetFoo()

Then there is an implied operation upon a property called Foo.  Due to the magic of encapsulation, I don't really care if the internal object is called Foo.  I just know that if I SetFoo() and then GetFoo() then there should be some degree of logical linkage between my operations.

So you don't have getters | setters in your example.  Yes, I know they are named that way, but that's not what they're doing.  The third snippet really shows the deviation from the concept of properties.  public Bar setFoo(String foo) means I set a Foo but I get a Bar back?  What?!

You need to pick a different verb than 'Set' to use in this case, because the function is not performing a set operation.  Something like public Bar AnalyzeFoo(String foo) may be a more appropriate description of what the function is doing and still hides the fact that there is a really expensive operation on Bar as part of the function.

A more concrete example may help.

This next example is bad, for the reasons explained above:

public ProfitMargin SetInvoice(Invoice inv)

But this example makes more sense:

public ProfitMargin AnalyzeInvoice(Invoice inv)

I don't know or need to know how expensive of an operation it is to break apart the Invoice and identify the profit margin; the AnalyzeInvoice() function takes care of that for me.

A quick note on what I meant with C# properties...

Yes, I still have to define the get & set routines but they are expressed as part of the Property and don't require additional functions like Java used to require.

So in C#, I have:

private ____ xyz
public ____ MyProp {
   get { .... return xyz; }
   set { .... xyz = value; }
}

Whereas old-school Java required explicit functions:

private ____ xyz;
public ____ GetMyPrep() { ... return xyz; }
public void SetMyPrep(____ value) { ... xyz = value; }

Both work well, and modern IDEs simplify the getter | setter creation.  The point is that both approaches are still one-way operations.


答:
The constructor should also make sure any structures (colloeections for example) are initialized according to your conventions.

For example,  if you expect a method or a property to always  return a non-null collection (even in the case there were never any items added to it) the constructor should initialize the collection.
That way any calls to methods or properties dependent on the collection will be able to rely on a valid collection.

Title: About classes and their valid states

Body:
I get stuck each time I need to write a constructor for any class I design. The reason is that I am not sure what should go into a constructor and what should not.

On googling for this, I got the answer that the constructor need to do only as much as to make sure that the opbect created is valid. But my query is

How do you know if an object is in the valid state?

My class represents a chess board:

```<code>public class ChessBoard
{
    List<ICellRow> lstRow;
    int cellOffset;

    //Other function

    public ChessBoard()
    {
        //What should go in here?
    }
}
</code>```

How do you decide when a class has the minimum information to be in the valid state? In this specific example, makes the board class valid?


答:
The purpose of the constructor is for you to setup the class into a user friendly default state.

E.g. If the chessboard was a graphical object for a video game then it would be reasonable to expect that the colors of the tiles would be defaulted to black and white so as to take some burden away from the programmer having to manually do this using extra function calls.

Title: About classes and their valid states


答:
I would think you might do the following:

```<code>    bar = getExpensiveBar();
    setBarState(bar);

    setBarState( Bar myBar)
    {
       myBar.setFlag(true);
       myBar.setOtherFlag(false);
    }
</code>```

But If the Bar object just has a flag then wouldn't you just do the following:

```<code>    bar = getExpensiveBar();
    bar.setFlag(true);
</code>```

Body:
I would think you might do the following:

    bar = getExpensiveBar();
    setBarState(bar);

    setBarState( Bar myBar)
    {
       myBar.setFlag(true);
       myBar.setOtherFlag(false);
    }

But If the Bar object just has a flag then wouldn't you just do the following:

    bar = getExpensiveBar();
    bar.setFlag(true);


答:
Here is my favorite solution for that problem:

```<code>class Baz {
    Bar _bar;

    /* make this public if you like */
    Bar getBar()
    {
       if(_bar==null)
           _bar = expensiveGetBar();
       return _bar;
    }

    public void setFoo(String foo)
    {
       Bar bar = getBar();
       ...
    }
}
</code>```

You may have to add a method to clear or update _bar, but that depends on your actual case.

Body:
Here is my favorite solution for that problem:

class Baz {
    Bar _bar;

    /* make this public if you like */
    Bar getBar()
    {
       if(_bar==null)
           _bar = expensiveGetBar();
       return _bar;
    }

    public void setFoo(String foo)
    {
       Bar bar = getBar();
       ...
    }
}

You may have to add a method to clear or update _bar, but that depends on your actual case.


问:
Alternative to "Passing/Broken build" indicator?
When having a continuous integration executing the tests at each commit, a common best practice is to have all the tests passing at all times (aka "do not break the build").

I find some problems with that:

For example one cannot help an open source project by creating tests corresponding to tickets. I know if I propose a Pull Request to an open source project containing failing test, the build will be marked as failed and the project will not want that merged into its repository because it would "break the build".

And I don't believe it is a bad thing to have failing tests in your repo, it's like having open issues in your tracker. These are just things waiting to be fixed.

The same goes in a company. If you work with TDD, you can't write tests, commit and then write the logic code that fulfills the test. That means if I have written 4-5 tests on my laptop, I can't commit them before going on holidays. Nobody can take back my work. I can't even "share" them with a colleague except by sending them by email for example. It also prevents working with one person writing the tests, the other one writing the model.

All that to say, am I misusing/misunderstanding the build process/continuous integration? It seems to me that "passing"/"not passing" is a too narrow indicator.

Is there a way to make continuous integration and TDD compatible?

Maybe there is a standard solution/practice to distinguish "new tests" (that can fail) and "regression tests" (that should not fail because they used to work)?

答:
I see where you're getting at, but these types of problems are typically solved in other ways.  There is a good reason why this is standard protocol.  If someone submits code that doesn't compile, everyone updating his/her code will have a program that doesn't compile.  That includes programmers who are currently working on something completely different and somehow find themselves in a situation in which they need to wait before they can compile and test what they're working on.

Standard protocol is that you can commit changes even for complete or even incomplete work, so long as it compiles so that programmers can update their code every day if necessary.

However, I still see what you're getting at.  Sometimes you want to commit in order to simply save your code.  For this, most source repositories support branching.  This allows you to create a private branch, work on it without disturbing others, then merge into the trunk when the work is completed.  This allows you to commit when you want without any of the backlash associated with causing the build to break.

If that's not suitable, GIT allows you to commit (pushing) to repositories on your local machine, but conceivably the repository could be anywhere.  You could create a repository for potentially partial/incomplete work and another repository for finished work, and on that repository you can add a nightly build.

Again, I can't stress the importance enough.  Do not commit broken code to trunk ever!  Your contributions cannot impact the work of other programmers.

Edit

I see that you intended broken tests, but in my humble opinion, there is little difference.  The whole point of a test is to determine if a particular aspect of a program passes or fails.  If it always fails and you do nothing, then the test, in the traditional usage of unit testing, serves nothing.  If you use it to perform some other metric which doesn't necessarily entail a "failed" commit if one such test fails, then I would strongly recommend you find another way to do the same thing.

Otherwise you risk that the test is never taken into consideration or if it causes your build to fail, that your fellow programmers ignore failed builds.  It's more important that programmers realize when they've broken a build than to perform a test which offers no real insight and may only result in bad practices.


问:
Web application (Spring, JSF) forks, how to reuse existing code for subprojects?
my question is going to be somewhat philosophical and "architectural oriented" so bear with me.

Right now we have existing Java web application built on top of Spring and JSF(facelets) with maven. These are basically our tools that limit our scope of possible solutions.

Now to the point. We need to implement a fork of this application that will be running on different domain for different "end consumers" and implement some change requests for both versions, but code base of these versions will probably always be ~90% same. Same change requests can be defined for implementation in both versions simultaneously BUT separate change requests only for chosen version might come as well. We have no control over what change requests there might come in later in project (but we are expecting quite a few). The differences in functionality may occur both on bean and view part of the application.

We don't want to create 2 completely separate projects as implementing changes might sometimes mean implementing them twice. THE BIG ISSUE is that we expect to have even more forks in the future so the effort might multiply even further.

The question is what ways of control or architectural patterns can we introduce to promote better maintainability of our projects. One solution might be for example:

using Spring profiles to inject proper components based on current fork of application and completely separating view (xhtml) implementation.

In summary we are looking for best way to implement application wide changes that can be isolated and activated only based on some context variable (how to propagate it everywhere?).

Any input, idea or new perspective is appreciated.

答:
Your problem is one of how to support a product line rather than a single product.  Luckily you're not the first person to have this problem.  There is a large community of people who work in this area, both industrial people and academics.

If you search for "software product lines" via your favourite search engine, you'll find lots of sites, books and other resources.

There are various patterns, going back to GoF, that allow variation to be plugged into a design in a controlled manner (Strategy immediately springs to mind, allowing interchangable implementations of a feature).  However, you need more than lots of individual changes - you need configurations of your product for particular customers that combine a number of variations together.  That's where the thinking from the product line community comes in (variation points and product configurations in particular).  As you say you can use technologies such as Spring profiles to implement this, but to avoid an almighty mess, you need to have a clear model of what you're trying to achieve to start with.

OwnerDisplayName: Jan Mathauser

OwnerDisplayName: Eoin


答:
Given a master branch with failing tests, how can you be sure - without comparing that list against previous builds - that you haven't introduced bugs?

Simply tracking the number of failing tests is insufficient: you might fix one test, and break another. And if you're on holiday, it won't be clear to others looking at the failing build.

Keep your master branch clean and green at all times. Work in a branch. Keep the branch under CI, in a separate job, and have failing tests to your heart's content. Just don't break master.

Have the branch's reviewer only merge your branch if it passes all tests. (More strongly: have the reviewer only able to merge your branch if the result of merging the branch into master passes all tests!)

Title: Alternative to "Passing/Broken build" indicator?

Body:
When having a continuous integration executing the tests at each commit, a common best practice is to have all the tests passing at all times (aka "do not break the build").

I find some problems with that:

For example one cannot help an open source project by creating tests corresponding to tickets. I know if I propose a Pull Request to an open source project containing failing test, the build will be marked as failed and the project will not want that merged into its repository because it would "break the build".

And I don't believe it is a bad thing to have failing tests in your repo, it's like having open issues in your tracker. These are just things waiting to be fixed.

The same goes in a company. If you work with TDD, you can't write tests, commit and then write the logic code that fulfills the test. That means if I have written 4-5 tests on my laptop, I can't commit them before going on holidays. Nobody can take back my work. I can't even "share" them with a colleague except by sending them by email for example. It also prevents working with one person writing the tests, the other one writing the model.

All that to say, am I misusing/misunderstanding the build process/continuous integration? It seems to me that "passing"/"not passing" is a too narrow indicator.

Is there a way to make continuous integration and TDD compatible?

Maybe there is a standard solution/practice to distinguish "new tests" (that can fail) and "regression tests" (that should not fail because they used to work)?


问:
Does it violate the DRY principle to use an MVC server-side framework and a client-side MVC framework
When using a MVC pattern for server side code (in my case django), the model definition is defined once in the model component. When using a client side MVC based library(in my case backbone) the model definition or some subset is redefined. If I were to make a change to my server side model definition, let's say add a field to a model, then I would have to make a similar model change to my client side model definition to include that new field.

Is this a violation of the DRY principle? Should server side model definitions auto-generate client side javascript based model definitions or is this an acceptable violation of the DRY principle?

答:
Since you posted this under the backbone.js tag, let's get the obvious answer out first: You're not violating the DRY principle, because you don't have to define the fields for Backbone.Model. Your model, at its simplest, can look like this:

```<code>var FooModel = Backbone.Model.extend({});
</code>```

If today your service returns {foo:1}, and tomorrow {foo:1, bar:2}, Backbone will quite happily use the new property.

Let's assume you were using a framework that required you to define your client model's properties, the question becomes more debatable...

<opinion>

The best you could do would be to codegen the client-side model properties from the server models. If you wanted to stretch it, you could possibly even generate simple validation code, but that's about it. Is it worth it? With the additional complexity added by code generation tools, I would say that unless you have hundreds of model types, the answer is a resounding no.

Consider what happens when you change a server model, in each of the following cases:

You add a property to the model

You remove a property from the model

You change a property of the model

Whether your client-side model is automatically generated or not, each of the changes will most likely require you to change some code on the client. Removing and changing a property are breaking changes: your application will most likely break or fail in unpredictable ways if it expects a certain property to be there, and it's not. Addition is more harmless, but unless you do some client-side code changes, a new property will not be very useful. You'll have to write code that uses the new property.

Now, if you're making changes to the client-side code anyway, the price of having to change the model definition is absolutely tiny. Any amount of quasi-theoretical DRY compliance can't make it worth your while.

I would go even one step further, and actually try to avoid directly mapping your server-side model to your client-side model, because it creates a tight coupling between them. There are numerous occasions when you may need to change the model in either end without changing the other, but if the models are expected to be directly equivalent, the change will propagate unnecessary change in its counterpart. Because in ORM-backed, "Active Model" type patterns the model is a participant in both persistence and business logic, there will be plenty of changes like this.

Instead you should write/generate Data Transfer Objects (DTO) for your server-side models. The DTO should contain a minimal necessary subset of the server model's properties, which the client needs. The DTO defines the interface between the server and the client. If the client model needs to change, you can change the DTO. If the server model changes, you can change the DTO.

</opinion>

OwnerDisplayName: Victor 'Chris' Cabral

Body:
Since you posted this under the backbone.js tag, let's get the obvious answer out first: You're not violating the DRY principle, because you don't have to define the fields for Backbone.Model. Your model, at its simplest, can look like this:

var FooModel = Backbone.Model.extend({});

If today your service returns {foo:1}, and tomorrow {foo:1, bar:2}, Backbone will quite happily use the new property.

Let's assume you were using a framework that required you to define your client model's properties, the question becomes more debatable...

<opinion>

The best you could do would be to codegen the client-side model properties from the server models. If you wanted to stretch it, you could possibly even generate simple validation code, but that's about it. Is it worth it? With the additional complexity added by code generation tools, I would say that unless you have hundreds of model types, the answer is a resounding no.

Consider what happens when you change a server model, in each of the following cases:

You add a property to the model

You remove a property from the model

You change a property of the model

Whether your client-side model is automatically generated or not, each of the changes will most likely require you to change some code on the client. Removing and changing a property are breaking changes: your application will most likely break or fail in unpredictable ways if it expects a certain property to be there, and it's not. Addition is more harmless, but unless you do some client-side code changes, a new property will not be very useful. You'll have to write code that uses the new property.

Now, if you're making changes to the client-side code anyway, the price of having to change the model definition is absolutely tiny. Any amount of quasi-theoretical DRY compliance can't make it worth your while.

I would go even one step further, and actually try to avoid directly mapping your server-side model to your client-side model, because it creates a tight coupling between them. There are numerous occasions when you may need to change the model in either end without changing the other, but if the models are expected to be directly equivalent, the change will propagate unnecessary change in its counterpart. Because in ORM-backed, "Active Model" type patterns the model is a participant in both persistence and business logic, there will be plenty of changes like this.

Instead you should write/generate Data Transfer Objects (DTO) for your server-side models. The DTO should contain a minimal necessary subset of the server model's properties, which the client needs. The DTO defines the interface between the server and the client. If the client model needs to change, you can change the DTO. If the server model changes, you can change the DTO.

</opinion>

OwnerDisplayName: fencliff


答:
I wasn't going to say anything, but someone piped up with "Ruby is a feat", so

John McCarthy with the original RECURSIVE FUNCTIONS OF SYMBOLIC EXPRESSIONS AND THEIR COMPUTATION BY MACHINE, ie the paper in which he defined Lisp back in 1960, when if was a concept people were just beginning to think seriously about. Talk about being ahead of your time.

Title: Whats the greatest most impressive programing feat you ever witnessed?

Body:
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?


问:
Choosing a open source licence for embedded system library
I'm writing a few libraries that I want to release as open source projects, but I want to find a licence that means I'll receive the credit when it is used in a project. Im not fussed about anything else, if people want to profit off of it then thats fine. So what licence is most appropriate? The only factor for me is that I receive the credit for producing the library if it is ever used. </p>

答:
Pretty well all permissive licenses (eg BSD and MIT) would suffice-  they all require the license bearing copyright owners name to be distributed with any copy of the software. Most software released under BSD uses New BSD License (3 clause).

Comparability with other licenses becomes an issue if someone uses your library in another open source package.  Also remember, if you used GPL in your code, then you must release it under GPL.


问:
Practical reference for learning about graph reduction
Are there any practical references (with actual examples) for getting started implementing a small, lazy functional programming language with graph reduction? A reference that included the lexing and parsing steps would be especially helpful.

So far I've read most of the Implementation of Functional Programming Languages by Simon Peyton Jones and the Wizard book (SICP).

答:
SPJ has written two books with very similar titles:

The implementation of functional programming languages, Simon Peyton Jones, Prentice Hall 1987.

Implementing functional languages: a tutorial, Peyton Jones and Lester.

Both are available here. The second one is more focused on compiling and executing code, including G-machines in Chapter 3. Quoting its overview:

The principal content of the book is a series of implementations of a small functional language called the Core language. The Core language is designed to be as small as possible, so that it is easy to implement, but still rich enough to allow modern non-strict functional languages to be translated into it without losing efficiency. It is described in detail in Chapter 1, in which we also develop a parser and pretty-printer for the Core language.

Appendix B contains a selection of Core-language programs for use as test programs thoughout the book.

The main body of the book consists of four distinct implementations of the Core language.

Chapter 2 describes the most direct implementation, based on template instantiation.

Chapter 3 introduces the G-machine, and shows how to compile the program to sequences of instructions (G-code) which can be further translated to machine code.

Chapter 4 repeats the same exercise for a different abstract machine, the Three Instruction Machine (TIM), whose evaluation model is very different from that of the G-machine. The TIM was developed more recently than the G-machine, so there is much less other literature about it. Chapter 4 therefore contains a rather more detailed development of the TIM's evaluation model than that given for the G-machine.

Finally, Chapter 5 adds a new dimension by showing how to compile functional programs for a parallel G-machine.

For each of these implementations we discuss two main parts, the compiler and the machine interpreter. The compiler takes a Core-language program and translates it into a form suitable for execution by the machine interpreter.

...