问:
Transactions and subresources with JAX-RS
I'm porting an existing application RESTful API to a Java web framework -- I don't actually care which -- but it's proving hard to get the basics right.

The core of the problem appears to be getting the bridge between JAX-RS and the database so that transactions work. The API uses subresources a lot, and the way JAX-RS appears to work involves returning a new locator. Now that's a nice pattern, but it means there is nowhere that makes an effective bound on the transaction, so the @Transactional annotations become a problem. I'd really like them to be scoped to the request somehow, but none of the frameworks I've tried seem to make that easy, or even possible.

It's a kind of a three body problem. I can do transactions and queries fine by pushing them into a repository layer, but then I'd have to not use subresources. Or I can do subresources and even queries nicely but then there is nowhere nice for the transactions to happen. Basically I can have any two of transactions, subresources, and complex queries, but I need all three.

So far, I've tried to get this working with Guice + Jersey + Querydsl, and with Spring Data and Spring REST. They all seem entirely based on the idea that each endpoint can be @Transactional, and (usually) that it is a simple CRUD API on tables. I have a very nice front end already built. and I can't see any good reason to totally rewrite it because Java makes the services awkward to build.

I know somehow I need to get the transactions tied to the request, and use DTOs anyway so I'm happy with that, but I can't find any way to make that happen. Does anybody have any useful pointers, templates, advice?

答:
If JAX-RS is not a requirement, then I'd suggest looking at Restlet. It uses conveyor architecture, so nesting resources into other resources is not a problem - see hierarchical URIs. When integrating with Spring, you typically define root SpringBeanRouter, in which you put actual resources, in each of which you can put another routers, and so on.

You can wrap every method of every resource by just defining top-level request filter, which could use Spring's transaction template or something similar. Or, since you're not required to return locators, you can just go with @Transactional annotation on methods of (sub)resources.

See org.restlet.ext.spring package for details.


问:
How are declarative languages executed by a computer?
I'm getting introduced to declarative languages and am beginning to love them. In particular Haskell, a functional language, is very expressive, easy to debug. But my question has to do with execution. Are such languages compiled or interpreted? If it is the latter then I would have to choose conventional languages like C++ or Java for performance reasons. But I would love to use declarative languages for their increased productivity and ease of maintenance.
Eager to hear from the esteemed members of this community.</p>

答:
By definition of declarative languages, they cannot be executed in their purely declarative form; see e.g. the An intelligent system can and must use declarative knowledge efficiently paper of J.Pitrat, or several entries of his blog e.g. "stop programming!", "CAIA, my colleague", "know thyself", etc...

So a declarative system is transforming the declarative knowledge into executable procedures, or interpreting it procedurally, or often a mix of both approaches.

J.Pitrat's mentra is that such work on declarative knowledge can and should be expressed in a declarative way (thru declarative meta-knowledge able to be applied to itself), with a bootstrapped system.

BTW, his CAIA system has lot of declarative knowledge and is bootstrapped, so translated itself into hundreds of thousands of lines of C.

You could follow his example and work on a declarative system which generates Java code, but it is a long journey... Your system will then have a "compiler" part, that is something which contextually translates some declarative knowledge into executable Java code.

Likewise, Haskell may transform (i.e. compile) some expression into several forms of code, depending upon the context, etc...

ContentLicense: CC BY-SA 3.0


问:
Is ReST useful in Read/Write Operations that involve over 100 Gig
I work in Healthcare and we use SAS to Extract and Transform medical and pharmacy claims data for use in downstream reporting applications.  For a given Report Request(usually 40 are running at a time) we have to extract from various DBMS's and transform the data. Once completed with this ET step, the data is over 100 gig in aggregated form(SAS Tables). This data is indexed and optimized for report consumption.  We don't have to go back to the database after we have extracted the data.

To me using ReST doesn't make much sense in this situation as XML is not very efficient for large data volumes.  But I thought I would ask to see what the rest of the Programmers' world thinks.

答:
As for if and how to use HTTP for the data transfer, I completely agree with MainMa's answer.

However, independently of the size of the data, the process which you describe doesn't sound a like a typical application for Rest. One of the main ideas of Rest is having named resources like mycompany.com/claims/customer/{number}/claim/{number} which can be individually queried and updated.

Your problem, on the other hand, sounds more like batch processing: You have a large bunch of data, even including indexes, and since you want to run reports over it later, why don't you store that data into a database or analytics engine like Elastic Search? You could then have the reporting logic efficiently query that database / search-engine and provide the report results via Rest: mycompany.com/healthreport/{year}/{month}/claimsdata/{region} or somesuch.

Depending how many entities and relationships you have, marshalling all this data on its way from the ET engine to the report generator can be a lot of work and is only worth the trouble if you need to decouple those two stages by a large extend. (For example, when they run in independent IT organisations / companies.) Using separate data bases can already provide some amount of decoupling with less effort.


问:
Working Agile on Mainframe
Why do teams that work in a mainframe environment barely use an agile working methodology?
What are the key factors of not doing this despite all the technology available?

If so, which agile methodology would suit a mainframe environment the best?

答:
I would suppose there are two factors which lead to this:

Mainframes are used for applications for which Waterfall is usually more suited:

Many mainframe applications are business-critical or life-critical: those projects require a lot of paperwork and don't fit well with Agile.

You rarely see mainframes in start-ups. Mainframes are rather used by government agencies, healthcare sector and financial institutions. Those entities have a habit of using Waterfall, defining the cost of the project prior to its beginning (as well as drafting the requirements specification).

Mainframes are used by developers who are habituated to Waterfall more than Agile. They worked with Waterfall for decades, and may not necessarily accept to radically change their methods.

In the same way, guess where would a young developer interested by Agile search for a job? In a start-up or in a government agency?

Title: Working Agile on Mainframe


问:
Proper MVC practice for a hierarchy of elements
I am trying to develop my first major MVC application, and as such I am new to doing this on a large scale. I've read as much as I can online and am continuously striving for making my code as clean as possible and not introduce any bad practices. Right now, I'm starting to question if my setup is the way it would be done in the real world.

Right now, I have my main container class and sub classes that can appear inside.

Lets pretend the view would look like this:

```<code>-----------------------------------------------------
|                                                   |
|                    Main    |-----------------|    |
|   |------|                 |D |-----------|  |    |
|   |  A   |                 |  |  B  |  C  |  |    |
|   |      |                 |  |     |     |  |    |
|   |------|                 |  |-----------|  |    |
|                            |-----------------|    |
-----------------------------------------------------
</code>```

Where Main is your main viewing container, and inside are elements A, B and C.

The inner views can be dynamic, so lets say we have our own MVC's for A, B and C as well.

1) Is it wrong for these classes to be connected to one other like so?

```<code>     /------A
    /
Main
    \         /-B
     \       /
      \-----D---C
</code>```

By this, I mean both connections are two way.
To get to 'A' from B, I might call something like this.getD().getMain().getA() from object C.

Does that indicate a design problem if it's a web where things can traverse back and forth?

Is there any bad practice of passing it object A so the chain doesn't have to be done?

This can assume there is no nulls for the sake of this example

2) If the above is not okay, is it unreasonable to make a static singleton out of the Main object and have other classes access it through a static getter?

I don't know if such a practice is bad or not if you know the main window is never meant to be instantiated twice (and you prevent it from doing so). An example would be to get A from C, something like Main.getA().

I apologize if some of this is vague. As I said I'm new to this and would love nothing more than to cut out any bad habits. If there is anything wrong or right about what I've done? If there's anything wrong, how would you do it?

答:
Just some thoughts, continue to do your research on best practices. First, respect encapsulation and avoid tight coupling between views. Consider using dependency injection to inject inner views into outer views in your hierarchy - or decorating, etc. depending on the use-case.

Is there a specific functional reason you want two-way chainable calling between the view components? If you want to know whether you are doing the right thing, ask yourself what the use-case is. Let's say you have a visible counter in A that increments/decrements based on data changing in C. Is there a reason for A (a counter control) to know anything about C (some kind of data entry control)? No.

For communication in this case, you should use an event model where changing data in C fires an event that is picked up by the controller, which then updates the model with the new counter value. The model variable for the count should be data-bound to the control A. When the event fired from C updates the model, control A's value changes. C is informing the application of the data used by A, but A has no knowledge of C, its structure or its methods.

Reading about patterns in OOP and MVC will help you.

Specific questions like making a Singleton out of Main really depend on the specifics of your app.


答:
There are many reasons:

Mindset: Many of the developers working on mainframes do their work for decades. They 'grew up' with water fall and aren't exposed that much to new ideas as other environments where the average developer has maybe 5years experience and brings lots of new ideas to the table.

The environment: A lot of stuff they code is tightly bound to a database. Also the components they create a often tightly coupled. This hinders automatic testing a lot, which is one of the important foundations of agile approaches.

Tooling: The tooling they have to live will is often horrible. They often don't have any testing framework nor a version control that would be acceptable for other developers. Automatic builds as a Java/C#/whatever developer expects are unheard of.

Of course the different reasons affect each other and normally enforcing them even more.

Title: Working Agile on Mainframe

Body:
Why do teams that work in a mainframe environment barely use an agile working methodology?
What are the key factors of not doing this despite all the technology available?

