答:
For this sort of question, I delegate to whichever solution best communicates my intent as a programmer, and makes the job of "Future Greg" easiest.

Using the object as arguments makes it easier to get the method call right 6 months from now and I've forgotten the gritty details of this application. To build on your "is this book in this person's wishlist example", let's say the isInWishList method really only needs to compare the integer Ids of books and members. In reality, this one method only needs two pieces of data in order to do it's job. Now let's take a step back from this one method, and look at the whole software system. I doubt it only requires a book Id and a member Id in order to operate. You'll be pulling the full book and member from the database anyway before even calling the isInWishList because it is likely you'll need to do something more than just call this one method. Maybe you do, but most times you'll need to do more.

Given that, you aren't realistically going to incur a performance penalty by fetching and mapping both objects in full from the database. Theoretically you'll require fewer database calls, but you'll find in practice that this simply isn't true. If you pass those Ids as parameters in the query string back to the server, then yeah, you'll just need to fetch the wishlist from the database. But this is a very narrow view of your whole application. There will be scenarios when you are performing other operations in addition to checking a wish list --- for instance, adding a book to a wishlist. You don't want to add duplicate items.

Go for the solution that is easiest for a new programmer, or your Future Self to understand, which is to pass the Book and Member objects in. Only after finding an actual performance problem should you really concern yourself with just passing the Ids.

Or, we could remember that statically typed languages like Java offer method overloading, so you can have your cake and eat it too:

```<code>public boolean isInWishList(int bookId, int memberId) {
    // ...
}

public boolean isInWishList(Book book, Member member) {
    return isInWishList(book.getId(), member.getId());
}
</code>```

The real answer to this question is to write both methods, call the integer-only version from the strongly typed version, and Bob's your uncle.

Title: Identifier vs domain object as a method parameter

Body:
Are there any objective arguments for or against using objects vs unique ID as method/function parameters? (and members of other objects?). Specially in the context of statically typed languages (C#/Java/Scala)

Pros of object itself:

More typesafe calls. With IDs there is a risk of wrong ordering of arguments. This can be mitigated though by keeping a 'mini' class for each class that only stores the ID of that class.

Get once from persistence, no need to get again

With ID, if the id type changes, say int -> long, then would require change across the board with possibility of mistakes.. (courtsey: https://softwareengineering.stackexchange.com/a/284734/145808)

Pros of using ID:

Most of the time no need for the actual object, just uniqueid would do, so having ID saves time from getting it from persistence.

A mixture of these techniques, as far as I can see, would only have cons of both and pros of neither.

Given that this is a concretely defined problem, I hope there are objective answers and not- "I think" or "I like" types... :-).

EDIT: Context on the suggestion of a commenter- The only restriction is a statically typed languages. The application is a general purpose application, although happy to get answers based on specific usage scenarios as well.

EDIT: Some more context. Say I have a book management system. My model is:

```<code>Book: { id: Int, isbn: String, donatedBy: Member, borrowedBy: Member }
Member: {id: Int, name: String}

Table- wishlist: { isbn: String, memberId: Int}
Table- borrows:  { id: Int, memberId: Int}

Method:
isInWishList( book: Book, member: Member ) vs isInWishList( bookId: Int,  memberId: Int)

handleBorrowRequest( memberId: Int, book: Book ){
   //the login system doesn't actually get the entire member structure, only the member id. I don't need the full member yet. can run a query to verify that the memberId has less than max allowed books for borrowing.
}
</code>```

Why would I want to keep only id and not the full member? Say when I get info about book, I rarely need to know about who has donated or borrowed it. Getting their full information to populate the donatedBy and borrowedBy fields is an overkill.

Ofcourse, these are only my points. I'm sure I'm missing things so wanted to know what are the points in favour/against.

Body:
For this sort of question, I delegate to whichever solution best communicates my intent as a programmer, and makes the job of "Future Greg" easiest.

Using the object as arguments makes it easier to get the method call right 6 months from now and I've forgotten the gritty details of this application. To build on your "is this book in this person's wishlist example", let's say the isInWishList method really only needs to compare the integer Ids of books and members. In reality, this one method only needs two pieces of data in order to do it's job. Now let's take a step back from this one method, and look at the whole software system. I doubt it only requires a book Id and a member Id in order to operate. You'll be pulling the full book and member from the database anyway before even calling the isInWishList because it is likely you'll need to do something more than just call this one method. Maybe you do, but most times you'll need to do more.

Given that, you aren't realistically going to incur a performance penalty by fetching and mapping both objects in full from the database. Theoretically you'll require fewer database calls, but you'll find in practice that this simply isn't true. If you pass those Ids as parameters in the query string back to the server, then yeah, you'll just need to fetch the wishlist from the database. But this is a very narrow view of your whole application. There will be scenarios when you are performing other operations in addition to checking a wish list --- for instance, adding a book to a wishlist. You don't want to add duplicate items.

Go for the solution that is easiest for a new programmer, or your Future Self to understand, which is to pass the Book and Member objects in. Only after finding an actual performance problem should you really concern yourself with just passing the Ids.

Or, we could remember that statically typed languages like Java offer method overloading, so you can have your cake and eat it too:

public boolean isInWishList(int bookId, int memberId) {
    // ...
}

public boolean isInWishList(Book book, Member member) {
    return isInWishList(book.getId(), member.getId());
}

The real answer to this question is to write both methods, call the integer-only version from the strongly typed version, and Bob's your uncle.


问:
Why is the Java bytecode instruction set not orthogonal?
Section 2.11.1 of the JVM 8 Specification includes the words:

In other words, the instruction set is intentionally not orthogonal.

From my perspective, that implies that the Java bytecode instruction set is full of dirty hacks.  I understand that the designers were restricted to only one byte to represent opcodes, but then they consumed 8 opcodes for aload and astore, not to mention individual opcodes for iload, fload, dload, etc.  The only reason I can think of for making the instruction set nonorthogonal is to optimize it for memory-constrained systems**; it seems these design decisions make it more difficult to write optimizers, not to mention limit the instruction set.

Surely I am missing something.  Why did the Java designers do it this way?

**When I say "memory-constrained", what I'm referring to is the size of the bytecode itself.  Presumably the reason they have aload_0 is because it saves a byte over aload 0, and it is used a ton.

答:
Surely I am missing something. Why did the Java designers do it this way?

Java grew out of Oak, which was originally intended to be used in "smart appliances".  It was first developed in 1991.  So we're talking about old-school embedded systems, highly resource-constrained by early 90s standards.

Today, when "embedded system" can mean a minimalist but full-featured computer that costs $9, it seems a bit mind-boggling to architect a system that way, but almost 25 years ago, saving a byte here and a byte there on an embedded system was still a big deal.

ContentLicense: CC BY-SA 3.0


问:
Javascript Constants in ES6
What would be the preferred way to create constants in javascript, specifically with ES6?

Currently I have a constants class which has methods that return the string I'm looking for.

```<code> class Constants {
    constructor() {}

    SOMECONSTANT() {
       return 'someconstant';
    }
 }
</code>```

答:
For backwards compatibility, I would create a read-only property of the encapsulating object, which could be the global object:

```<code>Object.defineProperty(this, 'CONST', {
  value: 123,
  writable: false
});
</code>```

See: Object.defineProperty - writable attribute

Otherwise, ES6 has a const keyword.

```<code>const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
</code>```

See const.

Title: Javascript Constants in ES6

Body:
For backwards compatibility, I would create a read-only property of the encapsulating object, which could be the global object:

Object.defineProperty(this, 'CONST', {
  value: 123,
  writable: false
});

See: Object.defineProperty - writable attribute

Otherwise, ES6 has a const keyword.

const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];

See const.


问:
What is the etymology of the "dot" operator for string concatenation?
Some languages have a . operator for string concatenation. The oldest language I could find that supports it is Perl. Was Perl the first to use it? Why was it chosen?

答:
If you want to stick with a single non-alphanumeric non-whitespace ASCII character for operators, there really aren't that many. I can only see a couple of alternative choices: !, ~, #, ,, and $. Of those, only . and , can be reached without ⇧ on a US keyboard, # is the comment character. Comma makes kind of sense, but it is already used for a different purpose in C and C-like languages, with which a lot of Perl programmers would also be familiar, and so has the same meaning in Perl.

This leaves you only with the dot. Note that a middle dot (·) is used in maths to denote function composition (and Haskell uses the ASCII dot as an approximation for that), which can be kinda-sorta related to concatenation.

There is, in fact, no standard operator symbol for concatenation in maths, some suggestions are the double plus ⧺ (Haskell uses ++ for concatenation) or the frown ⌢.

Some languages use + for concatenation, which is a terrible choice, because concatenation lacks several of the properties that we normally associate with an addition-like operation. Most importantly, concatenation is noncommutative.


问:
AngularJS Different Controller per Role?
I am creating an AngularJS app with a restful-back end. I have 4 types of users for which each component/page may have significantly differnt behavior. What is the best approach to implement this?

Do I have a single html/partial and assign a different controller per role with different implementations per method? Should I have a completely separate HTML for each role and a different controller? Should I just use ifIsInrolecommands?

答:
I've tried both independent controllers, and a single controller with conditionals. It's not fun dealing with slightly different behavior with types and modes. Different controllers will have a lot of repeated code. A single controller with ifs for each type will get very wordy.

My suggestion is to write out a couple of different controllers for two of your user types. When you see the equivalent behavior, move it into a parent controller and make the other two into children. Then finish your remaining two controllers as children of the parent controller. You should see the payoff pretty quickly.

