问:
Representing the hierarchy of groups of numbers using type inheritance
I've run into an interesting conundrum while coding my own implementations for the basic sets of mathematical numbers (Natural, Integer, Rational, Irrational, Real, Complex). I'm doing this mostly for fun, but also because I want properly represented numbers in code.

It started off with RationalNumber. I added two fields to my class: Numerator and Denominator. I've overloaded all the basic operators that I am able to (I'm using C#) so that I can define what it means to add, subtract, etc.. for these objects.

From here, I thought that I'd extend my definitions upward and make a RealNumber class such that this type can extend from it so that it could fill in for any RealNumber elsewhere in code... Except intuitively, the number system operates contrary to this definition.

Illustrating what I mean, consider starting off with the basic natural numbers. We can "extend" the natural numbers to include negative numbers as well (and zero if you weren't already including it) and then we call this new group the integers. In code, this would imply that Integer inherits from NaturalNumber. If I wanted to write a method that accepts an integer parameter, logically one would assume you could use a natural number as well; but with the way inheritance works, this doesn't fly.

How can I properly model the relationship between the sets of numbers through inheritance so that I can put a natural number into?

答:
You're thinking about it backwards. Integers aren't an extension of Natural Numbers in that sense, they are a superset. So Natural Numbers inherit from Integers with the proviso that they can't be negative or zero. An unsigned integer equivalent would be a natural fit.

Bear in mind that many of the machine versions of number types aren't quite the same as the way a mathematician might define a number type. Haskell has an interesting way of defining numbers. You might be able to implement something similar in C#.


问:
Why do VMs not execute the assembly directly?
Many VMs execute a language of binary form, knows as 'bytecode', which is assembled down from a human readable 'assembly' language.

For example the assembly instructions push 1 push 2 add are translated (I think) to a series of ones and zeroes, which is then executed by the VM.

Why? Why don't VMs, and the JVM as an example, execute the assembly instructions directly?

They don't have the limitation of physical computers that can only handle ones and zeroes. The JVM can very well take textual instructions such as push 1 push 2 and execute them as they are. Why the additional step of compilation?

答:
Assembly is not binary code.  Assembly is a textual representation of binary code.  In order to execute it, you have to first run it through an assembler that generates byte code or machine code, and that takes time.

Although it is possible to assemble a byte-code program from a byte-code assembler, most programmers don't do it.  Instead, they use a high-level language which compiles to byte-code, directly.

Consequently, the assembly step is not needed.

Byte code is not the same as the processor instructions that actually execute your program.  The VM must translate the byte code into processor instructions first, and then those processor instructions are executed.  It is done this way because byte code is machine-independent; you can use the same byte code on processors having a completely different instruction set, so long as you have a VM for that processor.

ContentLicense: CC BY-SA 3.0


问:
Better way for creating a 2D map?
I have an idea for a game map and have researched some into it. What i'm going to do is have a 2D map(s) that a GM can pick from, or they can create their own using predefined images or images of a particular size they can upload.

From what i've seen, people are using a 2-Dimensional Array, but this is for tiles.

So what my question would be, is there a better way of doing this, for Hexagon? Not necessarily easier, but better. Something that can be used on a large scale, say 1000x1000 hex (100x100 px, 50 radius)

Edit:
I found this site that explains a way to draw out the hexagons. I think i might follow it, unless someone knows a better way.

答:
You can totally use a 2-D array for a hexagonal map. Red Blob Games has a colossal list of hexagonal resources as well as a massively in-depth tutorial including how to map hexagons to a square grid for storage.

Now that you can map hexagons to a 2-D array, I'll let you in on a secret, it doesn't technically matter which you use since there's potentially a better way to store these.

This is a Quad Tree:

Quad Trees are commonly used to index spatial data and being that they are trees, the can be much more compact than arrays. They also are more flexible as they don't have to be stored sequentially. However, this will only be useful if you are storing maps that are very very large, so you might want to combine the two approaches depending on your allowed map sizes and other implementation related factors.

Title: Better way for creating a 2D map?


答:
The bytecode is more efficient to store and easier (hence faster) to parse for the VM.

The textual representation of the bytecode (the "assembly" language) is mainly used for understanding the internals of the bytecode compiler and/or for analyzing the optimization passes.  As Robert Harvey said, the majority of programmers will never deal with the bytecode directly so there is little reason to do this.

Title: Why do VMs not execute the assembly directly?

Body:
Many VMs execute a language of binary form, knows as 'bytecode', which is assembled down from a human readable 'assembly' language.

For example the assembly instructions push 1 push 2 add are translated (I think) to a series of ones and zeroes, which is then executed by the VM.

Why? Why don't VMs, and the JVM as an example, execute the assembly instructions directly?

They don't have the limitation of physical computers that can only handle ones and zeroes. The JVM can very well take textual instructions such as push 1 push 2 and execute them as they are. Why the additional step of compilation?


答:
Here are a couple of reasons to think about:

Using human readable assembly language would waste space on disk and in memory. That has an impact on caching, and therefore on performance. In your example the instruction 'push' takes up four bytes. Why not compress the program by using one byte tokens for all instructions instead of the human readable strings?

It wastes cycles on the processor. Your VM probably has at least two instruction mnemonics that start with 'p'. In order for your VM to figure out whether an instruction is 'push' or 'pop' it has to compare at least two bytes. It's much more efficient if each instruction can be uniquely identified by looking at single byte. The argument to your instructions is a string representing a number. The string has to be converted to a binary format appropriate for they underlying CPU before it can be used in arithmetic. That conversion will take dozens of instructions all by itself. Why do that every time the program is run? It's much more efficient to do it in a one-time pass when the byte code is created.


问:
Would it be the right software engineering system to move from AngularJS-based to jQuery-based or hybrid implementation for webapp?
I am presently working on an AngularJS-based chat webapp, and it polls the server for updates, and then renders them in what is pretty much a straight shot in AngularJS. The result looks appropriate for the maturity of the project, but it completely shuts down clipboard copying from the dialogue because it redraws the text for each polling interval and overwrites the relevant area of the screen with the most newly polled data.

I can see how to reduce this problem by more surgical DOM manipulations in jQuery, where there is one DIV for each completed chunk of data, only DIVs whose contents have actually changed are overwritten, and new DIVs are appended to the container rather than overall. And perhaps someone can point out how to make a more surgical AngularJS implementation so that updates to a small portion of the data rather than thrashing that area of the DOM when the data has been polled (
).

However, I wanted to ask for the appropriateness of my approach. AngularJS obviates most of the need for specifying low-level DOM manipulations; if something surgical desired, would a good AngularJS programmer shift to something like jQuery that's more intended to allow low-level DOM manipulations, or does AngularJS offer facilities for more surgical updates so that DIV's whose contents are static are not redrawn?

I thought about asking this on StackOverflow, and it might be appropriate to ask there how to make a more surgical update so that if the user has begun selecting an area, things that are not going to be changed again don't get thrashed. However, I wanted to ask here. I know jQuery better than AngularJS, and it seemed appropriate to make a "Take a step back" question here about using AngularJS right.

Would an AngularJS programmer who knew jQuery do it with jQuery, do it with a more surgical version of AngularJS usage, or do something else? How do programmers who think in AngularJS handle a situation where they need finer-grained control than the default version allows?

Thanks,

答:
Most of the time you can achieve your goal with any technology, so your question is "Should I stick with jQuery that I know well or take the time to learn AngularJS".
If you are looking short term and are pressed to have a result quickly, use jQuery. Learning AngularJS or any new technology takes time but is a long term investment.

Regarding your whole screen being redrawn, this is a technical question more appropriate for StackOverflow.

First when polling for new contributions, you shouldn't update your data if there is no change. This will leave the DOM unchanged and allow copying.

Then we have to handle the case when new contributions are received. What you are probably doing at a given point is this:

```<code>$scope.contributions = updatedListOfContributions;
</code>```

This effectively tells AngularJS to replace all the contributions. Instead, you should alter the existing list, using splice or push methods of the Array object.

```<code>$scope.contributions.push(newContribution);
</code>```

See the Plunker that updates the list. Select the first two months before the timeout expires and you'll your selection remain unchanged after the update.

Finally, if you are building real-time applications, you shouldn't poll your server periodically as it is not scalable. If possible, use WebSockets that will update your contributions only when there are changes.

Body:
Most of the time you can achieve your goal with any technology, so your question is "Should I stick with jQuery that I know well or take the time to learn AngularJS".
If you are looking short term and are pressed to have a result quickly, use jQuery. Learning AngularJS or any new technology takes time but is a long term investment.

Regarding your whole screen being redrawn, this is a technical question more appropriate for StackOverflow.

First when polling for new contributions, you shouldn't update your data if there is no change. This will leave the DOM unchanged and allow copying.

Then we have to handle the case when new contributions are received. What you are probably doing at a given point is this:

$scope.contributions = updatedListOfContributions;

This effectively tells AngularJS to replace all the contributions. Instead, you should alter the existing list, using splice or push methods of the Array object.

$scope.contributions.push(newContribution);

See the Plunker that updates the list. Select the first two months before the timeout expires and you'll your selection remain unchanged after the update.

Finally, if you are building real-time applications, you shouldn't poll your server periodically as it is not scalable. If possible, use WebSockets that will update your contributions only when there are changes.


问:
Decoupling when constructors have non-contractual parameters
By non-contractual parameters, I mean parameters that are not interfaces or service dependencies, something like class Person(string name).

I am writing a webpage scraping application, and so far I've written it in the wrong order (hence the creation of this question).  I made a class to parse HTML documents (from string format) and give me all the urls and images in it.

That class has the following description:

public class PageParser
{
    private readonly string _html;

    public PageParser(string html) {
        _html = html;
    }

    public IEnumerable<string> GetImages() {
        /* not important */
    }

    public IEnumerable<string> GetLinks() {
        /* not important */
    }
}
```

<p>This code works great, unit-tested, 100% coverage, etc...  The problem is now how do I write unit-tests for code that uses this class without worry about the constructor of this class.  I only need this new class to work with the behavior of the <code>PageParser</code>.</p>

<p>The pseudo code for this new functionality is as follows:</p>

<pre class="lang-cs prettyprint-override"><code>public Report CreateReport(string url)
{
    var html = _webClient.DownloadString(url);

    var parser = new PageParser(html);

    var images = parser.GetImages();
    var links = parser.GetLinks();

    var relevantLinks = links.Where(l => l.Contains('something'));

    return _reportBuilder.Create(images, relevantLinks);
}
</code>```

The problem that I have is I don't want to have a bunch of unit-tests that have epically sized HTML documents for all my various test cases the CreateReport method can have.

The options I have come up with are:

1) Leave everything as is

