答: Dependencies, even in binary form, should be checked in so that when someone else pulls down the project, it just works. The main concern is not the type of file, but how the file is created. The rule of thumb that I use is that if it can be generated using another file, it doesn't get checked in - this means automatically generated documentation, binary files that I create, and so on.</p>

Title: Arguments againts checking-in binary files into SCMs

Body:
I work for a company that primarily builds Java applications and I'm trying to convince everybody to stop checking-in binary files (dependencies and final products) to SCM.

They know it is a bad practice but they think that "it works" and it is not really a problem even when many people know about Maven and other tools for building besides Ant. Both PMs and programmers (around 50 people) are ready to listen to any argument against and even acknowledge that it is a waste of backup space but I want to be really convincing because the habit change would involve a lot of effort. What arguments do you use to support a change?

Edit: Okay, it makes sense to make a distinction between files that almost do not change, like dependencies, and generated files. Even so, I'm interested in reasons against the latter.


问:
Event places - venue and hotel (database design conceptual question)
Hope this question is right here.

TL;DR

Database design for event places (venue and hotel), hotels can be venues.

Long Version

Introduction

I'm developing a software for trainings. Trainings are like a template with information and events show time and place where a specific training will happen.
Events have a place where they happen, the venue. Events also have an (optional) hotel, where participants can book rooms. A hotel can also be a venue since they often have conference rooms.
So if a hotel is  venue all the contact information and address for the hotel and the venue are obviously the same.

Question

What is the best way to design the database for hotel and venue, so that a hotel can also be a venue.

Target of design:

avoid duplicate data if a hotel is a venue

easy to handle through my software

Possible solutions

one table "Place" with columns "hotel_ID" and "venue_ID" which link to
the tables "Hotel" and "Venue"

one table "place" with an "isHotel" and "isVenue" column indicating which it is

two separate tables "hotel" and "venue" and in hotel table a column "venueID" whch links to a venue?

... (something different)

答:
You can have 3 entities. Address, Hotel and Venue.
You store AddressId as FK in Hotel and Venue. So if your Venue and Hotel have same street address you dont have to enter Address again. </p>

ContentLicense: CC BY-SA 3.0


问:
Database Structure: A product that will only temporarily be available and then slightly change
I'm trying to migrate lagacy data to a new eCommerce system which I'm building myself and I have full control over (so I can modify it however I want).

There is a product that came with a free gift for the first 100 customers. After that, it was just the regular product. Now the way that was handled in the old system was by just changing the product description and omitting the "with free gift" part after 100 sales. So from a database perspective, it was always the same product with the same id, just a different description.

However, I do have some options to distinguish them, and that's what I want to do while migrating. But I'm not sure how to represent something like that from a database modelling point of view. Should it be

2 different products

which doesn't feel quite right, because it's not 2 different products, it's maybe 2 variations of it. Also, when creating reports, I don't want it to handle as 2 different products.

1 product with 2 variants*, where the 2 variants are distinguished by the option whether it's with a gift or not

this also doesn't feel right, because 'free gift for the first 100' doesn't really sound like an option and variants shouldn't have different descriptions.

What could be another way to represent a temporarily promotion of a product in a structured and comprehensible way?

Edit

what exactly do you need to do with that information later?

I want to be able to

query how many products were sold with and without the gift, but still be able to treat that product as one, because the gift part doesn't really matter in reports

Be able to re-generate invoices with the same item description that existed when the item was purchased. The item description also should be available in multiple languages.

*The variants concept shortly explained: A product can have options (like a T-Shirt can have sizes and colors), and a variant is a product with a specific set of options (like a T-Shirt with size M in blue)

答:
Free gifts are promotional and inherently temporary yet recurring. I suggest you create a promotion/campaign table where you store discounts/gift details.
When you do your transactions you store price (as mentioned by @Ixrec) and the promtionId applied to it.
The promotion table should have start and end date for every campaign/promotion that is added.
This will give you details about the discounts offered, re-running your invoice and other analytics</p>


问:
How to write maintainable, not brittle, unit tests for a GUI?
I tried writing UI unit tests for my GUI apps and I face the problem that, while they work well when I initially write them, they turn out to be brittle and they break whenever the design changes (that is, quite often). I'm struggling to find a set of guidelines that would lead me to having maintainable unit tests for the GUI.