As for the HTML, it's likely best to have different pages/partials for each. ng-include and ng-if would be nice for this.

Here's a quick explanation of parent/child controllers.

And the template design pattern will be pretty helpful. I expect it to work properly between parent and child controllers.

I'm more than happy to hear other opinions since I've hit this issue a few times, myself.


问:
verify a defect is a production defect or not
As a QA person, I always believe that a defect should have all the steps needed for anyone fixing it to be able to reproduce it.

however, is it crazy to think that every defect QA opens need to be checked if it already exists in production too? Reason, why I ask is we have a dev manager who constantly whines about, well if QA would have done this investigation whether if this issue exists in production or not it would save  time for dev folks. I understand that but I still think its kinda non sense to check if every bug QA finds in testing cycle exists in production too.

答:
Once a defect is found, I think that the most important thing to do is to get it logged with the key information - a title or summary, details about the defect or problem is, what actually happens and what you expect should happen, the steps you need to reproduce it, and the environment where it was found (such as the OS, web browser, software version under test, etc). Depending on your process, the person submitting the defect report may also assign a priority and/or severity.

From a QA perspective, you are usually looking at software that is still under development, or at best a release candidate. Although the development team should be performing unit, integration, and some system tests before you get to it, their tests aren't perfect and you're going to find issues that the dev team should look at before they go to release. Ultimately, it's up to someone in the organization to prioritize identified issues and decide if something will be fixed in this release cycle or a later release cycle.

Throughout the development cycle, both the development team and the QA team should be changing their tests. There may be a regression test suite that always gets executed, but I would suspect that testing is more thorough and focused on features or parts of the software that have changed. Defects could be exposed for any number of reasons. A change could have introduced a defect. A change could have made defect more obvious, easier to trigger, or more common. The new test cases could have found a defect that has been latent in the software for a long period of time. Regardless of why the defect was detected by the testing isn't that important right now - the first priority should be to fix the defect.

In some environments, such as customer self-hosted software or where there is an obligation to support or maintain multiple versions, it may be necessary to test multiple versions of the software to determine when the defect was first introduced so that customers can be notified, especially if it is a significant defect. In environments such as these, I would expect more of a burden to be placed on the QA team in identifying affected versions(s) out of those that are currently supported and to address why the issue escaped from multiple levels and rounds of testing.

However, in environments where only one version of the software is supported, I'm not sure that it really matters what version the defect started in. If the defect was affecting users and they have a mechanism to report issues, then they will report it as a problem. However, from a quality perspective, it is important to understand known issues with the software. From a project management perspective, the amount of open issues can be used to determine if software is ready to be released or to plan work for a future development cycle. Even if it's not scheduled to be fixed prior to the end of the current development cycle, it could be reflected in user-facing documentation, along with workarounds, until it can be fixed.

At the end, after the defect has been fixed, you may choose to perform some kind of root cause analysis to determine when the defect was injected (in the current development cycle), why the defect wasn't discovered in previous development and QA cycles (if it wasn't recently introduced), and what types of tests should be created, executed, and managed to prevent this defect from returning in the future.

As an aside, I would like to note that there are multiple ideas for what a Software QA organization should be responsible for. In some organizations, Software QA is essentially a test team that is the last line of defense for software releases to ensure that it meets requirements and has no significant issues. In other organizations, Software QA is not only responsible for product quality, but also process quality and may be involved in every step of the development process to ensure that all work products (from requirements through the distribution media) are complete and correct per standards. There are other expectations, as well. This answer focuses more on Software QA being responsible for product quality.


问:
How to store data that is recorded with different frequency?
I'm writing a metallurgical web application, that must store data (electrical parameters) recorded at different frequencies. For example:

six parameters recorded with frequency of one measure per second,

three parameters recorded with frequency of ten measures per second.

(all parameters are decimals with six digits following the decimal point -- DECIMAL(10,6)).

How should I design database structure to store such values efficiently? And to be able to query this kind of datasets easily for presenting them on any kind of graph?

Possibilities (ideas?), I came so far with:

Store both parameters sets in two different tables, with one record per corresponding time unit, store all parameters in columns declared as above (decimals), and query one record from first table and ten records from second table per each point on drawn graph. That would make 11 records per second.

Store all parameters in one table, with one record per one second, store each parameter from first group in decimal columns and each parameter from second group as an array of decimals, and query one record from this table only per each point of drawn graph. That would make 1 record per second.

Something different (if both above are wrong).

I have no idea which solution would be better in terms of better performance and lesser data redundancy.

First solutions seems to consume much more database space, because you have eleven records per each second of measures (and we can deal even with thousands of devices getting their measures each second), but in the same time seems to be faster on parsing, because you have direct access to each value in each record and in each column. While, in second case, you should get much lesser database size (cause we have one record per each second and each device) but parsing this data seems slower, because you have to parse array of ten values per each second and each parameter measured with 1/100 ms freq.

If my (above) assumtions are correct, then this question narrows to answering, what is more important in today database design -- database size or parsing time? For low-cost solutions (like shared hosting or low-hardware VPSes) I'd assume, that database size matters far more and therefore I'd go into second option.

I'm mainly focused on using MySQL, but I can accept nearly any other kind of database, if there would be any advantage of using different RDBMS.

Additional information:

There is no need (at least in my case) to store in DB microtime in case of second group of paramteres (i.e. those, that are recorded with 1/100 ms frequency). They only need to be correctly linked to that "second" (timestamp) under which other parameters (recorded with 1/1 s frequency) are stored.

There is no need to store each parameter in a separate record in database. As my ideas shows, all parameteres can be stored in one record per each measure.

答:
Probably the simplest solution is to collect the 1/10th second data in cache and write them with the 1 second fact when it arrives. Storing both values at the same time removes the complexity of dealing with summary tables and the related cleanup tasks. A good way to handle the 1/10th value is to add all the samples and divide by the # collected when the 1 second fact arrives. You can also keep other statistics of interest on the 1/10th fact such as min, max, stddev, and etc depending on the value of the 1/10th second values for information like spikes. A sample table design might be:

fact 1 is the 1 sec
fact 2 is the 1/10th sec

timestamp
fact_1
fact_2_avg
fact_2_min
fact_2_max
fact_2_count
fact_2_stddev

After this is in place, you might consider the granularity of the data you need over time and consider rolling both values up before writing them to the database so you might only write every minute or 5 minute or some time that is configured in the table.

Also, as the system runs for months or years you may consider if you need to know what the value was on 3/15/2012 12:03.55. If you don't need it, consider summary levels like you might see in MRTG where you have a live view for 24 hours, a 5 minute summary at a weekly view, then a 1 hour view at 30 days, and etc. This allows you to keep data and maintain fast performance and monitoring of trends without having the query through 31 million of rows of data per year.

Another trick for dealing with data like this is to use a table that is a 24 hour rolling table. Your key just uses hour, minute, second and no date. This way you have a free rolling 24 hour table. Just watch out for gaps (clean data between your last sample and this one so you don't have old data between your inserted values if you miss a second or two while collecting data). Think of it as an update instead of insert and you'll understand how this table works.


问:
How to use one web page to create and edit database entries
My team and I are developing a java web application which allows our admins to create and edit "methods" which can later be viewed by other users.

We are currently discussing the best way to implement this and aim for a screenflow similar to creating / editing events in google calendar.

I.e. The admin starts on a page which shows all current "methods" and a "create new method" button. If he chooses to edit a "method" he is redirected to page "EDIT" where he can change the method's attributes (editing and then sending it via AJAX to update the attribute).
If he chooses to create a new method he should be redirected to a page looking the same, changing attributes, etc. But if he does not change anything and goes back / closes the browser the method should not be saved.

We currently have 2 ideas to do this, both with some drawbacks:

A) Create the "method" with default values and redirect the user to the edit-page. Drawback: Should the user go back or close the browser, we have created an unnecessary entry in the db, which our product owner would like to avoid. (There is a 'delete' button, but this would require another action by the admin)

B) We create separate pages for create and edit (and the corresponding handlers). Drawback: We have to create and maintain 2 (or even 4) files which do basically the same thing.

Is there any way to negate our drawbacks or another alternative how to implement this? We are using Java Web Projects, JSPs and Servlets as technology.

答:
This is a common problem we encounter in our tools too. A nice UI solution we use is shown by a product by Telerek called Kendo. The grid can use a button to sync edits with the db inside the grid. Although the grid takes a professional license, you can try it out free and see if you like the style and follow the samples and build your own instead.

Basically, the data is shown in an HTML table, if the user clicks on the cell it goes into an edit mode to alter values directly in the cell. If they do not want to save the edit or simply close the browser, the value was only in the client browser and is thrown out. Optionally, edits can be sync'd live as the user moves between fields. It's up to you how the interface functions. The data is actually stored in a smart array in the browser like a small database where the grid is just displaying the array (MVC, Model View Controller design pattern). Click save just sends the dirty cells to the database via ajax.

Check out: http://demos.telerik.com/kendo-ui/grid/editing-inline

Even if you don't user their tools, the method is a great demo on how to manage the UI for table edits.


问:
Avoid having an initialization method
I have this existing code where they have a class and an initialization method in that class. It is expected that once the object of the class is created, they need to call initialize on it.

Reason why the initialize method exist
The object gets created early to have a global scope and then the initialize method gets called later after loading a dll which it depends on.

Issue with having the initialize
The class now has this bool isInitialized which needs to be checked in every method before it proceeds and returns error if it is not initialized. Simply put, it is a big pain.

One possible solution
Initialize in the constructor.
Have just a pointer to the object in the global scope.
Create the actual object after the dll is loaded.