Leave the class structure as is, just live with having tests with large setup variables

2) Expose the page parser (+interface) from a Factory

Create an interface for PageParser, and create a factory with corresponding interface.

interface IPageParserFactory
{
    IPageParser Create(string html);
}

class PageParserFactory : IPageParserFactory
{
    IPageParser Create(string html)
    {
        return new PageParser(html);
    }
}
```

<p>Then the resulting pseudo code would look something as follows.</p>

<pre class="lang-cs prettyprint-override"><code>// ... download string

var pageParser = _pageParserFactory.Create(html);

// ... create report
</code>```

3) Move the parameter html to each method and create an interface (so now the class has no construction dependencies)

interface IPageParser
{
    IEnumerable<string> GetImages(string html);
    IEnumerable<string> GetLinks(string html);
}
```

4) Something else entirely

If there's another pattern that solves this problem I would like to know it.

答:
From a quick glance, it seems that your CreateReport method is violating the single-responsibility principle, as it does a lot of things:

it reads HTML from URL via DownloadString

it creates the PageParser and retrieves its parsing results

it filters the result based on some relevance criterion

it does the actual creation of a report

Given the method name, one would expect that method to only have that last responsibility. What you have given here instead is something that is highly coupled together with the data retrieval, parsing and filtering logic.

The idea of creating a report is usually based on some sort of already prepared data. So one already starts wondering, why does your method take a URL as input?

From your proposed solutions 1) to 3), none addresses these issues really. When implementing either of these, you will still need to create local files with more-or-less complete HTML contents for your unit tests.

Note that some people even go as far as claiming that no unit test should access the filesystem, because that is generally too slow. Of course, one may disagree with this, but it should at least make you feel a little bit guilty, such that you only do that if you have a very good reason to do so.. and you don't have one in this case.

So let's go with option 4) something else entirely. Taking a different look at your problem, we see that it's really all about dealing with some sort of document data. Your PageParser is the first one to create such data, so what about changing it to not return individual IEnumerables, but instead a single PageData object, which in turn is able to provide the IEnumerables.

Continuing with this line of though, a report generation really only needs a PageData object. Your _reportBuilder.Create(images, relevantLinks) becomes a call to _reportBuilder.Create(pageData) and your CreateReport takes a PageData instead of an URL as input. Actually, CreateReport may get shortened to that one Create line. Everything else was not its responsibility anyways.

Outside of either of these classes (PageParser, PageData, report generator class) you can define an independent PageDataFilter interface and implementation classes. One of them will be the filter you had in your CreateReport. Note that the interface is a simple one-method filtering of the sort PageData ApplyFilter(PageData pageData). Dealing with filters like that gives you the advantages of easy testability of individual filters, easy composition of filters and it decouples the filters from everything else. The report generator need not care if its given PageData was filtered in one way or the other. (Note that for the implementation you have to decide if PageData is immutable, or can be modified by filters in-place. The first option is mathematically sound, easy to reason about, better suitable for parallelization, etc., whereas the latter is more efficient in terms of memory and cpu.)

At this point, you can easily test your PageParser, your report generator, and your link filter. On top of that you can do all of that testing by simply preparing one straightforward instance of a required class in memory. No more URL loading, no more involved HTML stuff outside of PageParser tests, no more file system accesses, and no more coupling that needs to be taken care of in your tests.

Addendum: What the above text is missing is how these components are wired together. Let's say you now have a PageParser that creates PageData which you can filter via PageDataFilter instances and create reports from via ReportCreator. What you still need is the instantiation and instrumentation of these classes - somewhere further outside. It depends on your application's design as to where a proper place would be for that. But for simplicity's sake, you could assume an Application class with a main method. In that method you would do the following:

Download HTML URL to a String

Instantiate a PageParser with this string as constructor argument

Instantiate the desired PageDataFilter objects

Apply the PageDataFilter objects to the PageData delivered by the PageParser

Instantiate the ReportCreator and give it the filtered PageData for creating a report.

Again, it depends on your overall design and architecture, if these things are manually instantiated, dependency-injected, or what-have-you. The major point though is: keep your classes small and limited to their one and only responsibility, then instrument them from the outside. If the instrumentation code gets larger and does too many things, then recursively apply the above ideas to that code as well.


问:
Divide and Conquer algorithms – Why not split in more parts than two?
In divide and conquer algorithms such as quicksort and mergesort, the input is usually (at least in introductory texts) split in two, and the two smaller data sets are then dealt with recursively. It does make sense to me that this makes it faster to solve a problem if the two halves takes less than half the work of dealing with the whole data set. But why not split the data set in three parts? Four? n?

I guess the work of splitting the data in many, many sub sets makes it not worth it, but I am lacking the intuition to see that one should stop at two sub sets.

I have also seen many references to 3-way quicksort. When is this faster? What is used in practice?

答:
Because of its binary nature a computer is very efficient at dividing things in 2 and not so much in 3.
You get a division in 3 by dividing in 2 first and then divide one of the parts again in 2.
So if you need to divide by 2 to get your 3 division, you might as well divide in 2.</p>


答:
Since this is a question about general divide and conquer, not just sorting, I'm surprised no one has brought up the Master Theorem

In brief, the running time of divide and conquer algorithms is determined by two counterveiling forces: the benefit you get from turning bigger problems into small problems, and the price you pay in having to solve more problems. Depending on the details of the algorithm it may or may not pay to split a problem into more than two pieces. If you divide into the same number of subproblems at each step, and you know the time complexity of combining the results at each step, the Master Theorem will tell you the time complexity of the overall algorithm.

The Karatsuba algorithm for multiplication uses a 3-way divide and conquer to achieve a running time of O(3 n^log_2 3) which beats the O(n^2) for the ordinary multiplication algorithm (n is the number of digits in the numbers).

Title: Divide and Conquer algorithms – Why not split in more parts than two?

Body:
In divide and conquer algorithms such as quicksort and mergesort, the input is usually (at least in introductory texts) split in two, and the two smaller data sets are then dealt with recursively. It does make sense to me that this makes it faster to solve a problem if the two halves takes less than half the work of dealing with the whole data set. But why not split the data set in three parts? Four? n?

I guess the work of splitting the data in many, many sub sets makes it not worth it, but I am lacking the intuition to see that one should stop at two sub sets.

I have also seen many references to 3-way quicksort. When is this faster? What is used in practice?


问:
Tournament bracket method to put distance between teammates
I am using a proper binary tree to simulate a tournament bracket. It's preferred any competitors in the bracket that are teammates don't meet each other until the later rounds.  What is an efficient method in which I can ensure that teammates in the bracket have as much distance as possible from each other?  Are there any other data structures besides a tree that would be better for this purpose?

EDIT: There can be more than 2 teams represented in a bracket and there is no requirement to have an equal number of people from each team in a bracket.  I intend to use this for individual sports where a person still has an affiliation with a team and we want to delay teammates facing each other until as late as possible.

Body:
Just sort the players by team and number them starting from 0, so e.g.

0(000)  T1a (team 1 player a)
1(001)  T1b
2(010)  T1c
3(011)  T2a
4(100)  T2b
5(101)  T3a
6(110)  T3b
7(111)  T3c

Then reverse the bits in each number to fill out your bracket sheet

0(000)  T1a\______
1(001)  T2b/      \_______
2(010)  T1c\______/       \
3(011)  T3b/               \________
4(100)  T1b\______         /
5(101)  T3a/      \_______/
6(110)  T2a\______/
7(111)  T3c/


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
When the management pulls the project into different directions simultaneously and the carriage remains still.

I was once involved in a project managed by two guys. Either they didn't talk to each other or each one has some ego to resolve, but they were commandeering our work into opposite direction about each week or so. Didn't take long to realize there's never going to be any result. Gladly my participation only lasted a few months.

ContentLicense: CC BY-SA 2.5


问:
How to best structure Git for our team
We're starting to develop many small web projects in our company, where mostly they will have one shared resource with some code pieces (SDKs, utilities and etc...)

Our team is small (~5) but is growing and is expected to grow x2-x3 in several months.

We're discussing what would be the right way to build our source control and came up with 2 main ideas:

Put all code in one repo which will be synced with Github. Everyone
will have the copy of all projects and will have the shared
resources folder as well - thus will be able to pull/push the shared
code and the project code with only one action. Also, there will be
no need to follow multiple repositories. On the other side, this
might create confusion and errors - as all the code pulled/pushed
even if working only on one project.

Put each project in its own repo and put the shared resources
project in its own repo. Thus everyone who is working on a project
will work only on that repo and won't have to push / pull other
repos. This will create a more streamlined work - but will make
everyone work with at least 2 repositories (shared resources and his
project), which might create confusion.

I would be glad to know if one of the options is a bad idea or if there is a better way.

Thanks!

答:
My team have taken a different approach to the shared resources issue, which is to publish it as a NuGet package and host it on a local network share. This has the advantage that when you update the shared resource with a breaking change, you don't break the projects that depend on it. One small disadvantage is that it is time-consuming to make small changes (e.g. adding an extension method), but I feel the pros outweigh the cons

More information on that can be found on the NuGet docs.

Title: How to best structure Git for our team


问:
How would you approach errors notification?
Recently we had a discussion with my colleagues caused by my intentional attempt to generate user friendly message about occurred error (business logic) at the server side.

They insisted on putting all string localizable resources inside web client assembly and not server one. The argument is to let client decide how to generate and present messages to the user. I can't but agree with the requirement of such flexibility for public services, however we develop intranet back-office system and we develop client part as well (both thin and thick client). Frankly speaking the code I've seen so far does nothing more as generating the message (identical to the code I tried to put in BL). There is no particular controls highlighting, accurately positioned popups or something like that. But now the logic is duplicated: web client + win client.

My point is that It's better to adhere to DRY and YAGNI principles. Copy paste is evil.

The second argument is encapsulation. If error occurred inside Business Logic then it's BL who knows how to describe the error and what additional information should be collected and presented to the user without compromising security or revealing implementation details to the client part.

For example, in case of concurrent changes we return ConcurrenAccessError from the server and client then converts this to "bla bla bla, object was changed by someone else, edit once again, please." Now, to add user name and timestamp of the changes I need to extend ConcurrentAccessError class with additional properties and change code of message generation in two places. I would ask whether client should even know about concurrency as a special error type if it does nothing about it besides user notification. System is not designed for conflict resolving via merge. I believe that high granularity of errors is important only when such structured information allows system somehow help user to make corrections. (Highlighted and focused email input field is better than just a message below the form)

Well, eventually I did not manage to persuade my colleagues. I had to follow the conventions. Yet I need more pro and contra arguments to continue the discussion or agree with them.

I'd like to know which strategies of error notification you usually use and why. Where do you put the logic of constructing the message?

答: I agree with @svidgen, server should process and probably log errors in a server way, UI should process errors and react on them in a user friendly manner, so the messages and code should probably reside on the client side. If you have two clients to you server (e.g. desktop client and web client) then you should stick to DRY and move the common client code to separate assembly used by both clients. Of course if it is internal application and you are 100% sure it will not need things like localisation, then creating this assembly solely for the purpose of generating error message is an overkill, but in general, both your clients could benefit of such a library.</p>


答:
I'd suggest to create a new repository for every project. Aside from the fact that it is common practice, it is practical as well. One of the advantages would be that you don't have to retrieve all projects, when you just want to work on a single project. A second advantage would be that everything files, branches, log-messages etc. are applicable to a single project, so you don't have to dig through irrelevant information.

If one project is dependent on another project, you can use the git submodule functionality. Changes made to the submodule can easily be pushed to the central repository (e.g., GitHub) and pulled by the other projects, such that they benefit as well. Of course you can also create branches for the submodule, in case you have project-specific changes. More on submodules in git can be found here at the Git Submodule Documentation.

Title: How to best structure Git for our team

Body:
We're starting to develop many small web projects in our company, where mostly they will have one shared resource with some code pieces (SDKs, utilities and etc...)

Our team is small (~5) but is growing and is expected to grow x2-x3 in several months.

We're discussing what would be the right way to build our source control and came up with 2 main ideas:

Put all code in one repo which will be synced with Github. Everyone
will have the copy of all projects and will have the shared
resources folder as well - thus will be able to pull/push the shared
code and the project code with only one action. Also, there will be
no need to follow multiple repositories. On the other side, this
might create confusion and errors - as all the code pulled/pushed
even if working only on one project.

Put each project in its own repo and put the shared resources
project in its own repo. Thus everyone who is working on a project
will work only on that repo and won't have to push / pull other
repos. This will create a more streamlined work - but will make
everyone work with at least 2 repositories (shared resources and his
project), which might create confusion.

I would be glad to know if one of the options is a bad idea or if there is a better way.

Thanks!


问:
Why do we need to serialize data using a serialization framework e.g. avro
In this book, the author is using avro to serialize data before it is being processed by pig. What I don't understand is, why we need to do it using a serialization framework like avro? Why don't we just use json as the serialization data format? This way we can just use serializer/deserializer library in a language e.g. data.json in clojure.

答:
Rendering data into JSON can be considered a form of serialization, albeit into a very unconstrained format. A lot of the value in a serialization protocol and library is the additional structure it imposes on the wire representation.

JSON used as-is is not able to represent via any built-in way the 'type' of objects or inter-object references. In order to represent them, you need to add additional ad-hoc structure yourself like fields encoding type information, object IDs so they can be linked, and so on.

A purpose of a serialization library is to encode these things in a consistent manner onto the chosen transport format (custom binary, JSON, XML, text), such that the important aspects of the data are not lost.

When you stuff a bunch of data into a JSON file, you are adhering to an informal contract by the encoding and interpretation of the producer and consumer. Concepts such as JSON Schema may help structure such an approach, but it's often easier to use an established serialization format.


问:
What to focus on when separating a monolithic codebase into separate (NuGet) packages?
I work on a fairly large web application. The main solution containing the web application project has over 100 projects. The average build time of that solution is 2 minutes on a 12 GB quad-core machine with an SSD.

We are looking into ways we can improve our deployment process. I am going to work on a proof-of-concept to move code out of the main source repository into separate repositories, to be built and packaged as NuGet packages. These will be hosted on an internal feed and installed into the main solution from there.

For the proof-of-concept I want to focus on the most important/challenging aspects. I have some experience building stand-alone libraries, and of course the experience of working on this monolithic codebase. I would like to ask you:

What should I focus on for the proof-of-concept?

Some areas I think I should experiment with:

Versioning

Assembly binding

Unit testing

ILMerge to merge dependencies

Debugging

Performance

PS. Automating the building and publishing of packages to the NuGet repository is not my responsibility.

答:
NuGet is just a package manager. Providing that it is the focus of your question, can you really say that the architecture of your project is already good enough and it's just package management that is missing? Otherwise, perhaps, the question should be reworded to focus on refactoring the monolithic architecture rather than introducing package management?

Saying that, here is what worked for me:

1) slice the solutions across business and concern boundaries: e.g. people, authentication, business modules;

2) apply the micro-services architecture;

3) package the very common helper types and functions: framework package.

4) package the common patterns / cross-cutting concerns: Repository Pattern package, Logging package, Caching package, REST package etc.

5) create a client package for every micro-service to benefit from the strong typing.


问:
Rule order for Parsing Lists with LALR(1)
When creating the grammar for parsing a list (something like “ITEM*”) with a LALR(1) parser, this basically can be done in two ways:

```<code>list
    : list ITEM
    |
    ;
