问:
How does Branch Target Prediction differ from Branch Prediction?
I do not understand how BTP differs from BP? Yes I understand BP evaluates whether a conditional is true/false, but surely implicitly this also determines the "target" instruction?

If I predict the first branch of an IF to be true, then surely I have just determined the branch target too (the code within the predicted IF branch)??

答:
Consider the following loop in assembly:

```<code>loop: ADDI R1, R1, #-1 ;subtract 1 from the value stored in R1
      BNEZ R1, loop ; if the value of R1 is not 0, go to the code at label "loop"

      SUBI R2, R2, #2 ; completely unrelated to the loop
</code>```

This code will continuously subtract 1 from the value stored in R1, until the value in R1 is 0.  Pretty simple, if not practical.  Equivalent C code might read

```<code>while(a != 0)
   a--;
</code>```

According to Wikipedia:

In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure.

In this example, the branch predictor will try to guess if the value of R1 is, in fact, 0, by various methods covered in the Wikipedia article.  All the branch predictor does is determine "Yes, this branch is going to be taken", or "No, this branch will not be taken."

On the other hand, a Branch Target Predictor will take the results of the Branch Predictor, and give the address that the program is going to jump to.

Using the example above, if the branch predictor says that the BNEZ instruction is going to take the branch, the branch target predictor will give the Address of the next instruction to execute after the ADDI instruction.  This might be the ADDI instruction, at the label loop, or it might be the SUBI instruction after the the branch instruction.

The Branch Predictor predicts the result of a comparison.  The Branch Target Predictor give where the program is going because of a branch.

Branches (and jumps, for that matter), are Program Counter (PC) relative.  The Branch Target Predictor will add the offset (given by the branch instruction), and add it to the current program counter.  This gives the address of the instruction to execute after the branch.

Branch Predictors give a Yes/No answer to the question "Am I going to branch".  The Branch Target Predictor needs that Yes/No answer to determine the answer to "WHERE am I going after the branch".

Body:
Consider the following loop in assembly:

loop: ADDI R1, R1, #-1 ;subtract 1 from the value stored in R1
      BNEZ R1, loop ; if the value of R1 is not 0, go to the code at label "loop"

      SUBI R2, R2, #2 ; completely unrelated to the loop

This code will continuously subtract 1 from the value stored in R1, until the value in R1 is 0.  Pretty simple, if not practical.  Equivalent C code might read

while(a != 0)
   a--;

According to Wikipedia:

In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure.

In this example, the branch predictor will try to guess if the value of R1 is, in fact, 0, by various methods covered in the Wikipedia article.  All the branch predictor does is determine "Yes, this branch is going to be taken", or "No, this branch will not be taken."

On the other hand, a Branch Target Predictor will take the results of the Branch Predictor, and give the address that the program is going to jump to.

Using the example above, if the branch predictor says that the BNEZ instruction is going to take the branch, the branch target predictor will give the Address of the next instruction to execute after the ADDI instruction.  This might be the ADDI instruction, at the label loop, or it might be the SUBI instruction after the the branch instruction.

The Branch Predictor predicts the result of a comparison.  The Branch Target Predictor give where the program is going because of a branch.

Branches (and jumps, for that matter), are Program Counter (PC) relative.  The Branch Target Predictor will add the offset (given by the branch instruction), and add it to the current program counter.  This gives the address of the instruction to execute after the branch.

Branch Predictors give a Yes/No answer to the question "Am I going to branch".  The Branch Target Predictor needs that Yes/No answer to determine the answer to "WHERE am I going after the branch".


问:
Is often using int constants as parameters in communication between objects considered bad design?
An app I'm working on is designed with MVC. The components often interacts with each other by passing int constants, which then have to be interpreted with if statements. I'm wondering if this is considered bad OO design. (Not specifically with MVC, but in general).

For example:

When the user clicks a specific button, the controller is told by the view controller.somethingHappened(Controller.SOME_INT_VALUE);

The view uses a constant int value in the controller as a message to tell what happened. The controller then has to have a lot of if statements to interpret the message from the view. E.g.:

```<code>public void somethingHappened(int message){
    if(message == AN_INT_VALUE) doSomething();
    if(message == ANOTHER_INT_VALUE) doSomeThingElse();
    if(message == A_DIFFERENT_INT_VALUE) doAnotherThing();
}
</code>```

As a result the controller passes another int value into the model, as a message to do something. I.e. model.doSomething(Model.SOME_INT_VALUE);.

Which forces to model to also have a bunch of if statements:

```<code>public void doSomething(int message){
    if(message == AN_INT_VALUE) doSomething();
    if(message == ANOTHER_INT_VALUE) doSomeThingElse();
    if(message == A_DIFFERENT_INT_VALUE) doAnotherThing();
}
</code>```

This results in both the controller and model having a lot of ifs to interpret the messages the receive.

Is this considered ugly and/or bad design? Should I try to pass actual objects into methods, or make more specific method calls - instead of passing constants that have to be interpreted with a bunch of ifs? Or is this practice of using a lot of constants as messages considered reasonable?

If it is considered bad design, how can I avoid this?