Issue with the above solution
Anyone who creates an object of this class needs to know that it needs to be created only after the dll is loaded or else it will fail.

Is this acceptable?

答:
This is a tricky question. I do feel that architecture may help with the problem.

From the evidence, it sounds like the .dll isn't loaded when the program is loaded. It almost sounds like a plugin.

One thing that comes to mind is that you have to initialize the .dll. The programmer has to assume that the object won't come back reliably, anyways. You might be able to take advantage of this ( bool isObjectLoaded() { return isInitialized;  } ) , but you'll definitely get more bug reports over your checks.

I was thinking of a singleton.

If you call the singleton, it should return the correct object if it can retrieve one. If it cannot return the correct object, then you should get some error value / nullptr / empty base object. This wouldn't work if the object can die on you, though.

Also, if you need multiple instances of the object, you can use something like a Factory instead.

OwnerDisplayName: Sriram Subramanian

Title: Avoid having an initialization method

ContentLicense: CC BY-SA 4.0


问:
Development approach for GUI application sharing on X
I'm curious about developing a simple system for GUI application sharing between users on a single computer, which uses Xorg (or perhaps any modern form of X11 display). I'd like user Alice to be able to authorize user Bob to view and control a particular selected application she's running, which will then appear for Bob exactly as it appears for Alice, permitting them to both control the application.

TL;DR: I'd like to know how to gather/scrape the graphical data.

Assumptions and requirements include:

Assuming Alice and Bob are logged into the same local machine.

Alice and Bob may be using any desired desktop (Gnome, KDE, XFCE, etc) and any graphics toolkit (GTK, Qt, etc). They may have different configurations.

Alice and/or Bob may be logged in via separate VNC server (eg. tigervnc), X11VNC framebuffer-grabbing server, X2Go, physical monitor and keyboard, VirtualBox window on a host screen, or some other means. The user should not need to care about how they are viewing their desktop.

The toplevel window and all descendent windows of Alice's selected application would appear for Bob at the same size/scale, but allow Bob to move them separately from what Alice sees. Resizes would be mirrored to both users.

For the moment I'm only interested in supporting basic 2D graphical operations -- 3D rendering and video are nonessential.

What I'm looking for is a way to hook or be informed of UI updates to the application, so I can stream those updates (the protocol doesn't matter for this question) and redraw them for Bob. How is this normally done?

I've noticed that Google Hangouts for example, is able to share a user's full screen. It can also share individual apps, which is what I'd like to do -- but only sometimes. It seems to fail on desktops not using a compositor of some kind, and it may fail for other reasons as well. I would not like to require a hardware framebuffer to snoop on, as one of my most important use cases is where one or both users are remote.

Is there a way I can "intercept" drawing/painting API calls at some level, to get a fairly hardware- and desktop-agnostic means of capturing an application's GUI?

EDIT: As an add-on thought, how might the situation have changed or how might it in the future, with regard to compositors and display servers like Wayland? The relationship between X servers and compositors seems a bit confusing at the moment, but might Wayland (or Mir?) offer a more straightforward means of doing this for both X and direct-API applications?

答:
With X, there are only three ways to do this:  require that programs be linked with a customized Xlib that has the hooks for communication with an application to show it elsewhere, use a customized server to capture single window contents (as VNC might do) or intercept and process the X protocol stream.

I designed and built a program called XTV in the late 1980s that replicated single X clients to multiple hosts and did keyboard and pointer sharing.  This was accomplished through protocol interception and modification for each destination display.  It was also, as far as I know, the first attempt to do it in a way that used unmodified clients and servers.  The closest thing to it that would work with more-modern X is Xpra.

There was a paper about it and subsequent research and development, some of which is covered by other papers that cite it.


问:
Why can't there be any implicit conversions?
As I understand it, implicit conversions can cause errors.

But that doesn't make sense -- shouldn't normal conversions also cause errors, then?

Why not have

```<code>len(100)
</code>```

work by the language interpreting (or compiling) it as

```<code>len(str(100))
</code>```

especially since that's the only way (I know of) for it to work. The language knows what the error is, why not fix it?

For this example I used Python, though I feel that for something this small it's basically universal.

答:
Languages that support implicit conversions/casts, or weak typing as it is sometimes referred to, will make assumptions for you that don't always match up with the behavior you intended or expected.  The designers of the language may have had the same thought process as you did for a certain type of conversion or series of conversions, and in that case you'll never see a problem; however if they didn't, then your program will fail.

The failure however, may or may not be obvious.  Since these implicit casts occur at runtime, your program will run along happily and you'll only see an issue when you look at the output or result of your program.  A language that requires explicit casts (some refer to this as strong typing) would give you an error before you program even begins execution, which is a much more obvious and easier problem to fix that implicit casts gone wrong.

The other day a friend of mine asked his 2 year old what 20 + 20 was and he replied 2020.  I told my friend, "He is going to become a Javascript programmer".

In Javascript:

```<code>20+20
40

20+"20"
"2020"
</code>```

Thus you can see the problems implicit casts can create and why it's not something that can just be fixed.  The fix I would argue, is to use explicit casts.

Body:
Languages that support implicit conversions/casts, or weak typing as it is sometimes referred to, will make assumptions for you that don't always match up with the behavior you intended or expected.  The designers of the language may have had the same thought process as you did for a certain type of conversion or series of conversions, and in that case you'll never see a problem; however if they didn't, then your program will fail.

The failure however, may or may not be obvious.  Since these implicit casts occur at runtime, your program will run along happily and you'll only see an issue when you look at the output or result of your program.  A language that requires explicit casts (some refer to this as strong typing) would give you an error before you program even begins execution, which is a much more obvious and easier problem to fix that implicit casts gone wrong.

The other day a friend of mine asked his 2 year old what 20 + 20 was and he replied 2020.  I told my friend, "He is going to become a Javascript programmer".

In Javascript:

20+20
40

20+"20"
"2020"

Thus you can see the problems implicit casts can create and why it's not something that can just be fixed.  The fix I would argue, is to use explicit casts.


问:
Are ANSI* Escape Sequences Proper For Coloring Text in Terminal(Linux)?
I just switched back to Linux after a few years of Windows use and am wondering if ANSI Escape Sequences are okay for coloring text. I ask because the way I did it on windows isn't capable of crossing platforms because of the use of windows.h.

Someone had mentioned NCurses or something but didn't explain it to me. Would this be a good alternative? Is there any negative aspects of NCurses or ANSI esc? Sorry if this question is dumb, I'm still a newbie.

This was the code I used for colored text on windows.

```<code>int setColor(const int foreground, const int background)
{
    int Color = foreground + (background * 16);
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, Color);

    return 0;
}
</code>```

Thanks,
xChubz

答:
ANSI escape sequences aren't supported by all terminals; the most common case you'll come across is a remote session that doesn't support color, where the terminal emulatior will attempt to display the color escape sequences. You definitely should be using a terminal/textual user interface (TUI) library (you may also see them called "console user interface" (CUI) libraries). Ncurses (or curses, its predecessor) is one such, but isn't the only one; newt is another. There are also terminal capabilities libraries, such as termcap and terminfo (the latter has generally supplanted the former), which contain terminal control sequences. Ncurses (and other TUI libs) use terminfo.

TUI libs provide not only cross-terminal portability, but cross-platform, as some libs (including ncurses) have been ported to Windows.

The trade-off is a certain type of complexity, but you'll also be getting rid of a different (and much less manageable) complexity (dealing with different terminal capabilities).


问:
Separating ASP.NET IdentityUser from my other entities
I have a ProjectName.Core library containing all my business logic and my entities and their behaviour. There's currently no relation whatsoever to Entity Framework or any other DAL because I like to keep those things seperated. The Entity Framework configurations (using the Fluent API) reside in a ProjectName.Infrastructure project so that takes care of pushing my entities into EF. Basically I'm going in the direction of an Onion-like architecture.

However, when adding the ASP.NET Identity framework into the mix, I have to make my ApplicationUser entity inherit from the IdentityUser class but my ApplicationUser class has relations to other entities. In inheriting from IdentityUser I'm introducing a reference to Entity Framework in my entities project, the one place where I wouldn't want to do so. Pulling the ApplicationUser class out of the entities project and into the Infrastructure project (since it is using an Entity Framework based identity system) will result in circular references, so that isn't the way to go either.

Is there any way around this so I can keep the clean seperation between the two layers besides not using ASP.NET Identity?

答:
You can create a User class that has nothing to do with ASP.NET Identity in your core library.

```<code>public class User {
    public Guid UserId { get; set; }
    public string UserName { get; set; }
    public string EmailAddress { get; set; }
    public string EmailAddressConfirmed { get; set; }
    public string PhoneNumber { get; set; }
    public string PhoneNumberConfirmed { get; set; }
    public string PasswordHash { get; set; }
    public string SecurityStamp { get; set; }

    ...

    public virtual ICollection<Role> Roles { get; set; }
    public virtual ICollection<UserClaim> UserClaims { get; set; }
    public virtual ICollection<UserLogin> UserLogins { get; set; }
}
</code>```

If you're using Entity Framework, create a configuration class for your entities (optional).