</code>```

or

```<code>list
    : ITEM list
    |
    ;
</code>```

What are the pros and cons of these two possibilities? In general, can an advice be given which one to choose, or does this depend on the complete grammar?

What about the case “ITEM+”, i.e.

```<code>list
    : list ITEM
    | ITEM
    ;
</code>```

and

```<code>list
    : ITEM list
    | ITEM
    ;
</code>```

Do the same pros and cons apply here, or others?

答:
Here is a nice explanation. In short:

For LALR(1) the opposite is true: left recursion is good, right recursion is bad.

This has to do both with distinguishing the ITEM elements from the separators, and with run-time efficiency.


问:
What is the best way for a programmer to handle being code reviewed?
I am fairly new to code review, but I have been coding for years during my PhD - which doesn't always make you a good programmer!

If the reviewer changes your code and goes through it with you line-by-line, what do you do if you disagree?  Sometimes you made choice X and the reviewer changes it to Y, and you had Y in your mind but decided not to do it because of the disadvantages, but the reviewer asserts that those disadvantages are not important. Should you verbalise your disagreement, or just not and listen to them?

Its difficult if you are not good at accepting criticism, and if the reviewer is a more senior person in the organisation.  It would not be good to come across as too defensive.

答:
The other answers contain very good information already. I would like to expand a bit on some aspects that have been hinted at by gbjbaanb (see my comment to his answer).

In my experience I have observed different kinds of feedback during code reviews:

"I honestly believe that this is wrong / suboptimal and that you should change it this way." I normally take this kind of feedback seriously, and I will only oppose the suggested change if I think I have a strong point against it.

"I find your solution OK, consider this alternative but it is up to you whether you accept the change or not." I take this kind of feedback seriously too: the reviewer is suggesting an alternative, even though they do not have a strong opinion that their solution is better. I have an opportunity to learn something and I will accept the change if I like it better. Otherwise, the reviewer finds it OK if I keep the code according to my taste.

"I would have done it differently so you have to change it, period.", or even "Oh, I have changed your code because ...", the change has not been suggested, it has been committed already! Some quick explanation regarding the change is given, with the hint that there is not much time to discuss the details because we have to move on to the next task.

The reviewer suggests small changes of trivial nature that do not improve the code but just make it different. When asked to discuss the suggested changes, the reviewer gets into lengthy discussions about trivial details until you give up out of exhaustion.

Options 3, 4 may come disguised as 1 and 2: "It was really important to do it the way I have suggested." or "You can refuse the change if you really want.", said with a tone that in fact means just the opposite of what is being said. In case you oppose to changes you consider unnecessary, shared code ownership can be used a justification of this attitude: "The code does not belong to you, it belongs to the team!" You can tell when the reviewer's intention is not honest if the reviewer is not very open for discussion, gets irritated and tries to push their solution at all costs. Basically they have already decided, and any further discussion is just a waste of time.

IMO options 1 and 2 are a sign of an honest reviewer who is trying to help, is trying to teach you something while respecting your work, and is also open to learn something himself. In this scenario I try not to be too proud when I get constructive feedback from a reviewer.

Options 3, 4 suggest that there is some power game going on: what is important is whether we do it my way or your way, not that we try to find a good solution that satisfies both. This may be related to the reviewer's ego, but also to them being unable to understand any code that does not follow their way of thinking. They are normally disturbed by code that does not look familiar to them and would like to impose their way on the whole code base.

If situations 3 and 4 happen too often, team work can get quite unpleasant.
In such a situation I would consider leaving the team.


问:
Web design standards
While designing web pages using php, are there standards that should be followed? For example suppose there are two pages. First page looks like this:

```<code><body>
<div>
<?php include 'page2.php';?>
</code>```

page2.php file looks like this:

```<code><?php print 'some text';?>
</div>
</body>
</code>```

Is such designing a standard practice? Does it affect search engine results?

答: What matters is the response, or what gets sent to the browser / crawler. How that is done server side doesn't matter.</p>

OwnerDisplayName: Sanket Raut

Title: Web design standards


答:
The code review is both an opportunity to catch potential issues and to pass on knowledge, for both reviewer and coder.

As a code reviewer the responsibility is to highlight possible areas of risk, non-conformance to standard practice, improvements, and generally just another point of view on the same area of code.

This should not result in a change to code without discussing/understanding the coders decisions at time of development.

If the reviewer is making changes they may have difficulty delegating work to others, which is tough for a lot of smart people to do.

As a coder receiving a review you are being protected from a possible issue when deployed, being given the chance to learn something new, and the opportunity to share your knowledge with the reviewer.

Irrespective of seniority your way of thinking can come up with a solution that just doesn't occur to some, so the review can be your chance to shine just by doing what you believe is right.

As long as both coder and reviewer accept that they can be wrong, and that it's ok to be wrong, a review becomes something that strengthens the team because you work together on the solution.

Title: What is the best way for a programmer to handle being code reviewed?

Body:
I am fairly new to code review, but I have been coding for years during my PhD - which doesn't always make you a good programmer!

If the reviewer changes your code and goes through it with you line-by-line, what do you do if you disagree?  Sometimes you made choice X and the reviewer changes it to Y, and you had Y in your mind but decided not to do it because of the disadvantages, but the reviewer asserts that those disadvantages are not important. Should you verbalise your disagreement, or just not and listen to them?

Its difficult if you are not good at accepting criticism, and if the reviewer is a more senior person in the organisation.  It would not be good to come across as too defensive.


问:
When is it appropriate to do calculations in front-end?
My team is developing a WEB based finance application and there was a bit of an argument with a colleague where to keep the calculations - purely in back-end or keep some in front-end too?

Brief explanation:
We are using Java (ZK, Spring) for front-end and Progress 4gl for back-end. Calculations that involve some hardcore math & data from database are kept in back-end, so I'm not talking about them. I'm talking about the situation where the user enters value X, it is then added to the value Y (shown in screen) and the result is shown in the field Z. Pure and simple jQuery-ish operations, I mean.

So what would be the best practice here:

1) Add values with JavaScript that saves from going to the back-end and back and then validate them at the back-end "on save"?

2) Keep all the business logic in the same place - therefore bring the values to the back-end and do the calculations there?

3) Do the calculations in the front-end; then send data to the back-end, validate them there, do the calculations again and only if the results are valid and equal, display them to the user?

4) Something else?

Note: We do some basic validation in Java but most of it is still in the back-end as all the other business logic.

Increase of data that would be sent by recalculating everything in a back-end wouldn't be a problem (small XML size; servers and bandwidth would withstand the increased amount of operations done by users).

答:
As always, such decisions involve a trade-off between different goals, some of which conflict with each other.

Efficiency would suggest that you perform calculations in the front-end - both because that way the user's computer uses more power and your server uses less, and because the user sees faster feedback, which improves the user experience.

Security demands that any state-changing operations cannot rely on data being checked or computed in the client computer, because the client computer may be under the control of a malicious attacker. Therefore, you must validate anything that comes from untrusted sources server-side.

Programming efficiency and maintainability suggests that you shouldn't do the same computation twice because of the wasted effort.

Superficially this sounds as if everything has to be done server-side, but that isn't always the case. If you can easily maintain the duplicated code (e.g. by auto-generating a javascript validator from your server-side Java validator), then repeating the computation can be a good solution. If the data involved are all unimportant, e.g. if the user could cheat only themselves and not you if they manipulate values, then server-side validation isn't necessary. If your response time is dominated by completely different bottlenecks so that a round-trip delay is not perceptible, then UX considerations aren't decisive, etc. Therefore you have to consider how strong each of these pressures is in your situation, and decide accordingly.


答:
To address your issue of what to do when you disagree...

Talking it our is the way to go as most folks have already pointed out.

If you have already done that, maybe more than once even, one useful technique we use is if there is still disagreement in some area(s) is to say 'yeah, it would be good to refactor that -

Can we put in a separate ticket for that?

A separate ticket allow you to get the code in, instead of the dreaded 'churn and never move on' mode that I've known well at some places.  This fits in well with agile, doing the smallest amount 'possible' and spreading the load.  Sometimes yagni will end up applying.  Some times the product manager will decide that there are more pressing needs than that refactor in terms of value to the client, deadlines and resources.


答:
There are strong reasons for doing calculations in the backend

Business logic doesn't belong in the presentation layer

Business logic in JavaScript poses a threat

You assume there's a one-front-end -> one-back-end relationship which is not always true, back-ends should be thought of as being capable or serving more than one front-end application, thus you cannot assume anything.

If calculations use a big ammount of data, it wouldn't be efficient to hold it in the front-end

If calculations uses the database, you will not be able to replicate it in the front end

My recommendation

Have the database enforce as much business rules as posible in the model, including foreign keys, primary keys, check constraints and triggers

Have the business layer throw exceptions when business rules are not met (either because the database returned an error or because the business layer itself validated the data )

If and only if response time is unacceptable, do validations or preprocessing using Ajax ( the work will not be really done in JavaScript, it will be done in the backend without having to reload the page )

You can do simple validation in JavaScript like not allowing an empty value, or values that are too long, or out of range (for the latter you may want to generate the ranges in the back-end )

Title: When is it appropriate to do calculations in front-end?

Body:
My team is developing a WEB based finance application and there was a bit of an argument with a colleague where to keep the calculations - purely in back-end or keep some in front-end too?

Brief explanation:
We are using Java (ZK, Spring) for front-end and Progress 4gl for back-end. Calculations that involve some hardcore math & data from database are kept in back-end, so I'm not talking about them. I'm talking about the situation where the user enters value X, it is then added to the value Y (shown in screen) and the result is shown in the field Z. Pure and simple jQuery-ish operations, I mean.

So what would be the best practice here:

1) Add values with JavaScript that saves from going to the back-end and back and then validate them at the back-end "on save"?

2) Keep all the business logic in the same place - therefore bring the values to the back-end and do the calculations there?

3) Do the calculations in the front-end; then send data to the back-end, validate them there, do the calculations again and only if the results are valid and equal, display them to the user?

4) Something else?

Note: We do some basic validation in Java but most of it is still in the back-end as all the other business logic.

Increase of data that would be sent by recalculating everything in a back-end wouldn't be a problem (small XML size; servers and bandwidth would withstand the increased amount of operations done by users).


答:
Because of different architectures and a common format that can be adapted to the platform at hand.

And possibly because of the vm code being less than comparable platform machine code if scripting language engine codes for garbage collection, hashes and stacks are also included that are referenced in.

Oh and as mentioned: single byte bytecodes instead of more complicated byte or word codes, easier to design.


问:
What is the verb for "to make something into a plugin"?
What is the verb for "to make something into a plugin"?

Example use: "Developer can you make Module Foo into a plugin?". "Yes sir, I can some verb Module Foo".

Terms I have considered: pluginify, pluginize, make pluggable

Criteria for Acceptance: A single verb which means "to make something into a plugin" or "to create something as a plugin". I am looking for a term which is already in use as opposed to a new one.

答:
I have never encountered any such word. Just say "We can turn Module Foo into a plugin" or "We can wrap Module Foo in a plugin".

If you're looking for documentation and examples on plugin systems you can start with searching for "plugin design".


答: I would say "extract," as in you pull the functionality of this module out of the main codebase and extract it into a plugin.</p>

Body:
What is the verb for "to make something into a plugin"?

Example use: "Developer can you make Module Foo into a plugin?". "Yes sir, I can some verb Module Foo".

Terms I have considered: pluginify, pluginize, make pluggable

Criteria for Acceptance: A single verb which means "to make something into a plugin" or "to create something as a plugin". I am looking for a term which is already in use as opposed to a new one.


答: 'Make pluggable' is the shortest it can get without inventing new words. Judging by latest Visual Studio and Chrome versions an 'extension' is a more fashionable word these days. Since the hardest bit is supporting plug-ins rather than writing a plug-in, searching for 'extensible architecture' would make more sense. 'Packages' and 'package management' are another trending pair of concepts of the day.</p>

Title: What is the verb for "to make something into a plugin"?


问:
How does requirements management work in the long term with Agile projects?
Requirements Management in the short term for Agile projects seems like a solved problem to me.

From the Scrum angle new requirements or changes to existing requirements are delivered through User Stories.  And User Stories grouped under an Epic or Feature facilitate the delivery of larger more complex requirements.

Of course, a User Story isn't technically a requirements document.  It is a manageable grouping of work which maps to what is often called a Vertical Slice of functionality.  And the scope of these stories can be defined unambiguously through the use of Acceptance Criteria (AC).

So, although User Stories aren't formal requirements, browsing through them can give you a pretty clear idea of their underlying requirements.  In the short term.

I say in the short term because, as a project progresses, the number of User Stories increases.  Thus, browsing through an ever increasing list of Stories to find a Requirement becomes less and less efficient over time.

This problem is compounded when you consider User Stories that expand on, supersede, or even negate previous Stories.

Now, imagine a 2 year gap between development iterations on a project (stable in production).  The original team is gone and so is all their knowledge.

If the original team knew this was going to happen (eg, it's the nature of the business), then what measures could they take to help subsequent teams?

Sure, the backlog will provide some information, but it's hardly in an easily browsable form.

So, what can be done to help subsequent teams understand the state of the project, including why and how it got there?

In my experience, the following things don't work:

Backlog grooming to delete or update previous User Stories so that the Backlog can be read as a requirements document.

Documentation Sprints where team members are tasked with documenting the current state of the system.

Documentation through Behaviour Tests.  This approach is the only one I have seen come close to working.  Unfortunately, Coded Behaviour tests are victims the Naming Problem.  Although the tests might properly document the system, getting a fluctuating team of developers to write their tests following the same Domain terminology, wording, and style is almost impossible.

So, to reiterate:

How does one manage Agile project Requirements in the long term?

答:
This seems to me to be the unspoken elephant in the room with Agile projects: how do you prevent them from evolving into chaos?

Let's look at the Agile Manifesto for a moment.  Agile desires:

Early and continuous delivery

Embracing changing requirements

Delivering working software frequently

Developers and business stakeholders working together daily

Building projects around motivated individuals, giving them the environment and support they need,
and trusting them to get the job done

Face to face conversation as the primary mode of communication

Working software as the primary measure of progress

Sustainable development

Continuous attention to technical excellence and good design

Simplicity - Maximizing the work you don't have to do

At regular intervals, the team reflects on how
to become more effective, then tunes and adjusts
its behavior accordingly

I've highlighted the last four.  Why?  Because they're the ones that will prevent the project from collapsing under its own weight.

Sustainable development means that you (hopefully) have someone that oversees the overall development process, someone who can steer the ship beyond growing the software a little bit at a time, someone who has an overarching vision of the entire project, someone with a keen knowledge of software architecture, system design, business logic principles and UI ergonomics.  An architect, in other words.

The architect is the one that says "I know you asked for this, but if we build this other thing, we can avoid these other three features that are just confusing, and focus on the core requirement."  He's the one that gives the team time to reduce technical debt.  He's the one that brings an overarching structure and organization to the project.  He's the one that calls meetings where the team gets together and asks "How can we do things better?"

And he's the one that maintains the master requirements document.

In the book Mastering the Requirements Process, the authors maintain that there are three kinds of customers, three kinds of software projects: Rabbits, Horses and Elephants. Rabbits are the small software projects that only need informal requirements; you work directly with the customer in small sprints, the scope of the project is reasonably constrained, and the software gets done within a relatively short time frame. Elephants are those mammoth projects that require a lot of up-front planning, a tremendous amount of documentation, and a long time horizon.  They are arguably not agile, although you can break them up into smaller projects that can be built using agile.

It's the Horse projects that are somewhat confounding from an agile perspective.  They can still be built iteratively, you can still use short sprints, but without some discipline in the requirements gathering and planning processes, they can easily run off the rails.  These are the projects that can benefit from a disciplined requirements gathering process, and then careful adaptation and modification of those requirements as the project grows, while still maintaining an overarching vision for the entire project.

From a personal perspective, I work with a small team of about a dozen developers.  At any given moment, we might be working on three software projects at the same time, ranging anywhere from a few thousand lines of code to over 100,000.  Our customer thinks they are a rabbit, but they're really a horse.  The customer is engaged, but not on a daily basis.

By far our weakest area is gathering specific, testable, measurable requirements and managing the customer's expectations relative to project scope.  But we're working on that.


问:
Is this a specific pattern and what is its purpose?
I recently stumbled over the following C++ Code which confused me a bit:

```<code>class One {/*definition*/};
template<class Base > class Two : public Base {/*definition*/};
template<class Base > class Three : public Base {/*definition*/};
template<class Base > class Four : public Base {/*definition*/};
class Five : public Four < Three< Two < One > > > {/*definition*/};
</code>```

I know the purpose of templates and more or less when and how to use them.

Is there a name or a common pattern for a cascade of several templates?

When would I use this pattern (instead of anything less complex)?

P.S.: definition of class Five actually is empty.

答:
At a guess I'd say that the author was implementing a form of mixin.

The class with the object's primary functionality would be One, but Two, Three etc are adding various pieces of orthogonal functionality that aren't particularly coupled to the primary class. Five is then just a placeholder for taking the aggregation.


问:
Naming convention: Final fields (not static)
Today I had a discussion with a co-worker about the naming of final fields in Java classes.

In his opionion final fields should also be considered constants since their values won't change after the creation of the instance.

This would lead to the following naming convention for final fields:

```<code>public class Foo {
    private static final String BLA_BLA = "bla";

    private final String BAR_BATZ;

    ...
}
</code>```

In my opinion only static final fields should be considered constants while fields which are only final should follow the usual camelCase naming convention.

```<code>public class Foo {
    private static final String BLA = "bla";

    private final String barBatz;

    ...
}
</code>```

Now I'm a bit uncertain since he is a far more experienced programmer than I am, so I'm looking for additional input on this.

答:
Sun (and now Oracle) maintained a document titled Code Conventions for the Java Programming Language.  The last update to this was in '99, but the essence of the style guide line lives on.

Chapter 9 covers naming conventions.

For an identifier type of 'constants':

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

The examples given:

```<code>static final int MIN_WIDTH = 4;