(Please note: For the purpose of this question I'm also referring to enums).

答:
Is this considered ugly and/or bad design?

Yes.

Should I [...] make more specific method calls - instead of passing constants that have to be interpreted with a bunch of ifs?

Yes, that's exactly what you should do. Unless there is some reason not to. Given that you've already thought of this much cleaner option yourself, I suspect that there might be, but it's not discernible from your question.

Update: If the called methods would have duplicate functionality, the object oriented solution is to put the functionality that differs into separate classes that all implement the same interface, and call that from within the function, using polymorphism instead of explicit branching.

So, using the information from the comment, you'd call

```<code>controller.applyStyle(new BoldStyle());
</code>```

or

```<code>controller.applyStyle(new UnderlineStyle());
</code>```

where BoldStyle and UnderlineStyle both are classes that implement a Style interface (or inherit from the same superclass) which contains one or more methods that do the different things and which are called by the applyStyle() method.

ContentLicense: CC BY-SA 3.0

Body:
Is this considered ugly and/or bad design?

Yes.

Should I [...] make more specific method calls - instead of passing constants that have to be interpreted with a bunch of ifs?

Yes, that's exactly what you should do. Unless there is some reason not to. Given that you've already thought of this much cleaner option yourself, I suspect that there might be, but it's not discernible from your question.

Update: If the called methods would have duplicate functionality, the object oriented solution is to put the functionality that differs into separate classes that all implement the same interface, and call that from within the function, using polymorphism instead of explicit branching.

So, using the information from the comment, you'd call

controller.applyStyle(new BoldStyle());

or

controller.applyStyle(new UnderlineStyle());

where BoldStyle and UnderlineStyle both are classes that implement a Style interface (or inherit from the same superclass) which contains one or more methods that do the different things and which are called by the applyStyle() method.


问:
Describe business logic with diagrams
I am currently developing a web application for my thesis.I was asked by my professor to make diagrams to describe the business logic.
Since I don't have a prior experience, I am pretty confused with all the terminology.
I managed to clarify,I think, what business rules and business logic are, but I can't find out how you describe the business logic. Is it something particular or is it something more general? Do I need to learn UML? Does the fact that I use MVC affects the way I'll describe it?</p>

答: While you can use some of the UML diagram types (especially activiti diagrams and state charts) to describe business logic, there is a more specialized graphical notation standard for that: BPMN.</p>

Title: Describe business logic with diagrams


问:
Is converting/casting a boolean to int a good idea?
Note: Even though this contains Python, it's not specifically about Python. It's more generally about expecting a certain behaviour from a language which is not necessarily the same across compilers/interpreters.

So I came across this question:

How do I convert a boolean to int in Python? Can I just do int(mybool)?

My response was to write:

```<code>1 if mybool else 0
</code>```

My reasoning was that blindly "casting" to int would rely on the internal implementation of the compiler/interpreter. And who knows, if running through a different interpreter int(mybool) might return something else. Explicitly stating the value for a "truthy" value and for a "falsey" value will always yield the expected behaviour.

This is surely something which one can consider for most languages.

Am I too picky about this? I know that I have written int(mybool) myself in the past. And that question made me think: Was that okay? Given that this is a very common case, are the compilers/interpreters smart enough to to "the right thing" for bool -> int conversions?

Now, for the special case for duck-typing languages like Python, int(mybool) might certainly be a really bad idea, but other languages are a bit clearer on their typing.

答:
Although I think it's generally best to use conditional language for the conversion regardless of what the Boolean variable represents, it's worthwhile to note that Boolean variables may be used in two semantically-distinct ways, and the preferred way of writing the code is different for each.

Although some people would suggest that someCondition == true or someCondition == false should always be regarded as redundant and replaced with someCondition and !someCondition, I would suggest that the two kinds of expressions be regarded as having slightly different meanings and implications.  Both will generate identical machine code, and in most cases the latter would be preferable, but the former would interpret someCondition as an abstract "value" rather than a statement about truth or falsity.  For example, if one is writing embedded system code and the devlopment tools provide a bool portState(pinNumber) method, writing buttonPressed = (portState(BUTTON_PORT) == false); may be better than buttonPressed = !portState(BUTTON_PORT);.  I would interpret the former as `The button is pressed when the I/O pin is a logic low level"; I'm not sure how I'd vocalize the latter.


问:
Is there a good way to communicate the intent that a class only contains referentially transparent methods?
My workplace mostly uses C# for writing code. I'm trying to figure out a good way to indicate that a class with referentially transparent methods is intended to be referentially transparent (i.e., given the same set of arguments, you will always get the same return value) for future maintainers. I've considered just using static classes for classes that are intended to only contain referentially transparent methods but received pushback from my colleagues as they prefer an approach to unit testing where all classes depending on are stubbed out which they use constructor DI to accomplish. I don't see a disadvantage to not stubbing out referentially transparent functions for unit testing since they are almost always in-memory anyway but I've been unable to convince my colleagues of that.

Our class names use typical OO pattern names like DTO or Factory or Controllers and Models for namespaces. I'm not aware of any pattern names in OO that would indicate the sort of intent I am going for (i.e., to not introduce side-effecting operations or depending on things that read out of the db or filesystem).

答: This is really jumping through hoops but what about creating a base class called ReferentiallyTransparentBase whose constructor throws an exception? Then when the person starts debugging the exception they'll see the comment // THIS CLASS'S METHODS WILL BREAK IF YOU CREATE INSTANCES OF IT. SO DON'T DO IT. Hopefully they'll get the picture.</p>


问:
As a .NET WPF developer what are key differences I should be aware of when working with ASP.NET MVC?
I'm a fairly experienced desktop .NET developer with a solid feel for MVVM and WPF, and I've worked with JavaScript, jQuery and HTML/CSS in the past - though I'm pretty dated and haven't had a ton of experience with the new frameworks (Angular, et al).

My question is, for anyone who has had to do it, what are the key pain points and differences I should be aware of when working on an ASP.NET MVC project?

I have a general sense of the MVC pattern and where it differs from MVVM, but ASP.NET tricks me by looking familiar, but with subtle and not-so-subtle differences in implementation and execution. I'm helping out with an ASP.NET project at work, and while my C# knowledge helps, my desktop habits seem to be a liability. Links to material I can review would be appreciated, or a succinct summary of what I need to change about my mindset.

答:
I went from MVC to MVVM and found that the main difference is that with MVC you deal with a single request from Controller to Model to View over and over, which you can turn into a single-page type app with AJAX.

In MVVM, the async of data/view is taken care of via properties notifying anything bound to them that the value has changed. Your Views can refresh themselves without having to re-do the entire MVC call and re-draw everything - instead only the affected properties are re-drawn so to speak.

I've found the async nature of MVVM to be favorable over MVC. The biggest hurdle for me has been trying to adhere strictly to MVVM pattern and not putting code in View Code-Behind or make Models/VMs aware of any Views etc. For smaller projects, it doesn't really matter.

Over-simplified example:

MVC: $user submits login request through controller, controller builds new View with $user defined from Model

```<code>Controller [$msg = Hello, $user!] => Model [$user = Bob] => View ["Hello, Bob!"]
</code>```

MVVM: $user submits login request through view, view model updates property with $user defined from Model, Property Notifies View that it has changed and View is updated (without having to re-draw or re-submit the entire process)

```<code>ViewModel [$msg = Hello, $user!] => Model [$user = Bob] => View ["Hello, Bob!"]
</code>```

Body:
I went from MVC to MVVM and found that the main difference is that with MVC you deal with a single request from Controller to Model to View over and over, which you can turn into a single-page type app with AJAX.

In MVVM, the async of data/view is taken care of via properties notifying anything bound to them that the value has changed. Your Views can refresh themselves without having to re-do the entire MVC call and re-draw everything - instead only the affected properties are re-drawn so to speak.

I've found the async nature of MVVM to be favorable over MVC. The biggest hurdle for me has been trying to adhere strictly to MVVM pattern and not putting code in View Code-Behind or make Models/VMs aware of any Views etc. For smaller projects, it doesn't really matter.

Over-simplified example:

MVC: $user submits login request through controller, controller builds new View with $user defined from Model

Controller [$msg = Hello, $user!] => Model [$user = Bob] => View ["Hello, Bob!"]

MVVM: $user submits login request through view, view model updates property with $user defined from Model, Property Notifies View that it has changed and View is updated (without having to re-draw or re-submit the entire process)

ViewModel [$msg = Hello, $user!] => Model [$user = Bob] => View ["Hello, Bob!"]


问:
Continuous Integration / Deployment: Test on commit, pull request, or what?
I read about CI/CD, loved it, but I'm having trouble with the details as everything I read was high level.

Some authors seemed to suggest that there couldn't be any failing commits on the repository (or master branch?), so a programmer that is delivering bad code would be stopped and he wouldn't be able to create a big mess. He would be forced into fixing his code so that the tests pass.

Others mentioned that the trigger would be the pull requests, not the commits. I haven't used pull requests a lot to be honest, and besides aren't they something external to git? They aren't part of git AFAIK, but part of services like github, bitbucket, etc., so I wasn't sure if I should bind my workflow to something like that.

Any thoughts on this will help me greatly. Please also mention which tools you are using, eg: Jenkins, Buildbot, etc. None of the tools I have tried were very friendly IMO. The docs and examples were lacking or tied to certain technologies like java, or services like github. I even considered building my own, it shouldn't be too hard to get the basic functionality. Right?

答:
The short answer is: Do what works for your team.

In a perfect continuous deployment scenario you might have this as a workflow:

each commit (in a centralized system) or push/pull to a particular branch (in a decentralized system) would trigger the code to be built.

If the build succeeds, that should trigger unit tests.

If that succeeds, that should trigger an integration test.

If the integration tests pass, that should trigger a deploy to a staging system

If the deploy works, that should trigger automated acceptance tests

If the acceptance tests pass, that should trigger a deployment to production

If that works, it should trigger some automated smoke tests.

Now, in the real world, rarely does it work that way. Every team has their own workflow. You might have a couple of phases for QA and staging, or you may deploy straight from a build machine to production. You might require a manual test phase, or you might require performance tests, etc.

There is no perfect answer, except whatever makes the most sense to you and your team. Trigger on every commit if you want, or only trigger on a push to a particular branch. Which is best for you depends on what is important to you and what sort of test coverage you have. It also depends on how long your tests take to run. You don't want to have to wait half an hour before committing a line of code.

All that being said, as a general rule you shouldn't move your code to where it affects others until it has been tested.


问:
Upcoming Google interview, looking for some preparation advice
Well I've been hitting the books wherever I can. I have an interview coming up, first one via phone, for a software engineer position. I've read all the blog posts, I've read all the accounts of interviews (some pretty old), and Google itself even suggested a reading list of books, none of which would surprise anyone here. Still, after some time preparing, I can't shake that feeling that there is such a large ground to cover, and I'm never sure whether to go with depth or breadth. I've found myself re-learning a whole area of compsci, only to forget most of the nitty details as I move on to another.

So, I don't know that there's a good answer to this question, but I'm looking for any practical advice on how to tackle the remaining weeks in advance of the interview. Part of my brain is tired from cramming, and of course the rest of it has to be utilized for some tough problems at my current place of employment.

答:
Relax

if your interview is anything like mine was, the interviewer is not there to grill you into submission, he's there to see how you think.

EDIT: this was just the initial phone interview, i don't know about anything further than that...and if i did i probably couldn't tell you anyway!

ContentLicense: CC BY-SA 2.5


问:
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?

答:
I think the easiest and most readable is, extracting the price and the label in the case, and keep the rest out of it:

```<code>switch($this->ship)
{
    case 'd':
        $price = $this->price->d;
        $label = 'Domestic';
        break;
    case 'e':
        $price = $this->price->e;
        $label = 'Export';
        break;
}
$cost = $this->price->base * $price;
$this->price->addLine($cost, 0, $label);
$this->price->total += $cost;
</code>```

That also allows you to break this method up in separate methods that return price and label based on the type (yeah, that's still two concerns, unless you see it as returning 'type properties' or something), another method that calculates the cost, etcetera.

Alternative: variable property name

Personally I don't really like solutions like this, because I think they are fragile, poorly readable and hard to debug, but they have their uses and maybe you'll like it:

You might also 'abuse' the fact that the character is the same as the property name, so you can use it like this:

```<code>$ship = $this->ship;
$price = $this->price->$ship;
</code>```

Maybe even this will work, but I'm not sure about this syntax. And even if it does, do you understand it? I don't. :)

```<code>$price = $this->price->($this->ship);
</code>```

Alernative: arrays with keys:

You might store the prices in an array by key, so you can read $this->price->prices['e']. Then your code might look like this:

```<code>$cost = $this->price->base * $this->price->prices[$this->ship];
$this->price->addLine($cost, 0, $this->labels[$this->ship]);
$this->price->total += $cost;
</code>```

I must say I can see the benefit of the array variant, although maybe the first variant is more readable and will require less work to refactor.

Body:
I think the easiest and most readable is, extracting the price and the label in the case, and keep the rest out of it:

switch($this->ship)
{
    case 'd':
        $price = $this->price->d;
        $label = 'Domestic';
        break;
    case 'e':
        $price = $this->price->e;
        $label = 'Export';
        break;
}
$cost = $this->price->base * $price;
$this->price->addLine($cost, 0, $label);
$this->price->total += $cost;

That also allows you to break this method up in separate methods that return price and label based on the type (yeah, that's still two concerns, unless you see it as returning 'type properties' or something), another method that calculates the cost, etcetera.

Alternative: variable property name

Personally I don't really like solutions like this, because I think they are fragile, poorly readable and hard to debug, but they have their uses and maybe you'll like it:

You might also 'abuse' the fact that the character is the same as the property name, so you can use it like this:

$ship = $this->ship;
$price = $this->price->$ship;

Maybe even this will work, but I'm not sure about this syntax. And even if it does, do you understand it? I don't. :)

$price = $this->price->($this->ship);

Alernative: arrays with keys:

You might store the prices in an array by key, so you can read $this->price->prices['e']. Then your code might look like this:

$cost = $this->price->base * $this->price->prices[$this->ship];
$this->price->addLine($cost, 0, $this->labels[$this->ship]);
$this->price->total += $cost;

I must say I can see the benefit of the array variant, although maybe the first variant is more readable and will require less work to refactor.


问:
Develop a website using mustache.js and PHP
I'm thinking of building a website using mustache.js to  render the website and having PHP as the backend. The PHP will then mainly contain queries to the database and some SESSION checkings.

Previously I've used plain PHP to render the frontend but it gets way too messy.

An example of what I'm thinking:

HTML File

```<code><html>
    <head>
        <script>
           $.ajax{
               url: "path/to/file.php",
               ...
               success: function(response){
                   var template = $('#template').html();
                   var rendered = Mustache.render(template, response)
                   $('#template').html(rendered);
               }
           }
        </script>
    </head>
    <body>
        <p id="template">Your favourite website is {{website}}</p>
    </body>
</html>
</code>```

PHP File

```<code><?php
    function getWebsite($userid){
        $mysqli = (...);
        $stmt = $mysqli -> prepare("SELECT name FROM websites WHERE userId = ?");
        $stmt -> bind_param("i", $userId);
        $stmt -> execute();
        ...
        ...
        echo json_encode($results);
    }
?>
</code>```

Is this a good structure or will it still get messy? Will it be slower?

答:
You really need to provide some more information for any advice to be suitable, but I'll try and answer in a general manner.

This does, in some ways, provide a rather neat separation of logic. However there's going to be some overhead in the way of HTTP requests - and potentially some pitfalls with regards to debugging.

The main issues that occur to me are:

HTTP Requests

For every page there will be an additional HTTP request, essentially one for the template (the .html file) and one for the content (the json payload).

JS Operations

This is going to introduce some fair overhead with regards to client side operations. For example, just to display a "page" you're going to need to make an AJAX request, parse the JSON response and associated template and then inject this in to the DOM. Whilst not the most heavy, arguably not essential either.

Accessibility

If, for whatever reason, Javascript isn't enabled - your viewers are stuck.

Maintenance

This may not seem like a big deal at the moment, but given time it could well become one.

Your real problem

However, from reading your post it appears that you're comfortable writing PHP and have used it inline previously. In that case, use a server side templating engine! There's even a port of Mustache, Mustache.php! Another one to consider could be Smarty. There are quite a few to choose from.

What you really seem to be expressing is the desire to use structured 'view's. A kin to what a lot of PHP MVC frameworks give you - depending on the complexity of your project using a framework may be a good way to go.

There's many frameworks to choose from, but I personally have experience with Yii, Laravel and CodeIgniter. CodeIgniter is quite possibly the simplest, but Laravel is my favourite. However, there are many options out there - and they all provide mechanisms for separating your views from the rest of the rest of the application, and as far as I know, they all include templating engines. They also make life a lot simpler with regards to database operations - and most other things you'll end up writing boilerplate for.

They can be a bit of a pain to get your head around at the beginning (suddenly you need to get used to how the framework wants you to do things) but actually, they do save time and help you manage complexity - it's a worthwhile learning curve to endure!


答:
We use ruby, rails, rspec and jenkins with the following workflow:

developer develops in a branch, writes unit tests and also runs the full test suite.

developer pushes branch

qa pulls branch, merges branch into master, resolves any merge conflicts and runs tests

if the tests pass, qa pushes updated master

git push of master triggers ci (jenkins) to run the full suite.

Title: Continuous Integration / Deployment: Test on commit, pull request, or what?

Body:
I read about CI/CD, loved it, but I'm having trouble with the details as everything I read was high level.

Some authors seemed to suggest that there couldn't be any failing commits on the repository (or master branch?), so a programmer that is delivering bad code would be stopped and he wouldn't be able to create a big mess. He would be forced into fixing his code so that the tests pass.

Others mentioned that the trigger would be the pull requests, not the commits. I haven't used pull requests a lot to be honest, and besides aren't they something external to git? They aren't part of git AFAIK, but part of services like github, bitbucket, etc., so I wasn't sure if I should bind my workflow to something like that.

Any thoughts on this will help me greatly. Please also mention which tools you are using, eg: Jenkins, Buildbot, etc. None of the tools I have tried were very friendly IMO. The docs and examples were lacking or tied to certain technologies like java, or services like github. I even considered building my own, it shouldn't be too hard to get the basic functionality. Right?


问:
Utility Functions Best Practices
Update: Most answers are about how to write a wrapping interface or what is a good wrapper around ADO. but my question is more about when to do so and when not.

I never found a good rule for deciding when to write a wrapper and when not. As nobody came up with a suggestion I think the reviewers are right in that this question has no general answer and is to broad.

Even in the specific case of ADONET the answer may depend on the use case and for most use cases a wrapper has been written already. Dapper and Orseis for e.g. as MainMa points out.

I would like to remove the question but I do not want to steel any ones points 8-)

Original Question

Let's take code executing a query using ADONET as an example.

```<code>var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT 1 FROM DUAL";
cmd.CommandTimeout = 1000;
var dataReader = cmd.ExecuteReader();
</code>```

Many will want to write this as a one-liner and create a bunch of utility functions in this example called as follows (or extension classes):

```<code>var cmd = connection.CreateCommand();
Utility.SelectToReader (connection, "SELECT 1 FROM DUAL", 1000);
</code>```

So what are good rules to introduce or deprecate utility functions? Apart from ADONET this question arises using almost any framework.

答:
John Gaughan already said it, "If you need a utility function to wrap the usage of another function, that is a sign that whatever you are wrapping was poorly designed."

Indeed, ADO.NET is old and requires to write much boilerplate, inelegant code which can easily cause mistakes (like forgetting to open a connection before starting a query or forgetting to complete a transaction when finishing working with it).

You may start doing utility functions. But remember, C# is object oriented, so you may want to use a more conventional way of a library. You may create your own, but why reinventing the wheel? There are already plenty of libraries which abstract ADO.NET calls and provide a much better interface. There are many ORMs, including Entity Framework and the much more lightweight LINQ to SQL, and if an ORM is an overkill for your current project, why not using something like Dapper?

What's wrong with utility functions, you may ask?

Nothing, except that there is no benefit whatsoever compared to an object-oriented approach of a library, and that you lose all you get with OOP. Let's see what it gives on an example of Orseis, a library similar to Dapper (but much, much better, because I created it; nah, just joking).

In this library, database is accessed this way:

var numberOfProducts = 10;
var query = @"select top (@Limit) [Id], [Name]
              from [Sales].[Product]
              order by [Sold] desc";

var products = new SqlDataQuery(query, this.ConnectionString)
    .Caching(TimeSpan.FromMinutes(5), "Top{0}Sales", numberOfProducts) // Cache the results.
    .Profiling(this.Profiler) // Profile the execution of the query.
    .TimeoutOpening(milliseconds: 1000) // Specify the timeout for the database.
    .With(new { Limit: numberOfProducts }) // Add query parameters.
    .ReadRows<Product>();
```

<p>This syntax has several benefits:</p>

<ol>
<li><p><strong>It's <s>slightly</s> much more readable and intuitive</strong> than the way it would be written using utility functions:</p>

<pre class="lang-cs prettyprint-override"><code>var numberOfProducts = 10;
var query = @"select top (@Limit) [Id], [Name]
              from [Sales].[Product]
              order by [Sold] desc";

using (Utility.OpenConnection(this.ConnectionString, timeoutMilliseconds: 1000))
{
    var parameters = new { Limit: numberOfProducts };
    Utility.Cache(
        TimeSpan.FromMinutes(5),
        "Top{0}Sales",
        numberOfProducts,
        () => Utility.Profile(
            () =>
            {
                using (var reader = Utility.Select(connection, query, parameters))
                {
                    var products = Utility.ConvertAll<Product>(reader);
                }
            }
        )
    );
}
</code>```

I mean, how a new developer could possibly understand what's happening here in just a few seconds?

It's not even about naming conventions (not that I want to criticize your choice of Utility as a name for a class), but about the structure itself. It simply looks like the plain old ADO.NET.

It's refactoring friendly. I can reuse a part of a chain (I can do it too with utility functions) very easily during a refactoring (that's much harder with utility functions).

Imagine that in the previous example, I want to be able to specify profiling and timeout policy once, and reuse it everywhere. I'll also specify the connection string:

this.BaseQuery = new SqlDataQuery(this.ConnectionString)
    .Profiling(this.Profiler)
    .TimeoutOpening(milliseconds: 1000);

// Later in code:

var numberOfProducts = 10;
var query = @"select top (@Limit) [Id], [Name]
              from [Sales].[Product]
              order by [Sold] desc";

var products = this.BaseQuery
    .Query(query)
    .Caching(TimeSpan.FromMinutes(5), "Top{0}Sales", numberOfProducts)
    .With(new { Limit: numberOfProducts }) // Add query parameters.
    .ReadRows<Product>();
```

<p>Such refactoring was pretty straightforward: it <em>just works</em>. With the variant using utility functions, I could have spent much more time trying to refactor the piece of code without breaking anything.</p></li>
<li><p><strong>It's portable.</strong> Adding support for a different database, such as Oracle, is seamless. I can do it in less than five minutes. Wait, I already did, and it took 5 lines of code and less than a minute (the time needed to install Oracle doesn't count, right?).</p>

