答:
Basically we want things to behave sensibly.

Consider the following problem:

I am given a group of rectangles and I want to increase their area by 10%.  So what I do is I set the length of the rectangle to 1.1 times what it was before.

public void IncreaseRectangleSizeByTenPercent(IEnumerable<Rectangle> rectangles)
{
  foreach(var rectangle in rectangles)
  {
    rectangle.Length = rectangle.Length * 1.1;
  }
}
```

<p>Now in this case, all of my rectangles now have their length increased by 10%, which will increase their area by 10%.  Unfortunately, someone has actually passed me a mixture of squares and rectangles, and when the length of the rectangle was changed, so was the width.</p>

<p>My unit tests pass because I wrote all my unit tests to use a collection of rectangles.  I now have introduced a subtle bug into my application which can go unnoticed for months.</p>

<p>Worse still, Jim from accounting sees my method and writes some other code which uses the fact that if he passes squares into my method, that he gets a very nice 21% increase in size.  Jim is happy and nobody is any wiser.</p>

<p>Jim gets promoted for excellent work to a different division. Alfred joins the company as a junior.  In his first bug report, Jill from Advertising has reported that passing squares to this method results in a 21% increase and wants the bug fixed.  Alfred sees that Squares and Rectangles are used everywhere in the code and realises that breaking the inheritance chain is impossible.  He also does not have access to Accounting's source code.  So Alfred fixes the bug like this:</p>

<pre class="lang-cs prettyprint-override"><code>public void IncreaseRectangleSizeByTenPercent(IEnumerable<Rectangle> rectangles)
{
  foreach(var rectangle in rectangles)
  {
    if (typeof(rectangle) == Rectangle)
    {
      rectangle.Length = rectangle.Length * 1.1;
    }
    if (typeof(rectangle) == Square)
    {
      rectangle.Length = rectangle.Length * 1.04880884817;
    }
  }
}
</code>```

Alfred is happy with his uber hacking skills and Jill signs off that the bug is fixed.

Next month nobody gets paid because Accounting was dependent on being able to pass squares to the IncreaseRectangleSizeByTenPercent method and getting an increase in area of 21%.  The entire company goes into "priority 1 bugfix" mode to track down the source of the issue.  They trace the problem to Alfred's fix.  They know that they have to keep both Accounting and Advertising happy.  So they fix the problem by identifying the user with the method call like so:

public void IncreaseRectangleSizeByTenPercent(IEnumerable<Rectangle> rectangles)
{
  IncreaseRectangleSizeByTenPercent(
    rectangles,
    new User() { Department = Department.Accounting });
}