static final int MAX_WIDTH = 999;

static final int GET_THE_CPU = 1;
</code>```

In a more recent document - its slipped in there.  From Variables (The Java Tutorials > Learning the Java Language > Language Basics:

If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

Many static analyzers for Java seek to enforce this.  For example checkstyle enforces:

Checks that constant names conform to a format specified by the format property. A constant is a static and final field or an interface/annotation field, except serialVersionUID and serialPersistentFields. The format is a regular expression and defaults to ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$.

This really boils down to the conventions of the community writing the code... and ideally keeping it the same.

The examples above are given as static final ones which are likely derived from the C conventions for #define - which like C, are replaced in the code during compilation rather than at runtime.

The question that then should be asked is "is this behaving like a constant? or is it behaving like a write once field?" - and then following the conventions accordingly.  The litmus test for such a question would be "If you were to serialize the object, would you include the final field?"  If the answer is that it is a constant then treat it as such (and don't serialize it).  On the other hand, if it is part of the state of the object that would need to be serialized, then it isn't a constant.

Whatever the case, it is important to stick with the code style however right or wrong it is.  Worse problems erupt from inconsistent conventions within a project than merely something that offends the eye.  Consider getting some static analysis tools and configure them to maintain consistency.

ContentLicense: CC BY-SA 4.0

Body:
Sun (and now Oracle) maintained a document titled Code Conventions for the Java Programming Language.  The last update to this was in '99, but the essence of the style guide line lives on.

Chapter 9 covers naming conventions.

For an identifier type of 'constants':

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

The examples given:

static final int MIN_WIDTH = 4;

static final int MAX_WIDTH = 999;

static final int GET_THE_CPU = 1;

In a more recent document - its slipped in there.  From Variables (The Java Tutorials > Learning the Java Language > Language Basics:

If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

Many static analyzers for Java seek to enforce this.  For example checkstyle enforces:

Checks that constant names conform to a format specified by the format property. A constant is a static and final field or an interface/annotation field, except serialVersionUID and serialPersistentFields. The format is a regular expression and defaults to ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$.

This really boils down to the conventions of the community writing the code... and ideally keeping it the same.

The examples above are given as static final ones which are likely derived from the C conventions for #define - which like C, are replaced in the code during compilation rather than at runtime.

The question that then should be asked is "is this behaving like a constant? or is it behaving like a write once field?" - and then following the conventions accordingly.  The litmus test for such a question would be "If you were to serialize the object, would you include the final field?"  If the answer is that it is a constant then treat it as such (and don't serialize it).  On the other hand, if it is part of the state of the object that would need to be serialized, then it isn't a constant.

Whatever the case, it is important to stick with the code style however right or wrong it is.  Worse problems erupt from inconsistent conventions within a project than merely something that offends the eye.  Consider getting some static analysis tools and configure them to maintain consistency.


问:
Why does Microsoft still ship VBA within Office products, instead of integrating .NET directly?
I know that it's possible to call .NET code from your VBA code, but why does VBA continue to exist? The only reason I can think about is legacy.

I just had to sort a Scripting.Dictionary and the amount of code needed was frightening.

The IDE looks like Visual Studio 2003. And there are many little details, that drive you insane (Like changing the line, and getting a warning because of some compilation error). Or, if you open more than one spreadsheet, it mixes into you "VBAProject" and this is really confusing.

The whole module/classmodule/form division is actually not that bad, but I end up everytime with directly writing logic in forms, or having one huge module that handles everything.

Why can't I press Alt+F11, and hack in C#?

答:
Microsoft Office have multiple ways to let you change/enhance the default behaviour programmatically. VBA is a battle tested, proven and widely spread language for in-doc scripting. A lot of office people know VBA and use it, while they don't know more complex programming languages like C#. Office would not be sold as much if customers had to rewrite loads of old macro enabled documents that does business critical things - after they learnt a new language or whatever. Backwards compability is a key feature!

A full .NET stack for Office likely requires some set of dependency management (dll:s, etc) and will easily get heavy to manage for simple tasks - it's hardly an alternative for lightweight scripting. VSTO gives you the ability to go with C#, but at the price of a heavier plugin development cycle.

A program manager at Microsoft has written about this here. It's clear that VBA is and will still be around for small scripting purposes.


答:
Well, the answer is not strictly "legacy".  The answer is that VBA is neither VB6 or VB.Net: it is VBA.  A seperate, but related language.  If replaced VBA with VB.Net it would inevitably break a lot of DOCUMENTS.

Replacing VBA with VB.Net would almost certainly result in data loss for a significant number of users of their prime products -- not a good thing.

And their target market for VBA is not programmers.

Title: Why does Microsoft still ship VBA within Office products, instead of integrating .NET directly?

Body:
I know that it's possible to call .NET code from your VBA code, but why does VBA continue to exist? The only reason I can think about is legacy.

I just had to sort a Scripting.Dictionary and the amount of code needed was frightening.

The IDE looks like Visual Studio 2003. And there are many little details, that drive you insane (Like changing the line, and getting a warning because of some compilation error). Or, if you open more than one spreadsheet, it mixes into you "VBAProject" and this is really confusing.

The whole module/classmodule/form division is actually not that bad, but I end up everytime with directly writing logic in forms, or having one huge module that handles everything.

Why can't I press Alt+F11, and hack in C#?


问:
When would you want two references to the same object?
In Java specifically, but likely in other languages as well: when would it be useful to have two references to the same object?

Example:

```<code>Dog a = new Dog();
Dob b = a;
</code>```

Is there a situation where this would be useful? Why would this be a preferred solution to using a whenever you want to interact with the object represented by a?

答:
Temporary variables: consider the following pseudocode.

```<code>Object getMaximum(Collection objects) {
  Object max = null;
  for (Object candidate IN objects) {
    if ((max is null) OR (candidate > max)) {
      max = candidate;
    }
  }
  return max;
}
</code>```

The variables max and candidate may point to the same object, but the variable assignment changes using different rules and at different times.

Body:
Temporary variables: consider the following pseudocode.

Object getMaximum(Collection objects) {
  Object max = null;
  for (Object candidate IN objects) {
    if ((max is null) OR (candidate > max)) {
      max = candidate;
    }
  }
  return max;
}

The variables max and candidate may point to the same object, but the variable assignment changes using different rules and at different times.


答:
You'd want this anytime your program has a chance of pulling an entity into memory in more than one spot, possibly because different components are using it.

Identity Maps provided a definitive local store of entities so that we can avoid having two or more separate representations.  When we represent the same object twice, our client runs the risk of causing a concurrency issue if one reference of the object persists its state changes before the other other instance does.  The idea is we want to ensure that our client is always dealing the definitive reference to our entity/object.

Title: When would you want two references to the same object?

Body:
In Java specifically, but likely in other languages as well: when would it be useful to have two references to the same object?

Example:

```<code>Dog a = new Dog();
Dob b = a;
</code>```

Is there a situation where this would be useful? Why would this be a preferred solution to using a whenever you want to interact with the object represented by a?


问:
Should you avoid adding unecessary stack frames?
I have been working with laravel (PHP) recently, and there is an option when using their fluent ORM to define where clauses using closures. This gives us two, functionally equivalent, ways to specify a where clause that should only be added in certain cases:

Example 1

```<code>    $query = App::make('Vendor_Orders')->
        where(function($query) use ($admin) {
            if (!$admin) {
                $query->where('vendor_id', '=', $this->id);
            }
        })->
        get();