```<code>internal class UserConfiguration : EntityTypeConfiguration<User>
{
    internal UserConfiguration()
    {
        ToTable("User");

        HasKey(x => x.UserId)
            .Property(x => x.UserId)
            .HasColumnName("UserId")
            .HasColumnType("uniqueidentifier")
            .IsRequired();

        Property(x => x.PasswordHash)
            .HasColumnName("PasswordHash")
            .HasColumnType("nvarchar")
            .IsMaxLength()
            .IsOptional();

        Property(x => x.SecurityStamp)
            .HasColumnName("SecurityStamp")
            .HasColumnType("nvarchar")
            .IsMaxLength()
            .IsOptional();

        Property(x => x.UserName)
            .HasColumnName("UserName")
            .HasColumnType("nvarchar")
            .HasMaxLength(256)
            .IsRequired();

        // EmailAddress, PhoneNumber, ...

        HasMany(x => x.Roles)
            .WithMany(x => x.Users)
            .Map(x =>
            {
                x.ToTable("UserRole");
                x.MapLeftKey("UserId");
                x.MapRightKey("RoleId");
            });

        HasMany(x => x.UserClaims)
            .WithRequired(x => x.User)
            .HasForeignKey(x => x.UserId);

        HasMany(x => x.UserLogins)
            .WithRequired(x => x.User)
            .HasForeignKey(x => x.UserId);
    }
}
</code>```

You'd have to also create classes for Role, UserClaim, and UserLogin. You can name them whatever you choose if you don't like the above names.

In the web layer, create a class called AppUser (Or another name if you choose). This class should implement the ASP.NET Identity IUser<TKey> interface, where TKey is the data type for the primary key (Guid in the above example).

```<code>public class AppUser : IUser<Guid>
{
    public AppUser()
    {
        this.Id = Guid.NewGuid();
    }

    public AppUser(string userName)
        : this()
    {
        this.UserName = userName;
    }

    public Guid Id { get; set; }
    public string UserName { get; set; }
    public string EmailAddress { get; set; }
    public string EmailAddressConfirmed { get; set; }
    public string PhoneNumber { get; set; }
    public string PhoneNumberConfirmed { get; set; }
    public string PasswordHash { get; set; }
    public string SecurityStamp { get; set; }
}
</code>```

Change all references to UserManager in the web project to UserManager<AppUser, Guid>.

Finally, create your own UserStore. Essentially, the custom UserStore will take in the AppUser object, convert it to an User entity object, then persist it. An example of one of these methods is shown below:

```<code>public class UserStore :
    IUserLoginStore<AppUser, Guid>,
    IUserClaimStore<AppUser, Guid>,
    IUserRoleStore<AppUser, Guid>,
    IUserPasswordStore<AppUser, Guid>,
    IUserSecurityStampStore<AppUser, Guid>,
    IUserStore<AppUser, Guid>,
    IDisposable
{
    private User MapFromAppUser(AppUser appUser)
    {
        if (appUser == null)
            return null;

        var userEntity = new User();

        PopulateUser(userEntity, appUser);

        return userEntity;
    }

    private void PopulateUser(User user, AppUser appUser)
    {
        user.UserId = appUser.Id;
        user.UserName = appUser.UserName;
        user.EmailAddress = appUser.EmailAddress;
        user.EmailAddressConfirmed = appUser.EmailAddressConfirmed;
        user.PhoneNumber = appUser.PhoneNumber;
        user.PhoneNumberConfirmed = appUser.PhoneNumberConfirmed;
        user.PasswordHash = appUser.PasswordHash;
        user.SecurityStamp = appUser.SecurityStamp;

        // First name, last name, ...
    }

    #region IUserStore<AppUser, Guid> Members

    public Task CreateAsync(AppUser appUser)
    {
        if (appUser == null)
            throw new ArgumentNullException("appUser");

        var userEntity = MapFromAppUser(appUser);

        // Persist the user entity to database using a data repository.
        // I'll leave this to you.
    }

    ...

    #endregion
}
</code>```

To get a full description of a possible implementation, click here.

In the end, it's your choice. Measure the amount of effort it would take for you to maintain this implementation versus just referencing the Identity framework in your Core library. Personally, I thought of doing it the way I described above, however, I didn't because I'd potentially have to change my code every time the ASP.NET Identity framework is updated.

Hopefully this helps and answers your question!

Body:
You can create a User class that has nothing to do with ASP.NET Identity in your core library.

public class User {
    public Guid UserId { get; set; }
    public string UserName { get; set; }
    public string EmailAddress { get; set; }
    public string EmailAddressConfirmed { get; set; }
    public string PhoneNumber { get; set; }
    public string PhoneNumberConfirmed { get; set; }
    public string PasswordHash { get; set; }
    public string SecurityStamp { get; set; }

    ...

    public virtual ICollection<Role> Roles { get; set; }
    public virtual ICollection<UserClaim> UserClaims { get; set; }
    public virtual ICollection<UserLogin> UserLogins { get; set; }
}

If you're using Entity Framework, create a configuration class for your entities (optional).

internal class UserConfiguration : EntityTypeConfiguration<User>
{
    internal UserConfiguration()
    {
        ToTable("User");

        HasKey(x => x.UserId)
            .Property(x => x.UserId)
            .HasColumnName("UserId")
            .HasColumnType("uniqueidentifier")
            .IsRequired();

        Property(x => x.PasswordHash)
            .HasColumnName("PasswordHash")
            .HasColumnType("nvarchar")
            .IsMaxLength()
            .IsOptional();

        Property(x => x.SecurityStamp)
            .HasColumnName("SecurityStamp")
            .HasColumnType("nvarchar")
            .IsMaxLength()
            .IsOptional();

        Property(x => x.UserName)
            .HasColumnName("UserName")
            .HasColumnType("nvarchar")
            .HasMaxLength(256)
            .IsRequired();

        // EmailAddress, PhoneNumber, ...

        HasMany(x => x.Roles)
            .WithMany(x => x.Users)
            .Map(x =>
            {
                x.ToTable("UserRole");
                x.MapLeftKey("UserId");
                x.MapRightKey("RoleId");
            });

        HasMany(x => x.UserClaims)
            .WithRequired(x => x.User)
            .HasForeignKey(x => x.UserId);

        HasMany(x => x.UserLogins)
            .WithRequired(x => x.User)
            .HasForeignKey(x => x.UserId);
    }
}

You'd have to also create classes for Role, UserClaim, and UserLogin. You can name them whatever you choose if you don't like the above names.

In the web layer, create a class called AppUser (Or another name if you choose). This class should implement the ASP.NET Identity IUser<TKey> interface, where TKey is the data type for the primary key (Guid in the above example).

public class AppUser : IUser<Guid>
{
    public AppUser()
    {
        this.Id = Guid.NewGuid();
    }

    public AppUser(string userName)
        : this()
    {
        this.UserName = userName;
    }

    public Guid Id { get; set; }
    public string UserName { get; set; }
    public string EmailAddress { get; set; }
    public string EmailAddressConfirmed { get; set; }
    public string PhoneNumber { get; set; }
    public string PhoneNumberConfirmed { get; set; }
    public string PasswordHash { get; set; }
    public string SecurityStamp { get; set; }
}

Change all references to UserManager in the web project to UserManager<AppUser, Guid>.

Finally, create your own UserStore. Essentially, the custom UserStore will take in the AppUser object, convert it to an User entity object, then persist it. An example of one of these methods is shown below:

public class UserStore :
    IUserLoginStore<AppUser, Guid>,
    IUserClaimStore<AppUser, Guid>,
    IUserRoleStore<AppUser, Guid>,
    IUserPasswordStore<AppUser, Guid>,
    IUserSecurityStampStore<AppUser, Guid>,
    IUserStore<AppUser, Guid>,
    IDisposable
{
    private User MapFromAppUser(AppUser appUser)
    {
        if (appUser == null)
            return null;

        var userEntity = new User();

        PopulateUser(userEntity, appUser);

        return userEntity;
    }

    private void PopulateUser(User user, AppUser appUser)
    {
        user.UserId = appUser.Id;
        user.UserName = appUser.UserName;
        user.EmailAddress = appUser.EmailAddress;
        user.EmailAddressConfirmed = appUser.EmailAddressConfirmed;
        user.PhoneNumber = appUser.PhoneNumber;
        user.PhoneNumberConfirmed = appUser.PhoneNumberConfirmed;
        user.PasswordHash = appUser.PasswordHash;
        user.SecurityStamp = appUser.SecurityStamp;

        // First name, last name, ...
    }

    #region IUserStore<AppUser, Guid> Members

    public Task CreateAsync(AppUser appUser)
    {
        if (appUser == null)
            throw new ArgumentNullException("appUser");

        var userEntity = MapFromAppUser(appUser);

        // Persist the user entity to database using a data repository.
        // I'll leave this to you.
    }

    ...

    #endregion
}

To get a full description of a possible implementation, click here.

In the end, it's your choice. Measure the amount of effort it would take for you to maintain this implementation versus just referencing the Identity framework in your Core library. Personally, I thought of doing it the way I described above, however, I didn't because I'd potentially have to change my code every time the ASP.NET Identity framework is updated.

Hopefully this helps and answers your question!


问:
Is ART an installation process? Or an OS? Or a virtual Machine?
When attempting to understand Android Runtime, I came across the wikipedia page. The graphic shown there adds to my confusion. If .dex is getting converted entirely to ELF, why is ART needed anymore?

Once an application is compiled by using ART's on-device dex2oat utility, it is run solely from the compiled ELF executable; as a result, ART eliminates various application execution overheads associated with Dalvik's interpretation and trace-based JIT compilation

My understanding is that ART converts .dex to ELF and the code should run natively. With ELF, is a virtual machine still involved? With ART, does the android application stack look like -

```<code>Android Apps
-----
ART (executing ELF)
-----
Linux
</code>```

Am I understanding this correctly? Should I see ART as an OS that provides services to the ELFed Android App?