If so, which agile methodology would suit a mainframe environment the best?


问:
What's the best way of building an administrative UI for an existing SPA application?
I’m working on an application where the client-side interface and backend server are completely separate applications. The backend is written in Ruby and only serves JSON via HTTP. The client is a completely “static” single-page browser application that communicates with the JSON API. I now need to build an administrative interface that will be used to curate content served by the JSON API.

I see a number of ways I could conceivably build this:

Extend the existing single-page application. Initially this seemed like the most obvious way to do it because I already have a lot of existing code for communicating with the API. The downside I see here is that the admin section would feel very tacked on. The admin concerns are largely orthogonal to the functionality of the existing SPA and I’m not convinced the amount of code reuse would actually warrant combining the two applications.

A separate single-page application. This could work fine. I would have to duplicate some code from the existing SPA but I think this makes a little more sense since the admin interface very much feels like a separate application. The admin area does not need a spectacular UI, though, and a traditional server-rendered web application might be a way to reduce the development effort required to build the admin interface.

A server-rendered web application. All the server-rendered web applications I’ve built in the past have been directly connected to a database. This, however, would need to communicate with the JSON API on each request. I’m sure it’s possible but it’s not very familiar to me and don’t see much discussion about this approach.

A server-rendered web application in the same process as the JSON API. This way the code rendering pages for the admin interface can directly access the db/model layer and doesn’t need to make separate HTTP requests to render the page. The part I don’t like about this is that it complects the API code with UI code and I’d rather keep those completely separate.

I’ve been considering the tradeoffs in each of these cases and would be very interested to hear other’s opinions. Have you developed a similar architecture? Which approach did you take and why?

答:
I think option 2 is your best bet.  While the public and admin sites are related and use the same DB most likely, admin use cases and work flows typically have little overlap with the use cases and workflows in the public site.  So the admin site will likely have its own distinct set of business logic.  You can certainly move code which is common into libraries which are shared so you can reuse where appropriate, both UI and domain code.

A separate admin site / app also means you can deploy it independently, and possibly lock it down better.  You may only need to allow access from your intranet for example.


问:
Do I have to learn html and javascript to create web applications?
I am an experienced Java programmer, and I want to create a complex web application requiring dynamic pages, drawings, etc (take SO as an example). Do I have to learn javascript/html in order to create such an application?

It is not that I don't want to learn another language (I've done this before), but technology on the javascript environment seems to change so fast that when you finish learning one framework it is already obsolete. I have checked a number of java framework for web development (spring, play), but not deeply. So can these frameworks (or other possible java frameworks that I'm not aware of) be used without learning html/javascript? I also have some python experience. So if I can do the app in python it is also an option.

答:
In a short answer YES. But, here is why HTML is the structure of all web and JS is the interaction of the web. I know you probably heard that a lot but, it is very important to know. Some frameworks will let you not use (or not use a lot) of HTML and JS but, they are the basics of the web. If you do not want to learn code hire someone. And also I know this was not in your question but, I made this mistake a lot trying to make the Twitters and the Gmail's I thought of without knowing any code and just googling a tutorial.

Well, Good Luck!


问:
DDD and the persistence of value objects; must we denormalize?
I've been reading up a lot on Domain-Driven Development, and I came to the question of how to preserve lack of distinct identity with value objects (VOs). While in the DDD world, this is a requirement (yet I'm not sure I understand the full power of this) it poses problems for the lower ORM layers in terms of persistence.

Tables, for the most part, like to be normalized. It makes life easy in terms of having no delete or insertion anomalies. My concern comes when implementing VOs; they do have primary keys - identities by definition (and foreign keys to their parent). Making them entities is violating DDD in favor of persistence. Instead, I could make a wrapper class that accepts a "bag" of parameters, and then attaches them to each parent's foreign key. While mechanically messy, it sounds like it will work.

I've read a lot of responses on the internet (Stack Overflow also) about denormalizing tables. This concerns me, as now we're violating persistence for DDD.

How to allow VOs to exist by their proper definition without a denormalization?

答:
This is an issue if you use an ORM to map your domain objects directly to the DB.  This falls apart rather quickly for all but the most trivial of applications.  Instead create separate classes to represent your data store and map those.  You will need code that maps the BOs to the DTOs, but you will not be forced to compromise your domain classes to make the ORM happy, which is invariably what happens.  You will also avoid the leaky abstraction that comes with using a ORM.

Given the above, how you persist value objects depends.  If you're storing for example geo coordinates, I probably wouldn't normalize these and store them in the same table as the entity.  If your value types really do have their own identity though, that suggests to me that they probably shouldn't be value objects in your domain layer.  That's really the defining difference between a value object and entity in DDD.  I always like to go to the source for DDD; unfortunately many of the blogs you'll see on the internet (especially those that really like NHibernate) don't really get DDD right at all, and following their advise usually leads you to the anemic domain model anti-pattern.


问:
Efficient way to map changes in a filesystem hierarchy
I'm currently working on a project that will enable file searching based on metadata found in the file.

It'll be comprised of 2 parts:

a filesystem crawler that passively scans for changes and indexes the results in a database

a search front-end that queries the database

The database will use a pseudo-hierarchical (ie flattened) model to create a map of the directory/file structure.

The fields stored in the index will include:

file/folder name

parent directory

modified time

metadata

...

What I'm wondering is, how does modified time on files/folders typically work and how can it be used to reduce the area that the crawler will have to index?

Note: assume the crawler will regularly run on a fixed interval to keep the index up-to-date.

答:
I assume you speak about unix-like OS. From Wikipedia (stat()):

stat() is a Unix system call that returns file attributes about an inode. The semantics of stat() vary between operating systems. As an example, the Unix command ls uses it to retrieve information on (among many others):

atime: time of last access (ls -lu),

mtime: time of last modification (ls -l), and

ctime: time of last status change (ls -lc).

From man 2 stat:

The field st_mtime is changed by file modifications, for example, by mknod(2), truncate(2), utime(2) and write(2) (of more than zero bytes).  Moreover, st_mtime of a directory is changed by the creation or deletion of files in that directory.  The st_mtime field is not changed for changes in owner, group, hard link count, or mode.

That means that last modification time is set on a file when:

file is created (mknod)

file is truncated (truncate)

modification time is changed explicitly (utime)

one or more bytes of data was written into a file (write) - that includes cases when same data was written twice and nothing actually changed

I am not sure if it is a complete list.

As for mtime on a directory:

It changes when you create, move or delete a file or a directory which is immediate child of this directory. Simple heuristic: mtime of a directory changes when the output of ls (just plain command, no recursion or any additional parameters) changes.

It does not change when you only modify the contents of any files inside (no matter how deeply nested), or do anything inside its' subdirectories. No propagation.

I'm wondering if storing the data you've mentioned in a DB would be of any help - it is already stored in a file system, which is a database by itself, and all the tools for querying it are already there.


问:
How to respond to a rude bug report?
I just received a quite rude bug report. The user basically says that we're doing it all wrong using capital letters here and there, although he's in fact just pointing at one bug.

On one hand, I care a lot about our users and want to maintain a good relationship and a good rating of our app. On the other I'd feel like a complete sell out if I would reply overly polite.

What's a decent way of responding? What should I keep in mind? What mindset should I have?

It should be added that the user seems to be a 24 year old CS student, and our product is an Android app that we're giving away free of charge.

答:
What's a decent way of responding?

Thank them for the report. Reassure them you are listening to their feedback.

What should I keep in mind?

That you can't please everyone and that some people don't seem capable of not being rude.

What mindset should I have?

You don't have to follow through on all the points that were brought up. It is your app and you decide where it goes. You will not be able to please everyone - so don't try. Make sure the group of people your app is for is catered for, but not everyone that uses it.

Title: How to respond to a rude bug report?


问:
Paired Programming - best approach
There is a new developer starting soon.  This person is at an entry level but has worked in app support for a couple of years.

I asked this question some time ago just before I started training someone else: Is Pair Programming also used to train less experienced developers and bring them up to speed?.  However, they were moved onto another project so it did not really go ahead.

My question is: How often should these sessions go ahead? From answers to my previous question I believe there are two approaches:

1) Spend one week training the person and come up with some objectives.  Then three months later have another one week session and set some more objectives.
2) Spend one morning per week on paired programming.  This would give me time to spend elsewhere.

Also this developer is "green" (term I took from an answer to my previous question), whereas I have worked as a developer for my current employer for seven years.  Unfortunately I am the only developer.  Is there any other approaches to knowledge transfer that work when the learner is "green" and the teacher is more experienced?

答:
Despite the "science" in "computer science" and the "engineering" in "software engineering" evoking the idea of having rules, guidelines, and some "correct" method, my experience is you need to trust your gut. Software engineering tells us that the process of paired programming works: your gut feeling tells you how to apply it. This is a human issue, not a technology issue.

I would gather metrics, even if informally. If you had to provide an official rating for this junior member in the "technical ability" box on his annual review, what would it be and what would you say based on the pair programming sessions?

If the feedback would be "his code needs to be constantly reviewed and he consistently makes rookie mistakes" then you need to continue paired programming. If the feedback is "paired programming sessions put the other programmer to sleep" then dial them back a bit. This is inherently subjective, but that is not necessarily a bad thing.