public void IncreaseRectangleSizeByTenPercent(IEnumerable<Rectangle> rectangles, User user)
{
  foreach(var rectangle in rectangles)
  {
    if (typeof(rectangle) == Rectangle || user.Department == Department.Accounting)
    {
      rectangle.Length = rectangle.Length * 1.1;
    }
    else if (typeof(rectangle) == Square)
    {
      rectangle.Length = rectangle.Length * 1.04880884817;
    }
  }
}
```

And so on and so forth.

This anecdote is based on real-world situations that face programmers daily.  Violations of the Liskov Substitution principle can introduce very subtle bugs that only get picked up years after they're written, by which time fixing the violation will break a bunch of things and not fixing it will anger your biggest client.

There are two realistic ways of fixing this problem.

The first way is to make Rectangle immutable.  If the user of Rectangle cannot change the Length and Width properties, this problem goes away.  If you want a Rectangle with a different length and width, you create a new one.  Squares can inherit from rectangles happily.

The second way is to break the inheritance chain between squares and rectangles.  If a square is defined as having a single SideLength property and rectangles have a Length and Width property and there is no inheritance, it's impossible to accidentally break things by expecting a rectangle and getting a square.  In C# terms, you could seal your rectangle class, which ensures that all Rectangles you ever get are actually Rectangles.

In this case, I like the "immutable objects" way of fixing the problem.  The identity of a rectangle is its length and width.  It makes sense that when you want to change the identity of an object, what you really want is a new object.  If you lose an old customer and gain a new customer, you don't change the Customer.Id field from the old customer to the new one, you create a new Customer.

Violations of the Liskov Substitution principle are common in the real world, mostly because a lot of code out there is written by people who are incompetent/ under time pressure/ don't care/ make mistakes.  It can and does lead to some very nasty problems.  In most cases, you want to favour composition over inheritance instead.

Body:
Basically we want things to behave sensibly.

Consider the following problem:

I am given a group of rectangles and I want to increase their area by 10%.  So what I do is I set the length of the rectangle to 1.1 times what it was before.

public void IncreaseRectangleSizeByTenPercent(IEnumerable<Rectangle> rectangles)
{
  foreach(var rectangle in rectangles)
  {
    rectangle.Length = rectangle.Length * 1.1;
  }
}

Now in this case, all of my rectangles now have their length increased by 10%, which will increase their area by 10%.  Unfortunately, someone has actually passed me a mixture of squares and rectangles, and when the length of the rectangle was changed, so was the width.

My unit tests pass because I wrote all my unit tests to use a collection of rectangles.  I now have introduced a subtle bug into my application which can go unnoticed for months.

Worse still, Jim from accounting sees my method and writes some other code which uses the fact that if he passes squares into my method, that he gets a very nice 21% increase in size.  Jim is happy and nobody is any wiser.

Jim gets promoted for excellent work to a different division. Alfred joins the company as a junior.  In his first bug report, Jill from Advertising has reported that passing squares to this method results in a 21% increase and wants the bug fixed.  Alfred sees that Squares and Rectangles are used everywhere in the code and realises that breaking the inheritance chain is impossible.  He also does not have access to Accounting's source code.  So Alfred fixes the bug like this:

public void IncreaseRectangleSizeByTenPercent(IEnumerable<Rectangle> rectangles)
{
  foreach(var rectangle in rectangles)
  {
    if (typeof(rectangle) == Rectangle)
    {
      rectangle.Length = rectangle.Length * 1.1;
    }
    if (typeof(rectangle) == Square)
    {
      rectangle.Length = rectangle.Length * 1.04880884817;
    }
  }
}

Alfred is happy with his uber hacking skills and Jill signs off that the bug is fixed.

Next month nobody gets paid because Accounting was dependent on being able to pass squares to the IncreaseRectangleSizeByTenPercent method and getting an increase in area of 21%.  The entire company goes into "priority 1 bugfix" mode to track down the source of the issue.  They trace the problem to Alfred's fix.  They know that they have to keep both Accounting and Advertising happy.  So they fix the problem by identifying the user with the method call like so:

public void IncreaseRectangleSizeByTenPercent(IEnumerable<Rectangle> rectangles)
{
  IncreaseRectangleSizeByTenPercent(
    rectangles,
    new User() { Department = Department.Accounting });
}

public void IncreaseRectangleSizeByTenPercent(IEnumerable<Rectangle> rectangles, User user)
{
  foreach(var rectangle in rectangles)
  {
    if (typeof(rectangle) == Rectangle || user.Department == Department.Accounting)
    {
      rectangle.Length = rectangle.Length * 1.1;
    }
    else if (typeof(rectangle) == Square)
    {
      rectangle.Length = rectangle.Length * 1.04880884817;
    }
  }
}

And so on and so forth.

This anecdote is based on real-world situations that face programmers daily.  Violations of the Liskov Substitution principle can introduce very subtle bugs that only get picked up years after they're written, by which time fixing the violation will break a bunch of things and not fixing it will anger your biggest client.

There are two realistic ways of fixing this problem.

The first way is to make Rectangle immutable.  If the user of Rectangle cannot change the Length and Width properties, this problem goes away.  If you want a Rectangle with a different length and width, you create a new one.  Squares can inherit from rectangles happily.

The second way is to break the inheritance chain between squares and rectangles.  If a square is defined as having a single SideLength property and rectangles have a Length and Width property and there is no inheritance, it's impossible to accidentally break things by expecting a rectangle and getting a square.  In C# terms, you could seal your rectangle class, which ensures that all Rectangles you ever get are actually Rectangles.

In this case, I like the "immutable objects" way of fixing the problem.  The identity of a rectangle is its length and width.  It makes sense that when you want to change the identity of an object, what you really want is a new object.  If you lose an old customer and gain a new customer, you don't change the Customer.Id field from the old customer to the new one, you create a new Customer.

Violations of the Liskov Substitution principle are common in the real world, mostly because a lot of code out there is written by people who are incompetent/ under time pressure/ don't care/ make mistakes.  It can and does lead to some very nasty problems.  In most cases, you want to favour composition over inheritance instead.


问:
C++ Web Development for REST API
I've been a C# developer for long time, focused on ASP MVC the most. Two years ago, basiclly due to the lower costs and ease of deployment/management I began to migrate my projects to linux using Node.js for serving HTML and Mono for all the backend operations. They talk to each other using HTTP REST API.

As my skills in Linux have improved more and more I find this Node.js/Mono combination kind of weird. Mono is a great thing but there are issues now and then, more related to the implementation itself than the language.

Now I have like three weeks available in between projects and I would like to dive into C++ as my backend. I have tried some Python and I really liked it, but I require fastest responses, that's why C++ came to me. Java is not an option, because although the language itself is pretty close to C#, it has a bunch of stuff I really wouldn't like to bother with (Maven to name one) and at the end of the day, that would decrease my productivity, at least while I become more proefficient on Java (just configuring Eclipse for a Jersey tutorial took me like 2 hours!).

I really don't need anything fancy, since all that node.js does for me is serving html/css/javascript, some real time notifications (socket.io) and that's it. My backends are more reading from tables, complex SQL transformation and validation of the data the client sends. The template engine I use is Jade which is cool since I type less, but I wouldn't mind to switch to plain HTML. 99% of the job in my projects is done using Angular.js via JSON calls. Most of them are single page applications with lots of logic on the client and consuming REST API's.

I really would like to cut all Mono/.NET dependencies and develop on something more native to Linux. At the same time I would like to say goodbye to Node.js as well in trade for one backend to serve my API and static HTML pages.

If you have been here before, please let me know what are the current choices and anything that would help me on this experiment.

Thanks a lot in advance for taking the time to read my concerns.

EDIT: I forgot to mention I read about Casablanca project. It looks promising but again, it belongs to Microsoft under the covers of the white open source, just what I have been avoiding lately.

答:
I recently had to implement some web-server functionality to an existing application and used Mongoose for this (actually I used CivetWeb, the non-GPL version), its very simple embedded web server - add 2 files to your project, read the options, call the server function, and implement a callback for each url route. Trivially easy and its very fast.

eg.

```<code>CivetServer myServer(options);
myServer.addHandler("/route", new CallbackHandlerClass());
</code>```

Then implement a handleGet() method in your handler class. You can get the parameters from the querystring and whatever else you need to do in there.

Its designed for embedded systems but there's no reason it can't work for more feature-rich environments. Obviously, you may have problems in extending your applications as you will have to recompile and then restart the server - no editing a script file and copying it to the server in this kind of compiled, native-code environment, but I guess you're already used to that with .NET

If you do want more, then there are other systems written in C++ that are available. CppCMS comes to mind which does allow dynamic reloading of shared objects so you can change handlers dynamically.

Or you could try the Boost option - boost::asio includes code for a simple http server but I'm not sure you'd want that for production as its single threaded (but that hasn't hurt node.js!)

All in all, after working with the embedded webserver, I think I prefer it simply for its simplicity. All the effort you have to take to get an Apache or IIS environment up and running is gone, its just code a service and run it.

And lastly - check out this SO link that has a link to some benchmarks for several C++ webservers.

ContentLicense: CC BY-SA 3.0

Title: C++ Web Development for REST API

Body:
I recently had to implement some web-server functionality to an existing application and used Mongoose for this (actually I used CivetWeb, the non-GPL version), its very simple embedded web server - add 2 files to your project, read the options, call the server function, and implement a callback for each url route. Trivially easy and its very fast.

eg.

CivetServer myServer(options);
myServer.addHandler("/route", new CallbackHandlerClass());

Then implement a handleGet() method in your handler class. You can get the parameters from the querystring and whatever else you need to do in there.

Its designed for embedded systems but there's no reason it can't work for more feature-rich environments. Obviously, you may have problems in extending your applications as you will have to recompile and then restart the server - no editing a script file and copying it to the server in this kind of compiled, native-code environment, but I guess you're already used to that with .NET

If you do want more, then there are other systems written in C++ that are available. CppCMS comes to mind which does allow dynamic reloading of shared objects so you can change handlers dynamically.

Or you could try the Boost option - boost::asio includes code for a simple http server but I'm not sure you'd want that for production as its single threaded (but that hasn't hurt node.js!)

All in all, after working with the embedded webserver, I think I prefer it simply for its simplicity. All the effort you have to take to get an Apache or IIS environment up and running is gone, its just code a service and run it.

And lastly - check out this SO link that has a link to some benchmarks for several C++ webservers.


问:
How to promote code reuse and documentation?
As a team lead of about 10+ developers, I would want to promote code reuse. We have written a lot of code-- a lot of them are repetitive over the past few years. The problem now is that a lot of these code are just duplicate of some other code or a slight variation of them.

I have started the movement ( discussion) on how to make code into components so that they can be reused for the future projects, but the problem is that I afraid the new developers or other developers who are ignorant of the components will just go forward and write their own thing.

Is there anyway to remind the developers to reuse the components/ improve the documentation/ contribute to the underlying component instead of duplicating the existing code and tweaking on it or just write their own?

How to make the components easily discover-able, easily usable so that everyone will use it?

I think every developer knows about the benefit of reusable components and wants to use them, it's just that we don't know how to make them discoverable. Also, the developers when they are writing code, they know they should write reusable code but lack of the motivation to do so.

答:
I think that this is actually two questions in one - I'll try to answer both.

1) How do we reduce duplicate code in a codebase.

It helps to remind ourself of the benefit of doing this: it results in fewer bugs due to duplicate business logic and less code needs to be maintained.
The best way to reduce this from happening is through communication - as mentioned in the other answers.  I'd strongly agree with the recommendation to use code reviews with the extra caveat that you should share code reviewing responsibilities equally to properly spread the knowledge.  You should also use daily stand-ups so that developers will often recognise when someone is trying to solve a problem for which there is existing useful code.  You should also consider code pairing as it increases knowledge sharing and helps to keep programmers disciplined.

I'd also recommend getting your developers as close together as possible, preferably in the same room.  With lots of shared whiteboards and space.  Then send them out for meals together.  The more your developers "bond" the better they'll communicate with each other.

I don't agree with the recommendation to use a wiki or similar to document code.  No matter how disciplined developers try to be the documentation will drift from the original code.  A more effective approach would be the use of specification by example style tests.  These document the code in a way that makes it clear how it should be used and your tests will fail if someone changes the code without changing the examples.

You already have a large codebase with lots of duplicate code so you should probably work on refactoring this out.  It can be difficult to find duplicate code that wasn't cut and pasted.  So rather than do that I suggest you analyse your change history.  Look for files that often change at the same time.  This will probably indicate problems with encapsulation if it doesn't indicate actual duplicate code and is worth cleaning up anyway.  If you can also analyse your bug fix history against your code changes you may find particular hotspots where fixes are often necessary.  Analyse these hotspots and you'll probably find many of them are due to duplicate business logic which a developer has only changed in one place not realising it needed changed twice.

2) How should we approach making shared widgets, components, libraries, etc that can then be used in other projects.

In this case you should not be trying to wrap business logic but share useful framework code.  This can be a tricky balance as the cost of creating and maintaining a set of shared components can be quite large and it can be difficult to predict in which instances it is worth doing.  The approach I'd suggest here is a three strikes rule.  Don't worry about writing a similar piece of code twice but when you need to do it a third time refactor it into a shared component.  At this point you can be reasonably sure it will be useful and you have a good idea of the broader requirements for the component.  Obviously, communication between developers is vital here.

Consider making as many of your shared component open source as possible.  It isn't business logic so it won't give your competitors much advantage but it means you'll get extra reviewers and maintainers for free.


问:
Is it good style to check explicitly for null in unit tests?
Whether or not a value is null could be checked implicitly like this:

```<code>assertThat(value).isEqualTo("something");
</code>```

Or it could be checked explicitly:

```<code>assertThat(value).isNotNull();
assertThat(value).isEqualTo("something");
</code>```

The latter makes the expectations a bit more clear, but it blows up the test code.

Is there a good reason to prefer the second approach over the first?

答:
It depends entirely on your general strategy and workflow of using unit tests.

Strict TDD advocates don't care very much precisely what happens when a unit test fails. A NullPointerException is as good as a AccountBalanceViolation to them. Some even advocate writing tests that don't even compile initially, and to treat the compile error as a normal failure that triggers creation of the next bit of business code. All that matters is that the bar is red, and you write code to get it green.

If you are more concerned about readability of test output (perhaps you fear that someone totally else will one day work with the code base, or maybe you are refactoring legacy code that doesn't have any tests), then it can be worthwhile to make sure that if a unit test fails, it will pinpoint the problem as exactly as possible.

In this case, seeing a null reference problem rather than a failed equality is somewhat less clear. But it isn't very much less clear; I don't think it is worth doubling the size of the test. In general, though, it can be.


答:
I suppose it ultimately comes down to preference.  Technically if you're not testing if a particular value is null, then you should test it assuming it isn't null.  The test will fail all the same, but there's the subtle difference that you didn't anticipate it in your test, so it is a bit like saying "There is something seriously wrong here."

Most times, null is a possibility when things go wrong, so I check explicitly.  If testing that the result is null is worth its own test, then I make an entire test testing just that.  Other tests which require that it isn't null don't check.  Ultimately it all fails, but at least in my humble opinion, it is clearer what I expect to test in this way.

Title: Is it good style to check explicitly for null in unit tests?

Body:
Whether or not a value is null could be checked implicitly like this:

```<code>assertThat(value).isEqualTo("something");
</code>```

Or it could be checked explicitly:

```<code>assertThat(value).isNotNull();
assertThat(value).isEqualTo("something");
</code>```

The latter makes the expectations a bit more clear, but it blows up the test code.

Is there a good reason to prefer the second approach over the first?


问:
Code Documentation First?
Has anyone ever tried creating a complete code documentation first, before actually writing the code? I was thinking about this earlier because I thought it would help to write a concrete interface and would make sure your initial design wasn't floored by making you think about how classes interact. Is this a good idea? Has anyone tried it? Ell</p>

答:
Writing the complete code documentation first is probably overkill and somewhat reminiscent of the waterfall methodology. However, I've found that a more pragmatic approach is writing the README first. Here's why:

The README does not document every detail of your project. Instead, it typically contains the following info:

Description: short "sales pitch". Tell the reader why they should keep reading.

Quick examples: short code snippets or screenshots to support the description.

Quick start: how to get going, install instructions, and more examples.

Further documentation: links to the full docs and more info.

Project organization: who are the authors, how to contribute, how to file bugs.

Legal notices: license, copyright, and any other legal details.

Writing the "sales pitch" up front forces me to be crystal clear about why this project should exist and why developers should use it. The mere act of writing full sentences to describe the project often changes it for the better: you understand it better, develop new ideas, and uncover potential problems. It's also a great prioritization tool: anything in the "sales pitch" is a must-have!

The "quick examples" and "quick start guide" force me to think through the key use cases from the user's perspective. I've found that doing this before writing any code - before being bogged down in implementation details and tight deadlines - leads to much cleaner APIs and designs. Remember: programs should be written for people to read, and only incidentally for machines to execute (SICP).

In "further documentation", I create an outline of the pieces that will need detailed documentation, to be done later. "Project organization" lets me figure out who will work on the project and the coding practices. "Legal notices"... well, may as well get those out of the way too.

Once you have this basic README in place, you have a document that's useful for discussion, design reviews, dividing up the work, and project planning. As you work on the project, frequently check back with the README to make sure you're still on track. Also, incrementally updating the README and the "further documentation" as you go means all your documentation will be done when the code is done, which is a much more pleasant experience than having to rush through documenting everything last minute.

For more info, check out the following:

Readme Driven Development

The most important code isn't code

You are what you document

ContentLicense: CC BY-SA 2.5

Title: Code Documentation First?


问:
Should we write a unit test for class that call another class that have code written
Suppose that there are two class 'A' and 'B'

'A' has a lot of nested conditions that have all unit test covered.

'B' has a property that will call class 'A' and return value according to the result of class 'A'

On class 'B', when i want to write unit test. Should i just mock class A and verify on class B that it has been called a specific class 'A' method.

答:
In general, yes. The point of a unit test for B is to demonstrate that method B.b() does its job given the appropriate collaborators. If there were a problem within A, it should already be discovered by the unit test for A, so duplicating this check in the test for B is wasted effort. Just go ahead and supply a MockA that you can query to demonstrate that A.a() was, in fact, called.

In practice, for small classes and methods it can become more effort to supply mocks for every collaborator than just to go ahead and test the result of B.b() for correctness. Strictly speaking, this is no longer a unit test because it depends on other classes, but since the major point of keeping tests small and focused is to save development effort without compromising correctness, I don't see why you shouldn't use the already-verified functionality of A to write a smaller, neater test for B.


问:
Are the following Use Case Levels determined correctly?
I am confused about use case levels. All I could understand was that use cases that are contained in another use case fall under the level which is below the level of the container use case.

I have identified the following use cases for an e-commerce store and I would like to know if their levels are correctly determined or not. Please provide a description of the differences between levels if I have done something wrong here.

答:
I'd just like to second Oliver's answer. To log in doesn't usually define a business goal: it is an implementation scenario subservient to some business goal. People don't go home at the end of the day and say, "Honey, I had a great day at work — I logged in 36 times!"

Alistair Cockburn frames his use cases in a goal (hence, "goal-driven use cases") and most good use case practice follows his vision.

Habits are a developer tool used to remember recurring sequences of implementation (usually code) and to remember how they fit into the overall flow during analysis. They came out of my work together with Gertrud Bjørnvig and Trygve Reenskaug on the DCI paradigm, which is a way to bridge the mental models of both end users and developers into the code.

Our (Gertrud's and my) own position — based on quite a bit of experience — is that decomposing use cases only confuses those who most need to buy in to what they say: the end user. While Jacobsson's original vision of formal use case relationships such as "refine" and "extend" have nice formal semantics, requirements acquisition in the end is a necessarily informal activity rife with inconsistency, innuendo and context. Hence, we recommend using use cases not to communicate requirement mandates from some market oracle to the team, but only to structure and document the conversations and decisions that arise between product management and development in an open dialog with very short-loop feedback.


答:
If your method under test is supposed to return null, test for that explicitly. If it isn't supposed to return null, returning null is an error condition and should be handled as such by your test.

Same with not-null, or indeed anything at all.


问:
How much effort should be put in each part of a waterfall project?
Where waterfall commonly includes:

Requirements

Functional design

Technical design

Build

Test

Review

(Deploy)

And iterations across this list. If I forgot a step, let me know.

答:
The best (and probably sole remain relevant) part of the (sadly now outdated) Mythical Man Month is P.20 which breaks down a projects time into 1/3 planning, 1/6 coding, 1/4 component test and 1/4 system test, a very good split which is sadly all too little adhered to.

Requirements

Functional design

Technical design

Build

Test

Review

(Deploy)

You can split these all, or group 2 & or 1,2 & 3

Does 4) build include unit test? What is 5) test? Unit test, software integration, system integration?

6) Review is a subset of 1, 2, and 3

Is writing of unit test specs part of 3) Technical design?

I think that you need to think a lot more about what these things mean, and to add some granularity.

Congratulations, though, on thinking about this, all too few people do.


问:
Image coordinates calculation algorithm
I was looking at Jcrop library code for scaled image size calculation, but I couldn't clearly understand algorithm used in following function:

https://github.com/tapmodo/Jcrop/blob/master/js/jquery.Jcrop.js#L187

```<code>function presize($obj, w, h)
{
  var nw = $obj.width(),
      nh = $obj.height();
  if ((nw > w) && w > 0) {
    nw = w;
    nh = (w / $obj.width()) * $obj.height();
  }
  if ((nh > h) && h > 0) {
    nh = h;
    nw = (h / $obj.height()) * $obj.width();
  }
  xscale = $obj.width() / nw;
  yscale = $obj.height() / nh;
  $obj.width(nw).height(nh);
}
</code>```

I know that its using jquery image object and boxWidth and boxHeight as described on following link:

http://deepliquid.com/content/Jcrop_Sizing_Issues.html

But I want to understand the algorithm used.

答:
I used some simple values to check how it works. My understanding:

If the required height and width are greater than the object's height and width, it does nothing.

If the required width is less than the object width, assume the new width to the required width. Calculate the new height based on the proportion of required and current object width.

If the calculated height above is greater than the required height, assume the new height to the required height. Calculate the new width based on the proportion of required and current object height.

Current: 100, 50 Required: 200, 100 => do nothing

Current: 200, 100 Required: 100, 50 => reduce the width and height by 50%

Current: 200, 100 Required: 100, 40 => reduce the width and height by 40%

Current: 200, 100 Required: 100, 60 => reduce the width and
height by 50%

Current: 200, 100 Required: 300, 60 => reduce the
width and height by 60%

Title: Image coordinates calculation algorithm


问:
Can I create a query which allows me to do this?
I have a table which stores user information, one column stores their ID. I had implemented four different attributes in the same table which stored a bit indicating which file operations that user could perform (read, create, update, delete).

Thankfully, I realized that was terrible implementation and instead created four different tables with one column (the userID) which indicated which actions they could perform. It's really about me being annoyed by the over-whelming number of zeros. It does save on space, even if it's negligible.

However, this database is also queried by an application in an OOP language, and one of the objects frequently created is a User. This class naturally stores which file operations the User can perform. In the old implementation, these (boolean-valued) object fields could be quickly populated from the user table, but not now.

Now I'm confused on how I should populate these object fields. I feel like I should be able to perform a single query telling me which permission tables the user belongs to, but cannot find the write syntax (if it even exists).

So my question is: is there a way to perform a single query to figure out which tables (which only consist of a single column) a value occurs in? Or do I have to query each table independently to fill these object fields?

答:
It's not a good idea to separate those attributes to their own tables. It makes your data unorganized.

If your attributes are simple boolean type, you can combine them as one numeric value.
Just think of each attribute as a specific bit position.

For example

read : 1st bit

create : 2nd bit

update : 3rd bit

delete : 4th bit

Use the binary or operator to create your attribute value.

read + update = 1 | 4 = 5

read + delete = 1 | 8 = 9

To query, you may use this syntax

- find all user with update attribute:

  select * from table1 where (attribute & 4) = 4

- find all user with delete attribute:

  select * from table1 where (attribute & 8) = 8


问:
Writing in C for Performance?
I know I have quite frequently heard that C typically has a performance advantage over C++. I didn't really think anything else of it until I realized that MSVC doesn't even seem to support the newest standard of C, but the newest it supports it C99 (as far as I know).

I was planning on writing a library with some code to render in OpenGL so I could reuse it. I was planning to write the library in C since any performance increase is welcome when it comes to graphics.

But would it really be worth it? The code using the library would likely be written in C++ and I prefer to code in C++ generally.

However, if it would produce even a small difference in performance, I would likely go with C.

It may also be noted that this library would be something that I would make to work across Windows/OS X/Linux, and I would likely compile everything natively (MSVC for Windows, Clang or GCC for OS X, and GCC for Linux...or possibly Intel's compilers for everything).

I've looked around and I've found some benchmarks and such, but everything I've seen has dealt with GCC rather than MSVC and Clang. Also, the benchmarks don't mention the standards of the languages used. Anyone have any thoughts on this?

EDIT: I just wanted to share my viewpoint on this question after a couple years more experience. I ended up writing the project I was asking this question for in C++. I started another project around the same time in C as we were looking to get out any small amount of performance we could and needed the project to be linkable in C. A couple months ago, I reached the point where I really needed maps and advanced string manipulation. I knew of the abilities for this in the C++ standard library and eventually came to the conclusion that those structures in the standard library would likely outperform and be more stable than maps and strings I could implement in C in a reasonable amount of time. The requirement to be linkable in C was easily satisfied by writing a C interface to the C++ code, which was done quickly with opaque types. Rewriting the library in C++ seemed to go much faster than when writing it in C and was less prone to bugs, especially memory leaks. I was also able to use the standard library threading library, which has been much easier than using platform-specific implementations. In the end, I believe writing the library in C++ led to great benefits with possibly a small performance cost. I haven't benchmarked the C++ version yet, but I believe that it may even be possible that I have gained some performance by using standard library data structures than ones I wrote.

答:
One reason that higher level languages are sometimes slower is that they can hide behind the scenes a lot more memory management than lower level languages.

Any language (or library, API, etc) that abstracts away low level detail can potentially be hiding costly operations. For example, in some languages simply trimming trailing whitespace from a string results in a memory allocation and a copy of the string. Memory allocation and copying in particular can get expensive if they are happening repeatedly in a tight loop.

If you wrote this kind of code in C it would be blatantly obvious. In C++ possibly less so, because the allocations and copying could be abstracted away into a class somewhere. They might even be hidden behind an innocent-looking overloaded operator or copy constructor.

So use C++ if you want to. But don't be beguiled by the seeming convenience of abstractions when you don't know what lies beneath them.

Of course, use a profiler to find out what is really slowing your code down.

Title: Writing in C for Performance?


答:
In general, it depends.

Specifically, I would say it depends on whether the dependended-on class A is encapsulated or injected.

In the first case, you are testing 'does B work?' In the second, it is more 'can B work, given a suitable A?'.

Getting this distinction wrong, in either direction, is a fairly common cause of bad tests, whether it is overly fragile mocks, test duplication/coupling, or missed integration issues.

Some would perhaps say 'never encapsulate', but if you took them seriously, you would end up mocking the likes of RegExp and BigInteger, which can't be sensible.

Of course, this is something of a chicken-and-egg situation, as how you are going to test B always has at least some influence on how it is designed.

Title: Should we write a unit test for class that call another class that have code written

Body:
Suppose that there are two class 'A' and 'B'

'A' has a lot of nested conditions that have all unit test covered.

'B' has a property that will call class 'A' and return value according to the result of class 'A'

On class 'B', when i want to write unit test. Should i just mock class A and verify on class B that it has been called a specific class 'A' method.


问:
Interface hierarchy design for separate domains
There are businesses and people. People could be liked and businesses could be commented on:

```<code>class Like
class Comment