答: ART is the Android Runtime, and in addition to the (static) AOT compiler which compiles Dalvik bytecode to native machine code, it also contains all of the runtime services that an Android program needs: the memory allocator, garbage collector, reflection system, core classes and interfaces, etc.


答:
From the development manager's standpoint, it absolutely matters whether the defect is new or whether it is an existing defect because it has a direct and immediate impact on how the bug needs to be handled.  From the development manager's standpoint, the most important question is whether a new bug needs to be resolved in the current release cycle or whether or whether it can wait and be prioritized in a later cycle.  That, in turn, often depends on whether the bug is new or not.

If you've found a new bug, that implies that one of the new features/ bug fixes in the current release cycle introduced the issue.  If that's the case, someone either needs to remedy the issue as part of the current release (either by reverting the change that introduced the bug or by fixing the bug itself) or the business needs to decide whether adding new feature X is worth deploying even if it introduces new bug Y.  Almost always, the bug has to be resolved in the current build cycle or the offending change needs to be rolled back.  On the other hand, if you've found an old bug that existed prior to the current round of changes, the current build cycle can generally continue and the new bug can be prioritized for a future release.  Of course, there are cases where a newly identified bug needs to be handled in the current release cycle because the bug is just that critical, those cases tend to be rare.

Now, whether it should be QA's responsibility to check whether the bug affects the current release or whether that should be done by whoever is prioritizing the bugs (assuming that prioritization happens immediately) is an open question.  My bias would be to ask QA to do it since they're already writing up the bug.  Since the QA person already knows how to reproduce the bug, they're best positioned to verify whether it exists in production or not.  The QA department also tends to have more hours available for this sort of investigation than the person doing the prioritization does since the work can be spread across many analysts.

Title: verify a defect is a production defect or not

Body:
As a QA person, I always believe that a defect should have all the steps needed for anyone fixing it to be able to reproduce it.

however, is it crazy to think that every defect QA opens need to be checked if it already exists in production too? Reason, why I ask is we have a dev manager who constantly whines about, well if QA would have done this investigation whether if this issue exists in production or not it would save  time for dev folks. I understand that but I still think its kinda non sense to check if every bug QA finds in testing cycle exists in production too.


问:
What's the proper way to model this real-world activity that seems to need circular references in OOP?
I've been wrestling with a problem in a Java project about circular references.  I'm trying to model a real-world situation in which it seems the objects in question are interdependent and need to know about each other.

The project is a generic model of playing a board game.  The basic classes are non-specific, but are extended to deal with specifics of chess, backgammon and other games.  I coded this up as an applet 11 years ago with half a dozen different games, but the problem is that it's full of circular references.  I implemented it back then by stuffing all the intertwined classes in a single source file, but I get the idea that that's bad form in Java.  Now I want to implement a similar thing as an Android app, and I want to do things properly.

The classes are:

RuleBook: an object that can be interrogated for such things as the
initial layout of the Board, other initial game State information
like who moves first, the Moves that are available, what happens to
the game State after a proposed Move, and an evaluation of a current
or proposed board position.

Board: a simple representation of a game board, which can be
instructed to reflect a Move.

MoveList: a list of Moves.  This is dual-purpose: a choice of moves
available at a given point, or a list of moves that have been made in
the game.  It could be split into two near-identical classes, but
that's not relevant to the question I'm asking and may complicate it
further.

Move: a single move.  It includes everything about the move as a list
of atoms: pick up a piece from here, put it down there, remove a
captured piece from there.

State: the full state information of a game in progress.  Not only
the Board position, but a MoveList, and other state information such
as who is to move now.  In chess one would record whether the king
and rooks of each player have been moved.

Circular references abound, for example: the RuleBook needs to know about the game State to determine what moves are available at a given time, but the game State needs to query the RuleBook for the initial starting layout and for what side effects accompany a move once it is made (e.g. who moves next).

I tried organising the new set of classes hierarchically, with RuleBook at the top as it needs to know about everything.  But this results in having to move lots of methods into the RuleBook class (such as making a move) making it monolithic and not particularly representative of what a RuleBook should be.

So what's the proper way to organise this?  Should I turn RuleBook into BigClassThatDoesAlmostEverythingInTheGame to avoid circular references, abandoning the attempt to model the real-world game accurately?  Or should I stick with the interdependent classes and coax the compiler into compiling them somehow, retaining my real-world model?  Or is there some obvious valid structure I'm missing?

Thanks for any help you can give!

答:
I've been wrestling with a problem in a Java project about circular references.

Java's garbage collector doesn't rely on reference counting techniques. Circular references do not cause any kind of problem in Java. Time spent eliminating perfectly natural circular references in Java is time wasted.

I coded this up [...] but the problem is that it's full of circular references. I implemented it back then by stuffing all the intertwined classes in a single source file, [...]

Not necessary. If you just compile all the source files at once (e.g., javac *.java), the compiler will resolve all forward references without problems.

Or should I stick with the interdependent classes and coax the compiler into compiling them somehow, [...]

Yes. Application classes are expected to be interdependent. Compiling all Java source files that belong to the same package at once isn't a clever hack, it's precisely the way Java is supposed to work.


问:
Auto-save user input - the smartest way?
I'm developing a social network website and I'm working with php/mysql/jquery and I want users to have the most user-friendly website experience. That's why I try to avoid a save (submit) button at all. So, when they're on their own profile and enter information like what languages they speak or where do they live, I want to auto-create a page entry, if it doesn't exist already.

For example if somebody speaks german and that entry isn't available in the database yet (it's called pages with rows title, text, date_added). This is most likely comparable with a Facebook page you can create on Facebook, but this should be about everything (languages, companies, locations, activities).

So my specific problem now is, how to implement this feature the most smartest way. I mean on what event should this save be triggered, because I obviously can't save a new entry on every letter that has been typed. I've already implemented an autocomplete function, so they can choose from entries that already exist, but as mentioned I want them to create new entries (pages), too. Most preferably without "flooding" the database with new entries.

The things I thought of:

When a user switches from one input to another and input has been
made. Can this even be registered by JQuery? But here's the
question, what if he leaves the page without switching to another
input.

Save all data only then if he leaves the current page. I think
    there is this onunload function in JQuery.

Get confirmation from the user: "This entry hasn't been made yet.
    Do you want to save this entry?". But when should I ask this? I
    can't predict when the user is finished with typing.

答:
I think that you should look for a combination of things here.

Look for loss of focus from an input item (blur)

Once the user has focus on an input item, listen in on the OnKeyPress event. Keep track of the last Key-Up and when that crosses a threshold (say 30 secs or whatever), save the input


答:
While OAT file is an ELF file, it is not your usual executable ELF with everything in it including the entrypoint. It actually has a small number of symbols that are beginning and end of a binary blob which in turn contains the executable code of compiled methods. Now which methods should be called or when is all determined by runtime.

How it all works - a class is loaded. There is a C++ object that represents the Java object that is that class. Then an instance of that class is created. That's another C++ object. Than a method of that object is called. You find the object's class and find the method entrypoint (which is the compiled code). That code calls some other method - for that you will return back to runtime code, find another object and its class and call the new method again. There are no direct calls between methods (that I know of).

All this linking and resolution is actually done at each application start. Bootclasspath stuff is initialized once and then the process is forked so the children don't have to re-init bootclasspath (it's a bit more complex than that because of boot.art actually).

So the ART is still a JVM and OAT files are just some intermediate representation of some pre-compiled code. The fact that they are ELF files doesn't help much - could be something else.

P.S. Actually OAT file also contains all the DEX files which were used to create it. It is needed to construct the classes and methods. It is also possible to run application in interpreter mode when it actually executes DEX instructions directly.

Title: Is ART an installation process? Or an OS? Or a virtual Machine?

Body:
When attempting to understand Android Runtime, I came across the wikipedia page. The graphic shown there adds to my confusion. If .dex is getting converted entirely to ELF, why is ART needed anymore?

Once an application is compiled by using ART's on-device dex2oat utility, it is run solely from the compiled ELF executable; as a result, ART eliminates various application execution overheads associated with Dalvik's interpretation and trace-based JIT compilation

My understanding is that ART converts .dex to ELF and the code should run natively. With ELF, is a virtual machine still involved? With ART, does the android application stack look like -

```<code>Android Apps
-----
ART (executing ELF)
-----
Linux
</code>```

Am I understanding this correctly? Should I see ART as an OS that provides services to the ELFed Android App?