<p>This one is crucial, and this is also why .NET developers got it wrong in .NET 1 when they designed <code>File</code> and <code>Directory</code> utility functions. Imagine you've created an app which spends a large deal of time working with files. You're preparing for your first release the next week when you receive a call from the customer: he wants to be able your app to work with Isolated Storage too. How do you explain to your customer that you'll need additional two weeks to rewrite half of your code?</p>

<p>If .NET 1 was designed with OOP in mind, they could have done a file system abstract provider with interchangeable concrete providers, something similar to another project I started, but not finished yet. Using it, I can seamlessly move from file storage to Isolated Storage to in-memory files to a native Win32 storage which supports NTFS transactions and doesn't have the stupid .NET constraint of 259 characters in a path.</p></li>
<li><p><strong>It's Dependency Injection (DI) friendly too.</strong> In point 2, I extracted a part of a chain in order to reuse it. I can as well push it even further and combine it with DI. Now, the methods which actually do all the work of querying the database don't even have to know that I'm using Oracle or SQLite. By the way, they don't have access to the query string; it's by design.</p></li>
<li><p><strong>It's easily extensible.</strong> I had to extend Orseis dozens of times, adding caching, profiling, transactions, etc. If I had to struggle with something, it was more the features themselves and how to make them fool-proof. For example, the notion of collection propagations I implemented to seamlessly bind queries containing joins to collections of objects wasn't a good idea, because despite all my efforts, it's still not obvious to use and can be a source of lots of mistakes.</p>