</code>```

Example 2

```<code>    $query = App::make('Vendor_Orders');
    if (!$admin) {
        $query->where('vendor_id', '=', $this->id);
    }
    $query = $query->get();
</code>```

As you can see, one of these is using a closure (and maintaining the "fluent-ness"), while the other avoids it. My instinct is to prefer the second, because using an anonymous function like that is adding an extra stack frame, which I would expect to make the program less efficient (possibly a holdover from my time working with C). On the other hand, my colleague (whose first language was PHP) prefers the first example, because it avoids the use of a second assignment operator, and he doesn't see anything wrong with piling up extra function calls.

This started me wondering - how much effect does that extra stack frame really have, in a modern system? Does it make any practical difference if one uses a function call instead of an if statement?

I'm not looking for subjective which-do-you-prefer answers, I'm asking for some sort of facts regarding the impact of unnecessary jumps - particularly to anonymous functions - in modern, interpreted languages (e.g. PHP, Java, etc.). Possibly also some notes on how this differs from old-school compiled languages.

答:
Interesting question, but I really think you are approaching this at the wrong level of abstraction. You are writing a web application, probably it will be maintained by yourself and colleagues who will need to make changes to your code. Your first cost to consider is your own productivity. Is one version of the code clearer than the other? Does one version fit better with your coding conventions and style? Is one version easier to test and refactor?

Once you have considered all of that, then thing about whether performance is really an issue. This is difficult for web applications, because the overall performance of an app can be influenced by many things which are outside of your control. However, if you can stress test this code then that would be a good idea. But don't just performance test this snippet, work through a whole use case. Then use a profiler to see whether using more or fewer closures really has an overall effect on your code.

In general though, I would suggest that this sort of micro-managing of performance will lead you down an unproductive rabbit hole. Not only is it difficult (and time consuming) to figure out whether your coding style is having a real effect on the end-user, it may be that performance can be improved by changing or updating or reconfiguring your PHP runtime.

There are SO MANY variables in performance benchmarking, better to deal with readability and maintenance issues first.


答:
The additional invocation is essentially trivial. Avoiding doing something better to avoid a function call is a premature micro-optimization. Write first for readability and maintainability. Once the program is written, you can benchmark performance, and make adjustments from there (and I would strongly suspect your performance bottleneck is not the stack).

Part of the reason this is so trivial is that code calls functions a lot, therefore compilers and interpreters have highly optimized the internals of calling a function. It is better to make the code more readable and not worry so much about the stack.

(I'd still say the second is better, but because it is more readable to me.)

Title: Should you avoid adding unecessary stack frames?

Body:
I have been working with laravel (PHP) recently, and there is an option when using their fluent ORM to define where clauses using closures. This gives us two, functionally equivalent, ways to specify a where clause that should only be added in certain cases:

Example 1

```<code>    $query = App::make('Vendor_Orders')->
        where(function($query) use ($admin) {
            if (!$admin) {
                $query->where('vendor_id', '=', $this->id);
            }
        })->
        get();