问:
Difference between synthesis and translation
Recently i have encountered two words describing transformation process of one language to another language - "translation" and "synthesis". I have some tips but i am not sure what is the difference. For example we say that C++ is "translated" into assembler (string is translated into another string), but VHDL (three levels of abstraction: Behavioral, RTL and Logical) is synthesized from Behavioral into RTL, from RTL into Logical etc (Gate description is still represented as string, so basically, it is still string translated into string, isn't it?).

Can anybody explain or refer me to exact difference of these concepts?

答:
tl;dr: different words for the same thing in different communities / circumstances.

The process of translating a program from one language A into another language B (or even the same language) is called compilation, and the program which performs this process is called a compiler.

Note: some people only use the term compilation if B is perceived as lower-level than A. Some people are even more strict and only call it compilation if B is some sort of binary machine language.

However, there are some specialized terms that are used in some circumstances.

If A == B, the process is sometimes called optimization, obfuscation, minimization, or pretty-printing, depending on what the goal of the process is.

If A is perceived to be lower-level than B, it is sometimes called decompilation. (And if A is some form of binary machine code and B is an assembly language, it is called disassembly).

If A is an assembly language and B is some form of binary machine code, it is called assembly.

If A and B are roughly on the same level of abstraction, and especially if the resulting B program is intended to be human-readable and idiomatic, it is called translation or source-to-source translation.

If A is some sort of macro or template language, it might be called expansion.

The term synthesis is specific to electronics engineering and refers to synthesizing an electronic system from a mathematical model, as opposed to the more traditional approach of engineering a system first and later modeling it mathematically. (I think the term is also used in Model-Driven Development in analogy to electronics.)


答:
Use a button

It is what users expect, don't discount the value of a familiar interface.

It gives the users the control they need, including the power to not publish something if they change their mind before finishing.

It gives users confidence that their submission has been properly saved. Not knowing for certain is agonising.

Autosave

Autosaving usually means to save a copy of the work without publishing it, overwriting the "real" save, or doing anything other than making the work recoverable in case the copy in memory is lost. Doing this in a website editor is quite common, and often a valuable feature. The easiest way of autosaving in a browser is to copy the input to localStorage, though this only allows recovery on the local computer and browser, so while saving the copy on the server may be a bit more elaborate, it could in some cases also lead to a better user experience.

Title: Auto-save user input - the smartest way?

Body:
I'm developing a social network website and I'm working with php/mysql/jquery and I want users to have the most user-friendly website experience. That's why I try to avoid a save (submit) button at all. So, when they're on their own profile and enter information like what languages they speak or where do they live, I want to auto-create a page entry, if it doesn't exist already.

For example if somebody speaks german and that entry isn't available in the database yet (it's called pages with rows title, text, date_added). This is most likely comparable with a Facebook page you can create on Facebook, but this should be about everything (languages, companies, locations, activities).

So my specific problem now is, how to implement this feature the most smartest way. I mean on what event should this save be triggered, because I obviously can't save a new entry on every letter that has been typed. I've already implemented an autocomplete function, so they can choose from entries that already exist, but as mentioned I want them to create new entries (pages), too. Most preferably without "flooding" the database with new entries.

The things I thought of:

When a user switches from one input to another and input has been
made. Can this even be registered by JQuery? But here's the
question, what if he leaves the page without switching to another
input.

Save all data only then if he leaves the current page. I think
    there is this onunload function in JQuery.

Get confirmation from the user: "This entry hasn't been made yet.
    Do you want to save this entry?". But when should I ask this? I
    can't predict when the user is finished with typing.


答: The standard way of removing a circular reference between two classes in object oriented programming is to introduce an interface that can then be implemented by one of them.  So in your case, you could have RuleBook referring to State which then refers to an InitialPositionProvider (which would be an interface implemented by RuleBook).  This also makes testing easier, because you can then create a State that uses a different (presumably simpler) initial position for test purposes.

Title: What's the proper way to model this real-world activity that seems to need circular references in OOP?

Body:
I've been wrestling with a problem in a Java project about circular references.  I'm trying to model a real-world situation in which it seems the objects in question are interdependent and need to know about each other.

The project is a generic model of playing a board game.  The basic classes are non-specific, but are extended to deal with specifics of chess, backgammon and other games.  I coded this up as an applet 11 years ago with half a dozen different games, but the problem is that it's full of circular references.  I implemented it back then by stuffing all the intertwined classes in a single source file, but I get the idea that that's bad form in Java.  Now I want to implement a similar thing as an Android app, and I want to do things properly.

The classes are:

RuleBook: an object that can be interrogated for such things as the
initial layout of the Board, other initial game State information
like who moves first, the Moves that are available, what happens to
the game State after a proposed Move, and an evaluation of a current
or proposed board position.

Board: a simple representation of a game board, which can be
instructed to reflect a Move.

MoveList: a list of Moves.  This is dual-purpose: a choice of moves
available at a given point, or a list of moves that have been made in
the game.  It could be split into two near-identical classes, but
that's not relevant to the question I'm asking and may complicate it
further.

Move: a single move.  It includes everything about the move as a list
of atoms: pick up a piece from here, put it down there, remove a
captured piece from there.

State: the full state information of a game in progress.  Not only
the Board position, but a MoveList, and other state information such
as who is to move now.  In chess one would record whether the king
and rooks of each player have been moved.

Circular references abound, for example: the RuleBook needs to know about the game State to determine what moves are available at a given time, but the game State needs to query the RuleBook for the initial starting layout and for what side effects accompany a move once it is made (e.g. who moves next).

I tried organising the new set of classes hierarchically, with RuleBook at the top as it needs to know about everything.  But this results in having to move lots of methods into the RuleBook class (such as making a move) making it monolithic and not particularly representative of what a RuleBook should be.

So what's the proper way to organise this?  Should I turn RuleBook into BigClassThatDoesAlmostEverythingInTheGame to avoid circular references, abandoning the attempt to model the real-world game accurately?  Or should I stick with the interdependent classes and coax the compiler into compiling them somehow, retaining my real-world model?  Or is there some obvious valid structure I'm missing?

Thanks for any help you can give!


答:
Granted, circular dependencies are a questionable practice from a design point of view, but they are not prohibited, and from a purely technical point of view they are not even necessarily problematic, as you seem to regard them to be: they are perfectly legal in most scenarios, they are inevitable in some situations, and on some rare occasions they can even be regarded as a useful thing to have.

Actually, there are very few scenarios where the java compiler will deny a circular dependency.  (Note: there may be more, I can only think of the following right now.)

In inheritance: You cannot have a class A extend class B which in turn extends class A, and it is perfectly reasonable that you cannot have this, since the alternative would make absolutely no sense from a logical point of view.

Among method-local classes: classes declared within a method may not circularly reference each other.  This is probably nothing but a limitation of the java compiler, possibly because the ability to do such a thing is not useful enough to justify the additional complexity that would have to go into the compiler to support it.  (Most java programmers are not even aware of the fact that you can declare a class within a method, let alone declare multiple classes, and then having these classes circularly reference each other.)

So, it is important to realize and get it out of the way that the quest to minimize circular dependencies is a quest for design purity, not a quest for technical correctness.

As far as I know there exists no reductionist approach to eliminating circular dependencies, meaning that there is no recipe consisting of nothing but simple predetermined "no-brainer" steps for taking a system with circular references, applying them one after the other, and ending up with a system free of circular references.  You have to put your mind to work, and you have to perform refactoring steps which are dependent on the nature of your design.

In the particular situation that you have at hand, it seems to me that what you need is a new entity, perhaps called "Game" or "GameLogic", which knows all the other entities, (without any of the other entities knowing it,) so that the other entities do not have to know each other.

For example, it seems to me unreasonable that your RuleBook entity needs to know anything whatsoever about the GameState entity, because a rule book is something that we consult in order to play, it is not something that takes active part in playing.  So, it is this new "Game" entity which needs to consult both the rule book and the game state in order to determine what moves are available, and this eliminates the circular dependencies.

Now, I think I can guess what your problem is going to be with this approach: coding the "Game" entity in a game-agnostic way will be very hard, so you are most likely going to end up with not just one but two entities that will need to have custom-made implementations for each different type of game: the "RuleBook" and the "Game" entity.  Which in turn defeats the purpose of having a "RuleBook" entity in the first place.  Well, all I can say about this is that maybe, just maybe, your initial aspiration of writing a system which can play many different types of games may have been noble, but perhaps ill conceived.  If I were in your shoes I would have focused on using a common mechanism for displaying the state of all the different games, and a common mechanism for receiving user input for all these games, and then I would have allowed the implementation of the different games to vary wildly, having very little code in common, so as to guarantee maximum flexibility in the implementation of each game.


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
When is ?: appropriate, and when is it not?

If you don't get a performance gain, don’t use it; it affects the readability of your code.

Use it once and don’t nest it.

It’s harder to debug.

Should it be taught to or hidden from beginners?

Doesn't matter, but it should not be intentionally hidden as it's not too complex for a “beginner” to learn.

Title: Ternary operator considered harmful?


答:
Game theory treats games as a list of previous moves (value types including who played them) and a function ValidMoves(previousMoves)

I would try and follow this pattern for the non UI part of the game and treat things like board setup as moves.

the UI can then be standard OO stuff with one way ref to the logic

Update to condense comments

Consider Chess. Games of chess are commonly recorded as lists of moves . http://en.wikipedia.org/wiki/Portable_Game_Notation

the list of moves defines the complete state of the game much better than a picture of the board.

Say for example we start making objects for Board, Piece, Move etc and Methods like Piece.GetValidMoves()

first we see we have to have piece reference the board, but then we consider castling. which you can only do if you have not already moved your king or rook. So we need a MovedAlready flag on the king and rooks. Similarly pawns can move 2 squares on their first move.

Then we see that in castling the valid move of the king depends on the existence and state of the rook, so board needs to have pieces on it and reference those pieces. we are getting into your circular ref problem.

However, if we define Move as an immutable struct and game state as the list of previous moves we find these problems vanish. To see if castling is valid, we can check the move list of the existence of castle and king moves. To see if the pawn can take en-passent we can check to see if the other pawn made a double move on the move before. No references are needed except Rules -> Move

Now chess has a static board, and the peices are always setup the same way. But lets say we have a variant where we allow an alternate setup. perhaps omitting some pieces as a handicap.

If we Add the setup moves as moves, 'from box to square X' and adapet the Rules object to understand that move, then we can still represent the game as a sequence of moves.

Similarly if in your game the board itself is non static, say we can add squares to chess or remove squares from the board so they cant be moved across. These changes can also be represented as Moves without changing the overall structure of your Rules engine or having to reference a BoardSetup object of similar