In both cases, code reviews are a must. Everyone makes mistakes and everyone has something to learn regardless of experience level.

Title: Paired Programming - best approach


问:
Are there memory-memory instructions?
From Tanenbaum's Structured Computer Organization,

Most instructions can be divided into one of two categories: register-memory or register-register.

Register-memory instructions allow memory words to be fetched into registers, where, for example, they can be used as ALU inputs
      in subsequent instructions. (‘‘Words’’ are the units of data moved
      between memory and registers. A word might be an integer. We will
      discuss memory organization later in this chapter.) Other
      register-memory instructions allow registers to be stored back into
      memory.

A typical register-register instruction fetches two operands from the registers, brings them to the ALU input registers, performs
      some operation on them (such as addition or Boolean AND), and stores
      the result back in one of the registers. The process of running two
      operands through the ALU and storing the result is called the data
      path cycle and is the heart of most CPUs. To a considerable extent,
      it defines what the machine can do. Modern computers have multiple
      ALUs operating in parallel and specialized for different functions.
      The faster the data path cycle is, the faster the machine runs.

Are there memory-memory instructions?

Or is a memory-memory "operation" implemented as two register-memory instructions (one for read and the other for write)?
Isn't this inefficient than moving data directly between two places in the same memory without going via a register?

答:
Lots of machine architectures have memory-memory instructions.

The IBM System/360 and its successors have a whole set of instructions that operate on two locations in memory (the Storage Storage (SS) group).  "Move Character" (MVC) instruction copies up to 256 bytes from one memory location to another, and even has a clear definition for when the source and destination ranges overlap.  Similarly there are Compare Logical Character (CLC) (which does a string-comparison), OR Character (OC), AND Character (NC), and XOR Character (XC), which are bitwise logical operators, etc.  The also have a set of decimal arithmetic instructions, which only operate on memory - there aren't any registers for decimal math.

Then there are the memory-immediate instructions, which have one operand in memory and the other in the instruction itself.  The DEC PDP-10 had Add One to Storage (AOS) and Subtract One from Storage (SOS). The IBM S/360 family had a wide range of Storage Immediate (SI) instructions, in which one operand was a memory location and the other was an 8-bit quantity in the instruction.

Title: Are there memory-memory instructions?


答: Your app is free, your time and pain are not.  Ignore the report, and don't feed the trolls.</p>

Title: How to respond to a rude bug report?

Body:
I just received a quite rude bug report. The user basically says that we're doing it all wrong using capital letters here and there, although he's in fact just pointing at one bug.

On one hand, I care a lot about our users and want to maintain a good relationship and a good rating of our app. On the other I'd feel like a complete sell out if I would reply overly polite.

What's a decent way of responding? What should I keep in mind? What mindset should I have?

It should be added that the user seems to be a 24 year old CS student, and our product is an Android app that we're giving away free of charge.


答:
Remember, we are software professionals. The best way to deal with rude or angry customers (even if they are not paying customers) is to respond politely and professionally.

There are two very important points to keep in mind:

Reputation is critical in any business. Do you want to be known as "that guy" who is rude to customers? That is a good way to lose business, both current and future.

Responding in any other way than completely polite and respectful will escalate the situation. It will devolve into very nonconstructive behavior: see my first point.

Sometimes you need to swallow your pride and tell people what they want to hear, not what you want to say.

Title: How to respond to a rude bug report?


问:
How to refactor my project to have less mutable objects?
There seems to be a trend towards immutable objects, and functional programming. I recently got aware about the benefits of immutability. However, I am not very familiar with this style of programming.

My current classes may have some private or public mutable variables (state variables). I think these variables are the source of mutable state for the objects of my class. If the number of these variables is high, then the state of objects will be more complex. (if there are other reasons for mutable state of the objects of my class, please guide me about them)

Then, my question is how to refactor this class or even redesign my project to have objects with immutable or less complex state.

For example decomposing of the class to other classes with less mutable variables or any other guideline?

Or in other words, I look for some guidelines to design and implement a project to have less mutable objects as possible?

答:
It's not clear what you're trying to do in that example, and the implementation details of your framework will limit somewhat what you need to do.

Here are some guidelines that I use, which have been successful. There are of course other approaches that are successful. I use C# as my primary language, things similar to C# can use this approach. Other languages may not be able to use it well.

Whenever I consider making a new class, I consider what it needs to do. Some classes represent some data. Some classes represent some functionality (that may or may not require state to work). Most importantly, I consider what dependencies that class has.

Especially for beginners, these dependencies are where mutability is unnecessarily introduced. Whenever practical, dependencies should be supplied in the constructor. They are not grabbed by the class. They are not set as the class is "being initialized". You pass them into the constructor of the class so that the class may squirrel them away as private state or as public immutable state.

For classes that are just data (colors, points, text, rectangles) just set their state in the constructor and leave it be. If they need changed, make a new one.

For classes that are largely functionality, focus on the functionality. If they need private state, so be it. Functionality alone should largely not need public state. Functions are far better when they are pure, and take their dependencies as parameters (or from private class state or immutable class state).

For classes that are stuff that really does change over time (where your warlock is on the map, how much money is in your bank account) then go ahead and make those mutable classes. But try and keep them "dumb". Mutable classes are best when they are like collections. You can manipulate them, and they make it easier to do that, but logic shouldn't be there unless it's burned in logic that is guaranteed to be part of every form of that class.

The key thing to note is that classes are either immutable or they aren't. There's no "less" immutable that gets you any benefits.


答:
I was in a similar position once where I was bringing several developers up to speed. The most important thing that we did were constant code reviews, meaning that every commit was reviewed and commented on by everyone. After about one or two months they were not only picking up good practices but also felt confident with the codebase.

Also you could try and let your new developer write some test cases first for your project, so he gets a feel for the codebase without breaking anything.

Title: Paired Programming - best approach

Body:
There is a new developer starting soon.  This person is at an entry level but has worked in app support for a couple of years.

I asked this question some time ago just before I started training someone else: Is Pair Programming also used to train less experienced developers and bring them up to speed?.  However, they were moved onto another project so it did not really go ahead.

My question is: How often should these sessions go ahead? From answers to my previous question I believe there are two approaches:

1) Spend one week training the person and come up with some objectives.  Then three months later have another one week session and set some more objectives.
2) Spend one morning per week on paired programming.  This would give me time to spend elsewhere.

Also this developer is "green" (term I took from an answer to my previous question), whereas I have worked as a developer for my current employer for seven years.  Unfortunately I am the only developer.  Is there any other approaches to knowledge transfer that work when the learner is "green" and the teacher is more experienced?


问:
Global gitignore v project
We have several web projects within our organisation - using different frameworks and with many different developers.

Each developer might use a different ide and use different operating system etc and my question is that should the project gitignore include ide and os specific ignores?

such as netbeans, phpstorm, ds etc

Or should we rely on individual developers ignoring the files relevant to them

答:
You don't want to check in the IDE created files, as you don't want Thumbs.db or .DS_Store. By making every developer create their own version, you are adding more work and the risk of laziness at absolutely no gain. Having a few extra lines doesn't hurt, and helps you make sure you are not creating files that could interfere with other developers' workflow.

Most of the open source projects I have explored the source do indeed follow this, explicitly gitignoring all these files. See, for example, Numpy.

Title: Global gitignore v project


答:
Making some of your objects immutable is an architectural decision that should rarely be changed later, so I would not recommend that you start refactoring all of your stuff just because. You should also think about the disadvatages of immutability when changing your project. For example, immutability can cause severe performance problems if you have to recreate thousands of objects per second because you want to change them.

Telastyn already gave a good answer how to make things immutable.
Most of the time you can make a mutable class immutable if you return a new object on every method call, e.g. like the standard String class in Java does it.
Just remember that you should not use it blindly.

Title: How to refactor my project to have less mutable objects?

Body:
There seems to be a trend towards immutable objects, and functional programming. I recently got aware about the benefits of immutability. However, I am not very familiar with this style of programming.

My current classes may have some private or public mutable variables (state variables). I think these variables are the source of mutable state for the objects of my class. If the number of these variables is high, then the state of objects will be more complex. (if there are other reasons for mutable state of the objects of my class, please guide me about them)

Then, my question is how to refactor this class or even redesign my project to have objects with immutable or less complex state.

For example decomposing of the class to other classes with less mutable variables or any other guideline?

Or in other words, I look for some guidelines to design and implement a project to have less mutable objects as possible?


问:
Should there only be one controller per page within a JavaScript-based MVC architecture?
Let's say that I create a page in my marketplace web application where buyers can see a catalog of all products offered by some or all sellers or sellers can see just their own products in a preview of this buyer's view.

Within my JavaScript code I would create a model object that synced data with the server, one or more view objects that would render various pieces of that data to the user and a controller object that routed messages between the model and views.

Now let's say I create another page in my application where a buyer can see a catalog of only the products offered by a single seller (yes, this is just a subset of the above functionality but just go with me on this for the sake of this hypothetical). In this case, though, the catalog exists on a tab on the page with sibling tabs that contain other unrelated data.