class Person implements iLikeTarget
class Business implements iCommentTarget
</code>```

Likes and comments are performed by a user(person) so they are authored:

```<code>class Like implements iAuthored
class Comment implements iAuthored
</code>```

People's like could also be used in their history:

```<code>class history
class Like implements iAuthored, iHistoryTarget
</code>```

Now, a smart developer comes and says each history is attached to a user so history should be authored:

```<code>interface iHistoryTarget extends iAuthored
</code>```

so it could be removed from class Like:

```<code>class Person implements iLikeTarget
class Business implements iCommentTarget

class Like implements iHistoryTarget
class Comment implements iAuthored

class history

interface iHistoryTarget extends iAuthored
</code>```

Here, another smart guy comes with a question: How could I capture the Authored fact in Like and Comment classes? He may knows nothing about history concept in the project.

By scalling these kind of functionallities, interfaces may goes to their encapsulated types which cause more type strength, on the other hand explicitness suffered and also code end users will face much pain to process.
So here is the question:
Should I encapsulate those dependant types to their parent types (interface hierarchies) or not or explicitly repeat each type for every single level of my type system or ...?

答:
I would say being an authored object is independent of being a history item so the way to reflect the domain more closely would be:

class Like implements iHistoryItem, iAuthored

This says that even if Like was not a history item, it would still be an authored action.


问:
How to refactor code that has 2 concerns
Say I have this code:

```<code>        if ($this->ship == "e") {
            $this->price->addLine($this->price->base * $this->price->e, 0, "Export");
            $this->price->total += $this->price->base * $this->price->e;

        } elseif ($this->ship == "d") {
            $this->price->addLine($this->price->base * $this->price->d, 0, "Domestic");
            $this->price->total += $this->price->base * $this->price->d;
        }