问:
Any benefits of writing coding articles
I always wonder if there is any benefit of publishing programming/code related articles/tips either on ones own website or coding sites? I think it has a benefit that a programmer can have a record of his/her learning and refer them later, other than that?

As far as I can imagine, forum participation like stackoverflow offers a place for mutual learning and you may get business also, but what will be returned if I write solution for "How to show toggle drawer on Android activity"... etc.

Such writing will only attract junior coders who immediately need solutions for their current problems, they will read it and move on, I doubt this will be ever noticed by business person or senior developers.

But lot of programmers do that why? if keeping record of leanings is a reason there can be number of other ways.

答:
Publicity Joel used his blog, joel-on-software to great effect in generating publicity for his company and product range.  It also helped launch this range of Q&A websites.

There are some personal benefits too.  The act of creating a clear, linear narrative to explain your thoughts, ideas and concepts will naturally help clarify your thinking and understanding of the subject.

The best articles are usually where someone is pushing the edges of what is possible.  For example, one article I read was where lastfm.com were investigating what it took to handle one million connections to the same server.

Good luck

Title: Any benefits of writing coding articles


答:
As a programmer, you should be dealing a lot with different problems where the solution is not immediately visible and requires additional searching.

The next time you encounter the same problem, there are chances that you have absolutely no idea how you solved it in the past. So you do the searching again, wasting the same amount of time.

And the next time. And again, six months later.

In order to be more productive, you can start by taking notes. What was the problem? In which context? What was the solution? This takes time in short term, but is tremendously helpful in long term.

Such notes may be kept private. In this case, only you benefit from them. Or they can be public at practically no cost (other than taking care of spelling and presentation) by publishing them in a blog.

The benefit of making them public is not necessarily SEO or advertisement, since as you have noted, you are attracting only junior programmers who don't care about you or your blog, but exclusively about the solution. On the other hand, the major benefit is that you can then use Google to search through your own blog. If your notes are private, you should either spend a lot of time organizing them, or you'll waste your time searching for a note every time you have a problem.

Further reading: Google Search is great, or why should your internal documentation be public

There are few second-class benefits:

By explaining the problem and the solution to others, you may discover things you weren't thinking about. This is essentially Rubber duck debugging applied in a scope larger than debugging per se.

Trying to communicate clearly the problem and the solution is a good opportunity to enhance your communication abilities. How many times have you seen programmers asking: “Hey, I have a problem: there is a error with my code, well, I kinda don't know how to explain it, I was doing... well... I was writing code, and then the error appeared, and I don't know why, and don't know what to do...”?

“Anything you say or do (on the internet) may be used against you in a job interview.” Interviewers do search about you; if you have a blog with high quality content, well written, well presented, it actually matters, even if the problems in this blog are actually basic. At least you have shown your communication skills and the fact that you are willing to share things with the community. Similarly, you may use your blog to back up your assertions during an interview.

“I'm quite experienced in WCF. See, for the last four years, I had to manage three large projects which were heavily relying on WCF, those project being described here and here on my website, and I also published more than 80 blog posts about the different problems I encountered with WCF.”—is much more solid than:

“I'm quite experienced in WCF. I worked on three large projects which were heavily relying on WCF, and I know how to handle many of WCF problems.”

Title: Any benefits of writing coding articles

Body:
I always wonder if there is any benefit of publishing programming/code related articles/tips either on ones own website or coding sites? I think it has a benefit that a programmer can have a record of his/her learning and refer them later, other than that?

As far as I can imagine, forum participation like stackoverflow offers a place for mutual learning and you may get business also, but what will be returned if I write solution for "How to show toggle drawer on Android activity"... etc.

Such writing will only attract junior coders who immediately need solutions for their current problems, they will read it and move on, I doubt this will be ever noticed by business person or senior developers.

But lot of programmers do that why? if keeping record of leanings is a reason there can be number of other ways.


答:
I believe the circular references and the god object in your case could be easily removed by separating the control of the game flow from the state and rule models of the game. By doing that you would probably gain a lot of flexibility and get rid of some needless complexity.

I think you should have a controller ("a game master" if you wish) that controls the game flow and handles actual state changes instead of giving the rule book or the game state this responsibility.

A game state object does not need to change itself or to be aware of the rules. The class just needs to provide a model of easily handled (created, inspected, altered, persisted, logged, copied, cached etc) and efficient game state objects for the rest of the application.

The rule book shouldn't need to know about or fiddle with any ongoing game. It should only need a view to a game state to be able to tell which moves are legal and it only needs to answer with a resulting game state when asked what happens when a move is applied to a game state. It could also provide a beginning game state when asked for an initial layout.

The controller has to be aware of game states and the rule book and perhaps some other objects of the game model, but it shouldn't need to mess with the details.


问:
Design Pattern - DLL per Strategy
I usually found myself designing my application in the following way:

One DLL containing interfaces for a desired subsystem. For example, Company.Framework.Persistence.dll.

One new DLL per each strategy (or implementations) of the said subsystem. For example:

Company.Framework.Persistence.MSSQL.dll

Company.Framework.Persistence.MySQL.dll

Company.Framework.Persistence.FileSystem.dll

This will result in a very big solution with a lot of projects, but on the other hand, would give the consumer the chance to choose the appropiate DLL for his needs.

If we had a single DLL called Company.Framework.Persistence.dll, the consumer would have to load a lot of strategies that he may never use. Having modularized DLL would solve this problem.

Is this good practice? Is there a disadvantage with this design?

答:
I do it that way too.

Projects/dlls are essentially free and make the code more readable and easier to use.

I have known people use a single large DLL and differentiate with name spaces. But as you say they have to deploy unused code, I don't see any benefits to the practice and many downsides such as

change to one implementation requires recompile of others

unused code is deployed to live (risk of bugs)

test code is deployed live (mocks etc, risk of bugs, misconfiguration)