<p>But adding simpler concepts (like cache invalidation of multiple entries or the reusing of a connection in multiple queries) was pretty straightforward. This straightforwardness is much more difficult to find in utility functions. There, you start adding something, and you find that it breaks consistency or requires to make the changes which are not backwards compatible. You end up creating a bunch of static methods which are so numerous, that they look more like patchwork than a consistent class which helps developers.</p>

<p>Let's take your example:</p>

<pre class="lang-cs prettyprint-override"><code>Utility.SelectToReader(connection, "SELECT 1 FROM DUAL");
</code>```

Later, you need to use the parameters, so it becomes:

Utility.SelectToReader(
    connection,
    "SELECT 1 FROM DUAL WHERE CATEGORY = @Category",
    new Dictionary<string, string>
    {
        { "Category", this.CategoryId },
    });
```

<p>Then, you notice that you have too many timeouts, so you must add a timeout too:</p>

<pre class="lang-cs prettyprint-override"><code>Utility.SelectToReader(
    connection,
    "SELECT 1 FROM DUAL WHERE CATEGORY = @Category",
    new Dictionary<string, string>
    {
        { "Category", this.CategoryId },
    },
    2500);
</code>```

Step by step, the method becomes unusable. Either you need to split it, or you keep one with a dozen of optional arguments.

Title: Utility Functions Best Practices

Body:
John Gaughan already said it, "If you need a utility function to wrap the usage of another function, that is a sign that whatever you are wrapping was poorly designed."

Indeed, ADO.NET is old and requires to write much boilerplate, inelegant code which can easily cause mistakes (like forgetting to open a connection before starting a query or forgetting to complete a transaction when finishing working with it).

You may start doing utility functions. But remember, C# is object oriented, so you may want to use a more conventional way of a library. You may create your own, but why reinventing the wheel? There are already plenty of libraries which abstract ADO.NET calls and provide a much better interface. There are many ORMs, including Entity Framework and the much more lightweight LINQ to SQL, and if an ORM is an overkill for your current project, why not using something like Dapper?

What's wrong with utility functions, you may ask?

Nothing, except that there is no benefit whatsoever compared to an object-oriented approach of a library, and that you lose all you get with OOP. Let's see what it gives on an example of Orseis, a library similar to Dapper (but much, much better, because I created it; nah, just joking).

In this library, database is accessed this way:

var numberOfProducts = 10;
var query = @"select top (@Limit) [Id], [Name]
              from [Sales].[Product]
              order by [Sold] desc";

var products = new SqlDataQuery(query, this.ConnectionString)
    .Caching(TimeSpan.FromMinutes(5), "Top{0}Sales", numberOfProducts) // Cache the results.
    .Profiling(this.Profiler) // Profile the execution of the query.
    .TimeoutOpening(milliseconds: 1000) // Specify the timeout for the database.
    .With(new { Limit: numberOfProducts }) // Add query parameters.
    .ReadRows<Product>();

This syntax has several benefits:

It's <s>slightly</s> much more readable and intuitive than the way it would be written using utility functions:

var numberOfProducts = 10;
var query = @"select top (@Limit) [Id], [Name]
              from [Sales].[Product]
              order by [Sold] desc";

using (Utility.OpenConnection(this.ConnectionString, timeoutMilliseconds: 1000))
{
    var parameters = new { Limit: numberOfProducts };
    Utility.Cache(
        TimeSpan.FromMinutes(5),
        "Top{0}Sales",
        numberOfProducts,
        () => Utility.Profile(
            () =>
            {
                using (var reader = Utility.Select(connection, query, parameters))
                {
                    var products = Utility.ConvertAll<Product>(reader);
                }
            }
        )
    );
}

I mean, how a new developer could possibly understand what's happening here in just a few seconds?

It's not even about naming conventions (not that I want to criticize your choice of Utility as a name for a class), but about the structure itself. It simply looks like the plain old ADO.NET.

It's refactoring friendly. I can reuse a part of a chain (I can do it too with utility functions) very easily during a refactoring (that's much harder with utility functions).

Imagine that in the previous example, I want to be able to specify profiling and timeout policy once, and reuse it everywhere. I'll also specify the connection string:

this.BaseQuery = new SqlDataQuery(this.ConnectionString)
    .Profiling(this.Profiler)
    .TimeoutOpening(milliseconds: 1000);

// Later in code:

var numberOfProducts = 10;
var query = @"select top (@Limit) [Id], [Name]
              from [Sales].[Product]
              order by [Sold] desc";

var products = this.BaseQuery
    .Query(query)
    .Caching(TimeSpan.FromMinutes(5), "Top{0}Sales", numberOfProducts)
    .With(new { Limit: numberOfProducts }) // Add query parameters.
    .ReadRows<Product>();

Such refactoring was pretty straightforward: it just works. With the variant using utility functions, I could have spent much more time trying to refactor the piece of code without breaking anything.

It's portable. Adding support for a different database, such as Oracle, is seamless. I can do it in less than five minutes. Wait, I already did, and it took 5 lines of code and less than a minute (the time needed to install Oracle doesn't count, right?).

This one is crucial, and this is also why .NET developers got it wrong in .NET 1 when they designed File and Directory utility functions. Imagine you've created an app which spends a large deal of time working with files. You're preparing for your first release the next week when you receive a call from the customer: he wants to be able your app to work with Isolated Storage too. How do you explain to your customer that you'll need additional two weeks to rewrite half of your code?

If .NET 1 was designed with OOP in mind, they could have done a file system abstract provider with interchangeable concrete providers, something similar to another project I started, but not finished yet. Using it, I can seamlessly move from file storage to Isolated Storage to in-memory files to a native Win32 storage which supports NTFS transactions and doesn't have the stupid .NET constraint of 259 characters in a path.

It's Dependency Injection (DI) friendly too. In point 2, I extracted a part of a chain in order to reuse it. I can as well push it even further and combine it with DI. Now, the methods which actually do all the work of querying the database don't even have to know that I'm using Oracle or SQLite. By the way, they don't have access to the query string; it's by design.

It's easily extensible. I had to extend Orseis dozens of times, adding caching, profiling, transactions, etc. If I had to struggle with something, it was more the features themselves and how to make them fool-proof. For example, the notion of collection propagations I implemented to seamlessly bind queries containing joins to collections of objects wasn't a good idea, because despite all my efforts, it's still not obvious to use and can be a source of lots of mistakes.

But adding simpler concepts (like cache invalidation of multiple entries or the reusing of a connection in multiple queries) was pretty straightforward. This straightforwardness is much more difficult to find in utility functions. There, you start adding something, and you find that it breaks consistency or requires to make the changes which are not backwards compatible. You end up creating a bunch of static methods which are so numerous, that they look more like patchwork than a consistent class which helps developers.

Let's take your example:

Utility.SelectToReader(connection, "SELECT 1 FROM DUAL");

Later, you need to use the parameters, so it becomes:

Utility.SelectToReader(
    connection,
    "SELECT 1 FROM DUAL WHERE CATEGORY = @Category",
    new Dictionary<string, string>
    {
        { "Category", this.CategoryId },
    });

Then, you notice that you have too many timeouts, so you must add a timeout too:

Utility.SelectToReader(
    connection,
    "SELECT 1 FROM DUAL WHERE CATEGORY = @Category",
    new Dictionary<string, string>
    {
        { "Category", this.CategoryId },
    },
    2500);

Step by step, the method becomes unusable. Either you need to split it, or you keep one with a dozen of optional arguments.


问:
Why were short, int, and long invented in C?
I'm having trouble understanding, what were the exact purposes of creating the short, int, and long data types in C?

The reason I ask is, it doesn't seem like their sizes are bounded -- they could be of any size, so long as short is smaller than an int, for example.

In which situations, then, should you use an unsigned int or unsigned long, for example, instead of a size_t, when doing so offers no hope of binary compatibility?

(If you don't know the size, then how would you know when to choose which?)

答:
Although today, a "byte" means "8 bits", that hasn't always been true.  Machines have used addressable chunks of 4 bits, 8 bits, 12 bits, 16 bits, 32 bits, and 36 bits (and probably some other sizes as well).  One of the design intentions of C was to be usable on machines with different memory sizes and configurations.

I think the design intention was originally that each type other than int be the smallest thing that could handle numbers of various sizes, and that int be the most practical "general-purpose" size that could handle +/-32767.  I don't think there was any desire or intention to create a language which would still be in use when computers became so powerful that operations on 64-bit numbers cost the same as operations on smaller ones.

The biggest problem with C's integer-type semantics is that in some contexts they represent cardinal numbers or mathematical integers, while in other contexts they're used to represent members of a wrapping abstract algebraic ring of integers congruent mod 2^n [so e.g. subtracting the maximum representable value from 0 is defined to yield 1], but the behaviors are specified more on the basis of what compilers seemed to do the days when computer word sizes were around 16 bits (and a 36-bit word size would have been huge), rather than on the basis of what would make sense on a 64-bit machine.  Consequently, the result of subtracting a 32-bit unsigned value from a smaller unsigned 32-bit value may either be a large 32-bit unsigned value, or a negative 64-bit number.


问:
Is integer used too much as a data type?
Do most application developers use signed integers in places where they really mean to use unsigned integers?  I do it all the time, so do my co-workers.  I haven't seen a lot of other extensive codebases (other than the Delphi VCL) and examples on the internet usually use integer.  Whereas the VCL developers use their own data types (which would be the most non-lazy way to go about declaring variables).

Something seems a little dreadful about code like this

```<code>TStuffRec = record
   recordID : Integer;
   thingID : Integer;
   otherThingID : Integer;