</code>```

Example 2

```<code>    $query = App::make('Vendor_Orders');
    if (!$admin) {
        $query->where('vendor_id', '=', $this->id);
    }
    $query = $query->get();
</code>```

As you can see, one of these is using a closure (and maintaining the "fluent-ness"), while the other avoids it. My instinct is to prefer the second, because using an anonymous function like that is adding an extra stack frame, which I would expect to make the program less efficient (possibly a holdover from my time working with C). On the other hand, my colleague (whose first language was PHP) prefers the first example, because it avoids the use of a second assignment operator, and he doesn't see anything wrong with piling up extra function calls.

This started me wondering - how much effect does that extra stack frame really have, in a modern system? Does it make any practical difference if one uses a function call instead of an if statement?

I'm not looking for subjective which-do-you-prefer answers, I'm asking for some sort of facts regarding the impact of unnecessary jumps - particularly to anonymous functions - in modern, interpreted languages (e.g. PHP, Java, etc.). Possibly also some notes on how this differs from old-school compiled languages.


问:
Why is the JavaScript-language different in different programs/sites?
I'm kind of new to programming and i have a question that's been bothering me for awhile.

Why is the JavaScript-language different in different programs/sites.
I've used Codecademy to practice and i've noticed it's different from Eclipse and Unity.

For example, in codecademy, you use: var blabla = "something" to declare a variable.
In eclipse though, you use: int x = 2, String x = "hey".

Why is it like this? Thanks in advance.

答:
Java and JavaScript are two different languages, see this answer on Stack Overflow:
https://stackoverflow.com/a/245068/111143

My guess is that Code Academy uses JavaScript, and Eclipse uses Java internally. Though the name sounds similar, they are not the same.

JavaScript is an ECMAScript dialect, and there are several dialects of this, that are often used in client side software for scripting. Often code that looks a lot similar to JavaScript, is a different ECMAScript dialect, like JScript, og ActionScript.

Java on the other hand is not an ECMAScript dialect, it is a wholly different programming language, JavaScript is named after Java since it was planned as a complementary scripting language for Java, after Netscape and Sun made a license agreement, it was originally called Mocha: https://stackoverflow.com/a/2018747/111143


问:
Choosing a class abstraction when multiple viable approaches exist
I'm having trouble trying to design a class structure for some search functionality.  It's quite possible that I'm approaching this incorrectly altogether, but putting that aside I'm curious how other people would approach a situation as follows:

We need search functionality that allows users to access parcel information:

People will be able to search via 3 different search methods -- MethodA, MethodB, MethodC.

(To give some perspective on what I mean by "method", lets think of these as things like a one line search that will do some intelligent parsing, another method has specific form fields for entering each parameter, etc.)

People will be able to search via 3 different search types -- TypeA, TypeB, TypeC.
(For example, search by owner, search by parcel address, etc.)

The situation isn't terribly complex, but what I'm stuck on is whether I should design my classes around an abstract method object, or an abstract type object.  Essentially, should I do this:

```<code>public class ConcreteMethodA : BaseMethod
{
  public ReturnDataType GetResultsTypeA(){};
  public ReturnDataType GetResultsTypeB(){};
  //Etc.
}
</code>```

Or this:

```<code>public class ConcreteTypeA : BaseType
{
  public ReturnDataType GetResultsMethodA(){};
  public ReturnDataType GetResultsMethodB(){};
  //Etc.
}
</code>```

If you do have some advice about how to solve my specific scenario, I will certainly appreciate it.  However, I'm more interested in heuristics for approaching a design problem of this nature.

答:
Your semantics are all off based on the intentions.

```<code>public ReturnDataType findBasedOnStaticQuery(){};
public ReturnDataType findByPredeterminedFields(Fields...){};
public ReturnDataType findBySomethingElse(){};
</code>```

The point of naming methods is to convey their intent, not their implementation.

getXXX usually means to retrieve and private instance value, get is not a good prefix when you are really doing searches. findXXX is more semantically correct.

Body:
Your semantics are all off based on the intentions.

public ReturnDataType findBasedOnStaticQuery(){};
public ReturnDataType findByPredeterminedFields(Fields...){};
public ReturnDataType findBySomethingElse(){};

The point of naming methods is to convey their intent, not their implementation.

getXXX usually means to retrieve and private instance value, get is not a good prefix when you are really doing searches. findXXX is more semantically correct.


答:
The question is not completely clear but it sounds like you are concerned with requirements traceability. One idea that tends to get lost in Agile in my experience is that business requirements are what the customer wants the system to do, while user stories are really functional requirements that state how the system works. "As a user, I want to be able to X." But that is done to satisfy a requirement, which may be lost in the user story.

What works well in my experience is linking the business requirements and user stories in both directions. BR #1 may be realize by stories A and B. Story C might cover BRs #2 and #3. Put this in your project tracker, spreadsheet, whatever you are using.

Long term, this helps link what the customer is asking for (BRs) with what the system does (stories) to achieve those requirements. This should be fairly minimal documentation that is not onerous to maintain, keeping with the Agile mindset of not producing documentation that nobody needs and is a chore to keep up to date.

It also provides a way for new project members to get to speed since they have something to review to get the history behind why the software does what it does.

Title: How does requirements management work in the long term with Agile projects?

Body:
Requirements Management in the short term for Agile projects seems like a solved problem to me.

From the Scrum angle new requirements or changes to existing requirements are delivered through User Stories.  And User Stories grouped under an Epic or Feature facilitate the delivery of larger more complex requirements.

Of course, a User Story isn't technically a requirements document.  It is a manageable grouping of work which maps to what is often called a Vertical Slice of functionality.  And the scope of these stories can be defined unambiguously through the use of Acceptance Criteria (AC).

So, although User Stories aren't formal requirements, browsing through them can give you a pretty clear idea of their underlying requirements.  In the short term.

I say in the short term because, as a project progresses, the number of User Stories increases.  Thus, browsing through an ever increasing list of Stories to find a Requirement becomes less and less efficient over time.

This problem is compounded when you consider User Stories that expand on, supersede, or even negate previous Stories.

Now, imagine a 2 year gap between development iterations on a project (stable in production).  The original team is gone and so is all their knowledge.

If the original team knew this was going to happen (eg, it's the nature of the business), then what measures could they take to help subsequent teams?

Sure, the backlog will provide some information, but it's hardly in an easily browsable form.

So, what can be done to help subsequent teams understand the state of the project, including why and how it got there?

In my experience, the following things don't work:

Backlog grooming to delete or update previous User Stories so that the Backlog can be read as a requirements document.

Documentation Sprints where team members are tasked with documenting the current state of the system.

Documentation through Behaviour Tests.  This approach is the only one I have seen come close to working.  Unfortunately, Coded Behaviour tests are victims the Naming Problem.  Although the tests might properly document the system, getting a fluctuating team of developers to write their tests following the same Domain terminology, wording, and style is almost impossible.

So, to reiterate:

How does one manage Agile project Requirements in the long term?


问:
Should you ever use private on fields and methods in C#?
I am somewhat new to C# and just found out that: in C# all of the fields and methods in a class are default private. Meaning that this:

```<code>class MyClass
{

string myString

}
</code>```

is the same as:

```<code>class MyClass
{

private string myString

}
</code>```

So because they are the same should I ever use the keyword private on fields and methods? Many online code samples use the keyword private in their code, why is that?

答:
Just because you can omit linefeeds and indentations and your C# compiler will still understand what you want to tell it, it's not automatically a good idea to do that.

```<code>using System; namespace HelloWorld{class
Hello{static void Main(){Console.WriteLine
("Hello World!");}}}
</code>```

is much less readable to the human reader than:

```<code>using System;
namespace HelloWorld
{
    class Hello
    {
        static void Main()
        {
            Console.WriteLine("Hello World!");
        }
    }
}
</code>```

And that's the whole point here—programs are written for two audiences:

The compiler or interpreter.

Yourself and other programmers.

The latter is the one who needs to understand and quickly grasp the meaning of what is written. Because of this there are a few good practices that have emerged over the years and are more or less commonly accepted quasi-standards. One of them is putting explicit scope keywords, another example is putting extra parentheses around complex expressions, even in cases where they would not be needed syntactically, like:

```<code>(2 + 5) & 4
</code>```

Body:
Just because you can omit linefeeds and indentations and your C# compiler will still understand what you want to tell it, it's not automatically a good idea to do that.

using System; namespace HelloWorld{class
Hello{static void Main(){Console.WriteLine
("Hello World!");}}}

is much less readable to the human reader than:

using System;
namespace HelloWorld
{
    class Hello
    {
        static void Main()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

And that's the whole point here—programs are written for two audiences:

The compiler or interpreter.

Yourself and other programmers.

The latter is the one who needs to understand and quickly grasp the meaning of what is written. Because of this there are a few good practices that have emerged over the years and are more or less commonly accepted quasi-standards. One of them is putting explicit scope keywords, another example is putting extra parentheses around complex expressions, even in cases where they would not be needed syntactically, like:

(2 + 5) & 4


答:
Adapter & repository pattern

my examples are written in php, because it is more verbose.

The type problem

As far as I can make out, your 'types' are in fact DataObjects (or models, or entitites or what ever you want to call them). Each type extends thid basic DataOBject class:

```<code>class TypeA extends|implements DataObject {}
class TypeB extends DataObject {}
</code>```

These data objects are representation of your data. They give you a nice set of methods to interact with the data. e.G. getGoo() and setBar('ook')

We also need a kind of interface to retrieve, create (CRUD stuff) the dataobjects. Thats where the repository comes in:

```<code>class TypeARepository extends AbstractRepository implements Repository {}
</code>```

with

```<code>interface Repository
{
    public function findAll();

    public function findById($id);

    public function where($key, $operator, $value);
}
</code>```

Now we have a nice interface to search our different types. Our controller doesn't even care what type he is searching. As far he knows it's just data returned from a repository:

```<code>class MyController
{
    private $repository;

    public function __construct(Repository $repository)
    {
        $this->repository = $repository;
    }
    public function doStuff()
    {
        $data = $this->repository->where('foo','=','bar');
        pass_to_View_magic($data);
    }
}
</code>```

And we isntantiate that controller:

//the controller doesn't car about what you pass in. as long as it is a Repository he can query.
$controller = new MyController(new TypeARepository());
$controller->doStuff();

But what about my different methods?

Your 3 different methods actually do the exact same thing. They search. The only thing they do is take in some kind of input and then pass it to the search function in the correct way. This is the adapter pattern. (google it). You can use the adapter pattern in functions of the Controller or as completly different classes:

```<code>class MyController
{
    private $repository;

    public function __construct(Repository $repository)
    {
        $this->repository = $repository;
    }
    public function doStuff()
    {
        $data = $this->repository->where('foo','=','bar');
        pass_to_View_magic($data);
    }
    public function doSuffDifferently($data)
    {
        $data = $this->repository->where($data[0],$data[1],$data[2]);
    }
}
</code>```

Now doStuffand doStuffDifferently act as small adapters of you Repository interface.

Hoep this helped

Title: Choosing a class abstraction when multiple viable approaches exist

Body:
I'm having trouble trying to design a class structure for some search functionality.  It's quite possible that I'm approaching this incorrectly altogether, but putting that aside I'm curious how other people would approach a situation as follows:

We need search functionality that allows users to access parcel information:

People will be able to search via 3 different search methods -- MethodA, MethodB, MethodC.

(To give some perspective on what I mean by "method", lets think of these as things like a one line search that will do some intelligent parsing, another method has specific form fields for entering each parameter, etc.)

People will be able to search via 3 different search types -- TypeA, TypeB, TypeC.
(For example, search by owner, search by parcel address, etc.)

The situation isn't terribly complex, but what I'm stuck on is whether I should design my classes around an abstract method object, or an abstract type object.  Essentially, should I do this:

```<code>public class ConcreteMethodA : BaseMethod
{
  public ReturnDataType GetResultsTypeA(){};
  public ReturnDataType GetResultsTypeB(){};
  //Etc.
}
</code>```

Or this:

```<code>public class ConcreteTypeA : BaseType
{
  public ReturnDataType GetResultsMethodA(){};
  public ReturnDataType GetResultsMethodB(){};
  //Etc.
}
</code>```

If you do have some advice about how to solve my specific scenario, I will certainly appreciate it.  However, I'm more interested in heuristics for approaching a design problem of this nature.

Body:
Adapter & repository pattern

my examples are written in php, because it is more verbose.

The type problem

As far as I can make out, your 'types' are in fact DataObjects (or models, or entitites or what ever you want to call them). Each type extends thid basic DataOBject class:

class TypeA extends|implements DataObject {}
class TypeB extends DataObject {}

These data objects are representation of your data. They give you a nice set of methods to interact with the data. e.G. getGoo() and setBar('ook')

We also need a kind of interface to retrieve, create (CRUD stuff) the dataobjects. Thats where the repository comes in:

class TypeARepository extends AbstractRepository implements Repository {}

with

interface Repository
{
    public function findAll();

    public function findById($id);

    public function where($key, $operator, $value);
}

Now we have a nice interface to search our different types. Our controller doesn't even care what type he is searching. As far he knows it's just data returned from a repository:

class MyController
{
    private $repository;

    public function __construct(Repository $repository)
    {
        $this->repository = $repository;
    }
    public function doStuff()
    {
        $data = $this->repository->where('foo','=','bar');
        pass_to_View_magic($data);
    }
}

And we isntantiate that controller:

//the controller doesn't car about what you pass in. as long as it is a Repository he can query.
$controller = new MyController(new TypeARepository());
$controller->doStuff();

But what about my different methods?

Your 3 different methods actually do the exact same thing. They search. The only thing they do is take in some kind of input and then pass it to the search function in the correct way. This is the adapter pattern. (google it). You can use the adapter pattern in functions of the Controller or as completly different classes:

class MyController
{
    private $repository;

    public function __construct(Repository $repository)
    {
        $this->repository = $repository;
    }
    public function doStuff()
    {
        $data = $this->repository->where('foo','=','bar');
        pass_to_View_magic($data);
    }
    public function doSuffDifferently($data)
    {
        $data = $this->repository->where($data[0],$data[1],$data[2]);
    }
}

Now doStuffand doStuffDifferently act as small adapters of you Repository interface.

Hoep this helped


答:
in both cases you have names like frobnicateTypeA and frobnicateTypeB. This is a strong indications that you should be passing instances of these types as parameters instead.

In this specific case, you are trying to design a system to perform queries. Let's collect a few general parameters:

users can use different methods to run a query, e.g. a form-based interface or natural language processing.

users can search by different properties, e.g. by parcel owner or by parcel address.

I find it important to note that hardcoding this in method names is not desirable, as it hinders extensibility:

You may want to add a different query method. E.g. you might have to add a speech-based query method. Do you want to add a GetResultsMethodSpeech method to each class that happens to touch query methods?

Luckily, this can be avoided.

You may want to allow queries for additional properties, such as parcel receiver or parcel weight or estimated time of arrival. Do you really want to have to add another method to each class that happens to touch these properties?

Sadly, this can't be avoided.

In short, both of your suggested architectures do not scale.

The key to the solution is that all query methods are just different expressions of the same content – with each query method there is an equivalent way to express the same query. Therefore, there will be only one class representing the query, but different functions assembling this query from the user input. E.g. we could have a QueryFactory that emits Querys. You would then pass that query on to some database wrapper.

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

class QueryFactory {
    public Query FromForm(FormData);
    public Query FromNLP(String);
    public Query FromAudio(AudioRecording);
}

// in the controller, different handlers would then invoke
// the correct method in the factory, and pass the query to the DB
QueryFactory makeQuery = ...;

database.Execute(makeQuery.FromForm(formInput));

// or in a different handler:
database.Execute(makeQuery.FromAudio(audioInput));
</code>```