obsoleted code requires refactoring to remove, (say we don't use MySQL anymore)

have to test unused code before deploying (we are testing right?)

refactoring can cause compilation error in unused component (say we change an interface)

I might cut corners and put the concrete implementation with the interface for small applications if it avoids a project which contains only a single interface. But normally I find the interfaces go with the models. So I would have

Company.Framework.Models.dll (includes interface for persistence)

Company.Framework.Persistence.MySQL.dll (ref Models, but needs to anyway)

Company.Framework.Persistence.Mock.dll (ref Models, but needs to anyway)

or (bad shortcut!)

Company.Framework.Models.dll (not including interfaces)

Company.Framework.Persistence.MySQL.dll (includes persistence interface, ref models)

Company.Framework.Persistence.Mock.dll (ref models and sql, but its not deployed to live)

Obvs, its pretty simple to refactor the interfaces out if the application increases in size/complexity

Title: Design Pattern - DLL per Strategy


问:
in trouble making a card game with pygame
I am designing a card game playable against the computer.

The rule is very simple

Both player and CPU gets 10 cards of 1 to 10.

Player and CPU plays a single card at the same time, every round.

The one who plays the bigger number wins the round.

Repeat this for 10 times.

At the end of the 10th round, the one who won the most rounds is the winner.

So the problem is, I cannot figure out the logic of the program. The first round was easy. I had figured of 3 characters, one is bold (he draws one of 8,9,10 at the first round) and timid (he draws one of 1, 2, 3 at the first round), and for the last, this is not confirmed but a character who randomly draws like bold and timid, so a player cannot be sure whom he is playing against.

But I could not figure out the logic after the first round. Each character must have a logic or pattern so player feels like he's playing against another player.

答:
If I understand you correctly, each player gets 10 cards numbered 1 through 10.  During each round, the player picks one of his cards to match against the other player.

Pretend for a minute that you are the bold player.  You'll pick "8" as your first card, leaving you with 1,2,3,4,5,6,7,_,9,10.

The human player will pick a number that's either lower than, the same as, or higher than your number.

In each of the 3 cases, what would you do next?

Human picked lower: you won.  Since you are "bold", you'll probably want to pick another "high" number.

Human picked the same: tie. Since you are "bold", you'll probably want to pick another "high" number.

Human picked higher: you lost. Since you are "bold", you'll probably want to pick another "high" number.

You can probably group your numbers into "Low" (1,2,3), "Medium" (4,5,6,7) and "High" (8,9,10).  Use a random number generator to pick from the right group if you still have any cards in that group.  If that group is empty, move to the next group and try again.

ps - The 3 cases listed above currently all have the same action - "you'll probably want to pick another 'high' number".  As you work on the game, you'll probably want to start thinking of different actions for each case.

To figure out the logic, pretend you are that player and play the game very slowly.  Another way to figure it out is to pretend you have someone acting as that player.  That person does not know the game and will not do anything unless you tell them what to think and what to do.


答:
The advantage of strategy two is to minimize dll hell.

Usually Company.Framework.Persistence.MySQL.dll will depend on some dll for interfacing with MySql. If I have no interest in MySql, Why should I download the dll from MySql?

Lets say your framework supported 20 different storage providers. Most users only use one. So all users have to go and get 19 dll's they are never going to use just to compile your framework.

By following strategy two you allow your users to only install the dll's they are going to use and thus minimizing dll hell.

Title: Design Pattern - DLL per Strategy

Body:
I usually found myself designing my application in the following way:

One DLL containing interfaces for a desired subsystem. For example, Company.Framework.Persistence.dll.

One new DLL per each strategy (or implementations) of the said subsystem. For example:

Company.Framework.Persistence.MSSQL.dll

Company.Framework.Persistence.MySQL.dll

Company.Framework.Persistence.FileSystem.dll

This will result in a very big solution with a lot of projects, but on the other hand, would give the consumer the chance to choose the appropiate DLL for his needs.

If we had a single DLL called Company.Framework.Persistence.dll, the consumer would have to load a lot of strategies that he may never use. Having modularized DLL would solve this problem.

Is this good practice? Is there a disadvantage with this design?


答:
Working out a winning strategy to this game is going to be a very hard problem and it will probably turn out to be something like choose a 'high' card 34.6% of the time.

consider the following game where timid plays bold

```<code>B 10,9,8,7
T  1,2,3,4
</code>```

at this point B has won 4 hands, but T is guaranteed win of 4 with his 7,8,9,10 which he has yet to play. It all comes down to the 5 and 6.

if T expects B to play

```<code>B 6,5,4,3,2, 1 .. he should break pattern and play
T 7,6,5,8,9,10
</code>```

for 6 wins and the game. B can only draw at this stage by either matching his 6 with T's 5 or matching both 6's and 5's eg.

```<code>B 1,2,6,5,3, 4
T 7,6,5,8,9,10
</code>```

So in general we can see the best play is to make each of your cards 1 higher than your opponents and lose only one round with your 1 vs their 10

as play proceeds you gain knowledge about the cards your opponent has remaining. In order to try and work out stratagems I would start with a condensed version of the problem.

say we only have 2 cards each. 1,2. then we should always play 2 first. which guarantees a win or draw

say we have 3 cards 1,2,3.

```<code>B 3,2,1  is beaten by
T 1,3,2
</code>```

in fact we don't even need to consider the 2nd and 3rd moves. T is guaranteed 1 more win with his 3. what about

```<code>B 2,?,?
T 1,?,?
</code>```

the remaining combinations are in B's favour

```<code>B 2,3,1 win - 2,1,3 draw - 2,3,1 draw - 2,1,3 win
T 1,2,3     - 1,2,3        1,3,2        1,3,2
</code>```

Title: in trouble making a card game with pygame

Body:
I am designing a card game playable against the computer.

The rule is very simple

Both player and CPU gets 10 cards of 1 to 10.

Player and CPU plays a single card at the same time, every round.

The one who plays the bigger number wins the round.

Repeat this for 10 times.

At the end of the 10th round, the one who won the most rounds is the winner.

So the problem is, I cannot figure out the logic of the program. The first round was easy. I had figured of 3 characters, one is bold (he draws one of 8,9,10 at the first round) and timid (he draws one of 1, 2, 3 at the first round), and for the last, this is not confirmed but a character who randomly draws like bold and timid, so a player cannot be sure whom he is playing against.

But I could not figure out the logic after the first round. Each character must have a logic or pattern so player feels like he's playing against another player.

Body:
Working out a winning strategy to this game is going to be a very hard problem and it will probably turn out to be something like choose a 'high' card 34.6% of the time.

consider the following game where timid plays bold

B 10,9,8,7
T  1,2,3,4

at this point B has won 4 hands, but T is guaranteed win of 4 with his 7,8,9,10 which he has yet to play. It all comes down to the 5 and 6.

if T expects B to play

B 6,5,4,3,2, 1 .. he should break pattern and play
T 7,6,5,8,9,10

for 6 wins and the game. B can only draw at this stage by either matching his 6 with T's 5 or matching both 6's and 5's eg.

B 1,2,6,5,3, 4
T 7,6,5,8,9,10

So in general we can see the best play is to make each of your cards 1 higher than your opponents and lose only one round with your 1 vs their 10

as play proceeds you gain knowledge about the cards your opponent has remaining. In order to try and work out stratagems I would start with a condensed version of the problem.

say we only have 2 cards each. 1,2. then we should always play 2 first. which guarantees a win or draw

say we have 3 cards 1,2,3.

B 3,2,1  is beaten by
T 1,3,2

in fact we don't even need to consider the 2nd and 3rd moves. T is guaranteed 1 more win with his 3. what about

B 2,?,?
T 1,?,?

the remaining combinations are in B's favour

B 2,3,1 win - 2,1,3 draw - 2,3,1 draw - 2,1,3 win
T 1,2,3     - 1,2,3        1,3,2        1,3,2


问:
Is it good that testers are competing to see who opens more bugs?
I'm a software developer. There is a team of testers who follow and run test cases written by the analyst, but also perform exploratory testing. It seems like the testers have been competing to see who opens more bugs, and I've noticed that the quality of bug reports has decreased. Instead of testing functionality and reporting bugs related to the operation of the software, the testers have been submitting bugs about screen enhancements, usability, or stupid bugs.

Is this good for the project? If not, how can I (as a software developer), try to change the thinking and attitudes of the team of testers?

Another problem is because the deadline is estimated and cannot change, so as the deadline nears, the testers will be scrambling to finish their test cases, and this will cause the quality of the tests decrease. This will cause legitimate bugs to be in the final product received by the client.

OBS: This competition is not a practice of the company! It is a competition between only the testers organized by them, and without any prizes.

答:
This is an expansion on @CandiedOrange's answer.

To get started on shifting the attention to more useful objectives, consider something very informal and unofficial. For example, the developers could buy some small tokens and trophies.

Each day that at least one significant bug was reported, leave a "Bug of the Day" token on the tester's desk. Once a week, hold a ceremony with a procession of developers delivering a bigger and better "Bug of the Week" token or trophy. Make the "Bug of the Month" trophy delivery even more dramatic, perhaps with cake. Each token or trophy should be accompanied by a citation saying why the developers thought it was a good thing that bug was found in testing. Copies of the citations should be put somewhere where the testers can all read them.

The hope is that the testers would switch their attention from finding the most bugs to collecting the most trophies and tokens. Their best strategy for doing that would be to read the citations and think about what approaches to testing are likely to bring out bugs the developers will consider important.

Simply ignore unimportant bug reports. Since it would all be very unofficial and informal, it could be shut down or changed at any time.


问:
License question regarding open-source project which may eventually contain a commercial component
I'm beginning work on a project which I may wish to commercialize in the future. For now, though, it's just a prototype which I would like to release it with a GPL license.

My concern is: if I am to receive contributions (code patches, artwork, etc) toward the prototype open source project, I don't want to be faced with the task of trying to determine which parts of the project I can and cannot use in the future commercial version.

To this end, my preference would be to license my prototype version with the GPL, and require that any contributions made to the project are either in the public domain or licensed according to some attribution license such as the BSD license. (In the event of a future commercial product, I don't mind giving blanket attribution to anyone who contributed to the prototype version).

Is this a realistic thing to do?  Are there examples of other projects doing similar things? How has this been met by potential contributors and/or users of the projects?

答:
The principle behind this strategy is perfectly sound: GPL-licensed projects include BSD-licensed components all the time.

Imagine each contributor published his or her contributions on a personal repository, with a BSD license, without involving your project at all. Now imagine that you discovered the code later. You can take that code and include it in your project. BSD-licensed code can always be included in a GPL-licensed project, because the BSD license is GPL compatible (which means that the requirements of the BSD license are a subset of the GPL's requirements). The work as a whole will still be GPL-licensed, and the specific component will still be BSD-licensed.

You simply need to skip the step where the contributor publishes the contribution independently. Instead, they give it to you directly, explicitly licensed under the BSD license. You then take that BSD-licensed code and include it in your GPL-licensed project, just as you could do with any other BSD-licensed code you found elsewhere.

It would be a good idea to require contributors to sign a contributor license agreement (CLA) that makes this very clear. Getting the wording exact might be tricky (so you should probably hire a lawyer who can draft a document for you), but the principle of including BSD-licensed code in a GPL project is perfectly sound and commonplace.


问:
Is the use of one-letter variables encouraged?
Is the use of one-letter variables encouraged in Java? In code snippets or tutorials, you often see them. I cannot imagine using them is encouraged because it makes the code relatively harder to read and I never see them being used in other programming languages!</p>

答:
If your loop does nothing but use a variable for counting

```<code>  for(int i = 0; i < 10; i++) {
     System.out.println("Stop it! I really mean it!!");
  }
</code>```

then yes, this is the best name you could use. Anything longer cannot possibly make the semantics any more obvious, but takes much longer to read.

If the variable is used inside the loop, a meaningful name can be useful.

```<code>for(int door = 0; door < 3; door++) {
  int reward = gauge(door);
  if(reward > max) {
    max = reward;
    best = door;
  }
}
</code>```

If your variable is used method-wide, its name should be longer; if it's used class-wide, its name had better be totally self-explanatory, otherwise it will almost certainly decrease the clarity of your code.

In short, the bigger the scope of the variable, the longer its name must be.

Body:
If your loop does nothing but use a variable for counting

  for(int i = 0; i < 10; i++) {
     System.out.println("Stop it! I really mean it!!");
  }

then yes, this is the best name you could use. Anything longer cannot possibly make the semantics any more obvious, but takes much longer to read.

If the variable is used inside the loop, a meaningful name can be useful.

for(int door = 0; door < 3; door++) {
  int reward = gauge(door);
  if(reward > max) {
    max = reward;
    best = door;
  }
}

If your variable is used method-wide, its name should be longer; if it's used class-wide, its name had better be totally self-explanatory, otherwise it will almost certainly decrease the clarity of your code.

In short, the bigger the scope of the variable, the longer its name must be.


答:
The proper way of dealing with this is to use interfaces. Instead of having two classes know about eachother, have each class implement an interface and reference that in the other class.
Let's say you have class A and class B that need to reference eachother. Have class A implement interface A and class B implement interface B then you can reference interface B from class A and interface A from class B.
Class A can than be in it's own project, as can class B. The interfaces are in a seperate project which both other projects reference.</p>