</code>```

I have multiple identical blocks of code like the above.  I also have other code (other than $this->ship) that is similar in structure.  Basically, this code adds a Line to a PDF, where the line says "Domestic" or "Export" along with other options.   The code above also computes price for that line and adds it to the total.

My thoughts on refactoring this:

I want to remove duplication.  I also want to abide by SOLID principles, i.e. separation of concerns.   I see that code above does two things (computes price and adds a line item to PDF).  I can surely split this code into two separate functions, but then I still end up with duplicated code -- I need to check if  $this->ship equals e or d in both places.  That is no good.  If I need to add a 3rd option, I have to change code in two places.

So then I can move my check for e or d into the main body of code, but still I have duplication because I will have

```<code>switch($this->ship)
{
    case 'd': $cost = $this->getShippingCost($this->price->base, $this->price->d);break;
    case 'e': $cost = $this->getShippingCost($this->price->base, $this->price->e);break;
}
</code>```

I get these two long lines of code for basically a single character change.  While maybe it is kind of acceptable, I am not quite liking it.  If I need to change the number of parameters for example, or base parameter or etc, I will need to change it in more than one place.

Basically, so far no matter what way I spin this code, I end up with some duplication somewhere.  I mean if it is unavoidable, I guess it's okay.  But here I come for advice on seeing if there is a way to separate the concerns, and remove duplication and have minimal number of places (ideally one) when I do need to change something.  can this be done?

答:
It is hard produce any really solid refactoring advice based on a few lines of code out of context, but in general don't worry too much about a few almost-identical lines, it is not a practical problem.

In some cases it may be a sign of bad design, simple duplication elimination will however only serve to hide the problem.

In your case, I can't imagine how you end up with that code, how can $this contain both the cumulative total and the price for individual items, with those items apparently not even being stored in an array? I think you have got way bigger problems than a few duplicate lines. It would seem that you have tried to use OOP without really being prepared for it. The typical result of that is spaghetti code with objects.

If you want a deeper analysis of your code I suggest that you write a post on Code Review.


问:
Diagram to express parallelism in a process workflow
I'm modelling part of a software architecture on which several processes run as a workflow. The architecture involves data parallelism, where a certain serial process produces N pieces of data which need to be distributed to N processes that must run in parallel.

I'm looking for a good way of expressing parallelism in a diagram. The objective of this diagram is to be informative and will be included in a paper about the system architecture. It does not need to be a formal model or strictly follow UML.

I've drawn 3 ways of representing the parallelism, one of which (2) basically follows the UML 2.0 Activity Diagram. I would like to know which one, if any, will more clearly convey the parallelism. What other information this sort of diagram should include?

答:
If there is standard way to represent something, you should use it.

I suppose that your audience has the minimum of technical knowledge required to understand your document. Therefore, I can reasonably suppose that your audience should have basic knowledge of UML so the diagram should be self-explaining. If you use your own convention you will have to also document it.


答:
I guess people often claim that C is faster than C++ because it's easier to reason about performance in C. C++ is not inherently slower or faster, but certain C++ code might obscure hidden performance penalties. For example, there can be copies and implicit conversions which are not immediately visible when looking at some piece of C++ code.

Let's take the following statement:

```<code>foo->doSomething(a + 5, *c);
</code>```

Let's further assume that doSomething has the following signature:

```<code>void doSomething(int a, long b);
</code>```

Now, let's try to analyse this particular statement's possible performance impact.

In C, the implications are quite clear. foo can only be a pointer to a struct, and doSomething must be a pointer to a function. *c dereferences a long, and a + 5 is integer addition. The only uncertainty comes from the type of a: If it's not an int, there will be some conversion. but apart from that, it's easy to quantify the performance impact of this single statement.

Now let's switch to C++. The same statement can now have very different performance characteristics:

doSomething could be a non-virtual member function (cheap), virtual member function (a little more expensive), std::function, lambda... etc. What's worse, foo could be a class type overloading operator-> with some operation of unkown complexity. So in order to quantify the cost of calling doSomething, it's now necessary to know the exact nature of foo and doSomething.

a could be an integer, or a reference to an integer (additional indirection), or a class type which implements operator+(int). The operator could even return another class type which is implicitly convertible to int. Again, the performance cost is not apparent from the statement alone.

c could be a class type implementing operator*(). It could also be a reference to a long* etc.

You get the picture. Due to C++'s language features, it is much harder to quantify a single statement's performance costs than it is in C. Now in addition, abstractions like std::vector, std::string are commonly used in C++, which have performance characteristics of their own, and hide dynamic memory allocations (also see @Ian's answer).

So, bottom line is: In general, there's no difference in the possible performance achievable using either C or C++. But for really performance-critical code, people often prefer using C because there are way less possible hidden performance penalties.

Title: Writing in C for Performance?

Body:
I know I have quite frequently heard that C typically has a performance advantage over C++. I didn't really think anything else of it until I realized that MSVC doesn't even seem to support the newest standard of C, but the newest it supports it C99 (as far as I know).

I was planning on writing a library with some code to render in OpenGL so I could reuse it. I was planning to write the library in C since any performance increase is welcome when it comes to graphics.

But would it really be worth it? The code using the library would likely be written in C++ and I prefer to code in C++ generally.

However, if it would produce even a small difference in performance, I would likely go with C.

It may also be noted that this library would be something that I would make to work across Windows/OS X/Linux, and I would likely compile everything natively (MSVC for Windows, Clang or GCC for OS X, and GCC for Linux...or possibly Intel's compilers for everything).

I've looked around and I've found some benchmarks and such, but everything I've seen has dealt with GCC rather than MSVC and Clang. Also, the benchmarks don't mention the standards of the languages used. Anyone have any thoughts on this?

EDIT: I just wanted to share my viewpoint on this question after a couple years more experience. I ended up writing the project I was asking this question for in C++. I started another project around the same time in C as we were looking to get out any small amount of performance we could and needed the project to be linkable in C. A couple months ago, I reached the point where I really needed maps and advanced string manipulation. I knew of the abilities for this in the C++ standard library and eventually came to the conclusion that those structures in the standard library would likely outperform and be more stable than maps and strings I could implement in C in a reasonable amount of time. The requirement to be linkable in C was easily satisfied by writing a C interface to the C++ code, which was done quickly with opaque types. Rewriting the library in C++ seemed to go much faster than when writing it in C and was less prone to bugs, especially memory leaks. I was also able to use the standard library threading library, which has been much easier than using platform-specific implementations. In the end, I believe writing the library in C++ led to great benefits with possibly a small performance cost. I haven't benchmarked the C++ version yet, but I believe that it may even be possible that I have gained some performance by using standard library data structures than ones I wrote.

Body:
I guess people often claim that C is faster than C++ because it's easier to reason about performance in C. C++ is not inherently slower or faster, but certain C++ code might obscure hidden performance penalties. For example, there can be copies and implicit conversions which are not immediately visible when looking at some piece of C++ code.

Let's take the following statement:

foo->doSomething(a + 5, *c);

Let's further assume that doSomething has the following signature:

void doSomething(int a, long b);

Now, let's try to analyse this particular statement's possible performance impact.

In C, the implications are quite clear. foo can only be a pointer to a struct, and doSomething must be a pointer to a function. *c dereferences a long, and a + 5 is integer addition. The only uncertainty comes from the type of a: If it's not an int, there will be some conversion. but apart from that, it's easy to quantify the performance impact of this single statement.

Now let's switch to C++. The same statement can now have very different performance characteristics:

doSomething could be a non-virtual member function (cheap), virtual member function (a little more expensive), std::function, lambda... etc. What's worse, foo could be a class type overloading operator-> with some operation of unkown complexity. So in order to quantify the cost of calling doSomething, it's now necessary to know the exact nature of foo and doSomething.

a could be an integer, or a reference to an integer (additional indirection), or a class type which implements operator+(int). The operator could even return another class type which is implicitly convertible to int. Again, the performance cost is not apparent from the statement alone.

c could be a class type implementing operator*(). It could also be a reference to a long* etc.

You get the picture. Due to C++'s language features, it is much harder to quantify a single statement's performance costs than it is in C. Now in addition, abstractions like std::vector, std::string are commonly used in C++, which have performance characteristics of their own, and hide dynamic memory allocations (also see @Ian's answer).

So, bottom line is: In general, there's no difference in the possible performance achievable using either C or C++. But for really performance-critical code, people often prefer using C because there are way less possible hidden performance penalties.


问:
Why would Square inheriting from Rectangle be problematic if we override the SetWidth and SetHeight methods?
If a Square is a type of Rectangle, than why can't a Square inherit from a Rectangle? Or why is it a bad design?

I have heard people say:

If you made Square derive from Rectangle, then a Square should be
  usable anywhere you expect a rectangle

What is the problem here? And why would Square be usable anywhere you expect a rectangle? It would only be usable if we create the Square object, and if we override the SetWidth and SetHeight methods for Square than why would there be any issue?

If you had SetWidth and SetHeight methods on your Rectangle base class
  and if your Rectangle reference pointed to a Square, then SetWidth and
  SetHeight don't make sense because setting one would change the
  other to match it. In this case Square fails the Liskov Substitution
  Test with Rectangle and the abstraction of having Square inherit from
  Rectangle is a bad one.

Can someone explain the above arguments? Again, if we over-ride SetWidth and SetHeight methods in Square, wouldn't it resolve this issue?

I have also heard/read:

The real issue is that we are not modeling rectangles, but rather
  "reshapable rectangles" i.e., rectangles whose width or height can be
  modified after creation (and we still consider it to be the same
  object). If we look at the rectangle class in this way, it is clear
  that a square is not a "reshapable rectangle", because a square cannot
  be reshaped and still be a square (in general). Mathematically, we
  don't see the problem because mutability doesn't even make sense in a
  mathematical context

Here I believe "re-sizeable" is the correct term. Rectangles are "re-sizeable" and so are squares. Am I missing something in the above argument? A square can be re-sized like any rectangle.

答:
If all your objects are immutable, there is no problem. Every Square is also a Rectangle. All the properties of a Rectangle are also properties of a Square.

The problem begins when you add the ability to modify the objects. Or really - when you start passing arguments to the object, not just reading property getters.

There are modifications that you can do to a Rectangle that maintain all the invariants of your Rectangle class, but not all Square invariants - like changing the width or height. Suddently the behavior of a Rectangle isn't just its properties, it is also its possible modifications. It's not just what you get out of the Rectangle, it's also what you can put in.

If your Rectangle has a method setWidth that is documented as changing the width and not modifying the height, then Square cannot have a compatible method. If you change the width and not the height, the result is no longer a valid Square. If you chose to modify both width and height of the Square when using setWidth, you are not implementing the specification of Rectangle's setWidth. You just can't win.

When you look at what you can "put into" a Rectangle and a Square, what messages you can send to them, you'll likely find that any message you can validly send to a Square, you can also send to a Rectangle.

It's a matter of co-variance vs. contra-variance.

Methods of a proper subclass, one where instances can be used in all cases where the superclass is expected, requires each method to:

Return only values that the superclass would return - that is, the return type must be a subtype of the superclass method's return type. Return is co-variant.

Accept all values that the supertype would accept - that is, the argument types must be supertypes of the superclass method's argument types. Arguments are contra-variant.

So, back to Rectangle and Square: Whether Square can be a subclass of Rectangle depends entirely on which methods Rectangle have.

If Rectangle has individual setters for width and height, Square won't make a good subclass.

Likewise, if you make some methods be co-variant in the arguments, like having compareTo(Rectangle) on Rectangle and compareTo(Square) on Square, you will have a problem using a Square as a Rectangle.

If you design your Square and Rectangle to be compatible, it will likely work, but they should be developed together, or I'll bet that it won't work.


答:
The performance difference between C++ and C is not due to anything in the language,
strictly speaking,
but in what it tempts you to do.
It's like a credit card vs. cash.
It doesn't make you spend more, but you do anyway, unless you're very disciplined.

Here's an example of a program written in C++, which was then aggressively performance tuned.
You need to know how to do aggressive performance tuning, regardless of language.
The method I use is random pausing, as shown in this video.

The kinds of costly things C++ tempts you to do are excessive memory management, notification-style programming, trusting your program counter to multi-layered abstraction libraries (as @Ian said), slowness hiding, etc.

Title: Writing in C for Performance?


问:
Is a large increase in velocity realistic in a Scrum environment?
My manager has recently really been pushing to use velocity as a target and measure of productivity. We are currently working at an average velocity of 50 story points. My manager wants us to increase it by 40% to 70 story points (with no increase in team members). If we don't achieve this increase he wants us to deliver a full break down explaining why.

The whole idea of measuring team performance by velocity and using it as a target seems wrong to me, but I am finding it difficult to explain why. Any help? Why isn't this the right way to measure and incentivize productivity?

答:
Well, I'm a bit surprised that the other answers take the boss' request seriously.  Someone who demands a 40% increase in productivity doesn't know the first thing about software development.

I still enjoy reading Phil Factor on this topic:

There are two basic routes into IT management. You can learn your
  trade through blood, sweat and tears and work your way up the ladder
  gradually, based on the credibility you've gained from hard-earned
  technical know-how and successful projects. Alternatively, you can don
  a sharp suit and tie, learn the lingo, and smooth talk your way to the
  top.

Both routes seem equally effective. Dealing with the latter breed
  can certainly cause some moments of dismay and incredulity… despair
  even… and some of that is documented in these stories.

However, it's easy to become sad and embittered when one
  encounters technical incompetence in positions of power, and to tar all
  managers with that same brush. Phil advises against it. Most managers
  work hard and contribute well to the company, and even poor managers
  can be trained up to the required standard, if you just follow a few
  simple guidelines. It's part of your team responsibility to help your
  manager function in a way that will benefit all.

Ultimately, if you can't train them, get them promoted, or avoid them,
  maybe you can learn to love them just for their unintended
  contribution to the rich comedy of the workplace.

The advise not to become "sad and embittered" is the best you can get.  Don't fight a technically incompetent boss over technical matters.  He'll just see that as a personal attack.


问:
Enforcing coding standards: What are the trade-offs of different methods?
Our team has recently agreed on some very light coding standards, and that we need a means of enforcing them. We already have a mature Continuous Integration practice including frequent, small check-ins and pre-tested commits.

We're considering two methods for implementing an enforcement mechanism: a pre-commit SVN hook, or a dedicated build configuration on the CI server. Here's the trade-offs we've considered so far:

An SVN hook ...

(-) requires SVN server admin privileges to setup, which we don't have. We can work with IT, but avoiding the overhead is nice.

(-) points to a script, which we'd like to keep under version control with the rest of the product. I don't immediately know how to point at the correct hook-script, taking into account branches, tags, and trunk work.

(-) requires more work for reporting. The script would need to handle both generating and publishing the report.

(+) gives quick feedback.

(+/-) provides hard enforcement: the code checks-in, or it doesn't . Usually a good thing (it's called "enforcement" for a reason), but may give false positives.

The CI build configuration ...

(-) consumes time on both the CI server and an agent. Might be trivial, but does add up.

(-) introduces some extra latency, making feedback less immediate.

(+) easily handles standards that evolve over time, by pointing to the version of the script that exists in whichever branch we're working on.

(+) provides easier reporting. We already use the CI system for other reports. Adding a new one would be straight-forward.

(+) configurable enforcement: easier to soften the requirements, if necessary. We could collect a list of violations to fix out-of-band, or provide warnings about standards we're adopting on a trial basis.

What are the trade-offs of these different methods in enforcing coding standards here?

Related: Should coding standards be enforced by the CI server? - Raises some good points, but doesn't consider SVN hooks.

答:
The svn-commit hook approach will have problems scaling beyond anything more than 'no tabs/leading spaces in file', 'right type of new line characters' and perhaps 'indentation is not completely borked'. Otherwise you will:

upgrade your tool or configuration

want to make some trivial, urgent change to a file

be unable to do so without entirely rewriting it to clean up everything that is no longer current best practise.

As a result of which you will likely never be able to upgrade your coding standards. Which may be ok now, but will suck by 2020 or so...

Kept to that simple level, hooks are still pretty useful though. Keeping such problems entirely out of your history can simplify diffs.


答:
The second way you depict not only follows the UML 2.x activity diagram notation but is also used in the Petri net formal modeling language. Indeed Petri net formalism is the source of UML 2.x activity diagram notation.

Using a Petri-net-like semantic for representing parallelism increases the potential audience who can understand your diagrams.

At the opposite, I read the third way as a choice among several options, just like a state machine.

Finally in my opinion, the first way just looks confuse and amateurish.

Title: Diagram to express parallelism in a process workflow

Body:
I'm modelling part of a software architecture on which several processes run as a workflow. The architecture involves data parallelism, where a certain serial process produces N pieces of data which need to be distributed to N processes that must run in parallel.

I'm looking for a good way of expressing parallelism in a diagram. The objective of this diagram is to be informative and will be included in a paper about the system architecture. It does not need to be a formal model or strictly follow UML.

I've drawn 3 ways of representing the parallelism, one of which (2) basically follows the UML 2.0 Activity Diagram. I would like to know which one, if any, will more clearly convey the parallelism. What other information this sort of diagram should include?


问:
How to take things step by step
This is about the third time I've had to write software to control a cellular modem.  For those unfamiliar with the process, you have a sequence of steps you have to take.  Each step takes a certain amount of time, and there's a few responses you should receive in that amount of time.  There are also some responses you can receive at any time, regardless of the step you are on.  Based on the response you have to go to another stage in the process.  If it times out, you have to go to a different stage. In some cases, steps are attempted multiple times before going to another stage.

These have to be non-blocking functions, which I can run as a task on a single threaded machine.  So the main program would be calling this modemTask() a few hundred times a second, it checks whether it needs to do something, then performs a function if needed, and exits.

In the past I've written this as a simple switch based state machine, with enumerated stages, somewhat like the following:

```<code>switch(stage){
   case Power:
      powerOn();                 // Turn the modem on
      nextstage = ResetCmd;      // Go perform a reset
      attemptsLeft = 5;          // Send the reset command up to five times
      break;
   case ResetCmd;
      modem.write("ATZ\n");      // ATZ - reset
      attemptsLeft--;            // Use one of our attempts
      nextstage = ResetReply;    // Next wait for a response (should be OK)
      timeout = millis() + 5000; // Wait for up to 5 seconds each attempt
      break;
   case ResetReply;
      if(receivedResponse() == OK)     // Success
      {
         nextStage = NetworkAttachCmd; // Attach to the cellular network
      } elseif(receivedResponse() == ERROR || timeout < millis())
      {        // If we get an error or timeout, reattempt if we can, power on if we can't
         if(attemptsLeft > 0)
         {
            nextStage = ResetCmd;
         } else {
            nextStage = Power;
         }
      }
      break;
   case NetworkAttachCmd:
   ...
}
stage = nextstage;               // Assign stage indirectly for debug purposes - nice to know where we came from at this point
</code>```

It's difficult to keep track of the whole flow of the system, inserting an additional step requires changes to the steps before and after, and it just seems like there should be an easier way.  The largest one I've had to design had fewer than 60 stages, so it's not unmanageable, but I can't help but think that there's a better strategy or pattern for this type of work.

While I use a few #define for most timeouts and attempts, it would be a bit nicer if this weren't embedded in the state machine.  Perhaps a structure of some sort could be made to hold each state, but since the responses vary it seems just as complicated. Most steps will have a simple "OK" but some contain status and data that have to be acted on, where the stage will change based on the exact response.

答:
State machines are a common design pattern in embedded systems, and it seems that you have a typical use case here. What you can do is simply have an infinite loop that let the current state handle the incoming message, transition to a new state if needed, then wait a bit.

Here's a simple C++ try. In my code, you need to bind or registers the possible states in some way, but the nice thing is that the really fixed part (handle event, switch to next state if needed) is really fixed in subclasses.

Additionnally, a nice win of state machines is that you can check their correctness easily with a combination of peer review, careful datasheet reading and a few unit tests.

```<code>class State {
public:
    // Forgetting constructors, etc.

    // Assume event is an integer, could be tuned to your case
    State *handleEvent(int event) {
        switch (event) {
           case EVENT1:
               this->doAction1();
               break;
            // etc.
        }
        State *nextState = this->nextStateForEvent(event);
        return nextState;
    }

    private:
        // Force each subclass (= posisble state) to re-implement all these
        virtual void doAction1() = 0;
        // etc.

        virtual State *nextStateForEvent(int event) = 0;
}
</code>```

Then, you get a main loop that becomes something like this:

```<code>#define DEFAULT_STATE 0