To add an additional query method, you only have to add the actual parsing logic for that kind of query method, and have to add the code for that specific user interface. You do not have to add any code in the classes that actually execute that query.

Body:
in both cases you have names like frobnicateTypeA and frobnicateTypeB. This is a strong indications that you should be passing instances of these types as parameters instead.

In this specific case, you are trying to design a system to perform queries. Let's collect a few general parameters:

users can use different methods to run a query, e.g. a form-based interface or natural language processing.

users can search by different properties, e.g. by parcel owner or by parcel address.

I find it important to note that hardcoding this in method names is not desirable, as it hinders extensibility:

You may want to add a different query method. E.g. you might have to add a speech-based query method. Do you want to add a GetResultsMethodSpeech method to each class that happens to touch query methods?

Luckily, this can be avoided.

You may want to allow queries for additional properties, such as parcel receiver or parcel weight or estimated time of arrival. Do you really want to have to add another method to each class that happens to touch these properties?

Sadly, this can't be avoided.

In short, both of your suggested architectures do not scale.

The key to the solution is that all query methods are just different expressions of the same content – with each query method there is an equivalent way to express the same query. Therefore, there will be only one class representing the query, but different functions assembling this query from the user input. E.g. we could have a QueryFactory that emits Querys. You would then pass that query on to some database wrapper.

class Query { ... }

class QueryFactory {
    public Query FromForm(FormData);
    public Query FromNLP(String);
    public Query FromAudio(AudioRecording);
}

// in the controller, different handlers would then invoke
// the correct method in the factory, and pass the query to the DB
QueryFactory makeQuery = ...;

database.Execute(makeQuery.FromForm(formInput));

// or in a different handler:
database.Execute(makeQuery.FromAudio(audioInput));

To add an additional query method, you only have to add the actual parsing logic for that kind of query method, and have to add the code for that specific user interface. You do not have to add any code in the classes that actually execute that query.