If I were to reuse all the objects I created for the first page, would it still be feasible to call the "central" piece a controller when it would be included in one tab of a page that would probably have its own controller object? Or would it be more proper to stick with a single controller per "page" and just call this some sort of view object even though its purpose remains to route messages between its own internal model and views?

The crux of my query is whether from a conceptual standpoint there should only be a single controller in the JavaScript code for a single page or whether abstracted component units can have their own MVC architecture hidden away from the page's larger MVC architecture?

答:
It really depends on the structure of the page. If a page has only one purpose and one concern, then you should try to use a single controller so that the code is grouped logically.

If there are multiple components on a page with different concerns, then you should absolutely use multiple controllers for the sake of decoupling.

For example, consider a page that has a body that tracks products by a seller and a header that tracks the user's information and login session. The controller for the seller's products should hold logic about prices, stock reporting, discounts and so forth. Giving that controller power over logging the user out, or changing their password, dilutes its purpose and makes it less reusable. On the other side, giving the user controller price information about the seller's products is useless when you switch to a page about shipping arrival dates.

At the heart of it, this is just a higher-level version of the encapsulation discussions that go 'round and 'round the OOP world. One section of code, one purpose, no meddling without explicit permission from the code in question. This prevents code duplication, code corruption, and strange side-effects. It also makes the code much more maintainable when you only have to reason about a single topic when looking at a specific section of code.


答:
The existing answers cover the ground of being professional quite well. There's nothing wrong with being polite and professional in response. I'm instead going to cover being magnanimous.

I think a magnanimous response can make it unambiguous that the user has been rude--and you will help them anyways. There was even a now semi-famous example just this week.

Reasons to follow this strategy:

Generously calling out etiquette errors (especially in public) performs a useful social function by both modeling and helping to clearly define appropriate behavior. ex: From time to time I will ask a server (reasonably politely) if we could get this or that--but will forget to say please. My girlfriend
will add the please to our interaction. While this is embarrassing and sometimes I stick my tongue out at her when the server leaves, she has made an effective intervention in my behavior.

Being able to respond to the offense will be far more mentally and emotionally healthy for you and your ability to continue to interact with your users than swallowing each offense and slowly growing bitter about the ingrates you have to suffer.

Keeping your response magnanimous will help clear your conscience when the inevitable user still takes offense at being called out politely and rants back at you.

If your bug tracker is public, sane users will recognize the fairness of your responses and respect both your dedication to your work and your ability to handle jerks deftly and without being a doormat. We all have interactions with nasty people in our lives, and we all have to make decisions about where to fall on the response scale. Because this is a shared experience we tend to empathize by:

Feeling shame or embarrassment when we watch someone else swallow these indignities. We may step in on your behalf, or try to comfort you after the episode is over.

Feeling catharsis when someone's nasty behavior is paid back to them.

Respecting those who are as noble and composed as we wish we could be, by taking the middle path and both refusing to be walked on while resisting the impulse to be rude.

Title: How to respond to a rude bug report?


问:
Why does this recursion method work? I have explored it for a day or two, and I cannot figure out why
Problem Statement:

I have a tree with node values ( i , j ) where i , j < 1. The children of each node take on the values (i - 1, j), (i - 1, j - 1), and (i, j - 1) respectively. Now, i and j have constraints where they cannot be less than zero, so, given i (or j WLOG) == 0 for a node, its only child becomes (0, j - 1) (assuming j > 0).

These nodes represent the indices of a matrix, and what the children represent are either the index to the West, the North, or the North West of the currently selected index. (Notice 0 either represents the West edge or the North edge of the matrix)

I have written a recursive algorithm that will produce the number of different directions you can walk to get from node_0 (i, j) to the beginning.

```<code>def backtrackrecursion( currentnode, counter ):
    if currentnode.getindex() == (0 , 0):
        return counter++
    if currentnode.geti() > 0:
        currentnode.addchild(Node(index=(i - 1, j)))
    if currentnode.getj() > 0:
        currentnode.addchild(Node(index=(i, j - 1)))
    if currentnode.getindex() >= ( 1 , 1 ):
        currentnode.addchild(Node(index=(i - 1, j - 1)))
    for child in currentnode.getchildren():
        counter += backtrackrecursion(child, counter)
    return counter
</code>```

I understand why this works. My girlfriend wrote another algorithm, and to my astonishment, it works as well.

```<code>def btr(cnode, cou):
    if cnode.getindex() == ( 0 , 0 ):
        return cou++
    if cnode.getindex() != (0 , 0):
        cou = btr(cnode.inddecr( -1, 0), cou) + btr(cnode.inddecr(0, -1), cou) + btr(cnode.inddrec( -1 , -1 ), cou)
    return cou
</code>```

now I might have missed a property in her class that deletes all children with index i or j < 0, but shouldn't this be an infinite call? Where is the logic that I am missing?

答: If i and j have to be less then one but not less then zero then no recursion is possible because if 0<=i<1 and 0<=j<1 then i-1<0 and j-1<0, so no new nodes can appear.</p>


答:
A good thing to do is look at most languages' String class. Strings in any language I can think of are immutable, but most of the time nobody has any problem working with them. It's good to think of the ways in which you interact with Strings and ask yourself if you can work on your class in the same way.

For example, if you want to take a String and replace all instances of upper case letters with lower case ones, there's a .toLower() method or something similar which returns a new String object that is a copy of the old string object. The original String stays the same. You can do similar things with most objects. Let's say you have a class that represents events for a venue. Currently, there's some really hip Bourbon tasting event that is set to go down on Thursday, but for whichever reason the event organizer needs to change the date of the event to Friday instead. Replace the old event with another one that has the date field changed from Thursday to Friday:

```<code>bourbonTasting = bourbonTasting.replaceDate(DAYS.Friday);
</code>```

So that's all fine and dandy now! Anything that is looking at the 'bourbonTasting' variable will now read that it is on Friday rather than Thursday.

The thing that becomes hard with immutability, however, is that since you didn't mutate the original anything else that was storing a copy of the old event needs to be updated. Now imagine there's a bunch of calendars out there that have this event on them. If they all had a reference to the original object, and the original object were mutable then these calendars wouldn't need to be updated because the object they were all pointing at would just have the new value. That poses a lot of problems with concurrency though, since if something is looking at that calendar and something about the event changes mid-way though, the person consuming that calendar could be left in an inconsistent state. These are side effects of mutating that object.

Since our hypothetical calendar event IS immutable though, we don't need to worry about changing things out from under people without them noticing, but what we DO have to worry about is how to update all of these calendars. In this case, it would be good to have the person 'subscribe' their calendar to the event. When the event changes, a new event can be pushed to those calendars. If those calendars are immutable too, then they will need to be recreated with the new event replacing the old one, too. If the list of subscribers to the event is immutable, a new subscriber list needs to be created any time someone new subscribes.

As you can see, having everything be immutable can clean up concurrency problems, but it can also get expensive. You can wind up having to create a lot of new objects just because one little thing changed. The key to using immutability well is knowing when to use it, and when to not. The event object is a very public detail and having it be immutable is probably good, so that you don't change things out from under people. The list of subscribers for the event can likely be kept private to the event or the event organizer, so it might make sense to keep that be mutable so that you're not doing a crazy amount of recreation of objects if you have a hot event. The calendars of people planning on attending the event could go either way, depending on what else the calendars are being used for.

It's one of those things where you have to be sound about paying attention to both object creation and consequences of change, and make a rational decision based on the balance of those two factors. If it's going to be expensive to keep creating new objects and it wouldn't be difficult to manage who is looking at the objects, it might be better to keep it mutable. If the key is avoiding side effects, and/or object creation isn't going to be relatively expensive, it should probably be immutable.

So, if you're running into situations where you're struggling with immutability, first make sure you're thinking of immutability correctly. Think about it like String, and how you operate on that. If you're already working in that right mental model, then it's time to start asking yourself if immutability is the right thing to be doing. If creating and replacing objects is painful, maybe immutability isn't right for that particular case.

Body:
A good thing to do is look at most languages' String class. Strings in any language I can think of are immutable, but most of the time nobody has any problem working with them. It's good to think of the ways in which you interact with Strings and ask yourself if you can work on your class in the same way.

For example, if you want to take a String and replace all instances of upper case letters with lower case ones, there's a .toLower() method or something similar which returns a new String object that is a copy of the old string object. The original String stays the same. You can do similar things with most objects. Let's say you have a class that represents events for a venue. Currently, there's some really hip Bourbon tasting event that is set to go down on Thursday, but for whichever reason the event organizer needs to change the date of the event to Friday instead. Replace the old event with another one that has the date field changed from Thursday to Friday:

bourbonTasting = bourbonTasting.replaceDate(DAYS.Friday);

So that's all fine and dandy now! Anything that is looking at the 'bourbonTasting' variable will now read that it is on Friday rather than Thursday.

The thing that becomes hard with immutability, however, is that since you didn't mutate the original anything else that was storing a copy of the old event needs to be updated. Now imagine there's a bunch of calendars out there that have this event on them. If they all had a reference to the original object, and the original object were mutable then these calendars wouldn't need to be updated because the object they were all pointing at would just have the new value. That poses a lot of problems with concurrency though, since if something is looking at that calendar and something about the event changes mid-way though, the person consuming that calendar could be left in an inconsistent state. These are side effects of mutating that object.