volatile int event = 0;

int main()
{
    // Create the states beforehand
    State *allStates = populate_the_possible_states;
    State *currentState = allStates[DEFAULT_STATE];

    while (1) {
        currentState = currentState->handleEvent(event);
        sleep(someMilliseconds);
    }
}
</code>```

Title: How to take things step by step

Body:
State machines are a common design pattern in embedded systems, and it seems that you have a typical use case here. What you can do is simply have an infinite loop that let the current state handle the incoming message, transition to a new state if needed, then wait a bit.

Here's a simple C++ try. In my code, you need to bind or registers the possible states in some way, but the nice thing is that the really fixed part (handle event, switch to next state if needed) is really fixed in subclasses.

Additionnally, a nice win of state machines is that you can check their correctness easily with a combination of peer review, careful datasheet reading and a few unit tests.

class State {
public:
    // Forgetting constructors, etc.

    // Assume event is an integer, could be tuned to your case
    State *handleEvent(int event) {
        switch (event) {
           case EVENT1:
               this->doAction1();
               break;
            // etc.
        }
        State *nextState = this->nextStateForEvent(event);
        return nextState;
    }

    private:
        // Force each subclass (= posisble state) to re-implement all these
        virtual void doAction1() = 0;
        // etc.

        virtual State *nextStateForEvent(int event) = 0;
}

Then, you get a main loop that becomes something like this:

#define DEFAULT_STATE 0

volatile int event = 0;

int main()
{
    // Create the states beforehand
    State *allStates = populate_the_possible_states;
    State *currentState = allStates[DEFAULT_STATE];

    while (1) {
        currentState = currentState->handleEvent(event);
        sleep(someMilliseconds);
    }
}


答:
Subtyping is about behavior.

For type B to be a subtype of type A, it must support every operation that type A supports with the same semantics (fancy talk for "behavior"). Using the rationale that every B is a A does not work - behavior compatibility has the final say. Most of the time "B is a kind of A" overlaps with "B behaves like A", but not always.

An example:

Consider the set of real numbers. In any language, we can expect them to support the operations +, -, *, and /. Now consider the set of positive integers ({1, 2, 3, ...}). Clearly, every positive integer is also a real number. But is the type of positive integers a subtype of the type of real numbers? Let's look at the four operations and see if positive integers behave the same way as real numbers:

+: We can add positive integers without problems.

-: Not all subtractions of positive integers result in positive integers. E.g. 3 - 5.

*: We can multiply positive integers without problems.

/: We can't always divide positive integers and get a positive integer. E.g. 5 / 3.

So despite positive integers being a subset of real numbers, they're not a subtype. A similar argument can be made for integers of finite size. Clearly every 32-bit integer is also a 64-bit integer, but 32_BIT_MAX + 1 will give you different results for each type. So if I gave you some program and you changed the type of every 32-bit integer variable to 64-bit integers, there's a good chance the program will behave differently (which almost always means wrongly).

Of course, you could define + for 32-bit ints so that the result is a 64-bit integer, but now you'll have to reserve 64 bits of space every time you add two 32-bit numbers. That may or may not be acceptable to you depending on your memory needs.

Why does this matter?

It's important for programs to be correct. It's arguably the most important property for a program to have. If a program is correct for some type A, the only way to guarantee that program will continue to be correct for some subtype B is if B behaves like A in every way.

So you have the type of Rectangles, whose specification says its sides can be changed independently. You wrote some programs that use Rectangles and assume the implementation follows the specification. Then you introduced a subtype called Square whose sides can't be resized independently. As a result, most programs that resize rectangles will now be wrong.

Title: Why would Square inheriting from Rectangle be problematic if we override the SetWidth and SetHeight methods?

Body:
If a Square is a type of Rectangle, than why can't a Square inherit from a Rectangle? Or why is it a bad design?

I have heard people say:

If you made Square derive from Rectangle, then a Square should be
  usable anywhere you expect a rectangle

What is the problem here? And why would Square be usable anywhere you expect a rectangle? It would only be usable if we create the Square object, and if we override the SetWidth and SetHeight methods for Square than why would there be any issue?

If you had SetWidth and SetHeight methods on your Rectangle base class
  and if your Rectangle reference pointed to a Square, then SetWidth and
  SetHeight don't make sense because setting one would change the
  other to match it. In this case Square fails the Liskov Substitution
  Test with Rectangle and the abstraction of having Square inherit from
  Rectangle is a bad one.

Can someone explain the above arguments? Again, if we over-ride SetWidth and SetHeight methods in Square, wouldn't it resolve this issue?

I have also heard/read:

The real issue is that we are not modeling rectangles, but rather
  "reshapable rectangles" i.e., rectangles whose width or height can be
  modified after creation (and we still consider it to be the same
  object). If we look at the rectangle class in this way, it is clear
  that a square is not a "reshapable rectangle", because a square cannot
  be reshaped and still be a square (in general). Mathematically, we
  don't see the problem because mutability doesn't even make sense in a
  mathematical context

Here I believe "re-sizeable" is the correct term. Rectangles are "re-sizeable" and so are squares. Am I missing something in the above argument? A square can be re-sized like any rectangle.


问:
What concrete steps can I take to assess PHP framework(s) without having to go to the extent of getting to know each framework in intimate detail?
This question is about what methodology to follow when evaluating one or more PHP frameworks to see which one would suit the needs of my project best.

In other words, given the time pressures that every developer faces, what concrete steps can I take to assess one or more PHP frameworks without having to go to the extent of getting to know each framework in intimate detail?

I know that some of the considerations would be subjective such as, which is my preferred language or my style of coding, but assessing your preferred language and style of coding would be a concrete step towards defining your chosen framework.

I'm narrowing this down to PHP just to assume that the choice of language has already been made.

答:
If you want to have a solid comparison you have to go and read the details, there is no other way around, unless you say I'm fine with reading some articles and blog post and I'm willing to rely on their assumptions. But anyways, here is how I would assess a new framework for a specific team and their project, while trying to avoid going deep into the framework specific details:

Order is not important.

Learning Curve

How long it's gonna take for you and the rest of team to understand the structure of the framework? You can feel if the learning curve is too steep very soon in the beginning. Don't you forget to start it by writing a real-world example like your actual program logic that is supposed to be finally implemented on top of that framework. A hello-world example from the getting started section wouldn't give you that much insight.

Meta-work

How much overhead this specific framework will add to your overall development time? Are there any automated CRUD generating tools for the framework and are you willing to use them? Try to see how much extra work you need to do in order to get a trivial task done.

Libraries

Try to see if the framework will bring anything to the table that you [might] actually need for your project. Check the libraries and classes that framework offers and try to be realistic. For example if you don't need a PayPal integration class, then don't count it as an advantage.

Structure

Some frameworks have serious design-flaw issues. Try to search on the 'net and see if you can find any serious problem regarding the structure of the framework. Again try to be realistic, don't look for some insane issues but make sure the developers of the framework has spend enough time thinking about the bare-bone structure of their framework.

Community

Try to see how active is their community. Don't count on the numbers, go to different places and ask couple of questions and see how long it's gonna take time until you get some real answers.


答:
You know how everyone is always saying that learning a functional programming language can help you in other languages, but you never know exactly how?  This is one of those cases.  Because of the way functional languages track state, they have come up with some innovative ways to do asynchronous programming tasks like state machines.  To use these patterns in C++, you probably need C++11 and/or boost.

Futures

Futures are a way to specify a sequence of asynchronous tasks, passing a value from step to step, with different paths for success and failure.  You could extend them for the retry behavior you want.  A state machine implemented using futures might look something like:

```<code>retryFuture(5)
.then(powerOn)
.then(resetCmd)
.then(attachNetwork)
.timeout(5000)
.failure(printFailureToScreen)
</code>```

Coroutines

Coroutines are a way to sort of interrupt a function in the middle and resume it from the same point later, like when a response is received.  It's a cooperative type of multitasking.  This allows you to specify a function in a more linear order.

```<code>powerOn()
yield
resetCmd()
yield
attachNetwork
yield
</code>```

Actors

Actors are a way to do message passing between tasks in an asynchronous manner.  You would set up an actor to do each step of the state machine, then pass a message to the next actor at the appropriate time.  This is similar to what you're doing now with the state variable, but in a somewhat more structured manner.

None of these ideas may be a perfect fit for your application, but hopefully it will give you a push in a direction to find a combination that may be useful for you.

Title: How to take things step by step

Body:
This is about the third time I've had to write software to control a cellular modem.  For those unfamiliar with the process, you have a sequence of steps you have to take.  Each step takes a certain amount of time, and there's a few responses you should receive in that amount of time.  There are also some responses you can receive at any time, regardless of the step you are on.  Based on the response you have to go to another stage in the process.  If it times out, you have to go to a different stage. In some cases, steps are attempted multiple times before going to another stage.

These have to be non-blocking functions, which I can run as a task on a single threaded machine.  So the main program would be calling this modemTask() a few hundred times a second, it checks whether it needs to do something, then performs a function if needed, and exits.

In the past I've written this as a simple switch based state machine, with enumerated stages, somewhat like the following:

```<code>switch(stage){
   case Power:
      powerOn();                 // Turn the modem on
      nextstage = ResetCmd;      // Go perform a reset
      attemptsLeft = 5;          // Send the reset command up to five times
      break;
   case ResetCmd;
      modem.write("ATZ\n");      // ATZ - reset
      attemptsLeft--;            // Use one of our attempts
      nextstage = ResetReply;    // Next wait for a response (should be OK)
      timeout = millis() + 5000; // Wait for up to 5 seconds each attempt
      break;
   case ResetReply;
      if(receivedResponse() == OK)     // Success
      {
         nextStage = NetworkAttachCmd; // Attach to the cellular network
      } elseif(receivedResponse() == ERROR || timeout < millis())
      {        // If we get an error or timeout, reattempt if we can, power on if we can't
         if(attemptsLeft > 0)
         {
            nextStage = ResetCmd;
         } else {
            nextStage = Power;
         }
      }
      break;
   case NetworkAttachCmd:
   ...
}
stage = nextstage;               // Assign stage indirectly for debug purposes - nice to know where we came from at this point
</code>```

It's difficult to keep track of the whole flow of the system, inserting an additional step requires changes to the steps before and after, and it just seems like there should be an easier way.  The largest one I've had to design had fewer than 60 stages, so it's not unmanageable, but I can't help but think that there's a better strategy or pattern for this type of work.

While I use a few #define for most timeouts and attempts, it would be a bit nicer if this weren't embedded in the state machine.  Perhaps a structure of some sort could be made to hold each state, but since the responses vary it seems just as complicated. Most steps will have a simple "OK" but some contain status and data that have to be acted on, where the stage will change based on the exact response.

Body:
You know how everyone is always saying that learning a functional programming language can help you in other languages, but you never know exactly how?  This is one of those cases.  Because of the way functional languages track state, they have come up with some innovative ways to do asynchronous programming tasks like state machines.  To use these patterns in C++, you probably need C++11 and/or boost.

Futures

Futures are a way to specify a sequence of asynchronous tasks, passing a value from step to step, with different paths for success and failure.  You could extend them for the retry behavior you want.  A state machine implemented using futures might look something like:

retryFuture(5)
.then(powerOn)
.then(resetCmd)
.then(attachNetwork)
.timeout(5000)
.failure(printFailureToScreen)

Coroutines

Coroutines are a way to sort of interrupt a function in the middle and resume it from the same point later, like when a response is received.  It's a cooperative type of multitasking.  This allows you to specify a function in a more linear order.

powerOn()
yield
resetCmd()
yield
attachNetwork
yield

Actors

Actors are a way to do message passing between tasks in an asynchronous manner.  You would set up an actor to do each step of the state machine, then pass a message to the next actor at the appropriate time.  This is similar to what you're doing now with the state variable, but in a somewhat more structured manner.

None of these ideas may be a perfect fit for your application, but hopefully it will give you a push in a direction to find a combination that may be useful for you.


问:
Agile retesting
I wrote some code about two years ago, which was deployed to the production environment.  The code deletes information that is six years old from a system.  When it was first deployed there were only 300 records deleted (because only 300 were six years old).

Now there are now 10,000 - 10,000 records become six years old tomorrow.  I want to retest the code but the project manager is against this (because it takes time - one day).

The deletion routine is very complex (the six year rule is only one of the rules but is the main rule).

The system has evolved over the last two years.  Is it reasonable to set some time for retesting or should I assume that is it worked at the time then it will work now (as the project manager assumes)?

Is there an Agile process that describes this sort of testing?

答:
I don't believe this scenario has anything to do with an agile process or not. Software development should have built-in time for regression. In a Scrum model, you probably are running this every sprint.

You should also be looking at automated unit tests and other ways to embed your regression into your builds. This allows you to have continuous feedback on whether your business logic is still working as changes occur.

Title: Agile retesting


答:
If you just want to step up from using a switch-based machine, I'd recommend a technique I learned back in school, which is splitting the machine up into 3 or 4 orthogonal functions:

A next-state determination function -- this would take the machine's current state and its current input and determine what the next machine state should be, returning that (no side effects)

A transition output function -- this would look at what state transition was being taken, along with the input, and react to it (comparable to a Mealy machine's output, running only when a transition occurs)

A state output function -- this would look at the current state and output for it (comparable to a Moore machine's output, running on each iteration of the machine's loop)

A transition function -- this would call the other three functions and set the machine's state

(This is copied from my answer here -- there's a code sample there too if you'd like an example.)

You might consider a fully OOP machine though. There are software packages which will allow you to diagram machines and generate the code for them, which should cut down on the tedium of implementing a state-machine.

If you're unsure which level to go with, I've successfully built into an OOP approach from the function approach.

Some of your requirements made me think of hierarchical state-machines (you might wanna start reading at the previous sub-section), so you might check that out.

Title: How to take things step by step


答:
Generally speaking, code doesn't "go bad" on its own. it doesn't rust, or require fuel or lubrication, it does't get weaker through use. If the only variable in your system is time, you don't need to retest, unless you have cause to believe it wasn't properly tested in the first place.

Now, if the system has changed, those changes need to be tested. If they were not tested, they should be.

So, I think the answer to your question lies in the answer to this other question: when the system was changed, was it properly tested (ie: was all dependent code also tested?)

The only way that agile addresses this issue is that it specifies software needs to be properly tested before it is considered "done". If you did that, you should have nothing to worry about.

All that being said, you also should ask yourself what the cost is for testing or not testing. If you don't test, and the system fails, how bad is it? Will it be catastrophic or just inconvenient? If you are talking about sending a probe to mars, the answer will be different than if you fail to update a web based dashboard on weekly game statistics.

Title: Agile retesting

Body:
I wrote some code about two years ago, which was deployed to the production environment.  The code deletes information that is six years old from a system.  When it was first deployed there were only 300 records deleted (because only 300 were six years old).

Now there are now 10,000 - 10,000 records become six years old tomorrow.  I want to retest the code but the project manager is against this (because it takes time - one day).

The deletion routine is very complex (the six year rule is only one of the rules but is the main rule).

The system has evolved over the last two years.  Is it reasonable to set some time for retesting or should I assume that is it worked at the time then it will work now (as the project manager assumes)?

Is there an Agile process that describes this sort of testing?


问:
Storing a single read/writeable value for a web service
I'm writing a web service for some physical visualizations of data we are collecting and showing as part of a project we are running locally http://tenisonroad.com/ Some of the visualizations will be screen based and some will be physical (e.g. page 25 of this presentation from Resonate 2014). One thing my web service will do is signal to the visualizations when to change dataset. To do that I have a single integer, DemoDataSetsDwellTime. I started off in SQL thinking to add this value amoung my existing table declarations, e.g.

```<code>CREATE TABLE ActiveDemoDwells
(secondsDwell INT NOT NULL)
</code>```

But this seems wrong - why make a table that is only ever going to store one single number, one single record.

So then I thought of using application settings in the Web.config file

```<code>[Route("api/getdemodwelltime/")]
[AcceptVerbs("GET", "POST")]
public int GetDemoDwellTime()
{
    return Int32.Parse(ConfigurationManager.AppSettings["DemoDataSetsDwellTimes"]);
}
</code>```

with corresponding entry

```<code><appSettings>
  <add key="DemoDataSetsDwellTimes" value="20"/>