end;
</code>```

when it could be written as

```<code>TStuffRec = record
   recordID : Cardinal;
   thingID : Cardinal;
   otherThingID : Cardinal;
end;
</code>```

Functionally, these records almost always work the same (and hopefully will continue to work the same even in 64-bit Delphi).  But very large numbers will have conversion issues.

But there are drawbacks to using unsigned ints too.  Mainly stemming from how annoying it is to mix the two.

The real question is, is this a thing that actually gets thought about or included in best practices?  Is it usually just up to the developer?

答:
Unsigned integer types should only be used to represent cardinal numbers in languages where they represent cardinal numbers.  Because of the way the computers that ran C happened to work, unsigned integer types behaved as members of mod-2^n algebraic rings (meaning calculations that overflowed would "wrap" predictably), and the language specifies that in many cases such types are required to behave as abstract algebraic rings even when such behavior would be inconsistent with the behavior of cardinal numbers or mathematical integers.

If a platform fully supported separate types for cardinal numbers and algebraic rings, then I would suggest that cardinal numbers should be processed using cardinal-number types (and things that need to wrap using the ring types).  Not only could such types store numbers twice the size of signed types, but a method receiving a parameter of such a type wouldn't have to check whether it was negative.

Given the relative lack of cardinal-number types, however, it's generally best to simply use integers to represent both mathematical integers and cardinal numbers.


问:
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.

答:
Code written in C++ can be faster than in C, for certain types of tasks.

If you prefer C++, use C++. Any performance issues are going to be insignificant compared to algorithmic decisions of your software.

Title: Writing in C for Performance?


答:
One of the design principles of C++ is that you don't pay for features you don't use. So, if you write code in C++ and avoid features that don't exist in C, then the resulting compiled code should be equivalent in performance (though you would have to measure this).

There is negligible cost to using classes, for example, compared to structs and a bunch of associated functions. Virtual functions will cost a bit more, and you'd have to measure the performance to see whether it matters for your application. The same goes for any other C++ language feature.

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.


答:
The biggest fallacy in your question is that vendors think that hard about their APIs. :) I (half) kid, but truthfully, vendors don't always write the best APIs. Sometimes this is to provide ultimate low-level flexibility. Other times this is to meet obscure or otherwise unknowable requirements. Yet other times its because vendors don't totally know or understand how developers are going to use their code. As an example, a number of languages provide straightforward APIs for reading XML from strings and manipulating it, but getting the result back out as a string is a chore.

In cases where you have this much boilerplate to perform a simple action, you can use the facade pattern to abstract away the complexities. Your utility methods are partway there, but having a single utility class like that is not the ideal approach. Such a class suffers from low cohesion, since it can have all kinds of unrelated methods. It would be better to create highly cohesive facade classes of related functionality. Highly cohesive classes make duplicate code or deprecated functionality more apparent because you are looking at code all in a similar vein.

Title: Utility Functions Best Practices

Body:
Update: Most answers are about how to write a wrapping interface or what is a good wrapper around ADO. but my question is more about when to do so and when not.

I never found a good rule for deciding when to write a wrapper and when not. As nobody came up with a suggestion I think the reviewers are right in that this question has no general answer and is to broad.

Even in the specific case of ADONET the answer may depend on the use case and for most use cases a wrapper has been written already. Dapper and Orseis for e.g. as MainMa points out.

I would like to remove the question but I do not want to steel any ones points 8-)

Original Question

Let's take code executing a query using ADONET as an example.

```<code>var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT 1 FROM DUAL";
cmd.CommandTimeout = 1000;
var dataReader = cmd.ExecuteReader();
</code>```

Many will want to write this as a one-liner and create a bunch of utility functions in this example called as follows (or extension classes):

```<code>var cmd = connection.CreateCommand();
Utility.SelectToReader (connection, "SELECT 1 FROM DUAL", 1000);
</code>```

So what are good rules to introduce or deprecate utility functions? Apart from ADONET this question arises using almost any framework.


问:
Practical use of generic inheritance and interactions with non-generics?
I've been trying to learn more about generics, and I finally felt that I ran into a situation that it would be more useful to use it instead of only regular classes. Would the following be a practical use of generics?

A spaceship has hardpoints that can equip only certain types of equipment. The equip function has code to determine if the hardpoint can equip an equipment item based on what the generic parameter T is assigned to.

```<code>class Equipment {
...
}