Since our hypothetical calendar event IS immutable though, we don't need to worry about changing things out from under people without them noticing, but what we DO have to worry about is how to update all of these calendars. In this case, it would be good to have the person 'subscribe' their calendar to the event. When the event changes, a new event can be pushed to those calendars. If those calendars are immutable too, then they will need to be recreated with the new event replacing the old one, too. If the list of subscribers to the event is immutable, a new subscriber list needs to be created any time someone new subscribes.

As you can see, having everything be immutable can clean up concurrency problems, but it can also get expensive. You can wind up having to create a lot of new objects just because one little thing changed. The key to using immutability well is knowing when to use it, and when to not. The event object is a very public detail and having it be immutable is probably good, so that you don't change things out from under people. The list of subscribers for the event can likely be kept private to the event or the event organizer, so it might make sense to keep that be mutable so that you're not doing a crazy amount of recreation of objects if you have a hot event. The calendars of people planning on attending the event could go either way, depending on what else the calendars are being used for.

It's one of those things where you have to be sound about paying attention to both object creation and consequences of change, and make a rational decision based on the balance of those two factors. If it's going to be expensive to keep creating new objects and it wouldn't be difficult to manage who is looking at the objects, it might be better to keep it mutable. If the key is avoiding side effects, and/or object creation isn't going to be relatively expensive, it should probably be immutable.

So, if you're running into situations where you're struggling with immutability, first make sure you're thinking of immutability correctly. Think about it like String, and how you operate on that. If you're already working in that right mental model, then it's time to start asking yourself if immutability is the right thing to be doing. If creating and replacing objects is painful, maybe immutability isn't right for that particular case.


问:
Which way is more efficient for getting the space count?
I have just started reading Cracking the Coding Interview. One of the problems (specifically 1.4) after solving and then looking at the answer made me question the way it is done and decided to post it up here to see if I am missing something.

Here is the problem:

Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the 'true' length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)

Example: Input "Mr John Smith    ", 13
         Output "Mr%20John%20Smith"

Author's solution:

```<code>public void replaceSpaces(char[] str, int length)
{
    int spaceCount = 0, newLength, i;
    for(i=0; i<length; i++)
    {
        if (str[i] == '')
        {
           spaceCount++;
        }
    }
    // ...
}
</code>```

I put ... because the rest is irrelevant to my question.

Why loop around to find the spaceCount if you can just compute (str.length - length) / 2?

答:
The definition you posted says:

You may assume that the string has sufficient space at the end of the string to hold the additional characters.

And not:

You may assume that the string has exactly enough space at the end of the string to hold the additional characters.

Lesson 1 in code interviewing is to read (or listen to) the specification carefully. It's entirely possible that the array length is 1 million, but the string only contains two spaces. In this case, by assuming that you can just subtract the two lengths, you've assumed (without verifying) a part of the specification that wasn't explicit, and you'd almost certainly lose points for that.


答:
the spaceCount loop counts all of the actual spaces in the string, and ignores the spaces at the end (since you've been given the actual length of the string minus the trailing space in the length parameter).

The spec doesn't say that the amount of space left at the end of the string coincides exactly with the required space to hold the additional characters, only that there is sufficient space.

Title: Which way is more efficient for getting the space count?

Body:
I have just started reading Cracking the Coding Interview. One of the problems (specifically 1.4) after solving and then looking at the answer made me question the way it is done and decided to post it up here to see if I am missing something.

Here is the problem:

Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the 'true' length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)

Example: Input "Mr John Smith    ", 13
         Output "Mr%20John%20Smith"

Author's solution:

```<code>public void replaceSpaces(char[] str, int length)
{
    int spaceCount = 0, newLength, i;
    for(i=0; i<length; i++)
    {
        if (str[i] == '')
        {
           spaceCount++;
        }
    }
    // ...
}
</code>```

I put ... because the rest is irrelevant to my question.

Why loop around to find the spaceCount if you can just compute (str.length - length) / 2?


问:
Are single method interface and function type definition the same?
In a language where it is possible to define interfaces and typedefs (using Dart here):

```<code>abstract class Receiver {
  void receive(int quantity);
}

typedef void Receive(int quantity);

abstract class Transport {
  void deliver(Receiver receiver);
  void deliver(Receive receive);
}
</code>```

Conceptually, are single method interface and type definition on functions the same thing? Is there any benefits from using one over the other?

答:
Conceptually, are single method interface and type definition on functions the same thing?

No.

In most languages that allow both, the function typedef defines a type whose values are  functions and nothing else. The abstract class defines an interface which has a function (and likely, other things).

Things can get muddled with closures (which are functions, but often have other things) and/or C++ style functors (classes that have operator() overloaded), or even with implicit conversions to function types.

But the two mechanisms serve different purposes and should be conceptually different, even if mechanically they can be made to do the same things.


问:
Separate Drawable objects and their Data
I am looking for a way to design my application. Suppose you had a car drawing thing. Car has multiple parts.Some are going to be visible some are not.For example battery should be drawn. So someone would create a class Battery. Some other data such as warranty tests passed etc arent going to be drawn. My problem is that I want to separate technical data from object to be drawn. For example battery has tons of technical specs (capacity,low/max temperature etc).

So for example I read the data from a file that has all the data both technical and other such as color etc and transform these data into Objects.
Then I want to add them to a canvas in order to be drawn. However not all objects need to be drawn.Problem here is that for example I dont want to put canvas specific components like renderer into class like Battery.

Only solution I can think of is to create another class for each drawable like BatteryObject.However that means that another object should be instantiated and deleting etc is going to be a pain. Is there any other approach ?

答:
The answer to your question is going to depend greatly on the degree that your "data" needs to be "intelligent."

For example, if you merely wanted to display the specifications on the screen, you could simply provide the data as a collection of attributes without type.  For example:

```<code>var attributes = new list<KeyValuePair<string, string>>();
</code>```

If, on the other hand, your battery is part of an electrical system  that you might want to analyze later, your data would not only have to be actual numeric values, but you would also need to know units, since current is treated differently from voltage and the gauge of wires takes on some relevance, etc.

Some attributes have constraints.  Lead-acid batteries are different from lithium ion batteries (though they are both batteries), but there are only a limited number of battery types, so you might want to constrain input to a known list of types.  Last time I checked, you couldn't put a Zero-Point Module in a car.

If you still want to represent your specifications as first-class object properties in your battery class, C# allow you to decorate those properties with a custom Attribute that will allow you to identify them as "product specifications."

```<code>[Specification]
public float AmpHours { get; set; }
</code>```

Body:
The answer to your question is going to depend greatly on the degree that your "data" needs to be "intelligent."

For example, if you merely wanted to display the specifications on the screen, you could simply provide the data as a collection of attributes without type.  For example:

var attributes = new list<KeyValuePair<string, string>>();

If, on the other hand, your battery is part of an electrical system  that you might want to analyze later, your data would not only have to be actual numeric values, but you would also need to know units, since current is treated differently from voltage and the gauge of wires takes on some relevance, etc.

Some attributes have constraints.  Lead-acid batteries are different from lithium ion batteries (though they are both batteries), but there are only a limited number of battery types, so you might want to constrain input to a known list of types.  Last time I checked, you couldn't put a Zero-Point Module in a car.

If you still want to represent your specifications as first-class object properties in your battery class, C# allow you to decorate those properties with a custom Attribute that will allow you to identify them as "product specifications."

[Specification]
public float AmpHours { get; set; }


答:
Single method interfaces and functions (or functions type definitions) are almost the same. Function type definitions are just anonymous interfaces. Interfaces and function type definitions both serve the same purpose. And together with their implementation they could be described as mathematical duals. An object (or in this case a single method interface with implemention) is data (state) with behavior and a function is behavior with data, called a closure when data is partially applied. In C# e.g. the compiled IL code is similar in both cases (at least when it is reverse engineered). This and the correspondence to the concept of duals is described by Mark Seemann here. Note that this holds for C# and might be different in other languages or with other compilers.

In object oriented languages the intent of interfaces is to decouple the code and to be able to inverse the control (as in IoC). This gives you lots of benefits like reduced dependencies and therefore maintainability, evolvability, testability etc. In functional programming the same thing is achieved by using functions type definitions. In some languages you can do both.

Major differences is that interfaces are a bit more verbose with some boiler plate code. Functions are more concise. I'm not sure if all IoC Containers can handle functions as parameters. Also and even more important the way of programming might become very different when you go for one or the other depending on the context. If it's not convenient (meaning not idiomatic) in the language to use type definitions e.g. it can make things complicated when working in a team. So a good advice is probably to check the language's coding guide lines and conventions. (I don't know Dart so I can't help you here.)

Title: Are single method interface and function type definition the same?

Body:
In a language where it is possible to define interfaces and typedefs (using Dart here):

```<code>abstract class Receiver {
  void receive(int quantity);
}

typedef void Receive(int quantity);

abstract class Transport {
  void deliver(Receiver receiver);
  void deliver(Receive receive);
}
</code>```