</appSettings>
</code>```

But I have realised (from this answer) that the settings file should not really be used for writeable data, it is more suited / intended for read-only settings.

So finally I thought about using a simple flat file, i.e. something like this

```<code>[Route("api/getdemodwelltime/")]
[AcceptVerbs("GET", "POST")]
public int GetDemoDwellTime()
{
    var lines = File.ReadAllLines("settings.txt");
    var dwellTimeLine = lines.TakeWhile(line => line.StartsWith("dwellTime=")).FirstOrDefault();
    int result;
    return (dwellTimeLine != null && Int32.TryParse(dwellTimeLine.Remove(0, "dwellTime=".Length), out result)) ? result : -1;
}
</code>```

But that may get in a mess in the (unlikely) event that get and set methods are called simultaneously (I think, I'm not sure how web servers manage local file system access).

So, which of these is the 'correct' approach, or is there another solution that I have overlooked?

Store the single readable and writeable value in its own table in a database,

Store it as an application setting in the Web.config file, or

Store it in a flat file.

答:
Other.  How about a static variable?  Singletons don't play well in the web environment, but that may work to your advantage.  See also Asp.net session variable.

Another thought - you're right about a one column / one record table, but if you already have the infrastructure set up to read & write tables, then the additional "cost" for this one would be pretty small.  It would be easy to maintain since it's using the same logic that everything else uses.


答:
My two cents:

This model allows for other types of actions besides "file actions" (operations, sorry I'd already created the model with 'action' instead of 'operation').

The query to see what file actions user 3 has permission to perform is (you can easily create a view based on this query leaving out the where clause) :

```<code>select
  a.action_code