For now, one thing that I discovered is that tests saying "this component should show its input data somewhere" are good (and that's very easy with HTML). Tests checking for a specific state of a specific part of the component are usually brittle. Tests going like click-click-click-expect, that try to follow the user behaviour and the underlying business logic (which is the most important part) usually turn out to be brittle. How do I write good tests?

To be more precise, I'd like to know some patterns about what could I test in my UI, not exactly how to test it. Naming conventions and fixed identifiers are good, but don't solve the core problem, which is, that GUIs change a lot. I'd like to test the behaviours that are most unlikely to change. How to find the right thing to test?

答:
This is a common problem.  I would pay attention to:

How you name elements

Use css id or class to identify elements.  Favor using the CSS ID when the object is unique.  Consider the framework you are using, for example with Ruby on Rails the name attribute is assigned automatically and can (non-intuitively) be better than using the css id or class

How you identify elements.

Avoid positional identifiers like table/tr/td/td in favor of forms such as td[id="main_vehicle" or td[class='alternates'].  Consider using data attributes when appropriate.  Even better try to avoid layout tags such as  altogether so for the above you could either add a span and use that, e.g.  or a wildcard selector such as *[id="main_vehicle"] where the * could now be a div, span, td, etc.

Using test specific data attributes that are only used for qa and testing.

Avoid unnecessary qualification for elements.
You might find yourself using the following:

body.main div#vehicles > form#vehicle input#primary_vehicle_name

However this requires that input field to remain in a form with an exact id of vehicle and on a page with a body that has a class of main and a div with an id of vehicles that has an immediate child of a form with an id of vehicle.  Any change to any of that structure and the test breaks.  In this case you might find that

input#primary_vehicle_name

is enough to uniquely identify the element.

Avoid tests that refer to visible text.  The text on the page that is shown to the user usually changes over time as the site is maintained and updated, so use identifiers such as css id and css class or data attributes.  Elements such as form, input and select used in forms are also good parts of identifying elements, usually in combination with id or class, e.g. li.vehicle or input#first-vehicle
You can also add your own identifiers, e.g.
.  This way you can avoid using the element IDs or classes, which are likely to be changed by developers and designers.  I've actually found over time that its better to just work with developers and designers and come to agreement over names and scopes.  It is hard.

How fixed data is maintained.

Similar to identifying actual elements, try to avoid in-line hard coded selector identifying values in favor of page objects - small pieces of text that are held in variables or methods and thus can be reused and also maintained centrally.  Examples of javascript variables following this pattern for hard-coded values:

```<code>storedVars["eqv_auto_year"] = "2015";
storedVars["eqv_auto_make_1"] = "ALFA ROMEO";
storedVars["eqv_auto_make_2"] = "HONDA";`
</code>```

More on page objects at selenium wiki and selenium docs

Communication with developers.

Regardless of technical approach in terms of 'developers make changes and break the QA automation' that is a workflow issue.  You need to make sure that: everyone is one the same team; developer run the same integrated tests; standards are agreed on and followed by both groups; the definition of done includes running and possibly updating the UI tests; developers and tester pair on test plans and both attend ticket grooming (if doing Agile) and talk about UI testing as part of the grooming.
You should make sure that whatever approach and strategy you use for naming is coordinated with application developers.  If you don't get on the same page you'll like clash over object naming.
Some examples of page object methods that I recently created for a ruby project:

```<code>def css_email_opt_in_true
  'auto_policy[email_opt_in][value=1]'
end

def css_phone_opt_in
  '*[name="auto_policy[phone_opt_in]"]'
end

def css_phone_opt_in_true
  'input[name=phone_opt_in][value=true]'
end

def css_credit_rating
  'auto_policy[credit_rating]'
end
</code>```

Here's the same page objects as javascript variables:

```<code>storedVars["css_email_opt_in"] = "css=*[name='auto_policy[email_opt_in]']";
storedVars["css_phone_opt_in"]="css=*[name='auto_policy[phone_opt_in]']";
storedVars["css_phone_opt_in_true"]="css=input[name='phone_opt_in'][value=true]";
storedVars["css_credit_rating"]="css=select[name='auto_policy[credit_rating]']";
</code>```

Body:
This is a common problem.  I would pay attention to:

How you name elements

Use css id or class to identify elements.  Favor using the CSS ID when the object is unique.  Consider the framework you are using, for example with Ruby on Rails the name attribute is assigned automatically and can (non-intuitively) be better than using the css id or class

How you identify elements.

Avoid positional identifiers like table/tr/td/td in favor of forms such as td[id="main_vehicle" or td[class='alternates'].  Consider using data attributes when appropriate.  Even better try to avoid layout tags such as <td> altogether so for the above you could either add a span and use that, e.g. <span id="main_vehicle"> or a wildcard selector such as *[id="main_vehicle"] where the * could now be a div, span, td, etc.

Using test specific data attributes that are only used for qa and testing.

Avoid unnecessary qualification for elements.
You might find yourself using the following:

body.main div#vehicles > form#vehicle input#primary_vehicle_name

However this requires that input field to remain in a form with an exact id of vehicle and on a page with a body that has a class of main and a div with an id of vehicles that has an immediate child of a form with an id of vehicle.  Any change to any of that structure and the test breaks.  In this case you might find that

input#primary_vehicle_name

is enough to uniquely identify the element.

Avoid tests that refer to visible text.  The text on the page that is shown to the user usually changes over time as the site is maintained and updated, so use identifiers such as css id and css class or data attributes.  Elements such as form, input and select used in forms are also good parts of identifying elements, usually in combination with id or class, e.g. li.vehicle or input#first-vehicle
You can also add your own identifiers, e.g. <div data-vehicle='dodge'>.  This way you can avoid using the element IDs or classes, which are likely to be changed by developers and designers.  I've actually found over time that its better to just work with developers and designers and come to agreement over names and scopes.  It is hard.

How fixed data is maintained.

Similar to identifying actual elements, try to avoid in-line hard coded selector identifying values in favor of page objects - small pieces of text that are held in variables or methods and thus can be reused and also maintained centrally.  Examples of javascript variables following this pattern for hard-coded values:

storedVars["eqv_auto_year"] = "2015";
storedVars["eqv_auto_make_1"] = "ALFA ROMEO";
storedVars["eqv_auto_make_2"] = "HONDA";`

More on page objects at selenium wiki and selenium docs

Communication with developers.

Regardless of technical approach in terms of 'developers make changes and break the QA automation' that is a workflow issue.  You need to make sure that: everyone is one the same team; developer run the same integrated tests; standards are agreed on and followed by both groups; the definition of done includes running and possibly updating the UI tests; developers and tester pair on test plans and both attend ticket grooming (if doing Agile) and talk about UI testing as part of the grooming.
You should make sure that whatever approach and strategy you use for naming is coordinated with application developers.  If you don't get on the same page you'll like clash over object naming.
Some examples of page object methods that I recently created for a ruby project:

def css_email_opt_in_true
  'auto_policy[email_opt_in][value=1]'
end

def css_phone_opt_in
  '*[name="auto_policy[phone_opt_in]"]'
end

def css_phone_opt_in_true
  'input[name=phone_opt_in][value=true]'
end

def css_credit_rating
  'auto_policy[credit_rating]'
end

Here's the same page objects as javascript variables:

storedVars["css_email_opt_in"] = "css=*[name='auto_policy[email_opt_in]']";
storedVars["css_phone_opt_in"]="css=*[name='auto_policy[phone_opt_in]']";
storedVars["css_phone_opt_in_true"]="css=input[name='phone_opt_in'][value=true]";
storedVars["css_credit_rating"]="css=select[name='auto_policy[credit_rating]']";


问:
Refactoring method with nested loops and 6 variables
I have a method which implements a small section of a (complex) algorithm. This algorithm has taken me several weeks to perfect and is by far the fastest method I can find. The method in question has 3 levels of nested loops and each run of the innermost loop refines the values of 6 variables which in turn determine the behaviour of the other loops.

I therefore have a method with nested loops and ifs with 6 variables that are frequently read from and assigned to. I can understand it perfectly, I wrote the thing, but I fear that it may be a bit daunting for someone who doesn't have me there to explain it.

I know I have too many loops for the code to be easily readable:

I am looking for tips on how to go about refactoring this and other similar methods to make them more readable.

For scale the method is currently ~70 lines long.

答:
Without seeing the code, or insight into what language this is implemented in its tough to provide a problem-specific solution. You say method so that may exclude some solutions that would be applicable in certain languages.

From the way the solution is posed it seems that speed is of the essence but you are bound to incur some overhead by decomposing the loop, although (if you are using a compiled language) it may inline some things for you.

If you are using C, C++ or another language that has pointers I would consider decomposing the loops into appropriately named functions and pass along those variables that the loop requires.

Additionally, depending on how your computation is laid out in memory you may still retain the speed you have acquired if the appropriate pointers are passed as you should not incur any cache-misses that you did not already have. But keep in mind conditional branching as you progress.

If you are using another language, you may have success in applying some of Martin Fowler's teachings (http://martinfowler.com/articles/refactoring-pipelines.html, http://www.refactoring.com/catalog/splitLoop.html).

The split loop is an often used performance optimisation in data intensive applications. When you are accessing to separate arrays in the same loop you can get hit badly by the cache misses. That is, if the arrays are large  enough you loose locality of reference and the cache fails to do the job. Put enough code here and every operation will not hit the cache and instead have to go back out to main memory.

By splitting loops up into small separate components that only act on one array you get significant performance increases. In rendering code I've seen up to an order of magnitude difference. This is particularly beneficial if it is primitive type based and less so if class reference or pointer based where you need an additional dereference off into a random memory location. This technique is also very similar to loop unravelling for performance gains (although something I doubt would ever appear in a refactoring/patterns/OO type book :)

The last suggestion is attempting to simplify your expression using logic or determining if there is some data-structure that would better suit your computation in the legibility aspect.


问:
How to test an algorithm with multiple inputs?
I want to check group of algorithms which has up to 8 input options. The native idea would be to check all possibilities via brute force. How can I reduce it without leaving out required combinations?

Since I do not know it better I'm using multiple loops which ends in worst case in a O(n8) complexity.

To give a hint what that inputs are:

Data point count (by default 28 but can be 14-70 or anything else > 5)

Date (s relative day index based on the data points)

Preferences (limited to 3)

Temperature (limited to 34-38°C in 0.05 steps)

A marker on a day (limited to the possible values from the data points)

I have multiple algorithms which have all the same interface, but some concrete algorithm just uses some fields and not all. However should I need to check those other cases too since the algorithm might been updated and the test was forgotten for some reasons?

Do you have some best practices how to check algorithm?

答:
You should write tests for the logic as it is now - not how it might be later on or for some hypothetical test case.

Unit tests are supposed to be fast, so concentrate on the racing line tests and those at the limits of the parameters.

If the sheer number of cases is causing you concern, some unit testing frameworks such as NUnit allow you to specify a range of values and spawn a test for them all. It can also crunch combinations of parameters. So say you had parameters X and Y where X could be 1 or 2, and Y could be 1-5, it would create all possible cases for you.

If you do wish to test all possible combinations, that is perfectly acceptable but should probably take place outside of the normal development unit test run cycle. Perhaps as integration or soak tests that are say, run once every build/week etc.


问:
Is `isNaN`' a bad design or a has-to-be design with tradeoffs?
My first programming language is python. And recently I'm learning C and javascript.

In javascript, there is a design which confused me a lot, default the function isNaN.

Put aside its weird exceptions in specification(Which is hard to find), such as isNaN(""), isNaN(["22"]).

The more frustrating thing is that the result of isNaN consumes my thinking energy, though a tiny bit every time, before I established an intuition about it.(Which requires quite a bit of efforts)

But man, we are lazy. And this design does not follow the human instinct.

The examples below records how my brain works when seeing the two types of expressions in python and javascript:

```<code>isNaN(n)
false

# THOUGHTS:
# The result of isNaN(n) is false, what does it mean?
# it means n is not a number is false.
# OK, let me think for a while..
# So, I assume it is a number(with hesitation)

type(n) == int
False

# THOUGHTS:
# type(n) == int returns False, what does it mean?
# So it tells us that `the type of n equals int` is false
# So the type of n is not equal to int!
# I think n is not a int.
</code>```

I think human beings have a tendency to assume everything is True at first.

Thus multiple negative levels on statement will increase our recognition cost.

On this sight of view, the design of isNaN is a bad one, and isN(isNumber) is a better solution for human understanding.

But as a sceptic, I'm wondering there may have some background story about this design, to achieving a important functionality, the author chosen this design as a tradeoff?
Was there a good reason, or is this just a design deficiency(in the sense of human friendly)?

答: "Not a Number" (NaN) has its roots in something much larger than JavaScript.  You have to go back to 1985 and the IEEE-754 standard for floating point mathematics to understand it.  NaNs occur in several ways during mathematical operations (e.g., division of 0 by 0), and isNaN() functions are intended to determine when a putative number is in fact not a number.  JavaScript's particular implementation of isNaN() is, unfortunately, a byproduct of its willingness to treat values that aren't obviously numbers as numbers.


问:
Will the Database connection be closed if we yield the datareader row and not read all the records?
While understanding how yield keyword works, I came across link1 and link2 on StackOverflow which advocates the use of yield return while iterating over the DataReader and it suits my need as well. But It makes me wonder as what happens, if I use yield return as shown below and if I don't iterate through entire DataReader, will the DB connection stay open forever?

```<code>IEnumerable<IDataRecord> GetRecords()
{
    SqlConnection myConnection = new SqlConnection(@"...");
    SqlCommand myCommand = new SqlCommand(@"...", myConnection);
    myCommand.CommandType = System.Data.CommandType.Text;
    myConnection.Open();
    myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
    try
       {
          while (myReader.Read())
          {
            yield return myReader;
          }
        }
    finally
        {
            myReader.Close();
        }
}

void AnotherMethod()
{
    foreach(var rec in GetRecords())
    {
       i++;
       System.Console.WriteLine(rec.GetString(1));
       if (i == 5)
         break;
  }
}
</code>```

I tried the same example in a sample Console App and noticed while debugging that the finally block of GetRecords() is not executed. How can I ensure then the closure of DB Connection? Is there a better way than using yield keyword? I am trying to design a custom class which will be responsible for executing select SQLs and stored procedures on DB and will return the result. But I don't want to return the DataReader to the caller. Also I want to make sure that the connection will be closed in all scenarios.

Edit Changed the answer to Ben's answer as it is incorrect to expect method callers to use the method correctly and with respect to DB connection it will be more expensive if the method is called multiple times for no reason.

Thanks Jakob and Ben for detailed explanation.

答:
What you did seems wrong, but will work fine.

You should use an IEnumerator<>, as it also inherits IDisposable.

But because you are using a foreach, the compiler is still using an IDisposable to generate an IEnumerator<> for the foreach.

in facts, the foreach involves a lot of thing internaly.

Check https://stackoverflow.com/questions/13459447/do-i-need-to-consider-disposing-of-any-ienumerablet-i-use


答:
The purpose of isNaN is not to check if a value is nummeric or not. It actual purpose is to check if a floating point number has the special value of NaN. The special NaN value is assigned to the results of mathematically impossible operations, like dividing 0/0 or converting an alphabetic string to a number.

However, when you try to use isNaN on a value which is not a floating-point number, Javascript first tries to convert it to a number and then checks if that number has the special NaN value. To make matters more confusing, undefined is also treated as NaN by Javascript, so when the value can not be converted to a number, it is considered NaN.

To protect yourself from headache, only use isNaN when you are really looking for the floating point NaN value.

When you want to know if a variable is a number, use typeof variable == 'number' (the value of NaN is also of type number, by the way). When you want to know if a string can be converted to a number, use isNaN(Number(variable)).

Title: Is `isNaN`' a bad design or a has-to-be design with tradeoffs?

Body:
My first programming language is python. And recently I'm learning C and javascript.

In javascript, there is a design which confused me a lot, default the function isNaN.

Put aside its weird exceptions in specification(Which is hard to find), such as isNaN(""), isNaN(["22"]).

The more frustrating thing is that the result of isNaN consumes my thinking energy, though a tiny bit every time, before I established an intuition about it.(Which requires quite a bit of efforts)

But man, we are lazy. And this design does not follow the human instinct.

The examples below records how my brain works when seeing the two types of expressions in python and javascript:

```<code>isNaN(n)
false

# THOUGHTS:
# The result of isNaN(n) is false, what does it mean?
# it means n is not a number is false.
# OK, let me think for a while..
# So, I assume it is a number(with hesitation)

type(n) == int
False

# THOUGHTS:
# type(n) == int returns False, what does it mean?
# So it tells us that `the type of n equals int` is false
# So the type of n is not equal to int!
# I think n is not a int.
</code>```

I think human beings have a tendency to assume everything is True at first.

Thus multiple negative levels on statement will increase our recognition cost.

On this sight of view, the design of isNaN is a bad one, and isN(isNumber) is a better solution for human understanding.

But as a sceptic, I'm wondering there may have some background story about this design, to achieving a important functionality, the author chosen this design as a tradeoff?
Was there a good reason, or is this just a design deficiency(in the sense of human friendly)?


答:
Your finally block will always execute.

When you use yield return the compiler will create a new nested class to implement a state machine.

This class will contain all code from finally blocks as separate methods. It will keep track of the finally blocks that need to be executed depending on the state. All necessary finally blocks will be executed in Dispose method.

According to C# language specification, foreach (V v in x) embedded-statement is expanded to

```<code>{
    E e = ((C)(x)).GetEnumerator();
    try
    {
        while (e.MoveNext())
        {
            V v = (V)(T)e.Current;
            embedded - statement
        }
    }
    finally {
        … // Dispose e
    }
}
</code>```

so the enumerator will be disposed even if you exit the loop with break or return.

To get more information about iterator implementation you can read this this article by Jon Skeet

Edit

The problem with such approach is that you rely on the clients of your class to use the method correctly. They could for example get the enumerator directly  and iterate through it in a while loop without disposing it.

You should consider one of the solutions suggested by @BenAaronson.

Title: Will the Database connection be closed if we yield the datareader row and not read all the records?

Body:
While understanding how yield keyword works, I came across link1 and link2 on StackOverflow which advocates the use of yield return while iterating over the DataReader and it suits my need as well. But It makes me wonder as what happens, if I use yield return as shown below and if I don't iterate through entire DataReader, will the DB connection stay open forever?

```<code>IEnumerable<IDataRecord> GetRecords()
{
    SqlConnection myConnection = new SqlConnection(@"...");
    SqlCommand myCommand = new SqlCommand(@"...", myConnection);
    myCommand.CommandType = System.Data.CommandType.Text;
    myConnection.Open();
    myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
    try
       {
          while (myReader.Read())
          {
            yield return myReader;
          }
        }
    finally
        {
            myReader.Close();
        }
}

void AnotherMethod()
{
    foreach(var rec in GetRecords())
    {
       i++;
       System.Console.WriteLine(rec.GetString(1));
       if (i == 5)
         break;
  }
}
</code>```

I tried the same example in a sample Console App and noticed while debugging that the finally block of GetRecords() is not executed. How can I ensure then the closure of DB Connection? Is there a better way than using yield keyword? I am trying to design a custom class which will be responsible for executing select SQLs and stored procedures on DB and will return the result. But I don't want to return the DataReader to the caller. Also I want to make sure that the connection will be closed in all scenarios.

Edit Changed the answer to Ben's answer as it is incorrect to expect method callers to use the method correctly and with respect to DB connection it will be more expensive if the method is called multiple times for no reason.

Thanks Jakob and Ben for detailed explanation.

Body:
Your finally block will always execute.

When you use yield return the compiler will create a new nested class to implement a state machine.

This class will contain all code from finally blocks as separate methods. It will keep track of the finally blocks that need to be executed depending on the state. All necessary finally blocks will be executed in Dispose method.

According to C# language specification, foreach (V v in x) embedded-statement is expanded to

{
    E e = ((C)(x)).GetEnumerator();
    try
    {
        while (e.MoveNext())
        {
            V v = (V)(T)e.Current;
            embedded - statement
        }
    }
    finally {
        … // Dispose e
    }
}

so the enumerator will be disposed even if you exit the loop with break or return.

To get more information about iterator implementation you can read this this article by Jon Skeet

Edit

The problem with such approach is that you rely on the clients of your class to use the method correctly. They could for example get the enumerator directly  and iterate through it in a while loop without disposing it.

You should consider one of the solutions suggested by @BenAaronson.


答:
The reason why people developed things like MVC, MVP and presenter first, and similar design patterns, was to separate the business logic from the user interface.

Obviously, the view part can only be tested by starting the program, and checking what it shows - in other words, it can only be tested in acceptance tests.

On the other hand, testing the business logic can be done in unit tests. And that is the answer to your question. Test everything in the model, and if you can and want, you can also test the controller's code.

GUIs change a lot

That can only happen when you got changing requirements. When a requirement changes, there is no way around it, except to modify the code. If you manage to create good design and architecture, the change will not propagate in many places.

Title: How to write maintainable, not brittle, unit tests for a GUI?

Body:
I tried writing UI unit tests for my GUI apps and I face the problem that, while they work well when I initially write them, they turn out to be brittle and they break whenever the design changes (that is, quite often). I'm struggling to find a set of guidelines that would lead me to having maintainable unit tests for the GUI.

For now, one thing that I discovered is that tests saying "this component should show its input data somewhere" are good (and that's very easy with HTML). Tests checking for a specific state of a specific part of the component are usually brittle. Tests going like click-click-click-expect, that try to follow the user behaviour and the underlying business logic (which is the most important part) usually turn out to be brittle. How do I write good tests?

To be more precise, I'd like to know some patterns about what could I test in my UI, not exactly how to test it. Naming conventions and fixed identifiers are good, but don't solve the core problem, which is, that GUIs change a lot. I'd like to test the behaviours that are most unlikely to change. How to find the right thing to test?


答:
Yes, you will face the problem you describe: until you finish iterating over the result, you will keep the connection open. There's two general approaches I can think of to deal with this:

Push, don't pull

Currently you're returning an IEnumerable<IDataRecord>, a data structure you can pull from. Instead, you could switch your method to push its results out. The simplest way would be to pass in an Action<IDataRecord> which is called on each iteration:

```<code>void GetRecords(Action<IDataRecord> callback)
{
    // ...
      while (myReader.Read())
      {
        callback(myReader);
      }
}
</code>```

Note that given you're dealing with a collection of items, IObservable/IObserver might be a slightly more appropriate data structure, but unless you need it, a simple Action is much more straightforward.

Eagerly Evaluate

An alternative is just to make sure the iteration entirely completes before returning.

You can normally do this by just putting the results in a list then returning that, but in this case there's the additional complication of each item being the same reference to the reader. So you need something to extract the result you need from the reader:

```<code>IEnumerable<T> GetRecords<T>(Func<IDataRecord,T> extractor)
{
    // ...
     var result = new List<T>();
     try
     {
       while (myReader.Read())
       {
         result.Add(extractor(myReader));
       }
     }
     finally
     {
         myReader.Close();
     }
     return result;
}
</code>```

Body:
Yes, you will face the problem you describe: until you finish iterating over the result, you will keep the connection open. There's two general approaches I can think of to deal with this:

Push, don't pull

Currently you're returning an IEnumerable<IDataRecord>, a data structure you can pull from. Instead, you could switch your method to push its results out. The simplest way would be to pass in an Action<IDataRecord> which is called on each iteration:

void GetRecords(Action<IDataRecord> callback)
{
    // ...
      while (myReader.Read())
      {
        callback(myReader);
      }
}

Note that given you're dealing with a collection of items, IObservable/IObserver might be a slightly more appropriate data structure, but unless you need it, a simple Action is much more straightforward.

Eagerly Evaluate

An alternative is just to make sure the iteration entirely completes before returning.

You can normally do this by just putting the results in a list then returning that, but in this case there's the additional complication of each item being the same reference to the reader. So you need something to extract the result you need from the reader:

IEnumerable<T> GetRecords<T>(Func<IDataRecord,T> extractor)
{
    // ...
     var result = new List<T>();
     try
     {
       while (myReader.Read())
       {
         result.Add(extractor(myReader));
       }
     }
     finally
     {
         myReader.Close();
     }
     return result;
}


问:
Why do we need frameworks for dependency injection?
I've been reading up more on the Inversion of Control principle and Dependency Injection as an implementation of it and am pretty sure I understand it.

It seems to be basically saying 'don't declare your class members' instantiations within the class'. Rather that the instantiations should be passed in and assigned through the constructor; 'injected' into the class from an outside source.

If it's this simple, which it seems to be, why do we need frameworks like spring or guice that implement this with annotations? Am I missing something fundamental here? I'm really struggling to understand what the use of Dependency Injection frameworks are.

Edit: About the possible duplicate, I believe my question is more unique as it is asking about DI frameworks in general, not just Spring. Spring is not just a DI framework, so there are many reasons that someone would want to use Spring that aren't related to DI.

答:
A few years ago I wrote a program to monitor web pages, web portlets, even certain database tables, at a company I used to work for.  I wanted it to be flexible enough that the user could specify which monitors would run and with which parameters (urls, logins, success criteria, etc.).  So I wrote it to read from an XML file and use Java reflection to instantiate the specified classes and use setter methods to set the specified parameters.

Later I found that out Spring will do the same thing for you, and a whole lot more.

So in my case I found that

Using a dependency injection framework helps make the program flexible and makes it easier to specify how it will operate (within well defined parameters of course).

Using a third party DI framework keeps you from having to reinvent the wheel.


答:
Javascript's isNaN is a bit of a botched job on the concept of what Not-A-Number represents. The intent of NaN is to represent indeterminate numerical forms such as 0/0 or ∞/∞, and to represent the result of out-of-range numerical calculations such as sqrt(-1) and asin(2). The ES6 release of ECMAScript addresses this issue by adding the Number.isNaN function. This new function doesn't coerce a non-numeric value into a numeric value before testing. The result of calling Number.isNaN with a non-numeric value is false. This makes it clearer that the purpose of isNaN is to test for a numerical value that does not represent a numerical value.

There's a funny thing about NaNs: Arithmetic comparisons that involves a NaN must always return false. Even x == x (or x===x in javascript) will return false in the special case that x is a NaN. Anything but a NaN will compare equal to itself, yielding a cryptic way of testing whether something is a NaN. Using isNaN(x) does a much better job of conveying intent than does !(x==x).


问:
Single File for different versions of a configuration file
Please suggest best design for accomodating different versions of configuration file(INI format) into a single file. My requirement is I have three different versions of a configuration say V1.config, V2.config, V3.config. The different versions needs to be supported. I would like to achieve a file V.config from which I can read configuration info of all differnt versions.

My Requirement would be to support 3 different versions simultaneously with a sinlge file.

I working on a design where somehow i could combine these versions to a single file say V and read the data according to the version.Lets say [A\A2] will be there in this common/combined file but it is there in V1 and in V3 but not in V2. How can that be achieved.

What is the best practice usually followed, what would be possible design?

To help visualize:
V1.config would be something like:

```<code>[A\A1]
/*section for config info */
[A\A2]
/*section for config info */

[A\A3]
/*section for config info */
</code>```

V2.config

```<code>[A\A1]
    /*section for config info */

/* Removed a section */

[A\A3]
    /*section for config info */
[A\A4]
    /*Added new section for config info */
</code>```

V3.config

```<code> [A\A1]
    /*section for config info */
 [A\A2]
    /*Re-introduced the section in Version V1 for config info */

 /* Removed a section in Version V2 */
 [A\A4]
    /*section for config info */
</code>```

答:
It depends - one 'best solution' is to have a common core of configuration settings, and then have a section with additions for different versions. This requires your system to handle obsolete settings still being present when new versions read them.

An alternative is to have a XML-style configuration where settings for different versions can be included in the same file. This is easier in that your settings block only has to contain an attribute saying what version it applies to, so you can have (for example)  and  in the sane file, and completely discard the obsolete version 1 set, or only have settings for 1 version. The disadvantage is that everything is duplicated.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
The best indication of software
  quality is consistent indentation

I read this when I was following up footnotes in SICP once but I've not been able to find it since, so a) I can't attribute it and b) I am writing from memory, and more than likely paraphrasing. I have, however, found it to be true.

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


答:
You could take the web browser/HTML route. That is, whenever your program comes across some config info it doesn't understand (such as something added in a future version, or removed from a past version), it ignores it, and instead only pays attention to the sections it does understand.

This does come with the requirement that individual options behave consistently across versions. Either that, or your config file will rapidly become convoluted and repetitive.

In your example, V1 doesn't know about A\A4, so it would read it with the rest of the file, but then simply ignore it. Similarly, V2 doesn't care about A\A2, so anything in that section is ignored by V2. V3 reintroduces A\A2, which was ignored, rather than removed by V2, so it's still there, ready to be read and used.

The key to this is to never remove or change existing options. You can only ignore existing options or add new ones, unless you want to create a breaking change.

Here's a more in depth example of a fictitious program that uses a config file to remember some window settings. Say your V1 config file looks something like this:

```<code>[WindowDimensions]
width=400
height=300

[WindowLocation]
x=100
y=100
</code>```

So V1 has a size and location for the window when it starts up. Here's a little pseudo code to read that and access the variables:

```<code>Dictionary loadConfig() {
    String configFile = readFile("config.ini")
    Dictionary config = parseIni(configFile) // parses the file into a tree of Dictionaries
    config = fillMissingDefaults(config) // check for missing elements
                                         // and fill any with (V1) defaults
    Log("Window width: %d, height: %d",
        config["WindowDimensions"]["width"],
        config["WindowDimensions"]["height"]) // logs "Window width: 400, height: 300"
    Log("Window location: (%d, %d)",
        config["WindowLocation"]["x"],
        config["WindowLocation"]["y"]) // logs "Window location: (100, 100)"
    return config
}
</code>```

Then, fully 3D holographic displays come out, and everyone buys one. V2 is written to support them. Unfortunately, the tech is still new, and windows are always full screen, though the resolution is adjustable. So the V2 config file would look something like this:

```<code>[WindowDimensions]
width=400
height=300
depth=200

[WindowLocation]
x=100
y=100
</code>```

We've added a depth to the WindowDimensions to account for the third dimension. Note that the WindowLocation section is still there. V2 doesn't need it (everything is fullscreen), but, since we want to maintain backwards compatibility with V1, it remains there. Now, for V2's config loader:

```<code>Dictionary loadConfig() {
    String configFile = readFile("config.ini")
    Dictionary config = parseIni(configFile) // identical to parseIni() in V1
    config = fillMissingDefaults(config) // check for missing elements
                                         // and fill any with (V2) defaults
    Log("Window width: %d, height: %d, depth: %d",
        config["WindowDimensions"]["width"],
        config["WindowDimensions"]["height"],
        config["WindowDimensions"]["depth"]) // logs "Window width: 400, height: 300, depth: 200"
    return config
}
</code>```

Note that the config dictionary returned by parseIni() still contains WindowLocation and all it's children, but, since V2 doesn't care about it, it simply doesn't use it. Similarly, V1 can still use this new config file, even though there is now a new element in the config["WindowDimensions"] child dictionary.

Since config contains everything from config.ini, this has the added benefit of V2 saving the WindowLocation settings despite not knowing about it, simply by writing out the whole dictionary.

Now what if the config file was newly generated by V2 and thus really does have no mention of WindowLocation? That's what the defaults are for. If V1 one reads a new config file that previously had only been written by V2, then it would use, for example a default location of (300, 300), and would save that into the config file for future V1 use, along with all the V2 stuff it "doesn't" know about.

Title: Single File for different versions of a configuration file

Body:
Please suggest best design for accomodating different versions of configuration file(INI format) into a single file. My requirement is I have three different versions of a configuration say V1.config, V2.config, V3.config. The different versions needs to be supported. I would like to achieve a file V.config from which I can read configuration info of all differnt versions.

My Requirement would be to support 3 different versions simultaneously with a sinlge file.

I working on a design where somehow i could combine these versions to a single file say V and read the data according to the version.Lets say [A\A2] will be there in this common/combined file but it is there in V1 and in V3 but not in V2. How can that be achieved.

What is the best practice usually followed, what would be possible design?

To help visualize:
V1.config would be something like:

```<code>[A\A1]
/*section for config info */
[A\A2]
/*section for config info */

[A\A3]
/*section for config info */
</code>```

V2.config

```<code>[A\A1]
    /*section for config info */

/* Removed a section */

[A\A3]
    /*section for config info */
[A\A4]
    /*Added new section for config info */
</code>```

V3.config

```<code> [A\A1]
    /*section for config info */
 [A\A2]
    /*Re-introduced the section in Version V1 for config info */

 /* Removed a section in Version V2 */
 [A\A4]
    /*section for config info */
</code>```

Body:
You could take the web browser/HTML route. That is, whenever your program comes across some config info it doesn't understand (such as something added in a future version, or removed from a past version), it ignores it, and instead only pays attention to the sections it does understand.

This does come with the requirement that individual options behave consistently across versions. Either that, or your config file will rapidly become convoluted and repetitive.

In your example, V1 doesn't know about A\A4, so it would read it with the rest of the file, but then simply ignore it. Similarly, V2 doesn't care about A\A2, so anything in that section is ignored by V2. V3 reintroduces A\A2, which was ignored, rather than removed by V2, so it's still there, ready to be read and used.

The key to this is to never remove or change existing options. You can only ignore existing options or add new ones, unless you want to create a breaking change.

Here's a more in depth example of a fictitious program that uses a config file to remember some window settings. Say your V1 config file looks something like this:

[WindowDimensions]
width=400
height=300

[WindowLocation]
x=100
y=100

So V1 has a size and location for the window when it starts up. Here's a little pseudo code to read that and access the variables:

Dictionary loadConfig() {
    String configFile = readFile("config.ini")
    Dictionary config = parseIni(configFile) // parses the file into a tree of Dictionaries
    config = fillMissingDefaults(config) // check for missing elements
                                         // and fill any with (V1) defaults
    Log("Window width: %d, height: %d",
        config["WindowDimensions"]["width"],
        config["WindowDimensions"]["height"]) // logs "Window width: 400, height: 300"
    Log("Window location: (%d, %d)",
        config["WindowLocation"]["x"],
        config["WindowLocation"]["y"]) // logs "Window location: (100, 100)"
    return config
}

Then, fully 3D holographic displays come out, and everyone buys one. V2 is written to support them. Unfortunately, the tech is still new, and windows are always full screen, though the resolution is adjustable. So the V2 config file would look something like this:

[WindowDimensions]
width=400
height=300
depth=200

[WindowLocation]
x=100
y=100

We've added a depth to the WindowDimensions to account for the third dimension. Note that the WindowLocation section is still there. V2 doesn't need it (everything is fullscreen), but, since we want to maintain backwards compatibility with V1, it remains there. Now, for V2's config loader:

Dictionary loadConfig() {
    String configFile = readFile("config.ini")
    Dictionary config = parseIni(configFile) // identical to parseIni() in V1
    config = fillMissingDefaults(config) // check for missing elements
                                         // and fill any with (V2) defaults
    Log("Window width: %d, height: %d, depth: %d",
        config["WindowDimensions"]["width"],
        config["WindowDimensions"]["height"],
        config["WindowDimensions"]["depth"]) // logs "Window width: 400, height: 300, depth: 200"
    return config
}

Note that the config dictionary returned by parseIni() still contains WindowLocation and all it's children, but, since V2 doesn't care about it, it simply doesn't use it. Similarly, V1 can still use this new config file, even though there is now a new element in the config["WindowDimensions"] child dictionary.

Since config contains everything from config.ini, this has the added benefit of V2 saving the WindowLocation settings despite not knowing about it, simply by writing out the whole dictionary.

Now what if the config file was newly generated by V2 and thus really does have no mention of WindowLocation? That's what the defaults are for. If V1 one reads a new config file that previously had only been written by V2, then it would use, for example a default location of (300, 300), and would save that into the config file for future V1 use, along with all the V2 stuff it "doesn't" know about.


问:
Where to put try-catch statements
I have the following code statement that calls a separate class.

```<code>if (newOrEdit.Equals("New"))
{
    try
    {
        BusinessLayer.InsertOperator(operatorDetails);
    }
    catch (Exception)
    {
        MessageBox.Show("Error unable to insert details.");
    }

}
</code>```

This calls a simple method that tries to insert the operator.

I have seen the same method done as follows

```<code>if (newOrEdit == "New")
{
    if (Business.insertNewUser(userDetails))
    {
        this.Close();
    }
    else
    {
        MessageBox.Show("Unable to insert new user", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        this.Close();
    }
}
</code>```

Now this method accepts a boolean back and inside the method it has the try catch inside the business class.

Which of the following is better and why?

答:
The general best practice is to only use exceptions on exceptions. The process of creating an exception and throwing it is generally very costly, so should be avoided for things that can fail through fairly normal operation.

Validation is a good example of this. People are going to send in garbage inputs all the time. That is an error, but not exceptional - so don't use exceptions.

So if inserting a new user should almost always succeed (baring some exceptional circumstance, like a lightning strike killing your network) then try/catch is fine. If inserting a new user might commonly fail, then the success bool would be better.

Title: Where to put try-catch statements


答:
Exception handling tends to be a fairly expensive operation, so if you are writing the code that is called, and you can handle it gracefully then you should.

If you are writing the code that can have an error condition, consider whether the error you are handling is recoverable. It would be rather harsh to force an exception to be thrown for a simple data entry error.

Title: Where to put try-catch statements

Body:
I have the following code statement that calls a separate class.

```<code>if (newOrEdit.Equals("New"))
{
    try
    {
        BusinessLayer.InsertOperator(operatorDetails);
    }
    catch (Exception)
    {
        MessageBox.Show("Error unable to insert details.");
    }

}
</code>```

This calls a simple method that tries to insert the operator.

I have seen the same method done as follows

```<code>if (newOrEdit == "New")
{
    if (Business.insertNewUser(userDetails))
    {
        this.Close();
    }
    else
    {
        MessageBox.Show("Unable to insert new user", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        this.Close();
    }
}
</code>```

Now this method accepts a boolean back and inside the method it has the try catch inside the business class.

Which of the following is better and why?


问:
When was block scope for variables introduced to C, and why is it still frowned upon?
In light of the recent OBJ_obj2txt vulnerability in LibreSSL (which was found during the OpenSMTPD audit, and does not affect OpenSSL), it came to my attention that the memory leak issue likely resulted from some earlier code refactoring, where the block scoped variable char *bndec was moved out to be function scoped instead.

I know first-hand that there is this great resistance to block scoped variables within old-school projects like OpenBSD, but what other justification would there be to move the char *bndec declaration?

More broadly, when was block scoping introduced for variables in C?  All I could find is that it was already part of C89.  Is that where it started, or was it also part of an earlier spec?

答:
In the C Reference Manual that came with 6th Edition Unix (May 1975, second volume entitled "Documents for Use With the Unix Time-sharing System") the only compound statement allowed to contain variable declarations is the function-statement:

function-body: type-decl-list function-statement

function-statement: { declaration-listopt statement-list }

In the first edition of K&R ("The C Programming Language", 1978) you can read:

Declarations of variables (including initializations) may follow the left brace that introduces any compound statement, not just the one that begins a function

This specification is a hint that block scoped variables was probably a recent, not well known feature (1978).

See also Dennis M. Ritchie's page


答:
TL;DR: It's not an issue of block scoping, but rather a misunderstanding of how pointers should be handled.

Courtesy of the vulnerability listing that you posted, let's take a look at the code in question.

```<code>489 int
490 OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name)
491 {
...
494         char *bndec = NULL;
...
516         len = a->length;
...
519         while (len > 0) {
...
570                         bndec = BN_bn2dec(bl);
571                         if (!bndec)
572                                 goto err;
573                         i = snprintf(buf, buf_len, ".%s", bndec);
...
598         }
...
601         free(bndec);
...
609 }
</code>```

And if we delve into the declaration of BN_bn2dec we see a comment of:

```<code>/* Must 'free' the returned data */
</code>```

What you see as a block scoping issue, I see as a poor understanding of pointer operations as the root issue.

This diff revision shows when the *bndec was moved from inside the while loop to outside the while loop.  The error was also introduced at the same time when the free(bndec) statement was moved outside the loop.

Where *bndec is declared for this function is a bit irrelevant.  It can safely be defined either outside or inside the while loop.  And if memory serves correctly, the actual declaration will be moved to the top of the function by the compiler anyway.

Declaring *bndec inside the loop merely would have forced an error if the free() call remained outside of the loop.  It remains to be seen whether that error would have been sufficient to alert the programmer to the fallacy behind their refactoring logic.

Being a bit of a pessimist when it comes to most programmers and pointers, I'm going to posit that the free accessing an out-of-scope variable error wouldn't have helped them discover the error of their ways.  Instead, they would have taken the naive (and incorrect) solution of resolving the error by merely moving the variable declaration outside of the block. And that's why I disagree with the contention that the root cause of this is a block scoping issue.

If C happened to have garbage collection, then block scoping would have been of more value in this case.  But it doesn't, and that line of thought becomes pointless speculation.

Unfortunately, we don't really know why the refactoring programmer chose to move that free(bndec) statement.  All that they left via check-in comments was this:

Clean up some of the nightmare of string and pointer arithmatic in
  this nasty function.

  This gets rid of the nasty tmp variables used to hold temporary strings
  and the DECIMAL_SIZE hack. it gets rid of the rather pointless null checks
  for buf (since the original code dereferences it before checking). It also
  gets rid of the insane possibility this could return -1 when stuff is
  using the return values to compute lengths All the failure cases now
  return 0 and an empty string like the first error case in the original
  code.

And while I respect their dedication to clean code, I'm not certain I fully agree with their removing of various checks from the code.  Having written a fair amount of C code with a fairly large team of developers, my experience is that defensive coding practices are almost always warranted.  And while a developer may not be able to justify the time expense to add those defensive practices, I can't say that I have ever found valid grounds to remove those defenses.

To delve into an equal amount of hyperbole as the refactoring programmer, I find their check-in comment to smack a little bit too much of hubris and not enough of humility.  That hubris is likely what led them to assume they "knew what they were doing" (TM) in moving the free(bndec) statement, and they didn't mentally walk through what that was going to do to the code.

This error was introduced with the refactoring not because of the block scoping, but because of the failure to understand how pointers operate and the failure to understand how pointers relate to memory.

While I think I have established why block scoping is irrelevant to this issue, I want to address what you see as "great resistance to block scoped variables within old-school projects".  And to my knowledge, ANSI C has always had block scoping available for variables.  Going out on a limb, I suspect K&R C also had it.

Keep in mind that C is not a gentle language for the naive or the initiate.  It was created in order to provide an additional layer of abstraction over B and assembly level programming.  Programmers writing in C were still expected to have an understanding of the underlying assembler that was being generated.  For example, variables are not automatically initialized, and many a programmer has been burned by that lack of initialization.  C expects the programmer to understand what that variable declaration maps to in memory.  C also has more than its fair share of unwritten style rules that are considered to be "good form."

Moving all variable declarations is one of those unwritten style rules, and the pragmatic reason goes back to the lack of automatic initialization.  Disciplined C programmers declared all of their variables at the beginning of the function so they could make a quick visual scan to verify that all declared variables had been initialized.  It's an easy way to make sure that a common mistake (e.g. lack of initialization) has been avoided.

Title: When was block scope for variables introduced to C, and why is it still frowned upon?

Body:
In light of the recent OBJ_obj2txt vulnerability in LibreSSL (which was found during the OpenSMTPD audit, and does not affect OpenSSL), it came to my attention that the memory leak issue likely resulted from some earlier code refactoring, where the block scoped variable char *bndec was moved out to be function scoped instead.

I know first-hand that there is this great resistance to block scoped variables within old-school projects like OpenBSD, but what other justification would there be to move the char *bndec declaration?

More broadly, when was block scoping introduced for variables in C?  All I could find is that it was already part of C89.  Is that where it started, or was it also part of an earlier spec?

Body:
TL;DR: It's not an issue of block scoping, but rather a misunderstanding of how pointers should be handled.

Courtesy of the vulnerability listing that you posted, let's take a look at the code in question.

489 int
490 OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name)
491 {
...
494         char *bndec = NULL;
...
516         len = a->length;
...
519         while (len > 0) {
...
570                         bndec = BN_bn2dec(bl);
571                         if (!bndec)
572                                 goto err;
573                         i = snprintf(buf, buf_len, ".%s", bndec);
...
598         }
...
601         free(bndec);
...
609 }

And if we delve into the declaration of BN_bn2dec we see a comment of:

/* Must 'free' the returned data */

What you see as a block scoping issue, I see as a poor understanding of pointer operations as the root issue.

This diff revision shows when the *bndec was moved from inside the while loop to outside the while loop.  The error was also introduced at the same time when the free(bndec) statement was moved outside the loop.

Where *bndec is declared for this function is a bit irrelevant.  It can safely be defined either outside or inside the while loop.  And if memory serves correctly, the actual declaration will be moved to the top of the function by the compiler anyway.

Declaring *bndec inside the loop merely would have forced an error if the free() call remained outside of the loop.  It remains to be seen whether that error would have been sufficient to alert the programmer to the fallacy behind their refactoring logic.

Being a bit of a pessimist when it comes to most programmers and pointers, I'm going to posit that the free accessing an out-of-scope variable error wouldn't have helped them discover the error of their ways.  Instead, they would have taken the naive (and incorrect) solution of resolving the error by merely moving the variable declaration outside of the block. And that's why I disagree with the contention that the root cause of this is a block scoping issue.

If C happened to have garbage collection, then block scoping would have been of more value in this case.  But it doesn't, and that line of thought becomes pointless speculation.

Unfortunately, we don't really know why the refactoring programmer chose to move that free(bndec) statement.  All that they left via check-in comments was this:

Clean up some of the nightmare of string and pointer arithmatic in
  this nasty function.

  This gets rid of the nasty tmp variables used to hold temporary strings
  and the DECIMAL_SIZE hack. it gets rid of the rather pointless null checks
  for buf (since the original code dereferences it before checking). It also
  gets rid of the insane possibility this could return -1 when stuff is
  using the return values to compute lengths All the failure cases now
  return 0 and an empty string like the first error case in the original
  code.

And while I respect their dedication to clean code, I'm not certain I fully agree with their removing of various checks from the code.  Having written a fair amount of C code with a fairly large team of developers, my experience is that defensive coding practices are almost always warranted.  And while a developer may not be able to justify the time expense to add those defensive practices, I can't say that I have ever found valid grounds to remove those defenses.

To delve into an equal amount of hyperbole as the refactoring programmer, I find their check-in comment to smack a little bit too much of hubris and not enough of humility.  That hubris is likely what led them to assume they "knew what they were doing" (TM) in moving the free(bndec) statement, and they didn't mentally walk through what that was going to do to the code.

This error was introduced with the refactoring not because of the block scoping, but because of the failure to understand how pointers operate and the failure to understand how pointers relate to memory.

While I think I have established why block scoping is irrelevant to this issue, I want to address what you see as "great resistance to block scoped variables within old-school projects".  And to my knowledge, ANSI C has always had block scoping available for variables.  Going out on a limb, I suspect K&R C also had it.

Keep in mind that C is not a gentle language for the naive or the initiate.  It was created in order to provide an additional layer of abstraction over B and assembly level programming.  Programmers writing in C were still expected to have an understanding of the underlying assembler that was being generated.  For example, variables are not automatically initialized, and many a programmer has been burned by that lack of initialization.  C expects the programmer to understand what that variable declaration maps to in memory.  C also has more than its fair share of unwritten style rules that are considered to be "good form."

Moving all variable declarations is one of those unwritten style rules, and the pragmatic reason goes back to the lack of automatic initialization.  Disciplined C programmers declared all of their variables at the beginning of the function so they could make a quick visual scan to verify that all declared variables had been initialized.  It's an easy way to make sure that a common mistake (e.g. lack of initialization) has been avoided.


答:
If there are a series of complex checks or calculations chained together by logic then give each a descriptive name so that the purpose is clear.

So:

```<code>Private Function CheckDateEntry(int day, int month, int year)
  If DayIsValid(day) And MonthIsValid(month) And YearIsValid(year)
    Return True
  End If
End Function
</code>```

Rather than:

```<code>Private Function CheckUserInput(int d, int m, int y)
  If (d > 0 and d <= 31) and (m > 0 and m <= 12) and (y > 0 and y <= 2015)
    Return True
  End If
End Function
</code>```

If you can, break the routine up into smaller (testable) routines. Developers have a lot more faith in a piece of code if there are a suite of automated tests for it.

Make sure your routines and variables following a sensible convention. So verb-noun for methods and noun for variables.

In your quest to make the code as fast as possible, it sounds like some code readability has had to be sacrificed, which is par for the course sometimes. However, if the code is unclear as a result of this in places, consider adding pertinent comments.

Title: Refactoring method with nested loops and 6 variables

Body:
I have a method which implements a small section of a (complex) algorithm. This algorithm has taken me several weeks to perfect and is by far the fastest method I can find. The method in question has 3 levels of nested loops and each run of the innermost loop refines the values of 6 variables which in turn determine the behaviour of the other loops.

I therefore have a method with nested loops and ifs with 6 variables that are frequently read from and assigned to. I can understand it perfectly, I wrote the thing, but I fear that it may be a bit daunting for someone who doesn't have me there to explain it.

I know I have too many loops for the code to be easily readable:

I am looking for tips on how to go about refactoring this and other similar methods to make them more readable.

For scale the method is currently ~70 lines long.

Body:
If there are a series of complex checks or calculations chained together by logic then give each a descriptive name so that the purpose is clear.

So:

Private Function CheckDateEntry(int day, int month, int year)
  If DayIsValid(day) And MonthIsValid(month) And YearIsValid(year)
    Return True
  End If
End Function

Rather than:

Private Function CheckUserInput(int d, int m, int y)
  If (d > 0 and d <= 31) and (m > 0 and m <= 12) and (y > 0 and y <= 2015)
    Return True
  End If
End Function

If you can, break the routine up into smaller (testable) routines. Developers have a lot more faith in a piece of code if there are a suite of automated tests for it.

Make sure your routines and variables following a sensible convention. So verb-noun for methods and noun for variables.

In your quest to make the code as fast as possible, it sounds like some code readability has had to be sacrificed, which is par for the course sometimes. However, if the code is unclear as a result of this in places, consider adding pertinent comments.


答:
There are two common mis-uses of the exception mechanism:  First, is to use it as a standard event information channel (which is not what it's designed for);  second, is to "swallow" exceptions in a way that hides problems from you.

The result of doing either of these is that the exception/error gets managed at an inappropriate point in the code.  How many times have you received an exception thrown, but it's cause is some code way up the chain?  Often! (if you've been doing this for any amount of time!)

For example:  You have a little yourPackage.util.ConvertDate class.  It does a reflection invocation on your input and gives you some derived value, but if one of your input values to a private internal method is null, it will throw an IllegalArgumentException or perhaps an InvocationTargetException.  In an ideal world, that method would be defined as "throws IllegalArgumentException" and that exception would "bubble up" to the next level.  In well designed exception trees, that exception would keep passing through "throws" declarations until it hit the very same line of code that set the unusable value!

The concept here is to have the exception bubble up to the exact spot in your code where you can effect the best recovery.

Another example:  you have a database insert routine that fails because there's a null value in your PreparedStatement parameters, for a non-nullable field in the database. It throws an SQLException.  If you "swallow" that exception and pass up a boolean false return value to show that a record wasn't inserted into the DB, (and likely you ignore the return value) then later on when you discover that your object doesn't exist, you have no way of knowing whether it was because of a null value, because there was something ELSE wrong with that value (i.e. putting a string into a BIGINT field) or that there was a syntax error in your SQL statement or even if you'd momentarily lost network connection to the database!  When you handled the exception down where you had no ability to make a relevant choice in the matter and SOLVE it, then you caused yourself a big huge debugging headache later on.

Title: Where to put try-catch statements


答:
Regardless of the specific yield behaviour, your code contains execution paths that will not dispose your resources correctly. What if your second line throws an exception or your third? Or even your fourth? You will need a very complex try/finally chain, or you can use using blocks.

```<code>IEnumerable<IDataRecord> GetRecords()
{
    using(var connection = new SqlConnection(@"..."))
    {
        connection.Open();

        using(var command = new SqlCommand(@"...", connection);
        {
            using(var reader = command.ExecuteReader())
            {
               while(reader.Read())
               {
                   // your code here.
                   yield return reader;
               }
            }
        }
    }
}
</code>```

People have remarked that this is not intuitive, that people calling your method may not know that enumerating the result twice will call the method twice. Well, tough luck. That's the way the language works. That's the signal that IEnumerable<T> sends. There is a reason this does not return List<T> or T[]. People that do not know this need to be educated, not worked around.

Visual Studio has a feature called static code analysis. You can use it to find out if you have disposed resources properly.

Body:
Regardless of the specific yield behaviour, your code contains execution paths that will not dispose your resources correctly. What if your second line throws an exception or your third? Or even your fourth? You will need a very complex try/finally chain, or you can use using blocks.

IEnumerable<IDataRecord> GetRecords()
{
    using(var connection = new SqlConnection(@"..."))
    {
        connection.Open();

        using(var command = new SqlCommand(@"...", connection);
        {
            using(var reader = command.ExecuteReader())
            {
               while(reader.Read())
               {
                   // your code here.
                   yield return reader;
               }
            }
        }
    }
}

People have remarked that this is not intuitive, that people calling your method may not know that enumerating the result twice will call the method twice. Well, tough luck. That's the way the language works. That's the signal that IEnumerable<T> sends. There is a reason this does not return List<T> or T[]. People that do not know this need to be educated, not worked around.

Visual Studio has a feature called static code analysis. You can use it to find out if you have disposed resources properly.


问:
What to do when hydrating whole domain model is unnecessary for concrete operation?
If some model can only exist if set of values are passed to it and validation on them are performed, then how to load such a model if only one of those values is needed for some action?

It seems a little overhead to do hydration of model all over again if only one value for action on that model is needed. That can be expensive.

I have an auction model. It has title, description, owner, current value, dates and bids. For particular operation like bid I only need current value and bids in this model to be populated. However, model, theoretically, cannot exist if other values are not received and validated (in constructor).

What to do? How to do separation? Is that normal/common for DDD and there is just some trade offs you cannot avoid?

答:
I believe I understand your dilemma.

Though it may be a waste to rehydrate the entire aggregate for this, the aggregate serves the specific purpose of being the consistency boundary. If you had a subset of the domain just to handle the bids, and the full aggregate for other operations, how are you going to maintain consistency when you have potentially two objects servicing operations on the same AR? You no longer have a single consistency boundary. Are you positive that performance is going to be a problem if rehydrate the entire thing for this minor operation? Have you measured it?

If it becomes a problem, one thing you can do is to move your use cases up a level so that they are intercepted before the aggregate root is loaded. This is common in messaging-based systems where you issue commands to the domain (not call a method directly on a loaded aggregate). Commands are received by handlers, which hydrate the aggregate as appropriate for the use case (e.g. a deleted version of the aggregate which refuses to do perform any operation since it is deleted, or in your case a limited version which only accepts bids). Sometimes the handlers even load other aggregates (for information only, otherwise the consistency boundary is violated again) or prepare services to hand off to the aggregate to perform the given use case.

In a non-messaging system you could accomplish the same with the Facade pattern. Essentially, you make an object that is your interface into the domain. The object has a method per use case. Inside that method, you run handler code; hydrate your appropriate aggregate, wrangle the resources/services necessary for the user case, and call the aggregate's method. Maybe save the changes as well. Eventually, you may get too many parameters on the Facade methods and you will need to refactor them to an object. At that point, you have a command message as your parameter. :)

However, if you do something like this you need some infrastructure guarantees. For example, a specific aggregate can only run one use case at a time. My first infrastructure like this, each type of aggregate (not each instance) could only run one use case at a time -- in other words if I submitted 100 operations, each to a different auction, they would still be performed one at a time. In practice, this was not a performance problem at all as you will usually be bottle-necked by I/O more than running domain operations.


问:
Dynamic query from view layer
In my current job they are defining a new corporate architecture for java development. It is something like this:

ProjectView: JSF view layer. Uses delegates on the ProjectClient layer.

ProjectClient: Defines Delegates and Facades. It does de lookup for the EJBs the business layer.

ProjectBusiness: Implements the Facades defined by the client layer as remotes EJBs. It also containes the model and the DAO layer.

The business layer maps entities to DTOs so the client and view only knows about DTOs clases.

My concern

Let's say we have an entity Car with attributes horsePower, numberOfDoors, engineType and releaseDate. Now, we need in the view to search the cars with 3 doors and more than 120hp. With the initial vision of the architecture I should write the functions needed in all layers that take this to arguments.

But if I need with 3 doors and more than 120hp or diesel engine? The answer was: build another function. Thats one in the delegate, on the facade interface, the facade impl and in the dao.

But our entities don't have 4 fields. More like 30. IMHO is going to be chaos and people dying when we start writing full apps, with hundreds of functions all over the place. Changing the model is not an option.

My solution

I've created a prototype inspired in queryDsl to create dynamic queries from the view that follows the layer pattern so you could write something like this in a manager bean from JSF. Just one class needs to be created in the ProjectClient layer.

```<code>ClientQuery query = new ClientQuery();
QCar qcar = QCar.qcar;
query.and(qcar.model.eq(model)).and(qcar.horsePower.get(minumuHp));
return carService.searchCars(query);
</code>```

The prototype keeps the layers separated and the dao layer can choose with query builder to use given a generic query.

My Question

This aproach makes sense? I haven't found anything on this subject so I am stating to think that maybe is an anti-pattern or some kind of bad practice.
If it makes sense, is there any framework/library or pattern to look further?

I've uploaded the prototype to Github and can share the link if asked to.

答:
In simple case you can use SearchCriteria dto:

```<code>class CarSearchCriteria {
   private integer horsePower;
   private integer numberOfDoors;
   private String model;
   // other needed parameters
   // getters/setters
}
CarSearchCriteria criteria = new CarsSearchCriteria()
    .withModel(model)
    .withHorsePower(minHorsePower);
return carService.searchCars(criteria);
</code>```

In complex case you can use your dynamic queries (it is criteria design pattern)

In more than complex case dynamic queries won't help you. It will be more complex than sql called with facade method.

Look on the next extreme case. It is obviously a bad design to place such things in a view layer:

```<code>String sqlQuery = "SELECT * from Car where model = ? AND horsePower > ?"
Object[] params = new Object[] {model, horsePower} // your parameters
return searchService.searchEntity(query, params, Car.class);
</code>```

But ask yourself: Do you really want to place your dynamic queries in a view layer?

Title: Dynamic query from view layer

Body:
In simple case you can use SearchCriteria dto:

class CarSearchCriteria {
   private integer horsePower;
   private integer numberOfDoors;
   private String model;
   // other needed parameters
   // getters/setters
}
CarSearchCriteria criteria = new CarsSearchCriteria()
    .withModel(model)
    .withHorsePower(minHorsePower);
return carService.searchCars(criteria);

In complex case you can use your dynamic queries (it is criteria design pattern)

In more than complex case dynamic queries won't help you. It will be more complex than sql called with facade method.

Look on the next extreme case. It is obviously a bad design to place such things in a view layer:

String sqlQuery = "SELECT * from Car where model = ? AND horsePower > ?"
Object[] params = new Object[] {model, horsePower} // your parameters
return searchService.searchEntity(query, params, Car.class);

But ask yourself: Do you really want to place your dynamic queries in a view layer?


答:
A common problem with GUI tests... The main reason these tests are considered brittle is because they cannot survive a change in the GUI that is not a change in requirements. You should strive to structure your test code in such a way that a change in the GUI is isolated to a single place in the tests.

As an example, consider a test that is worded as:

When the user enters '999' into the phonenumber field and clicks the save button, the error message popup should say 'invalid phone number'.

Plenty of room here for this test to break when you rework the interface, even if the requirement for the validation stays.

Now, lets put this into a little alternative wording:

When the user enters '999' as a phonenumber and saves the profile page, it should show an error that says 'invalid phone number'

The test is the same, the requirements are the same, but this kind of test will survive a makeover for your UI. You will need to change code, obviously, but the code will be isolated. Even if you have ten or twenty such tests for your profile page and you move your errormessage-displaying validation logic from javascript-alerts to jquery-popups for example, you only need to change the single test part that checks error messages.


答:
avoid duplicate data if a hotel is a venue

Is this really a problem? If you have any available data, you should look to see how much duplication there really is. A hotel with convention space could have different names, billing addresses, contact information, etc. Also, a single hotel could have multiple meeting places with different names. Avoiding potential duplicate data could get difficult if you're trying to offer some flexibility. As far as data changes, how often will these places really change? If they relocate a hotel, you'd probably make a new entry anyway.

easy to handle through my software

How important is the question to the user, "Which venues are also a hotel?" You could get a way with a Venue table and Hotel table. There's always a Venue, so there could be a FK_Hotel_ID field for the optional link.

With 3 tables, you can have the shared data in the Place table, but again, you have to decide how much there really is.
 - Place (PK_PlaceID)
 - Hotel (FK_PlaceID)
 - Venue (FL_PlaceID)

It's much easier to eliminate the Place table in smaller apps and give up some reporting and data integrity benefits. Obviously with thousands of places there is a greater need to avoid duplication and make multiple data changes easier.

The Hotel and Venue tables could have data specific to them and optional over-riding data (billing address) of the Place table. The more you normalize your data like this, the trickier (beyond checking a boolean field) it becomes to determine what venues double as hotel.

If you're suggesting hotels for multiple venues (especially for large events where you run out of space) and need to indicate how far they are, you'll need some sort of Event table that handles the many-to-many relationship with venues and hotels.

Title: Event places - venue and hotel (database design conceptual question)

Body:
Hope this question is right here.

TL;DR

Database design for event places (venue and hotel), hotels can be venues.

Long Version

Introduction

I'm developing a software for trainings. Trainings are like a template with information and events show time and place where a specific training will happen.
Events have a place where they happen, the venue. Events also have an (optional) hotel, where participants can book rooms. A hotel can also be a venue since they often have conference rooms.
So if a hotel is  venue all the contact information and address for the hotel and the venue are obviously the same.

Question

What is the best way to design the database for hotel and venue, so that a hotel can also be a venue.

Target of design:

avoid duplicate data if a hotel is a venue

easy to handle through my software

Possible solutions

one table "Place" with columns "hotel_ID" and "venue_ID" which link to
the tables "Hotel" and "Venue"

one table "place" with an "isHotel" and "isVenue" column indicating which it is

two separate tables "hotel" and "venue" and in hotel table a column "venueID" whch links to a venue?

... (something different)


问:
How to define what fields to check for equality?
I have an odd conceptual question, It's not about a specific incident, just a general best-practices approach.

I have asked myself on occasion when defining java Equal methods, what makes two objects equal.  The simple approach is to check rather every field is equal, however, there are occasions when this isn't always logical.  Here are three examples I could think of when I'm not certain rather a field should be part of an equals method:

transient fields and state data.  Any transient field on a JPA object for example.  or say I have a plugin class with a jar location and some other identification data to uniquely define where to find a plugin to load, and a transient isLoaded Boolean which tells me rather I got around to loading the plugin yet.  Should two references to the same plugin but with different isLoaded variables be equal?

Costly equality checks.  Lets say I have a person that has a family members array.  If I check everyone in the family member array I have to check everyone in their array etc and suddenly my equality method checks every person in memory, and has to check for cycles etc.

Data that may not be loaded at time of equality check.  Lets say I have a JPA object with consists of only two fields, a unique Name, and a UUID field generated by the database.  The name uniquely identifies the row of the database, but the UUID only exists when I load from the database.  How do I check if an Object I want to save  to the database is equal to the ones I already loaded to the database, does the fact that one object doesn't have the UUID that is generated by the database make them unique etc?

I realize that at times it depends on how you plan to use the quality method.  However, in situations where you are writing an object and aren't yet certain how it will be utilized how do you decide what to include in an equal method?  Do you never overwrite one unless you can include every field in the check?

If you need your hash function to behave in a certain manner, which indirectly defines how your equality method should work, but someone could easily assume a different definition of equality does this mean you simply need to notate your equal method well, or is it a code smell that you have done something wrong?

答:
I think if there were a one-size-fits-all way to compare objects, then Java (or any language) would make it the default, no?

Equality - like hashing and comparison - should be fast, simple and most importantly referentially transparent.

In the end, the question of what exactly the equals method is for is important. If you don't know, then just leave it as is. Physical comparison makes sense in many use cases, particularly if you have control over when objects are created vs. when they are reused.

Also, rather than trying to design comparison functions meaningful for all cases, write code using things like Comparator and let calling code inject whatever makes the most sense at the call site.


答:
First of all, there are two kinds of classes:

Classes with "value-type" semantics.

Classes with "reference" semantics.

You can google these terms to find information about precisely what they mean, and how they differ from each other, for your language of choice.

Every single class with "value-type" semantics must have an equals() method, and this method must take into consideration every single one of its fields, or at least give the illusion that it does so. If it is expensive, bite the bullet and spend clock cycles lavishly, because it is necessary.

Classes with "reference" semantics do not need an equals() method.  I would not go as far as to say that they should not have such a method, but if they are to have one, it should be thought of as a utility / helper method which is going to be used in some weird way which is unrelated to the original intent of equals. That's because under normal circumstances, these objects are compared by reference, not by value.

Reference equality is checked using the == operator in Java, while in C#, where the == operator may be overloaded, we use System.Object.ReferenceEquals().  (Though, again, you are not supposed to overload the == operator of a reference-semantics class.)

Incidentally, the kinds of classes that are complex and expensive to check for equality usually tend to be classes with reference semantics, so they do not need an equals() method.  And generally, if you have any doubts or second thoughts as to how the equals() method should be implemented, this is a good indication that what you have in your hands is a reference-semantics class, not a value-type-semantics class.

As for hashCode(), the only objects that should implement it are objects that not only have value semantics, but are also immutable. This is because hash containers generally obtain the hash code of an object once, and then cache it for as long as the object resides in the container, so if the object undergoes a mutation, the contents of the object will be in conflict with the cached hash code.  It is a very common newbie bug to use a non-immutable object as a key to a hashmap, and a very hard one to track down unless you know where to look first: the immutability of the class used as the key.

So, every class which is not immutable should have a hashCode() method coded as follows:

```<code>public int hashCode()
{
    assert false; //OMG! hashCode() was invoked on mutable object!
}
</code>```

So, since only immutable classes should implement hashCode(), ensuring that it works in a way which is in agreement with how equals() works is pretty straightforward, and probably a lot more simple than what you may have feared.

Title: How to define what fields to check for equality?

Body:
I have an odd conceptual question, It's not about a specific incident, just a general best-practices approach.

I have asked myself on occasion when defining java Equal methods, what makes two objects equal.  The simple approach is to check rather every field is equal, however, there are occasions when this isn't always logical.  Here are three examples I could think of when I'm not certain rather a field should be part of an equals method:

transient fields and state data.  Any transient field on a JPA object for example.  or say I have a plugin class with a jar location and some other identification data to uniquely define where to find a plugin to load, and a transient isLoaded Boolean which tells me rather I got around to loading the plugin yet.  Should two references to the same plugin but with different isLoaded variables be equal?

Costly equality checks.  Lets say I have a person that has a family members array.  If I check everyone in the family member array I have to check everyone in their array etc and suddenly my equality method checks every person in memory, and has to check for cycles etc.

Data that may not be loaded at time of equality check.  Lets say I have a JPA object with consists of only two fields, a unique Name, and a UUID field generated by the database.  The name uniquely identifies the row of the database, but the UUID only exists when I load from the database.  How do I check if an Object I want to save  to the database is equal to the ones I already loaded to the database, does the fact that one object doesn't have the UUID that is generated by the database make them unique etc?

I realize that at times it depends on how you plan to use the quality method.  However, in situations where you are writing an object and aren't yet certain how it will be utilized how do you decide what to include in an equal method?  Do you never overwrite one unless you can include every field in the check?

If you need your hash function to behave in a certain manner, which indirectly defines how your equality method should work, but someone could easily assume a different definition of equality does this mean you simply need to notate your equal method well, or is it a code smell that you have done something wrong?

Body:
First of all, there are two kinds of classes:

Classes with "value-type" semantics.

Classes with "reference" semantics.

You can google these terms to find information about precisely what they mean, and how they differ from each other, for your language of choice.

Every single class with "value-type" semantics must have an equals() method, and this method must take into consideration every single one of its fields, or at least give the illusion that it does so. If it is expensive, bite the bullet and spend clock cycles lavishly, because it is necessary.

Classes with "reference" semantics do not need an equals() method.  I would not go as far as to say that they should not have such a method, but if they are to have one, it should be thought of as a utility / helper method which is going to be used in some weird way which is unrelated to the original intent of equals. That's because under normal circumstances, these objects are compared by reference, not by value.

Reference equality is checked using the == operator in Java, while in C#, where the == operator may be overloaded, we use System.Object.ReferenceEquals().  (Though, again, you are not supposed to overload the == operator of a reference-semantics class.)

Incidentally, the kinds of classes that are complex and expensive to check for equality usually tend to be classes with reference semantics, so they do not need an equals() method.  And generally, if you have any doubts or second thoughts as to how the equals() method should be implemented, this is a good indication that what you have in your hands is a reference-semantics class, not a value-type-semantics class.

As for hashCode(), the only objects that should implement it are objects that not only have value semantics, but are also immutable. This is because hash containers generally obtain the hash code of an object once, and then cache it for as long as the object resides in the container, so if the object undergoes a mutation, the contents of the object will be in conflict with the cached hash code.  It is a very common newbie bug to use a non-immutable object as a key to a hashmap, and a very hard one to track down unless you know where to look first: the immutability of the class used as the key.

So, every class which is not immutable should have a hashCode() method coded as follows:

public int hashCode()
{
    assert false; //OMG! hashCode() was invoked on mutable object!
}

So, since only immutable classes should implement hashCode(), ensuring that it works in a way which is in agreement with how equals() works is pretty straightforward, and probably a lot more simple than what you may have feared.


问:
Vertical alignment: yea or nay?
For instance, non-vertically aligned:

```<code>Name:   Hamt
Version:  0.1.0
Cabal-Version:  >= 1.2
License:  BSD3
Author:  Jason Baker
</code>```

Or vertically aligned:

```<code>Name:           Hamt
Version:        0.1.0
Cabal-Version:  >= 1.2
License:        BSD3
Author:         Jason Baker
</code>```

Which do you prefer and why?

答: Personally, I'm of the opinion that the second version of the code is marginally more readable, but I don't think that maintaining it makes up for that readability.  Therefore, I'd only use the second version of this example if I was fairly certain that the code wouldn't change.</p>

Title: Vertical alignment: yea or nay?