Conceptually, are single method interface and type definition on functions the same thing? Is there any benefits from using one over the other?


问:
timed events to modulation of real-time audio
I am new very to audio programming and am having trouble figuring out the right kind of algorithm for converting control events (e.g. like MIDI) to real-time sound genesis with a buffer.

At the moment I am currently trying to convert data which comes from a modulation wheel to alter the pitch of a sine wave.  On one thread I am storing the events coming in in a ring buffer, with the value and timeStamp of when they occurred.  On the audio thread, I need to build a buffer with the sinewave using the arbitrary value->frequency mapping.

How is this normally done for optimal performance, i.e. if the buffer is very low, do you just take the most recent value for the control, do you interpolate, or what algorithm do you do to get a value for the control at each sample?

答:
in the MIDI control thread, you update the control values as soon as the complete MIDI control change message (0xB0) is received.  that control value remains constant until it is updated by another control change (for the very same control).

in the audio processing thread, you always refer to the current value of whatever control you're using.  you'll probably be scaling and offseting that control value so that 0x0000 is mapped to some MIN and so that 0x3FFF is mapped to some MAX values.

perhaps there will be slewing or portamento, but that is processing done in the audio processing thread to the scaled control value.  your slewing is always done toward the target value which is the current scaled value of that MIDI control.  it can be linear or, more simply, a decaying exponential:

```<code>value = (1.0 - slew_rate)*value + slew_rate*target_value;
</code>```

it's not particularly sophisticated.

Body:
in the MIDI control thread, you update the control values as soon as the complete MIDI control change message (0xB0) is received.  that control value remains constant until it is updated by another control change (for the very same control).

in the audio processing thread, you always refer to the current value of whatever control you're using.  you'll probably be scaling and offseting that control value so that 0x0000 is mapped to some MIN and so that 0x3FFF is mapped to some MAX values.

perhaps there will be slewing or portamento, but that is processing done in the audio processing thread to the scaled control value.  your slewing is always done toward the target value which is the current scaled value of that MIDI control.  it can be linear or, more simply, a decaying exponential:

value = (1.0 - slew_rate)*value + slew_rate*target_value;

it's not particularly sophisticated.


问:
What does "address translations" mean in discussing advantages of vector processors?
From the quote from Wikipedia, does "address translations" here mean the translation from virtual memory address to physical memory address?

Vector processors take this concept one step further. Instead of
  pipelining just the instructions, they also pipeline the data itself.
  The processor is fed instructions that say not just to add A to B, but
  to add all of the numbers "from here to here" to all of the numbers
  "from there to there". Instead of constantly having to decode
  instructions and then fetch the data needed to complete them, the
  processor reads a single instruction from memory, and it is simply
  implied in the definition of the instruction itself that the
  instruction will operate again on another item of data, at an address
  one increment larger than the last. This allows for significant
  savings in decoding time.

To illustrate what a difference this can make, consider the simple
  task of adding two groups of 10 numbers together. In a normal
  programming language one would write a "loop" that picked up each of
  the pairs of numbers in turn, and then added them. To the CPU, this
  would look something like this:

```<code>execute this loop 10 times
  read the next instruction and decode it
  fetch this number
  fetch that number
  add them
  put the result here
end loop
</code>```

But to a vector processor, this task looks considerably different:

```<code>read instruction and decode it
fetch these 10 numbers
fetch those 10 numbers
add them
put the results here
</code>```

There are several savings inherent in this approach. For one, only two
  address translations are needed. Depending on the architecture, this can represent a significant savings by itself. Another saving is
  fetching and decoding the instruction itself, which has to be done
  only one time instead of ten. The code itself is also smaller, which
  can lead to more efficient memory use.

Thanks!

答:
Short answer: yes.

Long answer for the benefit of those who might not be familiar with the guts of a CPU:

In a modern architecture such as amd64, the CPU needs to take a virtual address that is basically an offset into a process's address space and map it into the raw (physical) address space - this is likely what you meant by virtual memory (not swap space).

This distinction is done both to simplify program code and to insulate userspace programs from each other. Back in the DOS days one rogue program could crash the whole operating system. Modern operating systems and CPUs prevent this by giving each program its own virtual sandbox to play in and closely guarding shared resources such as memory, hard disk, the network interface, etc.


答:
I like to ask myself a few questions.

Is the bug legitimate? Can I relate to their frustration? Are they misusing/misunderstanding the product?

In my experience we have to attempt to relate with customers/users. Sure, often they are stupid, but they do see things differently, and often this can be an indication of where improvements (in either documentation or user experience) could be made.

If they are misinformed, tell them you understand that it may have been confusing/frustrating and try to point them in the right direction and thank them for bringing it to attention.

If the bug is legitimate, then again, tell them you see their frustration, and thank them.

Sometimes using software can be very frustrating for non-tech, I know this, so I don't take it personally.

Title: How to respond to a rude bug report?


问:
How is a dictionary better than a big switch, when mapping data to action?
Often times we see stuff like that in code:

```<code>void myFunction(string someValue) {
    if (someValue == "a") {
        // ...
    } else if (someValue == "b") {
       // ...
    } else if (someValue == "c") {
       // ...
    } else {
       // ...
    }
}
</code>```

This is a basic example of mapping data to actions. Doing this using a big switch or a long series of if else-if is considered a bad practice.

A common approach is to use a Dictionary (or HashMap, etc.) as a replacement. E.g.:

```<code>Dictionary<string, Action> _actions = new Dictionary<string, Action>();

// .. fill in the dictionary somewhere

void myFunction(string someValue) {
    _actions[someValue]();
}
</code>```

Somehow it does feel like a more elegant approach. However I don't see how it is so.

When mapping data to actions, how is a dictionary better than a big/growing switch?

答:
What if you have hundreds of values to choose from? How would your switch statement look like? Would it be maintainable? I think not.

What you lose by using a map is very minimal hit in performance because of more misdirection - what you gain is huge, huge boost in maintainability.

As mentioned by greyfade in the comments, you can also change the map during runtime, you are not hardcoding the possible values of the switch statement.


答:
I terms of readability and maintainability you will be better of with a dictionary if there are anything more than five or six actions.

In terms of performance (depending on language, version, hardware etc. etc.) the trade off is:-

Switch: one comparison per test value plus one branch per action if you assume the values are evenly distributed then you will average 50% of the tests on each pass through the switch. (For C programs with small integer values (like an EVAL) this will be optimized to one branch table look up per pass).

Dictionary: Calculate hash, lookup entry then branch.

So say its 20 instructions to calculate an integer hash, and another 10 to de-reference your branch table then the dictionary starts to outperform the hard coded switch after just 60 test values.

Title: How is a dictionary better than a big switch, when mapping data to action?

Body:
Often times we see stuff like that in code:

```<code>void myFunction(string someValue) {
    if (someValue == "a") {
        // ...
    } else if (someValue == "b") {
       // ...
    } else if (someValue == "c") {
       // ...
    } else {
       // ...
    }
}
</code>```

This is a basic example of mapping data to actions. Doing this using a big switch or a long series of if else-if is considered a bad practice.

A common approach is to use a Dictionary (or HashMap, etc.) as a replacement. E.g.:

```<code>Dictionary<string, Action> _actions = new Dictionary<string, Action>();

// .. fill in the dictionary somewhere

void myFunction(string someValue) {
    _actions[someValue]();
}
</code>```

Somehow it does feel like a more elegant approach. However I don't see how it is so.

When mapping data to actions, how is a dictionary better than a big/growing switch?


问:
Exception versus return code in DAO pattern
After reading a lot about the abusive use of exceptions in Java and how you should let an exception bubble up through the different layers of an application, I've come to a point where I don't know what I am supposed to do with the potential errors my application can have.

Basically, I have a webservice which uses the DAO pattern to access data in my database. All of the database actions can throw a SQLException.
As of today, I'm using a try catch to catch the SQLException and then thow a specific defined exception called ExceptionDAO that will be handle by the webservice to return a correct message to the users (a mobile application) of my webservice.

After reading a lot about how exception should be exceptional and should not be used in control flow, I've come up with a mixed understanding of what I should do to handle any errors:

Use return codes for anything that is likely to happen (e.g. username already exists) and therefore, to comply with the DAO pattern, pass my business objects as parameters instead. I could also use a specific pair which would return the code + the business object instead. The webservice would then use the return code to display a specific message.

Use checked exceptions for anything that I can't predict will happen and let them bubble up to the webservice to handle and return a message to the users. (e.g. SQLException that I can't predict : connection aborted)

Let unchecked exceptions bubble up aswell and display a sort of 404 error in this case.

I also had a look at the null pattern but I don't think it suits this particular situation really well.
I'm also concerned to not give too much information to the users, but rather useful and straight to the point information. Indeed, the messages returned by the webservice will be used by a mobile application to then display a message to the end-user.

I hope that I was clear enough about the problem I'm having, and I'm looking forward to your answers !

N.B. : This a repost of a subject I posted on stackoverflow, which relates to programming and not a language specific problem.

答:
You seem to have some misunderstandings about exceptions, so let's try and clear those up first.

Throw an exception when some condition occurs that you can't handle in your code.