from
  user u join permission p on (u.user_id = p.user_id)
  join action a on (p.action_code=a.action_code)
  join action_type t on (t.act_type_code=a.act_type_code)
where
  u.user_id = 3 and
  t.act_type_code = 'FILE';
</code>```

Which will yield this:

Title: Can I create a query which allows me to do this?

Body:
I have a table which stores user information, one column stores their ID. I had implemented four different attributes in the same table which stored a bit indicating which file operations that user could perform (read, create, update, delete).

Thankfully, I realized that was terrible implementation and instead created four different tables with one column (the userID) which indicated which actions they could perform. It's really about me being annoyed by the over-whelming number of zeros. It does save on space, even if it's negligible.

However, this database is also queried by an application in an OOP language, and one of the objects frequently created is a User. This class naturally stores which file operations the User can perform. In the old implementation, these (boolean-valued) object fields could be quickly populated from the user table, but not now.

Now I'm confused on how I should populate these object fields. I feel like I should be able to perform a single query telling me which permission tables the user belongs to, but cannot find the write syntax (if it even exists).

So my question is: is there a way to perform a single query to figure out which tables (which only consist of a single column) a value occurs in? Or do I have to query each table independently to fill these object fields?

Body:
My two cents:

This model allows for other types of actions besides "file actions" (operations, sorry I'd already created the model with 'action' instead of 'operation').

The query to see what file actions user 3 has permission to perform is (you can easily create a view based on this query leaving out the where clause) :

select
  a.action_code
from
  user u join permission p on (u.user_id = p.user_id)
  join action a on (p.action_code=a.action_code)
  join action_type t on (t.act_type_code=a.act_type_code)
where
  u.user_id = 3 and
  t.act_type_code = 'FILE';

Which will yield this:


问:
Help in ensuring unit tests are meaningful
I've just written a unit test for this function, which loops through a collection of dates and sets properties equal to true or false depending on whether they're before or after a given comparison date:

```<code>public void CheckHistory(int months)
{
    var endDate = DateTime.Today.AddMonths(months);
    Dictionary<Order, bool> orders = new Dictionary<Order, bool>();

    foreach (var kvp in this.Orders)
    {
        if (kvp.Key.Date >= endDate)
        {
            orders.Add(kvp.Key, true);
        }
        else
        {
            orders.Add(kvp.Key, false);
        }
    }
    this.OrderHistories = orders;
}
</code>```

So here's the test I wrote:

```<code>public void Assert_CheckHistory_SelectsCorrectDates()
{
    MyViewModel vm = GetVmWithMockRepository();
    vm.OrderHistories = new Dictionary<OrderHistory, bool>();

    OrderHistory ohOld = new OrderHistory();
    ohOld.MailingDate = DateTime.Today.AddMonths(-12);
    vm.OrderHistories.Add(ohOld, false);

    OrderHistory ohNew = new OrderHistory();
    ohNew.MailingDate = DateTime.Today.AddMonths(-3);
    vm.OrderHistories.Add(ohNew, false);

    vm.CheckOrderHist(-6);

    int selectedOrders = vm.OrderHistories.Where(o => o.Value == true).Count();
    Assert.AreEqual(1, selectedOrders, "Unexpected number of selected Order Histories");
}
</code>```

Nothing wrong there. Test passes and all is good with the world.

However, I'm haunted by a nagging feeling that I'm not actually testing anything useful, and am just writing tests for the sake out it.

I get this a lot. A creeping paranoia that the tests I'm writing are incomplete in the sense that while they cover the lines of code in the target function, they don't really trap any likely problems and are therefore just a maintenance overhead.

Is that sample test worthwhile? Is even a badly-designed test worth worthwhile over no test at all? And most of all are there any principles to help programmers identify whether a test is useful or not, or to guide them in constructing useful tests in the future?

To be clear, I'm adding tests to an existing application. Going test-first in true TDD style isn't possible.

答:
The value of a regression test is not in succeeding when things are well - you could get the same effect by painting a green rectangle on your monitor! Its value is in failing when things are wrong, and doing so as early as possible, before the cost of correcting the problem becomes too big.

The easiest way of ensuring that it does in fact fail when things are wrong is to write it first and verify that it fails. Pick any situation that occurs to you that could go wrong with date calculations, write a test that checks this, run it on a stub implementation and watch it fail. Then you can write the business code that handles this case and watch it succeed. This gives you two vital assurances:

Your business logic is correct

If, at some time in the future, someone changes the business code so that it handles this case wrongly, you will know immediately.

Coding test-first is not the only way of ensuring that your tests are appropriate and reliable - it's just the easiest and smoothest I can think of. Many people are initially turned off by the seemingly out-of-order of steps, but if you consider what a test is really supposed to do, I find it rather obvious.


答:
If a Square is a type of Rectangle than why cant a Square inherit from a Rectangle?

The problem lies in thinking that if things are related in some way in reality, they must be related in exactly the same way after modelling.

The most important thing in the modelling is to identify the common attributes and the common behaviours, define them in the basic class and add additional attributes in the child classes.

The problem with your example is, that's completely abstract. As long as noone knows, what you plan to use that classes for, it's hard to guess what design you should made. But if you really want to have only height, width and resize, it would be more logical to:

define Square as base class, with width parameter and resize(double factor) resizing the width by the given factor

define Rectangle class and the subclass of Square, because it adds another attribute, height, and overrides its resize function, which calls super.resize and then resizes the height by the given factor

From the programming point of view, there's nothing in Square, that Rectangle doesn't have. There's no sense of making a Square as the subclass of Rectangle.