class Thruster : Equipment {
...
}

class Spaceship {
    void Equip<T>(Hardpoint<T> hardpoint, Equipment equipment) {
        hardpoint.Equip(equipment);
    }
}

class Hardpoint<T> where T : Equipment {
    void Equip(Equipment equipment) {
        ...(check if equipment inherits from or is of type T)
    }

    ... (some other code common to all hardpoints)
}

class ThrusterHardpoint : Hardpoint<Thruster> {
    .... (some code specific to thruster hardpoints)
}
</code>```

答:
I don't see any point to your use of the generics in your example.  You're also following into a trap with your usage here:

```<code>class Thruster : Hardpoint<Thruster>
</code>```

This is similar to creating a class

```<code>class EmployeeList : List<Employee>
</code>```

There is no reason to do this because List allows you to specify the Employee once only in the usage, not for each separate case.  Consider this to make my point.  If you had a method that took one of your EmployeeList types as a parameter, but all you had was an IEnumerable you'd have to first build this new type and populate it before you could pass it to your methods.  That's extra work for the programmer, compiler, and cpu. This serves me much better.

```<code>public static void DoSomething(this IEnumerable<Employee> value) { }
</code>```

If order matters then it would be.

```<code>public static void DoSomething(this IOrderedEnumerable<Employee> value) { }
</code>```

If indices are needed.

```<code>public static void DoSomething(this IList<Employee> value) { }
</code>```

Now it works for any kind of list, not just your specific EmployeeList type.

So in code you use it like this instead:

```<code>var employees = new List<Employee>();
employees.Add(new Employee(1));
// Notice this code doesn't need this extra redundant type EmployeeList at all.
</code>```

In the above example the generic was useful so that the Add method would have a type it expects.  You specified the type when you declared the instance using its default constructor.  So basically this saves you from having to cast your objects into something, and also so the intellisense and the compiler can make sure you are indeed passing Employee instances into the Add method of an instance of List.

Before generics existed you had to do this instead for the previous example:

```<code>var employees = new List();
employees.Add(new Employee(1));
employees.Add(new Car(2)); // Compiler won't see this as an error, because a Car is an object.
Console.WriteLine(((Employee)employees[0]).EmployeeID); // Have to case anything coming out of the List because compiler thinks they are just objects, not Employee instances.
</code>```

As you can see the old way would let you do a bad thing, add Car instances to a list of Employee's.  It also required the programmer to type more and cast everything manually.  It would blow up in this case if you did this:

```<code>Console.WriteLine(((Employee)employees[1]).EmployeeID); // Subset item 1 is not an instance of Employee, cast will fail.
</code>```

EDIT: Added explanation of why class EmployeeList is extra and there are better solutions to domain specific set based operations.

Body:
I don't see any point to your use of the generics in your example.  You're also following into a trap with your usage here:

class Thruster : Hardpoint<Thruster>

This is similar to creating a class

class EmployeeList : List<Employee>

There is no reason to do this because List allows you to specify the Employee once only in the usage, not for each separate case.  Consider this to make my point.  If you had a method that took one of your EmployeeList types as a parameter, but all you had was an IEnumerable you'd have to first build this new type and populate it before you could pass it to your methods.  That's extra work for the programmer, compiler, and cpu. This serves me much better.

public static void DoSomething(this IEnumerable<Employee> value) { }

If order matters then it would be.

public static void DoSomething(this IOrderedEnumerable<Employee> value) { }

If indices are needed.

public static void DoSomething(this IList<Employee> value) { }

Now it works for any kind of list, not just your specific EmployeeList type.

So in code you use it like this instead:

var employees = new List<Employee>();
employees.Add(new Employee(1));
// Notice this code doesn't need this extra redundant type EmployeeList at all.

In the above example the generic was useful so that the Add method would have a type it expects.  You specified the type when you declared the instance using its default constructor.  So basically this saves you from having to cast your objects into something, and also so the intellisense and the compiler can make sure you are indeed passing Employee instances into the Add method of an instance of List.

Before generics existed you had to do this instead for the previous example:

var employees = new List();
employees.Add(new Employee(1));
employees.Add(new Car(2)); // Compiler won't see this as an error, because a Car is an object.
Console.WriteLine(((Employee)employees[0]).EmployeeID); // Have to case anything coming out of the List because compiler thinks they are just objects, not Employee instances.

As you can see the old way would let you do a bad thing, add Car instances to a list of Employee's.  It also required the programmer to type more and cast everything manually.  It would blow up in this case if you did this:

Console.WriteLine(((Employee)employees[1]).EmployeeID); // Subset item 1 is not an instance of Employee, cast will fail.

EDIT: Added explanation of why class EmployeeList is extra and there are better solutions to domain specific set based operations.


问:
Dealing with similar objects with different method signatures
I am fairly new to OO design and have problems with the design of some software and looking for a pattern or a combination of patterns that could help me solving my problem.

I have a type that has a collection of different geometric shapes (say lines, rectangles, and cubes). I actually even have composites of these shapes.
Each shape has one or more values. A value is a coordinate (between one-dimensional for lines and three-dimensional for cubes).

All types of shapes have two methods that are essential. A method for adding values and a method for getting all values of a shape. E.g. Cube.AddValue(new Value3D{X=4,Y=7,Z=11}) or Line.AddValue(new Value1D{X=42}) respectively Cube.GetValues() would return a collection of Value3D and Line.GetValues() would return a collection of Value1D.

Since these methods have fundamentally different signatures, I can't just derive from a single interface to store all of these different objects in one collection. Splitting the collection into multiple separate collections, one for each type would be possible, but not desirable since they belong together (domain wise).

I've considered using three-dimensional values for all shapes and just ignoring Y/Z for lines/rectangles, but that isn't really nice and would actually violate the O and L in SOLID (a 4th dimension is possibly needed in the future).

Another possibility would probably be to use a generic Interface like IShape<T> where T is Value*D. This interface would look like:

```<code>public interface IShape<T> {
    public IEnumerable<T> GetValues();
    public void AddValue(T value);
}
</code>```

But this would require another, non-generic interface INonGenericShape {} because I can't use a generic interface without specifying the type. I would end up with something like this:

```<code>public class SomeShape{
    private IList<INonGenericShape> _shapes = new List<INonGenericShape>();
}
</code>```

But then I could as well use System.Object, since IShape does not provide any valuable information. So here I am, not knowing how to solve this (storing the objects in a single collection for consumers of that class). Can anyone provide some idea or insight?

答:
Your shapes shouldn't hold their values through the interface.  The interfaces are things you need to be able to do with them.  The classes are the various ways you can fulfill those same things.

If your effort is to draw these shapes to the screen your interface is going to have nothing to do with values of any kind directly.

```<code>public interface IDrawable {
    void Draw(Graphics g);
}
</code>```

This way you can invent completely new shape ideas you never thought of without having to change the signatures of how they interact.  That is all the OO is for.  Isolate the interaction to a single thing that will work for everything.  (hint:  You will often be abstracting a function, not a value.)

Now when you decide you need to be able to write these shapes to a data storage you can add.

```<code>public interface IWritable {
    void Write(Stream s);
}
</code>```

Now there is place for these values to be typed, everything works better if its typed.  Notice you can pretty much put anything here now, and freely mix-and-match.

```<code>public class Line : IDrawable , IWritable {
    public Point Start { get; set; }
    public Point End { get; set; }
    public void Draw(Graphics g) { }
    public void Write(Stream s) { }
}