For example, if your code is supposed to open a file and do something with that file, but the user supplies a path to a file that does not exist, then you should throw an exception (or allow a thrown exception to go up the call stack) because the user has created conditions by which your code cannot meaningfully continue to execute.

Rethrow an exception when you want to log or change the exception type.

For example, if you want to write the exception to a log or do something similar that does not correct the exceptional condition, catch the exception, log it, and then rethrow, perhaps with an exception that's more appropriate to your specific code.

A final thought: software guidelines and best practices are just that: guidelines.  Respect them, but do the thing that is most appropriate for your specific situation.  If that means breaking a guideline, then so be it.  Don't let guidelines stand in the way of better programming.  There are no absolutes in programming.


答:
Here is the mindset that I have asked my developers to follow:

1) Imagine you are the doctor in the emergency room treating the obstinate patient.  The doctor is professional in every way and helps the patient even if the patient is yelling to not help.

2) Imagine that the person who is rude just had something terrible happen to them and they are terribly upset about it.  Then the urge to reply negatively turns into pity and it is mentally much easier to reply professionally.  This helps overcome the problem of keeping the bad situation on your mind.

Title: How to respond to a rude bug report?


问:
Why don't terminals support standard keyboard shortcuts?
On OS X you can use cmd+left/right to jump to the beginning/end of the line, or option+left/right to jump word by word. In just about every application.

But not in the Terminal. Nor iTerm. You have to learn other, weird ways of jumping around... ctrl+a jumps you to the beginning of the line. ctrl+e is end of line. For jumping word-by-word it's ctrl+b or ctrl+f. The letters seem completely arbitrary.

On Windows it's even worse – you can't even ctrl+c and ctrl+v. The official method for copying and pasting is insane.

Why is this?

NB. I'm not asking for help with configuring my terminal. I just want to understand why this situation exists.

答:
cmd+left/right in OS X and ctrl+c in Windows are no less arbitrary than terminal shortcuts.

To answer your question, it's because of how these things developed. At some point when the Bourne shell was designed, back in the 1970s, someone decided which keyboard shortcuts should do what. Your modern OS X terminal is running bash, which descends from Bourne, and for compatibility is has many of the same features. OS X is Unix at its core, with a GUI and other features built on top by Apple. I suppose a better question would be "Why doesn't the OS X GUI use the same keyboard shortcuts as the terminal?" The reason is probably that, being a different user interface, there are approaches that work better than others.

It's the same deal with Windows. Windows was originally just a GUI sitting on top of DOS. While that's no longer the case, cmd (the Windows shell) still uses many of the same conventions as the DOS shell for compatibility reasons.


问:
How do you respond to: "Ever since the update..." questions from clients?
Ever since the update, people keep calling and saying "Ever since the update X, Y and Z are slow, bad and crashing"

This has happened ever since the dawn of updates.

What do people expect? Gamma comes after beta, and gamma testing always turns our users into The Incredible Hulks...

Perhaps you've never heard this from a client, perhaps you're in college or a FLOSS Dev who can spread the blame around more than 5 or 6 guys, perhaps you unit test your code, perhaps you're not in that interesting situation where customers actually call you requesting the exact time of day you'll be releasing today's patch (I'd love to do that to Microsoft) or perhaps you're a sorry son-of-a-biscuit like me who just shipped a new update and went home and is dreading going back to work tomorrow.

Anyway, ya'll are smarter than me anyway. How do you field criticism framed in "You must be a bad programmer because you're making your software worse"?

答:
Just to cover another aspect:

We keep a list of customers who claim this when it turned out not so. While are software is buggy, often very buggy, many of our customers will claim "started with the update" to get prompt attention, not realizing this ends up wasting everybody's time as we will walk the deltas for the indicated feature looking for the problem. If the customer is telling the truth this tends to get it found fast. If the customer is on the false list too many times we don't bother as we don't like wasting time.

I cannot imagine what manner of mindset is required to think telling us a lie would speed up the process. These people are or work with doctors and should know full well what happens when people lie to doctors. Same principle applies.

ContentLicense: CC BY-SA 2.5


问:
Adding Logging to a pre-existing Program
I have a game that I have been writing in java as a hobby for a number of years. I have very sparse logging, just some simple output when something goes really wrong. It's about 25,000 lines of code.

I just released a first beta, and I'm realizing it is going to be a nightmare to deal with bug reports without good logs. Whenever something goes wrong on my test machine, I have the luxury of looking at the code and adding print statements if I need to figure out what's going wrong. Obviously, that's not available once its released in the wild.

Do you think it is advisable to try to add logging to this program now? Or do you think that I'm too far along to try to fix this problem?

Do you have any recommendations on how to go about doing it? I honestly don't know where to start.

Do you have a recommendation for a logging system for Java?

Do you have any good articles / best practices recommendations on what to log and how to log it?

Thanks! Any and all information is greatly appreciated.

答:
I'd suggest reading up on Aspect-Oriented Programming, specifically as it applies to logging:
http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html

AOP is a technique for keeping your methods clean and focused on business logic while extracting "plumbing" code - such as security, validation or, yes, logging - to external classes, and having the infrastructure apply them automatically. In this case, you create an Aspect called "MethodLogger" and apply it to your classes, and it hooks into your code before and/or after each method execution and performs its code, which can log the method call and its parameters.

It's not perfect logging, especially if you have long and complicated methods that need logging their computation state in the middle, but it can give you a whole lot of logging info, throughout your program, in one go.


答:
The rule of thumb when it comes to logging: "it's never too late!"

Do you think it is advisable to try to add logging to this program
  now? Or do you think that I'm too far along to try to fix this
  problem?

You can start off with some generic logging, which is agnostic to your application as such:

ENTRY/EXIT logs: You can add a logging statement at the start of every method and at every exit point at the TRACE level. (Logging the in/out arguments is optional)

```<code>public int myMethod(int input) {
    logger.trace(String.format("+++ [%d]", input));
    .
    .
    .
    logger.trace(String.format("--- [%d]", output));
    return output;
}
</code>```

This may sound trivial and benign at first, but if you compare having zero logs v/a having a trail of TRACE logs, you'd be far better with the latter. It also helps in encapsulating logs from a single method between the ENTRY and EXIT statements in the logfile.

It can be cumbersome to add such logs in every method ever, so you can choose to be a ninja and use Aspect-Oriented Programming to do it quicker:  How to automatically log the entry/exit of methods in Java?

EXCEPTIONS: You can quickly replace all your e.printStackTrace() statements with a logging statement that puts the stack trace in the log file.

Do you have any recommendations on how to go about doing it? I
  honestly don't know where to start.

Assuming you don't want to become an expert in logging and are simply looking for a way to 'logify' your code before the beta release, you can take a look at this quick tutorial on adding log statements.

Do you have a recommendation for a logging system for Java?

If you want to start quick, use log4j with the PatternLayout. All it takes is a simple .properties file and the JAR included to your classpath to see the logs rolling.

If you want to evaluate several logging libraries, but don't have the time right now, then I would suggest starting off with log4j but use the slf4j wrapper on top of it. What slf4j does is, it abstracts out the logging library so that later, you can easily swap log4j for something else, like logback, without having to change imports and logging statement across your code.

Do you have any good articles / best practices recommendations on what
  to log and how to log it?

A few suggestions off the top of my head:

Declare a static logger object for every class: this will ensure proper location reporting of where the log statements come from

```<code>final static Logger logger = Logger.getLogger(classname.class);
</code>```

Log an INFO message for every successful operation that a method has done. It helps to not have a bird's-eye view at the code and only focus on one method at once instead when adding logs for functionality (and is also quicker since you can warp through your code base adding logs like a machine!)

Make sure you log the EXCEPTION in the ERROR message in your catch() block - this will log the stack trace in the logfile instead of just the message

Log a TRACE or an INFO just before starting time-intensive operations, so that if a pedantic user is staring at the logs while your program is running, he/she will be tranquilized by the fact that something time-intensive is happening and the program hasn't crashed just because the logging paused for a while

Happy logging! Be assured that your efforts will pay off.

Title: Adding Logging to a pre-existing Program

Body:
I have a game that I have been writing in java as a hobby for a number of years. I have very sparse logging, just some simple output when something goes really wrong. It's about 25,000 lines of code.

I just released a first beta, and I'm realizing it is going to be a nightmare to deal with bug reports without good logs. Whenever something goes wrong on my test machine, I have the luxury of looking at the code and adding print statements if I need to figure out what's going wrong. Obviously, that's not available once its released in the wild.

Do you think it is advisable to try to add logging to this program now? Or do you think that I'm too far along to try to fix this problem?

Do you have any recommendations on how to go about doing it? I honestly don't know where to start.

Do you have a recommendation for a logging system for Java?

Do you have any good articles / best practices recommendations on what to log and how to log it?

Thanks! Any and all information is greatly appreciated.

Body:
The rule of thumb when it comes to logging: "it's never too late!"

Do you think it is advisable to try to add logging to this program
  now? Or do you think that I'm too far along to try to fix this
  problem?

You can start off with some generic logging, which is agnostic to your application as such:

ENTRY/EXIT logs: You can add a logging statement at the start of every method and at every exit point at the TRACE level. (Logging the in/out arguments is optional)

public int myMethod(int input) {
    logger.trace(String.format("+++ [%d]", input));
    .
    .
    .
    logger.trace(String.format("--- [%d]", output));
    return output;
}

This may sound trivial and benign at first, but if you compare having zero logs v/a having a trail of TRACE logs, you'd be far better with the latter. It also helps in encapsulating logs from a single method between the ENTRY and EXIT statements in the logfile.

It can be cumbersome to add such logs in every method ever, so you can choose to be a ninja and use Aspect-Oriented Programming to do it quicker:  How to automatically log the entry/exit of methods in Java?

EXCEPTIONS: You can quickly replace all your e.printStackTrace() statements with a logging statement that puts the stack trace in the log file.

Do you have any recommendations on how to go about doing it? I
  honestly don't know where to start.

Assuming you don't want to become an expert in logging and are simply looking for a way to 'logify' your code before the beta release, you can take a look at this quick tutorial on adding log statements.

Do you have a recommendation for a logging system for Java?

If you want to start quick, use log4j with the PatternLayout. All it takes is a simple .properties file and the JAR included to your classpath to see the logs rolling.

If you want to evaluate several logging libraries, but don't have the time right now, then I would suggest starting off with log4j but use the slf4j wrapper on top of it. What slf4j does is, it abstracts out the logging library so that later, you can easily swap log4j for something else, like logback, without having to change imports and logging statement across your code.

Do you have any good articles / best practices recommendations on what
  to log and how to log it?

A few suggestions off the top of my head:

Declare a static logger object for every class: this will ensure proper location reporting of where the log statements come from

final static Logger logger = Logger.getLogger(classname.class);

Log an INFO message for every successful operation that a method has done. It helps to not have a bird's-eye view at the code and only focus on one method at once instead when adding logs for functionality (and is also quicker since you can warp through your code base adding logs like a machine!)

Make sure you log the EXCEPTION in the ERROR message in your catch() block - this will log the stack trace in the logfile instead of just the message

Log a TRACE or an INFO just before starting time-intensive operations, so that if a pedantic user is staring at the logs while your program is running, he/she will be tranquilized by the fact that something time-intensive is happening and the program hasn't crashed just because the logging paused for a while

Happy logging! Be assured that your efforts will pay off.


问:
Should I avoid data duplication?
I'm trying to design a relatively simple ERP system. However, there are some requirements that complicate things a little bit:

It must be possible to add all sorts of contacts to the people table, including clients and co-workers.

It must be possible to assign a user to a contact, so users can access their schedules and stuff.

It must be possible for users to be assigned to multiple customers, when for instance a user works for several organisations.

It must be possible for different organisations to have different contact details for one user.

When — in the future — a project management functionality is added, it must be possible to share projects between organisations.

I came up with this simple data model:

As you can see, there is some data duplication between tables.

Should I just just get rid of the customer's organisation name, and retrieve that from the customer's contact field instead? And yes, the customer's contact is the person that receives invoices and such from us. Is this a good design decision or should I not use the people table for this?

The user's name is a duplication of the contact's name, but I don't think this is avoidable? I don't want to tie the user's details to the contact's details, see point 4.

Again, this is just a very simple 'mockup' to visualise things, but what kind of improvements can I make to this model? Is there a more elegant way?

答:
TL;DR; Normalization is a good approach and if you have problems with that it may be sign there's an issue with your approach - try redesign the problem.

I would normalize this as much as possible (and reasonable) because that what leads to better design in general. For example your 'people' table looks more like 'contact_info' table, if that's true - it probably doesn't need a name.

Then: Organization probably needs a name, and person (a.k.a. customer?) also have one because it's something different.

Lastly: Users probably don't need name, but login (or e-mail if it can be used as login - which I think is a good practice because it's easier to remember it and you don't have to deal with already taken usernames) and password is needed.

With such design customer can belong to one or many organisations (in the latter - you need extra table for that connection), and organization can dafault_contact which is FK to contact_info.id or customers.id (you're the one to decide what makes more sense in this case).

With such aproach there's no 'people' table which accepts organizations, customers and actual people (this is confusing) - you name your tables by what they actually contain: contact_data, person (personal data), company (tax id, website url. etc), users, and if needed customers (see below).

Questions for spacifying customers table
- can customer be only company or also private person?
- can customer be a company without any person assigned to it?

Answers could help you determine if you need 'is_customer' in person/organization table OR customers table with FK person_id or organization_id or both.

Title: Should I avoid data duplication?


问:
Recommend an approach to decouple Product and Access code constructs, in order to simplify Product testing
I have some code that tightly couples Product specific code and Product-Access code.  I am not sure how to untangle it.  So for example, for testing Product, I have to mock up Access objects.  And maybe there is no way around it, but maybe there is.  I have code that goes something like this:

```<code>class Product
{
    function __construct() {
        global $user;   //current logged in user object
        $id = $user->getId(); //used to make calls to DB
        $this->access = $db->query("SELECT access ... where id=$id");
        //DB returns "product access" information which is used to allow/reject access
        //code of product is tightly coupled with code for authorization
    }
}

class ProductA extends Product
{
    function __construct() {
        parent::__construct();
        if ($this->access != "all_access") doPartialAccess();
        else doFullAccess();
    }
}
//...
class ProductX extends Product
{
    function __construct() {
        parent::__construct();
        if ($this->access != "all_access") doPartialAccess();
        else doFullAccess();
    }
}
</code>```

Approach 1

My first thought is to use dependency injection, to inject $user (or $access object directly) into constructor of Product.  but wait ... I will have to do this with every Product* extending Product.  Even if I do this, it will be effectively just moving the instantiation of $user elsewhere in the code (outside of Product* classes).  As such, I am not sure it will be the best solution necessarily, because I think it will convolute the codebase with introducing what I think are unnecessary parameters into constructors, instead of making the codebase more maintainable.

Approach 2

Another thought is to have some kind of a "registry" for access object, where I can put objects in it and extract objects out of it.  But wait, Registry pattern is deemed an anti-pattern.  And I am already using it -- see the global $user!?  Not an object oriented way to do this, mind you, but registry concept nevertheless.

Question

My long term goal is to decouple product code (various computations, assembling a product model string, etc.) from user permissions code controlling access to the class.  Product access constructs are actually used to build some SQL queries, so code of Product and Access are pretty much entangled right now.  Product needs Access and I am not sure if I can de-tangle them.  I think I can't walk around the fact that Product does need Access.  Perhaps I just need to pull out the currently-sparsely placed code lines that do control access, and put them into their own Access class and call that class ProductAccess, or the like.  There may be no way around it, but I am not entirely sure how to do this correctly.  DI seems to be inappropriate(?)

My short-term goal is that want to be able to test code for ProductA, without mocking up Access class.  But then this could be a wrong goal to have.  Maybe I need to mock up Access, since How will I test Product without knowing what level of access it needs...

My overall goal is to find a way to decouple classes as much as I can, while keeping existing functionality and getting rid of the registry pattern I have there now.  Is there a way to do this, or is my goal flawed?

答:
For this particular problem I would recommend something similar to your's second aproach.

Check out Service Locator pattern (Is this a good service locator, and is this service locator pattern(?) OK?) this is basically what you called "registry".

Secondly - don't put User as a service there. Most probably you need something like Session, and in your code do something like

$user = ServiceLocator::get("Session")->currentUser();

I would say ServiceLocator is basically Singleton made mockable ;)

And don't forget to cover your ServiceLocator with tests ;)

Dependency injection may be useful or not - depending on your framework. For your case it seems that it doesn't fit - especially that $user is global, so generally it fits Singleton description.


问:
How to respond to a rude bug report?
I just received a quite rude bug report. The user basically says that we're doing it all wrong using capital letters here and there, although he's in fact just pointing at one bug.

On one hand, I care a lot about our users and want to maintain a good relationship and a good rating of our app. On the other I'd feel like a complete sell out if I would reply overly polite.

What's a decent way of responding? What should I keep in mind? What mindset should I have?

It should be added that the user seems to be a 24 year old CS student, and our product is an Android app that we're giving away free of charge.

答:
Don't take it personally!

Because it is not:

The author was angry - but pretty sure not about you or a colleague in person.

The bug report text expresses negative human emotions - against some abstract, vague opponent, representing the software, and the organisation creating the software.

If you see that very clear, you can just ignore the negative part - it's just noise.

A bug report with bad text layout, hard to read, nothing more.

Title: How to respond to a rude bug report?


问:
Is it wise for a high level developer to spend time studying assembly?
It is clear that the knowledge of low level stuff is very important in our work.

But in a situation where you're already developing commercial software on a high level, and when you already have a chosen direction but don't have any assembly skill, isn't it more reasonable to focus on studying stuff related to your direction? Or is there a reason you should spend some time to learn the low-level basics anyway?

When is it too late, and when it is not? And if it is not too late, then how would one go about learning optimally (in the sense of not spending excessive time to get some depth and understanding)?

答:
You don't need to learn assembly language, you just need to understand how it works. You need to know what XOR is and count in binary in your sleep, etc. But I have never needed assembly code in my work, ever.

So as you say, knowledge of low level stuff is important, but practical knowledge in assembly is not.