public class ThreePointTriangle : IDrawable , IWritable {
    public Point First { get; set; }
    public Point Second { get; set; }
    public Point Third { get; set; }
    public void Draw(Graphics g) { }
    public void Write(Stream s) { }
}

public class SinRightTriangle : IDrawable , IWritable {
    public Point AngleA { get; set; }
    public Line Opposite { get; set; }
    public Line Hypotenuse { get; set; }
    public void Draw(Graphics g) { }
    public void Write(Stream s) { }
}

public class Car : IDrawable {
    public void Draw(Graphics g) { }
}
</code>```

Body:
Your shapes shouldn't hold their values through the interface.  The interfaces are things you need to be able to do with them.  The classes are the various ways you can fulfill those same things.

If your effort is to draw these shapes to the screen your interface is going to have nothing to do with values of any kind directly.

public interface IDrawable {
    void Draw(Graphics g);
}

This way you can invent completely new shape ideas you never thought of without having to change the signatures of how they interact.  That is all the OO is for.  Isolate the interaction to a single thing that will work for everything.  (hint:  You will often be abstracting a function, not a value.)

Now when you decide you need to be able to write these shapes to a data storage you can add.

public interface IWritable {
    void Write(Stream s);
}

Now there is place for these values to be typed, everything works better if its typed.  Notice you can pretty much put anything here now, and freely mix-and-match.

public class Line : IDrawable , IWritable {
    public Point Start { get; set; }
    public Point End { get; set; }
    public void Draw(Graphics g) { }
    public void Write(Stream s) { }
}

public class ThreePointTriangle : IDrawable , IWritable {
    public Point First { get; set; }
    public Point Second { get; set; }
    public Point Third { get; set; }
    public void Draw(Graphics g) { }
    public void Write(Stream s) { }
}

public class SinRightTriangle : IDrawable , IWritable {
    public Point AngleA { get; set; }
    public Line Opposite { get; set; }
    public Line Hypotenuse { get; set; }
    public void Draw(Graphics g) { }
    public void Write(Stream s) { }
}

public class Car : IDrawable {
    public void Draw(Graphics g) { }
}


问:
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.

答:
Abstract it on its function, not state.  States receive messages, they do things in response to those messages, and they alter the state of some variables that are persisted across the states.

Your attempts, timeout, next state are persisted across.  I'd put these in some kind of singleton type manager, or simply some static variables.

The functionality with the state is left is what to do when it receives a message.  It needs to be able to do things like change the static variables, run functions based on other functions.  Here's one example I can think of, but these ideas should be tailored to what it is you want to be able to write one time that works with all your different states.  Is it the waiting loops?  Is it the checking for the command to be in a valid list of commands based on the current state?  Is it being able to keep track of the sessions?

```<code>public interface IState {
    void Process(string message);
}
</code>```

Now any class you make can be one of your states by implementing this interface and adding a void Process(string) method to the class.

```<code>public class PowerOn : IState {
    public void Process(string message) {
        powerOn();
        StateManager.NextStage = new ResetCmd();
        StateManager.AttemptsLeft = 5;
    }
}

public class ResetCmd : IState {
    public void Process(string message) {
        modem.write("ATZ\n");
        StateManager.AttemptsLeft--;
        StateManager.NextStage = new ResetReply();
        StateManager.Timeout = millis() + 5000;
    }
}
</code>```

Title: How to take things step by step

Body:
Abstract it on its function, not state.  States receive messages, they do things in response to those messages, and they alter the state of some variables that are persisted across the states.

Your attempts, timeout, next state are persisted across.  I'd put these in some kind of singleton type manager, or simply some static variables.

The functionality with the state is left is what to do when it receives a message.  It needs to be able to do things like change the static variables, run functions based on other functions.  Here's one example I can think of, but these ideas should be tailored to what it is you want to be able to write one time that works with all your different states.  Is it the waiting loops?  Is it the checking for the command to be in a valid list of commands based on the current state?  Is it being able to keep track of the sessions?

public interface IState {
    void Process(string message);
}

Now any class you make can be one of your states by implementing this interface and adding a void Process(string) method to the class.

public class PowerOn : IState {
    public void Process(string message) {
        powerOn();
        StateManager.NextStage = new ResetCmd();
        StateManager.AttemptsLeft = 5;
    }
}

public class ResetCmd : IState {
    public void Process(string message) {
        modem.write("ATZ\n");
        StateManager.AttemptsLeft--;
        StateManager.NextStage = new ResetReply();
        StateManager.Timeout = millis() + 5000;
    }
}


问:
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.

答:
And why would Square be usable anywhere you expect a rectangle?

Because that's part of what being a subtype means (see also: Liskov substitution principle). You can do, need to be able to do this:

Square s = new Square(5);
Rect r = s;
doSomethingWith(r); // written assuming a Rect, actually calls Square methods
```

You actually do this all the time (sometimes even more implicitly) when using OOP.

and if we over-ride the SetWidth and SetHeight methods for Square than why would there be any issue?

Because you can't sensibly override those for Square. Because a square can't "be re-sized like any rectangle". When the height of a rectangle changes, the width remains the same. But when the height of a square changes, the width must change accordingly. The issue isn't just being re-sizable, it's being re-sizable in both dimensions independently.

Body:
And why would Square be usable anywhere you expect a rectangle?

Because that's part of what being a subtype means (see also: Liskov substitution principle). You can do, need to be able to do this:

Square s = new Square(5);
Rect r = s;
doSomethingWith(r); // written assuming a Rect, actually calls Square methods

You actually do this all the time (sometimes even more implicitly) when using OOP.

and if we over-ride the SetWidth and SetHeight methods for Square than why would there be any issue?

Because you can't sensibly override those for Square. Because a square can't "be re-sized like any rectangle". When the height of a rectangle changes, the width remains the same. But when the height of a square changes, the width must change accordingly. The issue isn't just being re-sizable, it's being re-sizable in both dimensions independently.


问:
Have objects delivered in terms of code reuse?
I have often heard it said that objects have not delivered in terms of code reuse. Do you agree? If you believe that they haven't, why not?</p>

答:
Yes

OOP gives you more ways to reuse code

No

there is no silver bullet

It Depends

on what you put into it, and what you expected in return!


问:
How can I "inspect" C++ code?
For reference, I am a JavaScript developer learning C++. The browser is a pretty powerful debugger, and I can easily place a breakpoint in my code, hover over a variable or expression and get the value of that expression. Is this even possible in C++ or am I in a different world entirely?

I'm starting to write a bit of C++ code for an online course, and debugging with Code::Blocks gives me very opaque information. For example, I see stuff like this: 0x8049bc3  push   ebp in the 'watches' window. Even if I write something like int foo = 3;, I have found no way of telling that foo is 3 while I'm stepping through my code. Am I missing something?

答:
You need to build a debug version of your program:

Make sure that the project is compiled with the -g (debugging symbols)
  compiler option on, and the -s (strip symbols) option off. This
  ensures that the executable has debug symbols included. Compiler
  optimization switches should be turned off, stripping symbols (-s)
  must be turned off.

C++ compiles into machine code, where variables are just memory addresses. Symbols, such as variable names, can be appended to the executable by using appropriate compiler flags.

Title: How can I "inspect" C++ code?


答:
From a mathematical perspective, a square is-a rectangle. If a mathematician modifies the square so it no longer adheres to the square contract, it changes into a rectangle.

But in OO design, this is a problem. An object is what it is, and this includes behaviors as well as state. If I hold a square object, but someone else modifies it to be a rectangle, that violates the square's contract through no fault of my own. This causes all sorts of bad things to happen.

The key factor here is mutability. Can a shape change once it is constructed?

Mutable: if shapes are allowed to change once constructed, a square cannot have an is-a relationship with rectangle. The contract of a rectangle includes the constraint that opposite sides must be of equal length, but adjacent sides need not be. The square must have four equal sides. Modifying a square through a rectangle interface can violate the square contract.

Immutable: if shapes cannot change once constructed, then a square object must also always fulfill the rectangle contract. A square can have an is-a relationship with rectangle.

In both cases it is possible to ask a square to produce a new shape based on its state with one or more changes. For example, one could say "create a new rectangle based on this square, except that opposing sides A and C are twice as long." Since a new object is being constructed, the original square continues to adhere to its contracts.

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.


答:
Because by LSP, creating inheritance relation between the two and overriding setWidth and setHeight to ensure square has both as same introduces confusing and non-intuitive behavior. Lets say we have a code:

Rectangle r = createRectangle(); // create rectangle or square here
r.setWidth(10);
r.setHeight(20);
print(r.getWidth()); // expect to print 10
print(r.getHeight()); // expect to print 20
```

But if the method createRectangle returned Square, because it is possible thanks to Square inheriting from Rectange. Then the expectations get broken. Here, with this code, we expect setting width or height will only cause change to width or height respectively. The point of OOP is that when you work with the superclass, you have zero knowledge of any subclass under it. And if subclass changes the behavior so that it goes against expectations we have about superclass, then there is high chance that bugs will occur. And those kind of bugs are both hard to debug and fix.

One of the major ideas about OOP is that it is behavior, not data that is inherited (which is also one of the major misconceptions IMO). And if you look at square and rectangle, they have no behavior themselves that we could relate in inheritance relation.

Body:
Because by LSP, creating inheritance relation between the two and overriding setWidth and setHeight to ensure square has both as same introduces confusing and non-intuitive behavior. Lets say we have a code:

Rectangle r = createRectangle(); // create rectangle or square here
r.setWidth(10);
r.setHeight(20);
print(r.getWidth()); // expect to print 10
print(r.getHeight()); // expect to print 20

But if the method createRectangle returned Square, because it is possible thanks to Square inheriting from Rectange. Then the expectations get broken. Here, with this code, we expect setting width or height will only cause change to width or height respectively. The point of OOP is that when you work with the superclass, you have zero knowledge of any subclass under it. And if subclass changes the behavior so that it goes against expectations we have about superclass, then there is high chance that bugs will occur. And those kind of bugs are both hard to debug and fix.

One of the major ideas about OOP is that it is behavior, not data that is inherited (which is also one of the major misconceptions IMO). And if you look at square and rectangle, they have no behavior themselves that we could relate in inheritance relation.


答:
It's a totally different beast. WPF is all about binding your ViewModel with the views using XAML. There are frameworks (I think Caliburn Micro is the one I used once) that help building this bridge automatically hence allowing you to reuse more code.

On the other hand, ASP MVC is about using a template for your C# objects, but once your page has been served, you usually need more programming on the client side. Name it JQuery, Knockout, AngularJs, etc. This way you can make bindings for each control, kind of what XAML does, but with more power in my opinion.

As you learn more about how http request/response cycle works, believe me, you will crave more and more programming in the browser and less on ASP side. At least that was what happened to me. Nowadays I use C# as a console application to serve/recieve JSON, serialize/deserialize and read/write in databases. Even the attempt to put logic on ASP views is not appealing to me anymore. Plain HTML happens to be a great fit for javascript without the need of server templating.

Title: As a .NET WPF developer what are key differences I should be aware of when working with ASP.NET MVC?

Body:
I'm a fairly experienced desktop .NET developer with a solid feel for MVVM and WPF, and I've worked with JavaScript, jQuery and HTML/CSS in the past - though I'm pretty dated and haven't had a ton of experience with the new frameworks (Angular, et al).

My question is, for anyone who has had to do it, what are the key pain points and differences I should be aware of when working on an ASP.NET MVC project?

I have a general sense of the MVC pattern and where it differs from MVVM, but ASP.NET tricks me by looking familiar, but with subtle and not-so-subtle differences in implementation and execution. I'm helping out with an ASP.NET project at work, and while my C# knowledge helps, my desktop habits seem to be a liability. Links to material I can review would be appreciated, or a succinct summary of what I need to change about my mindset.