答:
In order to get an infinite list of items, you need two things:

The ability to get the first item

The ability to get a list containing the rest of the items.

There different names for this pattern such as first/rest, head/tail.

I think you are looking for something more along the lines of the following. It does not implement java's List interfaces, but it would be possible to.

```<code>import java.math.BigInteger;

public class InfiniteList {

    private BigInteger _current;

    public InfiniteList(BigInteger start){
        _current = start;
    }

    public BigInteger first(){
        return _current;
    }

    public InfiniteList rest(){
        return new InfiniteList(_current.add(BigInteger.ONE));
    }
}
</code>```

It has a way to get the first element, but then it also has a way to get a list containing the rest. The list only allocates enough memory for one element, and then allows you to get a new list, containing the rest of the elements, but of course that next list only allocates one element, but gives you a way to get the rest.

If you call rest 99 times and then call first, it will only have allocated 100 elements total. If you do not hold on to any of the items when you're traversing the list, the ones in the beginning can get garbage collected.

Body:
In order to get an infinite list of items, you need two things:

The ability to get the first item

The ability to get a list containing the rest of the items.

There different names for this pattern such as first/rest, head/tail.

I think you are looking for something more along the lines of the following. It does not implement java's List interfaces, but it would be possible to.

import java.math.BigInteger;

public class InfiniteList {

    private BigInteger _current;

    public InfiniteList(BigInteger start){
        _current = start;
    }

    public BigInteger first(){
        return _current;
    }

    public InfiniteList rest(){
        return new InfiniteList(_current.add(BigInteger.ONE));
    }
}

It has a way to get the first element, but then it also has a way to get a list containing the rest. The list only allocates enough memory for one element, and then allows you to get a new list, containing the rest of the elements, but of course that next list only allocates one element, but gives you a way to get the rest.

If you call rest 99 times and then call first, it will only have allocated 100 elements total. If you do not hold on to any of the items when you're traversing the list, the ones in the beginning can get garbage collected.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: Every programmer should know about testing.</p>

ContentLicense: CC BY-SA 2.5


问:
How can I present some printed Visual Basic source code in an aesthetically pleasing manner?
Right now I'm interning at a major engineering company. I'll be leaving in a few months though, so my project manager has requested a print out of my source code for a VBA project I've been working on.

He would like to have it reviewed to make sure I didn't do anything ridiculous, and to make sure it's organized well enough for someone to maintain easily enough once I'm gone.

I'm not really sure why he would want a print out instead of files, but since the VBA editor is ugly as sin this is probably a good thing.

I would like to make an impression with this - however minor - so my question is how can I make this look professional? I.e., maybe there are certain fonts that make sense here, perhaps I could apply a color scheme to the words, etc?

答:
Use something like Notepad++ or a similar syntax highlighting application that will print out your code in colour (if you're allowed to). Otherwise, black and white is fine - but colour with highlighting makes it easier to read. Some points to consider:

Ensure you have consistant spacing and formatting in your code, and your code is as readable as you can possibly make it.

Make sure any code that spans over one line prints nicely, you may need to mess about a bit.

Use a monospaced font - it will improve readability by miles. Once again, most "advanced" notepad-like applications will do this for you by default.

Print with line numbers, as in a paper-based code review many people will refer to a line number rather than a statement when making comment.

Put a header and/or footer that contains the file/module name and page number. Even with line numbers printed, it's nice to have page numbers to give your readers an easy way to sort pages out in the event they get mixed up.

ContentLicense: CC BY-SA 3.0


问:
I have data that sends in "bursts" of 100 records with a significant delay. How do I structure my classes for multithreading?
My datasource sends information in 100 batches of 100 records with a delay of 1 to 3 seconds between batches.

I would like to start processing data as soon as it's received, but I'm not sure how to best approach this.

Some ideas I've been playing with include:

yield

Concurrent Dictionary

ConcurrentDictionary with INotifyProperyChanged

Events

etc.

As you can see I'm all over the place, and would appreciate some tested guidance on how to approach this

答:
I would look into the TPL Dataflow APIs for this kind of work. At bare minimum you would do something as simple as:

```<code>ActionBlock<MyData> myActionBlock = new ActionBlock<MyData>(data =>
{
    // your processing logic here
});
</code>```

And then as your messages arrive from whatever external event you just post them to that block:

```<code>myActionBlock.Post(data);
</code>```

That's it. TPL Dataflow then implements all the producer/consumer scale for you by farming the work you've provided in your action definition out to as many possible worker threads as the machine can handle (which is based on all the usual TPL heuristics).

From there you can start to get a little more advanced by simply taking control of governing exactly how much capacity/scale you want with ExecutionDataflowBlockOptions. You can also hand in a CancelationToken via EDBO.

Then you can start to get really advanced by using the composition features of TPL Dataflow's many different "block" types and do things like introduce a BufferBlock which, in your case, would allow you to receive that burst of 100 items and not block the producer who is doing the .Post call. Only if you reach 100 would the producer then be blocked from adding any more. There's also BatchBlock which, depending on your exact workload, it might make more sense to use so that you can send maybe 20 items off to a worker thread to be processed rather than 1 at a time.

You can link together any concoction of blocks as you can imagine. There's filtering, transforming... you name it. To top it all off you can even write your own custom blocks.  For example, if you wanted to introduce temporal coupling into the mix you could, for example, batch up to 20 item or if you haven't received 20 for 10s you send through however many you have already received. The possibilities are pretty much limitless.

Body:
I would look into the TPL Dataflow APIs for this kind of work. At bare minimum you would do something as simple as:

ActionBlock<MyData> myActionBlock = new ActionBlock<MyData>(data =>
{
    // your processing logic here
});

And then as your messages arrive from whatever external event you just post them to that block:

myActionBlock.Post(data);

That's it. TPL Dataflow then implements all the producer/consumer scale for you by farming the work you've provided in your action definition out to as many possible worker threads as the machine can handle (which is based on all the usual TPL heuristics).

From there you can start to get a little more advanced by simply taking control of governing exactly how much capacity/scale you want with ExecutionDataflowBlockOptions. You can also hand in a CancelationToken via EDBO.

Then you can start to get really advanced by using the composition features of TPL Dataflow's many different "block" types and do things like introduce a BufferBlock which, in your case, would allow you to receive that burst of 100 items and not block the producer who is doing the .Post call. Only if you reach 100 would the producer then be blocked from adding any more. There's also BatchBlock which, depending on your exact workload, it might make more sense to use so that you can send maybe 20 items off to a worker thread to be processed rather than 1 at a time.

You can link together any concoction of blocks as you can imagine. There's filtering, transforming... you name it. To top it all off you can even write your own custom blocks.  For example, if you wanted to introduce temporal coupling into the mix you could, for example, batch up to 20 item or if you haven't received 20 for 10s you send through however many you have already received. The possibilities are pretty much limitless.


答:
If you understood him correctly

He would like to have it reviewed to make sure I didn't do anything
  ridiculous, and to make sure it's organized well enough for someone to
  maintain easily enough once I'm gone.

then that is your goal, not aesthetics or to please him because it makes you feel better.

When I write code that is for use for others, I write it for others with good comments, meaningful variable names, following the standard formatting conventions of the language or the group and move on.

If you didn't try and sabotage the company with malicious code then you probably pass the first requirement. If you have confidence in your code and good comments then what more do you need to meet his requirements. Print it out, hand it over and move on.

Title: How can I present some printed Visual Basic source code in an aesthetically pleasing manner?

Body:
Right now I'm interning at a major engineering company. I'll be leaving in a few months though, so my project manager has requested a print out of my source code for a VBA project I've been working on.

He would like to have it reviewed to make sure I didn't do anything ridiculous, and to make sure it's organized well enough for someone to maintain easily enough once I'm gone.

I'm not really sure why he would want a print out instead of files, but since the VBA editor is ugly as sin this is probably a good thing.

I would like to make an impression with this - however minor - so my question is how can I make this look professional? I.e., maybe there are certain fonts that make sense here, perhaps I could apply a color scheme to the words, etc?


问:
MVCS - Model View Controller Store
I recently decided to start learning iOS Development, and to this end I’ve been reading iOS Programming: The Big Nerd Ranch Guide. In the book the authors describe a  design pattern MVCS - Model-View-Controller-Store, the basic idea being that since many applications make use of multiple external sources of data keeping the request logic in the controller can get very messy, instead the authors propose that moving all the request logic out of the controller and into a separate object.

In short to quote the book

Model-View-Controller-Store puts request logic into a separate object,
  and we call this object a store (Figure 28.4). Using a store object
  minimizes redundant code and simplifies the code that fetches and
  saves data. Most importantly, it moves the logic for dealing with an
  external source into a tidy class with a clear and focused goal. This
  makes code easier to understand, which makes it easier to maintain and
  debug, as well as share with other programmers on your team.

And

The cool thing about asynchronous stores is that even though a lot of
  objects are doing a lot of work to process a request, the flow of the
  request and its response are in one place in the controller. This
  gives us the benefit of code that’s easy to read and also easy to
  modify.

I wanted to find out more about this pattern and to see what others might have to say about it, but while searching online the only references I could find were to that same book (is the pattern perhaps known by some other name?).

To me the author’s logic seems to make sense, and it seems like a logical extension of the regular MVC pattern,  but perhaps that's because I don’t really have much experience with the MVC pattern in practice (aside from foray into iOS development I have sort of used MVV with backbone.js (that is, if you consider it MVC)).

I was hoping that perhaps someone with more experience can shed some light on whether there are any obvious flaws/problems with the MVCS pattern that I’m missing.

答:
'Store' in this context sounds very much like a Repository or Service.  In that case, this is an extremely common pattern.  The flaws/problems will vary with your implementation and the problem domain.

On a general level, it sounds like the book is using 'Store' to represent a level of business logic + a level of data retrieval logic that handles a set of data that may or may not be part of your application.

For instance, wrapping the twitter api in a 'Store' is a nice way to compartmentalize that logic.

Upon further thought

Using this definition of MVC (which I think is pretty spot on), the 'Store' is really a subset of the model.  The delineation between whether it's an extension to MVC or whether it's a data retrieval pattern isn't terribly useful.  They end up looking like the same code.

Bottom line, I think you'll be fine following the advice they suggest (seems sound overall).

Title: MVCS - Model View Controller Store


问:
NodeJS as an avenue towards learning JavaScript
I'm a backend programmer who works mainly in Python. I'll probably never want to be a full time front end developer, but with the goal of growing my skill set, I would like to become at least passably proficient in JavaScript. It seems like a language that is wearing a lot of hats nowadays, and if nothing else, I'd like to a little more knowledgable about 'their world' when I'm working with front end guys.

We're using NodeJS for some server side work at my company, and I was curious about it. I've found a few good tutorials and it seems interesting. It seems like it might be a good way to familiarize myself with JavaScript, since it comes at it from an angle that I understand -- server side programming.

But I am also a little worried that if I learn both at once, I won't be able to keep track of what's 'Stock JavaScript' vs features that are particular to NodeJS.

What do you guys think? Is bootstrapping myself into JavaScript familiarity by learning NodeJS a good idea? Or will I just confuse myself if I jump into Node without a solid understanding of the fundamentals of JavaScript?

答:
It won't matter.

In either case, you'll be learning things that are specific to the domain in which you're working. On the client, you'll be learning things about DOM and cross-browser compliance. On the server-side you'll be learning things like file access and database libraries.

It's really six to one, and half-dozen to the other. If anything, you'll be less distracted by the the intricacies of Node than you will the intricacies of browser-based JavaScript.


答:
JavaScript, by itself, is a pretty small language that is easily understandable by most programmers, especially if you're a proficient Python programmer. There are no new programming concepts in core JavaScript. You probably already know 90% of what there is to know about JavaScript itself.

The real learning curve comes when you use JavaScript to try to do some useful work. Inside a browser, you use the DOM (Document Object Model) to interact with web pages. That is sometimes annoying, so you can also use jQuery to manipulate the DOM with shorter expressions.

NodeJS is a way of writing back-end server processes in JavaScript using a highly asynchronous programming model. Unless you're using Twisted in Python, you're probably not going to be very familiar with the asynchronous style of programming used in NodeJS. So that would be another learning curve.

Basically it depends on what you want to actually do with JavaScript - it's just a programming language tool. The libraries that people build around JavaScript are where the interesting things happen.

Title: NodeJS as an avenue towards learning JavaScript

Body:
I'm a backend programmer who works mainly in Python. I'll probably never want to be a full time front end developer, but with the goal of growing my skill set, I would like to become at least passably proficient in JavaScript. It seems like a language that is wearing a lot of hats nowadays, and if nothing else, I'd like to a little more knowledgable about 'their world' when I'm working with front end guys.

We're using NodeJS for some server side work at my company, and I was curious about it. I've found a few good tutorials and it seems interesting. It seems like it might be a good way to familiarize myself with JavaScript, since it comes at it from an angle that I understand -- server side programming.

But I am also a little worried that if I learn both at once, I won't be able to keep track of what's 'Stock JavaScript' vs features that are particular to NodeJS.

What do you guys think? Is bootstrapping myself into JavaScript familiarity by learning NodeJS a good idea? Or will I just confuse myself if I jump into Node without a solid understanding of the fundamentals of JavaScript?


答:
Getting into JavaScript is definitely a good idea, as JavaScript is only getting better and more popular.

Front-end JavaScript development is extremely different then Node.js (Server-side) programming/development. Each browser has their own support of JavaScript features, meaning, features are not always readily available across every browsers. Especially with the new version of ECMAScript, it's becoming extremely hard to take advantage of, as most browsers, or the majority of users (apart from chrome) are on older browsers. Chrome has had auto-updates for a long time, so it's users don't need to take any action. They typically get the majority of their users upgraded within a few weeks. You still have Internet Explorer 6,7, and 8 problems, and even 9 (Not many new features that are in HTML5 and ECMAScript spec). Firefox is fairly good, and they seem to be on a good track implementing new features all the time.

On the client-side you have 3-5 different JavaScript engines; V8 (Chrome & Node.js), IonMonkey (Firefox has had multiple engines), Carakan (Opera), JavaScriptCore (Safari), Chakra (Internet Explorer). Each engine has different architectures (JIT, byte-code, machine code, etc...) and now each have different support for ECMAScript 6 (Harmony).

With Node.js, you can start to take advantage of newer JavaScript features as you only have to support one JavaScript engine (V8). This makes it extremely easy to work with, as you're not jumping through hoops trying to do feature detection, hack the system, etc...

Lesson 1: Developing within Node.js is luxury compared to the client-side, but with the power of frameworks and libraries like JQuery, Ember.js, Angular, Handlebars (Templating), Modernizr, etc... your work load dramatically decreases.

Performance, Optimization, and the DOM... This is what client-side development is like. If you start with Node.js, you'll start to use (hopefully) build and deploy tools like GruntJS, Yeoman, Cake, etc... These will be incredibly useful when working with client-side JavaScript. Start looking into different module systems; Node.js uses CommonJS. AMD is another choice for development.

JavaScript as a language is simple to get started with. Once you dig deeper down, you'll find how flexible a prototypal model is.

The asynchronous model might be a little scary at first, but no need to be afraid. It's quite simple when you understand it. You'll go through the traditional stage of callback hell, but you'll be able to learn some design patterns to avoid them.


问:
How do you interview someone with more experience than you?
The company I'm working for is looking to hire a senior developer with more experience than me, and they expect me to do the technical part of the interview. I've only been programming a few years and am not sure I have the knowledge needed to evaluate the coding skills of someone who has greater understanding/experience than I do.

Can anyone recommend some technical interview questions to ask that are a good means for evaluating higher-level programming skills, but still be ones I can understand?

I would say I'm past the jr. programmer level, but nowhere near senior. Most of what I've done is built small apps (web and desktop), some of them fairly complicated, but all of them have been meant to be used by no more then a handful of users. I feel I have a decent understanding of most programming concepts and am capable of learning/teaching myself just about anything, however I lack experience. As my boss is fond of telling me, "You don't know what you don't know".

In particular, things we'd like the person we hire to have experience with (that I don't have) is: Multi-tier development, multi-user environment, large-scale application development, two-way messaging, shared sessions, and Multi-threading/BackgroundWorkers.

UPDATE:

In response to Thor's comment below, we hired someone a few months ago and I think it has been working out great. I am learning a lot, not just about coding but also about things like design patterns, software architecture, documentation, and how other larger programming teams get stuff done. Its not always easy having someone come in and point out better ways to do things you have done, but if you can swallow your pride and be willing to try out new things you can learn a lot.

The interview process went better than I expected. I started asking questions about things I was familiar with, then asked some questions about some things I was struggling with. Whenever the interviewee said something I didn't understand, I'd ask them to explain it to me and then write it down so I could look it up later on. Overall, I felt I was able to get a pretty good idea of the applicant's skill level, intelligence, and what they'd be like to work with.

答:
A thing I did not see explicitly pointed out, is "You know technology X very well, and it sounds very interesting.  Could you please explain it to me in five minutes?"

Since you will most likely be expected to be able to maintain the code eventually coming out of the new person, it is crucial that he or she is capable of explaining it to other programmers efficiently and well.  Consider it to be communication skills.

A thorough understanding is necessary to be able to meet any other developer on their skill level and communicate thoughts and ideas on their level.

If the person cannot communicate verbally, he or she most likely only write the code for the compiler, not for the maintainer.


答:
Node essentially capitalizes on all the stuff that makes JavaScript stand out as a language so I'd say it's probably a better start than client-side work for you. Also, Python's trust-the-user philosophy and the Python community's devotion to writing cross-platform software that isn't clumsy, hamfisted and stupid tends to be a good fit with JavaScript's complete abandon with regards to giving its users plenty of rope to do with as they please and the JS community's legacy of normalizing for browsers that refuse to agree on how things are done exactly fits nicely with that Python-cross-platform chutzpah.

So I guess what I'm saying, is that I wouldn't sweat it. You've got the server-side paradigm down and Python and JS, while different, tend to come from similar lines of thought which I would boil down to:

Don't protect me from myself or the other guy

Don't assume I'm a dummy or that I'll never want to learn anything after college

Be easy to use right out of the box but give me serious power when I bother to really learn the crap out of the language and what it's capable of

The important thing to remember about JavaScript is that in spite of what all the bigwig speaking-engagement-types say, JS is not a language we are "stuck with." It is not something that happened to dominate web UI and then spread across all platforms like a super-virus by accident. It did not kick the crap out of VB, Flash, ActionScript and Java applets merely because of foolishly misguided efforts at owning the front end of the web by abstracting from how everything actually works, or being intolerably proprietary in terms of how those language business models were in their own right completely and 100% unacceptable. And it sure as Hell isn't the only real choice for writing cross-platform mobile platform apps just because JS devs are hyperactive and prolific. It won those battles because it's a really good tool for those jobs.

It's elegant, it has a strong, highly-focused opinion, and it walks a nice line of being accessible to people who just want to get simple things done in obvious ways while offering very powerful options to people who are willing to take it a step further and properly understand how it fuses functional and functionally-OOP into a master-blend.

And remember that the whole point of Node.js is to basically bury threads with JavaScript. You can run two I/O processes simultaneously but JS is just the thing that sets processes off and waits for them to finish. The fact that the language is naturally blocking but highly proficient at asynchronous response essentially turns JS into a kind of auto-queuing messenger. It's probably not the best tool for everything you'd ever want to do on a server but it's a pretty interesting paradigm for a lot more than just covering basic web server stuff. But not if you don't accept it for what it is and why that's been successful. So, have fun with it. Learn more about Python as you learn more about how JavaScript is different from it.

And sorry about the C-based syntax. You won't notice as much after a while, I promise. But skip CoffeeScript until you know how it limits you on the OOP front. You probably won't want it.


问:
Automated object creation from user input
I am working on a command-line application that runs simulations. It has to be heavily configurable; the user should be able to provide a very large number (100+) of parameters, some mandatory and some optional. Obviously, these parameters will be used by a variety of classes in the application.

I can see two approaches I can use; which one is a better design in the long run?

Approach 1

Have the (text) input file directly control object creation in the application. For example, user would provide the following input:

```<code>root=Simulation
  time=50
  local_species=Sentient
    strength=3.5
    intelligence=7.1
  invading_species=Primitive
    strength=5.1
    sociability=2.6
</code>```

The application would then recursively create objects of the class specified on the rhs of the equal sign, passing the class' constructor the arguments provided in the relevant sub-branch of the input file, if any. I'm using Python, which supports keyword arguments and default argument values when no argument is provided, but I hope the question isn't terribly language-specific.

For example line 1 would tell the app to create an object of class Simulation, with three constructor arguments. The first constructor argument is time=50. The second argument is an instance of class Sentient, which is created by passing Simulation's constructor arguments strength=3.5, intelligence=7.1. The third argument is an instance of class Primitive, which is created with by passing the constructor arguments strength=5.1, sociability=2.6.

The whole object creation is handled automatically, with just a few lines of (recursive) code. The highest-level object (instance of Simulation in this case) would be passed to the visualization layer.

Approach 2

The input file still looks the same. However, the application's classes now have full control over how they interpret user input. The lhs and rhs values may or may not correspond to keyword parameters and classes. For example, the above input may result in the application creating an instance of class InvasionSimulation with arguments strength_local=3.5, intelligence_local=7.1, strength_invading=5.1, sociability_invading=2.6, and then calling its method set_runtime(time=50), before passing the object to the visualization layer.

One obvious advantage of approach 2 is that the user's input can remain stable even as the application is completely redesigned internally. But I think there's nothing wrong with designating a subset of classes as "public API", and therefore ensuring that it doesn't change in the future, is there?

On the other hand, if the application internally follows something quite similar to approach 1 anyway, it feels that approach 2 requires adding a lot of redundant code: instead of automatically interpreting user input, we now need to do it "by hand" for each class.

Any additional considerations would be much appreciated. Are there any names for these approaches that I can search for?

答:
In my personal experience the single best approach to pulling command or config arguments into a command line program is a dictionary. The input is naturally structured as key-value-pairs so it just make sense from an input standpoint, but the bonus is maintainability when you merely have to add new key handlers and never new parsing code as the parser simply pulls everything into a dictionary allowing whatever keys needed. Also it doesn't force scoping onto the consumer of the arguments space, so each argument and value is available by default to any consumer who feels it relevant, you don't have to do leg work to publicize the argument and value to consumers.

Moreover, I have had a habit of creating at start a dictionary available to main which has a list of keys that correspond to arguments, and a list of values which are functions to parsing and handling said keys in so far as those keys require configuration of the system state before processing occurs. For example, a key of v may have a func that parses the value of that arguments key into setting System.Verbosity = true; and the argument parser just calls _startupDictionary[argument](value); and if the function returns false that means the argument was invalid or had an invalid argument, in this way it may notify the argument parser that the system state will be inconsistent given the set of arguments available and cannot therefore process correctly.


问:
What's the difference between fault, error and defect?

Possible Duplicate:

  Difference between defect and bug in testing

In computer science technical writing, especially in software engineering, what's the difference between fault, error and defect?

I want to quote an answer on Stack OverFlow by Daniel Joseph:

To quote the Software Engineering Body of
  Knowledge

Typically, where the word “defect” is used, it refers to a “fault” as
  defined below. However, different cultures and standards may use
  somewhat different meanings for these terms, which have led to
  attempts to define them. Partial definitions taken from standard
  (IEEE610.12-90) are:

Error: “A difference…between a computed result and the correct result”

Fault: “An incorrect step, process, or data definition in a computer
  program”

Failure: “The [incorrect] result of a fault”

Mistake: “A human action that produces an incorrect result”

Based on my understanding of above definition, error is the result of fault, i.e., failure. Could someone explain more clearly?

答:
According to Fundamental Concepts of Dependability:

A system failure is an event that occurs when the delivered
  service deviates from correct service. A system may fail either
  because it does not comply with the specification, or because the
  specification did not adequately describe its function. An error
  is that part of the system state that may cause a subsequent failure:
  a failure occurs when an error reaches the service interface and
  alters the service. A fault is the adjudged or hypothesized cause
  of an error.

I understand defect as just another name for fault.

Bug is confusing and can represent a fault or a failure depending on the context.

OwnerDisplayName: David


问:
Why is CATALINA_HOME named that way and other interesting program names
I work with open source software a lot and keep coming across weird and funny names for executables, variables, constants and etc. Currently I am wondering why CATALINA_HOME environment variable was named that way? I did a quick search on google with but nothing relative came up. My only guess is that it is named after the island of the shore of south California.

On the related note, very often I find amusing and clever names used in open source programs. One of my favorites are slapd and slurpd executables of OpenLDAP suite. What are your favorite/noteworthy variable/executable names that you have seen in your programming career? Do you think it is OK to name your variables/executables this way, or would you rather see boring but clear names?

PS. This is not really a programming question but I think it somewhat fits in here, according to faq.

答:
Catalina is the code name for the Tomcat servlet implementation.  Home customarily refers to the root directory of a distribution.

Hence CATALINA_HOME refers to the Tomcat root.


问:
Are we using the repository pattern right?
We are using a bunch of separate classes suffixed with -repository to retrieve the data from the database; for each table its own repository.

We have for instance a customerrepository class which has all kind of methods to retrieve customers, and a vacancyrepository which has all kind of methods to retrieve vacancies.

I have two questions about this way of doing things:

How about getting data which spans multiple tables? For instance I have a screen which shows all customers who have not yet created a vacancy. Can a customerrepository use methods from the vacancyrespository, or do both repositories return results and is there a class higher in the hierarchy (let's name it a dataservice) which gets the results from both repositories and combine them into 1 result?

how much logic can such a repository handle?

I think it's OK to implement the 'where active == true' in a repository to retrieve only active records, or should even that simple logic be handled by a class higher in the hierarchy (let's name it a dataservice)?

The example I was running into now is this one:

We have a questions list, which contains one or more questions.

The question can have a result, which is hold in a separate table.

So when you want to retrieve the total result of the questions list, you have to combine data from the questionlist table, the question table and the questionstatus table.

Right now we have 3 different repositories for these tables.

If I would ask the questionlistrepository what it's the total result for list number 12, it would have to get data from two other repositories and hence have some logic in it, is that allowed?

Or is there a questionlistdataservice which knows which repositories to use?

One more thing: our repositories can result an IQueryable so a calling service can easily combine the results, but how about when this isn't the case, I don't think it's a good idea to retrieve all the content of all three tables from the database.

答:
Repository returns domain objects and is built on top of mapping layers. For a very simple domain domain objects and database tables can be very much the same.

If your repository is always returning exact representation of your data structure then it might actually be Table Data Gateway aka Data Access Object(DAO).

Example:
Your database has tables for person and address. In your application domain address is not an entity of it's own, it is just a property of Person. In this case you would not have PersonRepository and AddressRepository. You just have PersonRepository. Domain should not be concerned how the domain data is persisted. Those responsibilites are in a layer behind repository.

From your example it would seem you actually have DAOs and have just named them Repositories.


答:
I would use somethink like JAXB (in java and with xml configuration), or some JSON mapper (with JSON configuration) (I don't like languages where number of whitespaces is significant, but thats personal taste). Or some other mapper for your prefered/forced format.

With this, I would use mapped objects if they match what I need inside aplication (approach 1) , and if not I would use them as parameter for factory methods (similar to approach 2), so format of their textual source does not matter, only their content while loaded.
This would allow to use multiple input formats without changing anything else than reading of those files.

I would start with approach 1 if it looks promising and refactor later.

Title: Automated object creation from user input

Body:
I am working on a command-line application that runs simulations. It has to be heavily configurable; the user should be able to provide a very large number (100+) of parameters, some mandatory and some optional. Obviously, these parameters will be used by a variety of classes in the application.

I can see two approaches I can use; which one is a better design in the long run?

Approach 1

Have the (text) input file directly control object creation in the application. For example, user would provide the following input:

```<code>root=Simulation
  time=50
  local_species=Sentient
    strength=3.5
    intelligence=7.1
  invading_species=Primitive
    strength=5.1
    sociability=2.6
</code>```

The application would then recursively create objects of the class specified on the rhs of the equal sign, passing the class' constructor the arguments provided in the relevant sub-branch of the input file, if any. I'm using Python, which supports keyword arguments and default argument values when no argument is provided, but I hope the question isn't terribly language-specific.

For example line 1 would tell the app to create an object of class Simulation, with three constructor arguments. The first constructor argument is time=50. The second argument is an instance of class Sentient, which is created by passing Simulation's constructor arguments strength=3.5, intelligence=7.1. The third argument is an instance of class Primitive, which is created with by passing the constructor arguments strength=5.1, sociability=2.6.

The whole object creation is handled automatically, with just a few lines of (recursive) code. The highest-level object (instance of Simulation in this case) would be passed to the visualization layer.

Approach 2

The input file still looks the same. However, the application's classes now have full control over how they interpret user input. The lhs and rhs values may or may not correspond to keyword parameters and classes. For example, the above input may result in the application creating an instance of class InvasionSimulation with arguments strength_local=3.5, intelligence_local=7.1, strength_invading=5.1, sociability_invading=2.6, and then calling its method set_runtime(time=50), before passing the object to the visualization layer.

One obvious advantage of approach 2 is that the user's input can remain stable even as the application is completely redesigned internally. But I think there's nothing wrong with designating a subset of classes as "public API", and therefore ensuring that it doesn't change in the future, is there?

On the other hand, if the application internally follows something quite similar to approach 1 anyway, it feels that approach 2 requires adding a lot of redundant code: instead of automatically interpreting user input, we now need to do it "by hand" for each class.

Any additional considerations would be much appreciated. Are there any names for these approaches that I can search for?


问:
What performance topics should I be aware of?
When coding performance-critical portions of code (not necessarily large, but code that gets executed a lot), what topics should I be aware of/take into account.

I'm already fairly familiar with caching, aliasing, branching, cost of arithmetic operations, loop unrolling (and I guess some others that don't come to mind).

What else should I know? (not necessarily looking for details, just concepts I can look up on my own)

答:
First of all, most performance problems end up being caused either by using, possibly by mistake, algorithm with unfavourable complexity. So first and foremost, keep on lookout for anything that is done more times than expected.

When you've flushed those out and are really down to micro-optimizations as your last chance, tuning for memory cache utilization can make some difference. It can be profiled using valgrind cachegrind skin. General suggestions are to keep the working set (frequently accessed memory) small, related objects together and possibly employ allocator that can do cache coloring.

Also despite the research that went into allocators, standard libraries still often provide rather poor memory allocators, so consider using a custom one (umem, tcmalloc, ...) and/or employ memory pools for common data structures (improvements to allocator specification in C++11 make that much easier and more usable).


答:
I think when it comes to performance, being familiar with the compiler optimization strategies and methods is essential. What this helps you with is that when you understand what kind of optimizations the compiler is capable of doing and under which circumstances, you actually can offload the performance tuning to the compiler(as you should anyway, if possible) by making sure that you give it the maximum possible opportunity to optimize the code.

Of course being familiar with tools which assist you with profiling and benchmarking your code/implementations is an essential. Infact, there's no point in optimizing unless you can measure the benefit. In the end this boils down to being able to reason between multiple implementations and what and why the performance differs at the lowest level possible - without this understanding it is very hard to come up with valid optimizing opportunities which you can reason about.

As the bottom line I would argue that being familiar with the compiler and it's optimizing capabilities and opportunities as well as being familiar with tools to measure benefits and spot bottlenecks as well as understanding the CPU's capabilities and instruction set are the three most important things for any programmer when it comes to writing performant native code. Yes, this is very general but as such it's also very applicable. Everything boils down to this in the end.

Title: What performance topics should I be aware of?

Body:
When coding performance-critical portions of code (not necessarily large, but code that gets executed a lot), what topics should I be aware of/take into account.

I'm already fairly familiar with caching, aliasing, branching, cost of arithmetic operations, loop unrolling (and I guess some others that don't come to mind).

What else should I know? (not necessarily looking for details, just concepts I can look up on my own)


答:
I agree with Steven about mentoring part. In fact I would say that you can ask him/her questions about what are his/her views on mentorship and how does (s)he go about it in different scenarios. Then evaluate based on the answer (you can get feedback from your boss if you feel like it or discuss the actual answers in the debrief).

You can also ask questions you would ask a peer, as the candidate should probably be able to solve or at least understand your work.

Title: How do you interview someone with more experience than you?

Body:
The company I'm working for is looking to hire a senior developer with more experience than me, and they expect me to do the technical part of the interview. I've only been programming a few years and am not sure I have the knowledge needed to evaluate the coding skills of someone who has greater understanding/experience than I do.

Can anyone recommend some technical interview questions to ask that are a good means for evaluating higher-level programming skills, but still be ones I can understand?

I would say I'm past the jr. programmer level, but nowhere near senior. Most of what I've done is built small apps (web and desktop), some of them fairly complicated, but all of them have been meant to be used by no more then a handful of users. I feel I have a decent understanding of most programming concepts and am capable of learning/teaching myself just about anything, however I lack experience. As my boss is fond of telling me, "You don't know what you don't know".

In particular, things we'd like the person we hire to have experience with (that I don't have) is: Multi-tier development, multi-user environment, large-scale application development, two-way messaging, shared sessions, and Multi-threading/BackgroundWorkers.

UPDATE:

In response to Thor's comment below, we hired someone a few months ago and I think it has been working out great. I am learning a lot, not just about coding but also about things like design patterns, software architecture, documentation, and how other larger programming teams get stuff done. Its not always easy having someone come in and point out better ways to do things you have done, but if you can swallow your pride and be willing to try out new things you can learn a lot.

The interview process went better than I expected. I started asking questions about things I was familiar with, then asked some questions about some things I was struggling with. Whenever the interviewee said something I didn't understand, I'd ask them to explain it to me and then write it down so I could look it up later on. Overall, I felt I was able to get a pretty good idea of the applicant's skill level, intelligence, and what they'd be like to work with.


答:
My 2 cents:

It's about how effectively you manage your resources and utilize the available hardware.

Generally, you will be limited in the amount of memory you have(RAM), but there's aplenty of processing speed available than we utilize.

While effective utilization of memory is largely dependent upon the techniques and algorithms(caching, aliasing, branching, cost of arithmetic operations, loop unrolling (and I guess some others that don't come to mind)). In platforms where memory is managed(Java, .NET), having GC run frequently takes a toll on performance. If there is less free memory, GC keeps running frequently trying to free memory. So, keep a tab on how your objects are created and destroyed. In languages where memory is explicitly managed(C,C++), by rule of thumb, you always keep a check(you free the memory as soon as you finish the task). So, in both cases, having enough free memory will ensure having little/less toll on performance.

Concurrency is the way to utilize CPU effectively. Instead of blocking and keeping CPU idle, concurrency allows you to utilize CPU effectively on tasks that could be run in parallel. While concurrency is one step above single threaded programs, the advent of multi-core machines and its ubiquity needs us to take one more step(see here) to effectively utilize all the cores. Utilizing CPU effectively improves the performance.


答:
if you need to work with numbers and 100% accurate results are not needed then don't be shy to try out faster less accurate algorithms

this is heavily apparent in game development where the results on screen don't need to be exact they just need to be close enough too look right, it's more important the calculations happen fast; see the fast inverse square root for a classic example


答: With reference to the definitions used in the linked article, an error is not the result of a fault, but potentially the cause - if the error is outside of the tolerance of the system. Most systems dealing with real data have some degree of error, but are designed to tolerate them.

Title: What's the difference between fault, error and defect?

Body:
Possible Duplicate:

  Difference between defect and bug in testing

In computer science technical writing, especially in software engineering, what's the difference between fault, error and defect?

I want to quote an answer on Stack OverFlow by Daniel Joseph:

To quote the Software Engineering Body of
  Knowledge

Typically, where the word “defect” is used, it refers to a “fault” as
  defined below. However, different cultures and standards may use
  somewhat different meanings for these terms, which have led to
  attempts to define them. Partial definitions taken from standard
  (IEEE610.12-90) are:

Error: “A difference…between a computed result and the correct result”

Fault: “An incorrect step, process, or data definition in a computer
  program”

Failure: “The [incorrect] result of a fault”

Mistake: “A human action that produces an incorrect result”

Based on my understanding of above definition, error is the result of fault, i.e., failure. Could someone explain more clearly?


问:
Reveal detailed license-errors?
So after one has programmed and integrated a licensing solution into his or her application, how should one deal with licensing errors?

My understanding is:
Show whether a license is valid or invalid - and report if the license server is not reachable. Nothing more, nothing less.

Licenses could be invalid due to a variety of reasons: Invalid Machine-Code, maximum number of activations reached, invalid licensed version...

But should we report them to the user or just tell him "okay", "not okay" or "license server not reachable"?

I don't know if this is the right place to ask, maybe security.stackexchange.com is more suitable, but that could be true for ux.stackexchange.com, too... So I'm asking it here.

答:
In my view what you're proposing is exactly correct. Only reveal what's necessary.

From a security point of view if you consider an "attacker" trying to learn from why the license is wrong the correct way to handle the situation is to leak no information. For example if you try to "optimize" the user experience by being nice and telling the user that "It seems the license is otherwise valid but the last few characters contain an error. Please re-check them and try again!" it is very obvious that this gives information away to the attacker which can then be used to defeat the licensing procedure by being able to guess a correct license.

Sometimes the possible security considerations are not just about securing your own product/service but to actually secure that of your customers too. As an example consider this: I have licensed your software with my username + license. Now, if your software is "kind" enough to let the user know if the username was incorrect or if the license digest was incorrect the software leaks information. A malicious user could use this feature to determine if I as your customer use or at least have licensed your software. This is a potential security issue against me, your customer rather than against you or your service. "Funnily" enough, something similar has lead to divorces for married couples when the suspecting other has been able to figure out if their partner has registered on a dating website with their personal email.

There are other forms of leaking information too, but they are side channel attacks such as measuring the power consumption or the time it takes to verify a given license and trying to modify it so that giving a bit different license produces different timing information and as such can possibly reveal if the modifications modifed the input license towards a legit one or not. To counter such side channel attacks one would need to be able to create such an implementation of the license validation measure which does not leak this information. Such as the validation taking constant time(to a nanosecond precision, mind you, so we're talking about exact identical amount of CPU cycles for example) regardless of whether the given license for validation is valid or not.

Title: Reveal detailed license-errors?


问:
Running pieces of code distributed through out the system, automatically
I have pieces of code, written in java, which I can convert in jar and run from the terminal.

I also have some node.js script, which I would like to run before running these jar files.

So the process of running my project is as follows:

Start mongodb from terminal->Run Node.js script-> Run the java code(jar file)

So I want to know, is there a way I could automate my project by just calling some one single file instead of running so many files separately? if so, how?

答:
Expanding Florian's comment, Ant would probably be your best bet.

There's a decent example and explanation here.  My advice to you would be to try to understand how it works, instead of just hastily modifying it to suit your needs.  Ant is incredibly powerful to those who use it right.

You can call it from the command line.  The ant package also comes with a bin folder containing both a batch file and a shell script to call ant in a convenient fashion:

```<code>ant -buildfile <name of build file.xml goes here> <task name>
</code>```

It has the added advantage that like Java, it is platform independent and makes the difficulty of adapting it to new platforms as trivial as creating a shell script or batch file that calls it.

Body:
Expanding Florian's comment, Ant would probably be your best bet.

There's a decent example and explanation here.  My advice to you would be to try to understand how it works, instead of just hastily modifying it to suit your needs.  Ant is incredibly powerful to those who use it right.

You can call it from the command line.  The ant package also comes with a bin folder containing both a batch file and a shell script to call ant in a convenient fashion:

ant -buildfile <name of build file.xml goes here> <task name>

It has the added advantage that like Java, it is platform independent and makes the difficulty of adapting it to new platforms as trivial as creating a shell script or batch file that calls it.


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
I can't believe no one mentioned this yet.

Paul Graham's writings, particularly:

Hacker and Painters

What businesses can learn from Open Source

Great Hackers

How to make wealth


问:
Why does Internet Explorer have so many incompatibilities with other browsers?
Internet Explorer has a number of proprietary features that aren't found in other browsers as well as a number of incompatibilities with the standards.  Does anyone have an idea what is the cause of those incompatibilities?

For example: I develop a browser extension using Crossrider framework. The extension works well with all combinations of [Windows | Mac OS | Linux] and [Chrome | Firefox] but it does not work with IE because IE handles $(window).height() and $(window).scrollTop() a bit differently.

Is there a known thorough analysis of that situation, or an interview with an insider that would clarify the cause? Is it the corporate culture, the design process, a QA flaw, or some horrid unknown legacy?

答:
As usual, the question is one of incentives. If you need to know why something actually happens (as opposed to what people claim, or would like to believe), follow the money.

Imagine the situation where you have a comfortable market position in a key technology (personal computing). The value of networks is to a large degree in its size, so you want to be able to reach as many users as possible with your products. Since they are very probably already using your system, it is worthwhile to introduce new features and spend effort only on backwards compatibility with your own products. Compatibility with competitors' products is lower on the priority list, since it doesn't create as much value potential for yourself; in fact, it can cost you value if competitor's products become interoperable enough that somebody could do without your system altogether.

Note you needn't even posit any conscious malice on the part of developers or management here. Doing your own thing and promoting your own protocols, standards etc. rather than contributing to general ones is simply natural behaviour for a dominant player, and probably unavoidable without very stringent legal measures that the public in general is apparently not willing to authorize. In fact, most of what I've heard and read about the mindset at Microsoft leads me to believe that most of their people genuinely, honestly think that their products are so wonderful and superior that only unpleasable malcontents would want to use anything else in the first place, and that they would do their loyal customers a great disservice if they spent effort on interoperability rather than 'innovate' cool new stuff.

Causing pain to web developers who do have to support different products is simply a side effect of this attitude. It seems very callous and even evil to us outside practitioners, but I suspect that many of us would take the same stance if tables were magically reversed.


答: The grief IE causes is a 2 part problem, both of them really stem from the fact IE won the first browser war. It used to be the best and most advanced browser, but they sat idle for a long time and are now playing catchup, but they have a huge legacy burden now other browser has, because many companies have millions invested in internal sites that only work on a specific version of IE. MS would be committing suicide if they didn't make the transition between versions as pain free as possible. Second because they won the first browser war and were approaching total monopoly the W3C actively wrote standards that conflicted with existing IE functionality in an attempt to remain relevant as a standards body as far as browsers were concerned and thanks to newer browsers that followed those standards it worked.</p>

Title: Why does Internet Explorer have so many incompatibilities with other browsers?

Body:
Internet Explorer has a number of proprietary features that aren't found in other browsers as well as a number of incompatibilities with the standards.  Does anyone have an idea what is the cause of those incompatibilities?

For example: I develop a browser extension using Crossrider framework. The extension works well with all combinations of [Windows | Mac OS | Linux] and [Chrome | Firefox] but it does not work with IE because IE handles $(window).height() and $(window).scrollTop() a bit differently.

Is there a known thorough analysis of that situation, or an interview with an insider that would clarify the cause? Is it the corporate culture, the design process, a QA flaw, or some horrid unknown legacy?


问:
Does it make sense to create a Ruby wrapper to reference a Java object that does exactly the same thing?
I am using JRuby.

In my Java code, I have a class called Texture, capable of doing some graphic manipulation stuff.

In my Ruby code, I will usually need to draw things, so though I should simply call Java's Texture class to do the drawing for me.

However, I ended up making a Ruby class called Texture, which wraps an instance of Java's Texture. Somehow like this (just an example, but rather accurate):

```<code>class Texture
    def initialize
        @reference = getMeAnInstanceOfAJavaTexture
    end
    def draw
        @reference.draw
    end
    def rotate
        @reference.rotate
    end
    def clear
        @reference.clear
    end
end
</code>```

As you can see, all this Texture class does is... well, tell a Java Texture to do the job for it. Just that.

Subconsciously, I think I wanted to do it this way because it looks pretty (lol).

Now, getting a bit more technical, a possible advantage I see is that this way I don't have to interact much with the Java-side of the project. Most of the work I will do will be in Ruby, and maintaining a constant interaction between Ruby and Java can be confusing. If I make a Ruby class that handles this stuff for me, I might feel more comfortable in the future when I have to make like a hundred textures, but instead of interacting a hundred times with Java, I do it with Ruby, my main environment.

Does my reasoning make sense or is it a lame excuse to do something that looks pretty? Or perhaps there is indeed a good reason to do what I just did?

答:
Yes, this probably makes sense.

Without such a class, you will need to remember the details of calling out to the Java class at each place where you use this, and get those details right at each place -- and even if this is a simple enough use of Java to make this not a burden, those lines of code will "feel" more in the Java idiom than the Ruby idiom, breaking the flow of your program when reading the code.  As you find yourself repeating this usage in more places, the value in fixing this grows (i.e. one use of a Java class probably does not justify a wrapepr).

Bottom line:  creating a class or method to wrap something you find yourself doing over and over again in a simple interface which feels right in the context of your program can make your code easier to read and maintain.


答:
Why is Microsoft® Internet Explorer® incompatible with other browsers and published standards?

To add features that other browsers don't have

When programmers write web pages that use IE-only features, the code will not work on other browsers.  This encourages end-users to view those sites in IE (and thus more people use IE, and since it only runs on Windows, more people use Windows).

Microsoft tools (FrontPage is the most famous for this) tend to produce code that only works on IE, or works best on IE.  While this promotes #2 above, it deserves its own bullet because the next developer to work on that web site or web application is now has to use the same Microsoft technologies that were originally used produce it, or have to rewrite the entire project in a different technology.

Corporate intranets are particularly vulnerable to this strategy because they provide an environment where all users are on the same browser (until a new version comes out).  Also, if a site is not customer facing, there will be no budget for even the tiny cost of supporting multiple browsers.  Over time, the legacy intranet sites at a company prevent that whole company from abandoning IE (or even a specific version of IE) for another browser.

Microsoft's approach is a double-edged sword.  On the one hand, it has produced the XML/HTTP asynchronous request functionality which made AJAX possible (and other positive innovations) which other browsers quickly copied.  But Microsoft also ends up producing versions of IE which are incompatible with each other, thus biting the very developers who played the most into Microsoft's plans.

My favorite example of intra-version IE incompatibility is Micrsoft's own IE6 Countdown campaign where they encourage people not to use their own browser.  The theory being that Microsoft can encourage people to upgrade to a more recent version of IE, whereas others who shout "IE6 Must Die" are more likely to encourage users to use another brand of browser instead of IE.

In short, it's a fairly successful market-domination strategy by Microsoft which has sometimes hurt and sometimes helped the rest of the industry.  For myself, I try to produce only validated, standards-compliant HTML that is tested on the latest version of any browser with 2% or more market share (plus the latest 3 versions of IE).

Microsoft and Internet Explorer are registered trademarks of Microsoft corporation in the US and/or other countries.


问:
Getting non-programmers to understand the development process
When starting a project for a company that's not primarily a programming company, one of the expectations is that there's a finished product at the end free of all bugs and does everything needed right away. However, that's rarely the case.

What are some ways to manage expectations and explain to non-programmers how software development differs from other types of product development?

答: I have discovered, that it might actually help when you show them what it means to write code. Show the stakeholders the codebase you're working with. Even when you've chosen good variable and method-names, most of the people will think you're using some sort of black magic. Maybe they'll understand, why you need more than "a few days" to implement a new feature for their software.</p>


问:
In what meaningful ways does Erlang prevent race conditions in concurrent programming?
Reading about concurrency in Erlang, reminds me of the Akka concurrency toolkit.  Both give you tools to prevent or limit race conditions.  But you can send links to mutable data to other processes using the Akka toolkit, which is still unsafe.  I see Akka as a useful tool, but it does not provide protection against out-of-order access to objects and data leading to race-conditions, deadlock, and/or starvation.  It doesn't prevent you from writing unsafe code the way Java or C# protects you from writing most of the kinds of memory leaks you can write in C++ (you can still create memory leaks in Java by tricking the garbage collector, but it is less of a problem than having to remember to free every byte you allocate).

Does Erlang guarantee a degree of correctness, performance, and robustness in concurrent programming?  I think operating systems provide protection when accessing system resources (assuming the driver writers did their jobs well). ACID databases provide protection for reads and updates.  So it seems this is a solvable problem.  Or would a generic safe solution would erase the performance gains that concurrency provides?  Do other languages or toolkits provide the kind of concurrent safety that Erlang does (or doesn't)?

This is a follow-up question to @Malfist's comment on @user1249's answer to What programming language generates fewest hard-to-find bugs?.

答:
There are a few things that Erlang does to help with these.

Data is immutable, so no data races

OTP gen_servers and gen_fsm's provide a very well tested pattern for servers

Supervisors allow for recovery from crashes

processes are small and cheap

Memory is allocated on a per process basis (no GC freezes)

the erlang VM is optimised to work under very heavy loads

Software can be updated on the fly, so no upgrade downtimes

The major thing here is that in Erlang there is no shared state that could require a lock, so there is no need for locks. It is a brilliant language for soft real time applications that need no downtime and high fault tolerance and concurrency

ContentLicense: CC BY-SA 4.0


问:
How and why to decide between naming methods with "get" and "find" prefixes
I always have trouble figuring out if I should name a certain method starting with getSomething versus findSomething.

The problem resides in creating helpers for poorly designed APIs. This usually occurs when getting data from an object, which requires the object as a parameter. Here is a simple example:

public String getRevision(Item item) {
    service.load(item, "revision");
    // there is usually more work to do before getting the data..
    try {
        return item.get_revision();
    }
    catch(NotLoadedException exception) {
        log.error("Property named 'property_name' was not loaded", exception);
    }
    return null;
}
```

How and why to decide between naming this method as getRevision() or findRevision()?

答:
To quote a conversation I often have with my kids:

me:  Hey kid!  Go find me some batteries

kid: But where are they?

me: That's why I told you to go find them.  If I knew where they were, I would have told you to go get them.  Or you could ask your mother.

The same idea holds:

use "get" for a method which returns a cheaply available piece of information (and can probably be inlined or otherwise optimized away), or for  a piece of information uniquely owned by this object.

use "find" for a method which does work to get a piece of information, or uses other objects to find it.


问:
Does decoupling trump DRY in REST?
I am building a REST API to expose most of functionality of an existing Java API.  Both APIs are for internal use within my organization; I do not have to design for external use.  I have influence over both APIs but am implementing the REST one.  The Java API will continue to be used for local applications (it's not being "retired"), but the REST API will be used for significant new development.

Some of the Java API classes are simply data (beans with properties, getters, setters).  And at least some of these make sense to transmit (in some form) over the REST API as data (which will be marshalled to XML or JSON).  For example, a class that stores info about a server machine.  I am faced with the following choice for these data classes:  Do I...

expose the original Java class (or a subclass) directly in the REST API, or

make a new data transfer class (DTO pattern) specifically for the REST API?

Either way I'll have REST data transfer classes; the question is whether to annotate the originals or create new ones (which may be near copies of the originals).  There may be other choices, but I'll focus mainly on those two.

Arguments for #1:

DRY (don't repeat yourself)

Faster to implement

Easier to upgrade REST API

Arguments for #2:

What if REST API needs to be versioned separately from Java API?  (This is somewhat likely.)

What if there are significant changes to the Java data classes such as removal of properties, adding of behavior, or changes to class hierarchy?  (This is also somewhat likely.)

Bottom line is that it seems like a tradeoff between DRY (#1) and decoupling (#2).

I'm leaning toward starting with #1 and then if problems arise moving to #2 later, following the agile guideline of not building what you can't prove you need.  Is this a bad idea; should I start with #2 if I think I may end up there anyway?

Are there major arguments/consequences missing from my lists?

答:
Good question, simply put, decouple. That's the way to go here, you do not want to be tied to the version of java.

There's one scenario you don't decouple: if your technology will allow for non-type-specific objects to be sent over the wire, that is, if you can use the current java objects now as a YAGNI, and the replacement with a different type that you custom up will be a simple drop-in that won't break anything due to type information going over the wire. So, basically if type information doesn't cross the wire you could YAGNI on this.

Just be very careful and watchful that any upgrades to your java version don't change any of these objects. Otherwise just decouple now and don't worry about it, I guess it depends on how much time you have if you have a choice.

However, if type information goes across the wire in your protocol then a flat drop-in of new types when the underlying java types change may not be possible and may rather be a larger effort. If that's the case, going YAGNI now means accruing technical debt and risk related to your underlying technology.

Personally I would just decouple now.

Also, DRY doesn't play into this because you didn't write the underlying pieces so you aren't duplicating code and therefore won't have the pains of bugs repeated all-over which is the main concern of DRY (and general maintainability issues which again you won't have because you don't have duplicates to maintain)

Title: Does decoupling trump DRY in REST?


问:
Do I need to understand algorithms and data structures to be called a programmer?
It has been six years since I have been coding. Coding into all kinds of things like ActionScript, JavaScript, Java, PHP, Ajax, XML HTML, ASP, etc. I have used arrays, maps, linked lists, sets, etc and wherever I worked people like me. But whenever I am interviewed it is very likely that people ask me question on hashes, trees, stacks, and queues. Some questions are on juggling some sorting algorithms.  I don't know if I should really know them or should I stop calling myself a programmer. There is something in me which also tells me even if people who are asking all these questions select me, they will never be making me work of these things. Am I really required to know all this?</p>

答:
Well, working in a language like JavaScript makes this quite obsolote, since an Array is a mix between a vector, a hash and a tree and can be used as a stack or queue. It is very unlikely you will ever need to or be able to implement a data structure in JavaScript that outperforms the Array class. This is also the case in PHP.

For Java OTOH, there's a difference. I suppose Java's standard library provides you about any datastructure your need. However:

You need to know and distinguish those datastructures and understand how they perform in different situations so that you'll be able to chose the right one.

In Java, it is not absolutely unlikely you will eventually want to write your own implementation for a hashmap to get better speed in some very specific case (for example if the keys you want to handle fullfill some special constraints that allow optimization).

When it comes to sorting algorithms, there isn't much need to know or understand them, because there's no need to ever implement one on your own. However, if such an algorithm is given to you, you should be able to understand and implement it.

Two things are certain:

You can make a career as a programmer without relying on knowledge like this.

It most definitely won't hurt you to know them.

Data structures and algorithms are simply a thing, that is good to understand. And it is something extremely clear and formalized and thus quite trivial compared to the intricacies of application or systems engineering. They are just one small piece in the puzzle, but they are easy to grasp - if you're willing to invest some time.

So no, you don't need them, but it would only be for your benefit to know them.


答:
The main arguments for #1 are ease of implementation and upgrades, but does it satisfy your requirements?

In your arguments for #2, you indicate that the Java API and REST API may likely change independently.  This means they are separate concerns and you are not repeating yourself by using separate classes.  Just because two things look the same, doesn't mean they are the same.

Title: Does decoupling trump DRY in REST?

Body:
I am building a REST API to expose most of functionality of an existing Java API.  Both APIs are for internal use within my organization; I do not have to design for external use.  I have influence over both APIs but am implementing the REST one.  The Java API will continue to be used for local applications (it's not being "retired"), but the REST API will be used for significant new development.

Some of the Java API classes are simply data (beans with properties, getters, setters).  And at least some of these make sense to transmit (in some form) over the REST API as data (which will be marshalled to XML or JSON).  For example, a class that stores info about a server machine.  I am faced with the following choice for these data classes:  Do I...

expose the original Java class (or a subclass) directly in the REST API, or

make a new data transfer class (DTO pattern) specifically for the REST API?

Either way I'll have REST data transfer classes; the question is whether to annotate the originals or create new ones (which may be near copies of the originals).  There may be other choices, but I'll focus mainly on those two.

Arguments for #1:

DRY (don't repeat yourself)

Faster to implement

Easier to upgrade REST API

Arguments for #2:

What if REST API needs to be versioned separately from Java API?  (This is somewhat likely.)

What if there are significant changes to the Java data classes such as removal of properties, adding of behavior, or changes to class hierarchy?  (This is also somewhat likely.)

Bottom line is that it seems like a tradeoff between DRY (#1) and decoupling (#2).

I'm leaning toward starting with #1 and then if problems arise moving to #2 later, following the agile guideline of not building what you can't prove you need.  Is this a bad idea; should I start with #2 if I think I may end up there anyway?

Are there major arguments/consequences missing from my lists?


问:
use of jquery-latest
I recently had some code I wrote a year ago fail because someone linked my code to

http://code.jquery.com/jquery-latest.js

In the latest version, jquery had deprecated/replaced a function.

Nice to have a dynamically updated version but my code isn't going to change, it's going to break. Is there any reason to use jquery-latest?

答: "Latest" could be useful during initial development to keep up with the most recent changes.  jQuery does provide feature updates relatively often.  Expect your code using it to break.  When you release your project you should support, reference, and document a specific jQuery version.  Typically it's safe to reference a minor version and support revision changes since the interfaces won't change (e.g. 1.9.x).

Title: use of jquery-latest


问:
Temporary variables vs line length requirements
I've been reading Martin Fowler's Refactoring. It is generally excellent but one of Fowler's recommendations seems to be causing a little trouble.

Fowler recommends that you replace temporary variables with a query, so instead of this:

```<code>double getPrice() {
    final int basePrice = _quantity * _itemPrice;
    final double discountFactor;
    if (basePrice > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice * discountFactor;
}
</code>```

you pull out into a helper method:

```<code>double basePrice() {
    return _quantity * _itemPrice;
}

double getPrice() {
    final double discountFactor;
    if (basePrice() > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice() * discountFactor;
}
</code>```

In general I agree except that one reason I use temporary variables is when a line is too long. For example:

```<code>$host = 'https://api.twilio.com';
$uri = "$host/2010-04-01/Accounts/$accountSid/Usage/Records/AllTime";
$response = Api::makeRequest($uri);
</code>```

If I tried inlining that, the line would go longer than 80 characters.

Alternately I end up with chains of code, which are themselves not that much easier to read:

```<code>$params = MustacheOptions::build(self::flattenParams($bagcheck->getParams()));
</code>```

What are some strategies for reconciling the two?

答:
I don't think you need to strictly follow 80 character guidelines or that ever local temp variable should be extracted. But long lines and local temps should be investigated for better ways of expressing the same idea. Basically, they indicate that a given function or line is too complicated and we need to break it down. But we need to be careful, because breaking a task into pieces in a bad way only makes the situation more complicated. So I am to break things down into resuable and simple components.

Let me look at the examples you posted.

```<code>$host = 'https://api.twilio.com';
$uri = "$host/2010-04-01/Accounts/$accountSid/Usage/Records/AllTime";
$response = Api::makeRequest($uri);
</code>```

My observation is that all twilio api calls will start with "https://api.twilio.com/2010-04-1/", and thus there is a very obvious reusable function to be had:

```<code>$uri = twilioURL("Accounts/$accountSid/Usage/Records/AllTime")
</code>```

In fact, I figure that the only reason to generate a URL is to make the request, so I'd do:

```<code>$response = TwilioApi::makeRequest("Accounts/$accountSid/Usage/Records/AllTime")
</code>```

In fact, many of the urls actually start with the "Accounts/$accountSid", so I'd probably extract that as well:

```<code>$response = TwilioApi::makeAccountRequest($accountSid, "Usage/Records/AllTime")
</code>```

And if we make the twilio api an object that holds the account number, we could do something like:

```<code>$response = $twilio->makeAccountRequest("Usage/Records/AllTime")
</code>```

Using a $twilio object has the benefit of making unit testing easier. I can give the object a different $twilio object that doesn't actually call back to twilio, which will be faster and won't do strange things to twilio.

Let's look at the other one

```<code>$params = MustacheOptions::build(self::flattenParams($bagcheck->getParams()));
</code>```

Here I'd think about either:

```<code>$params = MustacheOptions::buildFromParams($bagcheck->getParams());
</code>```

or

```<code>$params = MustacheOptions::build($bagcheck->getFlatParams());
</code>```

or

```<code>$params = MustacheOptions::build(flatParams($backCheck));
</code>```

Depending on which is the more reusable idiom.

Body:
I don't think you need to strictly follow 80 character guidelines or that ever local temp variable should be extracted. But long lines and local temps should be investigated for better ways of expressing the same idea. Basically, they indicate that a given function or line is too complicated and we need to break it down. But we need to be careful, because breaking a task into pieces in a bad way only makes the situation more complicated. So I am to break things down into resuable and simple components.

Let me look at the examples you posted.

$host = 'https://api.twilio.com';
$uri = "$host/2010-04-01/Accounts/$accountSid/Usage/Records/AllTime";
$response = Api::makeRequest($uri);

My observation is that all twilio api calls will start with "https://api.twilio.com/2010-04-1/", and thus there is a very obvious reusable function to be had:

$uri = twilioURL("Accounts/$accountSid/Usage/Records/AllTime")

In fact, I figure that the only reason to generate a URL is to make the request, so I'd do:

$response = TwilioApi::makeRequest("Accounts/$accountSid/Usage/Records/AllTime")

In fact, many of the urls actually start with the "Accounts/$accountSid", so I'd probably extract that as well:

$response = TwilioApi::makeAccountRequest($accountSid, "Usage/Records/AllTime")

And if we make the twilio api an object that holds the account number, we could do something like:

$response = $twilio->makeAccountRequest("Usage/Records/AllTime")

Using a $twilio object has the benefit of making unit testing easier. I can give the object a different $twilio object that doesn't actually call back to twilio, which will be faster and won't do strange things to twilio.

Let's look at the other one

$params = MustacheOptions::build(self::flattenParams($bagcheck->getParams()));

Here I'd think about either:

$params = MustacheOptions::buildFromParams($bagcheck->getParams());

or

$params = MustacheOptions::build($bagcheck->getFlatParams());

or

$params = MustacheOptions::build(flatParams($backCheck));

Depending on which is the more reusable idiom.


问:
Does "Inversion of Control" promote "Anemic Domain Model"?
When I used IoC Container in my last project, I ended up with anemic entities and most of my business logic in Stateless Services.

I have seen projects written by other developers that utilize "Inversion of Control" and they are always "Anemic".

Since "Anemic Domain Model" is anti-pattern, is it possible to use IoC and Rich Domain?
Are their any good examples, open source projects that do that?

答:
is it possible to use IoC and Rich Domain? Are their any good
  examples, open source projects that do that?

I assume you mean DI instead of IoC, and the project you worked on uses a DI container like Spring. IoC has two main flavors: DI and Locator pattern. I don't see why the Locator pattern should be a problem, so let's focus on DI.

I don't think it's possible, or at least would be very impracticle. The main aspect of DI containers is that they control the creation of objects when they inject them into others ("managed objects"). The set of managed objects that is alive when the projects runs is independent from which domain items exist in your project but depends on how objects are wired and which scopes (singleton, prototype) are assigned to them.

This is why you don't want to let the DI container manage your domain objects. But if you create objects manually (with new), you can't get other objects injected to your domain objects. (Leaving potential work-arounds with manual wiring aside.) Since you need these injections to replace implementations with others, you can't replace the functionality of rich domain objects using DI. Hence, you will not want to place functionality into domain objects, or you'd lose the features of the DI.

I don't see how a hypothetical DI container could work that doesn't manage your objects, and none of the existing implementations allows that. So it's fair to claim that DI relies on managing objects. It will therefore always tempt you to split potential Rich Domain objects into one anemic class and one or several transaction script classes.


问:
MVCS - Model View Controller Store
I recently decided to start learning iOS Development, and to this end I’ve been reading iOS Programming: The Big Nerd Ranch Guide. In the book the authors describe a  design pattern MVCS - Model-View-Controller-Store, the basic idea being that since many applications make use of multiple external sources of data keeping the request logic in the controller can get very messy, instead the authors propose that moving all the request logic out of the controller and into a separate object.

In short to quote the book

Model-View-Controller-Store puts request logic into a separate object,
  and we call this object a store (Figure 28.4). Using a store object
  minimizes redundant code and simplifies the code that fetches and
  saves data. Most importantly, it moves the logic for dealing with an
  external source into a tidy class with a clear and focused goal. This
  makes code easier to understand, which makes it easier to maintain and
  debug, as well as share with other programmers on your team.

And

The cool thing about asynchronous stores is that even though a lot of
  objects are doing a lot of work to process a request, the flow of the
  request and its response are in one place in the controller. This
  gives us the benefit of code that’s easy to read and also easy to
  modify.

I wanted to find out more about this pattern and to see what others might have to say about it, but while searching online the only references I could find were to that same book (is the pattern perhaps known by some other name?).

To me the author’s logic seems to make sense, and it seems like a logical extension of the regular MVC pattern,  but perhaps that's because I don’t really have much experience with the MVC pattern in practice (aside from foray into iOS development I have sort of used MVV with backbone.js (that is, if you consider it MVC)).

I was hoping that perhaps someone with more experience can shed some light on whether there are any obvious flaws/problems with the MVCS pattern that I’m missing.

答:
"Store", in the case of MVCS design patterns, tends to lean towards storage logic. In the case of iOS, this is usually a Core Data implementation. If you create a Core Data-backed template in Xcode, you'll see the "Store" aspect of this design pattern tucked away in the AppDelegate class.

To take this to the next level, I will often create a singleton manager class that handles setting up the Core Data stack, and deals with all of the fetching/saving that is involved with the stack. As the quote you mentioned says, this makes it very easy to not only call those methods, but to adjust them if needed, as opposed to having saving/fetching calls all over the place in different view controllers.

The "Store" paradigm isn't restricted to Core Data, though. Your store may just be a web service. Perhaps you have a class that interacts with Facebook, Twitter, Yelp, or some other REST-based API. I have found (and similarly follow the trend) that these kinds of classes also have are named Manager. They are very literally managing all of the internal details so that your other classes can just put in or get out exactly what they need.

As far as obvious flaws or problems with this design pattern...As with any design pattern, the most glaring problem is ensuring that you've set up your project in such a way that jives with the paradigm. Especially with a design pattern that is new to you, this can sometimes be the hardest part. The benefit of breaking your "Store" logic out into its own class is the very fact that it makes code maintainability much easier.

Title: MVCS - Model View Controller Store


问:
What should you bring to the table as a Software Architect?
There have been many questions with good answers about the role of a Software Architect (SA) on StackOverflow and Programmers SE. I am trying to ask a slightly more focused question than those. The very definition of a SA is broad so for the sake of this question let's define a SA as follows:

A Software Architect guides the
  overall design of a project, gets
  involved with coding efforts, conducts
  code reviews, and selects the
  technologies to be used.

In other words, I am not talking about managerial rest and vest at the crest (further rhyming words elided) types of SAs. If I were to pursue any type of SA position I don't want to be away from coding. I might sacrifice some time to interface with clients and Business Analysts etc., but I am still technically involved and I'm not just aware of what's going on through meetings.

With these points in mind, what should a SA bring to the table? Should they come in with a mentality of "laying down the law" (so to speak) and enforcing the usage of certain tools to fit "their way," i.e., coding guidelines, source control, patterns, UML documentation, etc.? Or should they specify initial direction and strategy then be laid back and jump in as needed to correct the ship's direction?

Depending on the organization this might not work. An SA who relies on TFS to enforce everything may struggle to implement their plan at an employer that only uses StarTeam. Similarly, an SA needs to be flexible depending on the stage of the project. If it's a fresh project they have more choices, whereas they might have less for existing projects.

Here are some SA stories I have experienced as a way of sharing some background in hopes that answers to my questions might also shed some light on these issues:

I've worked with an SA who code reviewed literally every single line of code of the team. The SA would do this for not just our project but other projects in the organization (imagine the time spent on this). At first it was useful to enforce certain standards, but later it became crippling. FxCop was how the SA would find issues. Don't get me wrong, it was a good way to teach junior developers and force them to think of the consequences of their chosen approach, but for senior developers it was seen as somewhat draconian.

One particular SA was against the use of a certain library, claiming it was slow. This forced us to write tons of code to achieve things differently while the other library would've saved us a lot of time. Fast forward to the last month of the project and the clients were complaining about performance. The only solution was to change certain functionality to use the originally ignored approach despite early warnings from the devs. By that point a lot of code was thrown out and not reusable, leading to overtime and stress. Sadly the estimates used for the project were based on the old approach which my project was forbidden from using so it wasn't an appropriate indicator for estimation. I would hear the PM say "we've done this before," when in reality they had not since we were using a new library and the devs working on it were not the same devs used on the old project.

The SA who would enforce the usage of DTOs, DOs, BOs, Service layers and so on for all projects. New devs had to learn this architecture and the SA adamantly enforced usage guidelines. Exceptions to usage guidelines were made when it was absolutely difficult to follow the guidelines. The SA was grounded in their approach. Classes for DTOs and all CRUD operations were generated via CodeSmith and database schemas were another similar ball of wax. However, having used this setup everywhere, the SA was not open to new technologies such as LINQ to SQL or Entity Framework.

I am not using this post as a platform for venting. There were positive and negative aspects to my experiences with the SA stories mentioned above. My questions boil down to:

What should an SA bring to the table?

How can they strike a balance in their decision making?

Should one approach an SA job (as defined earlier) with the mentality that they must enforce certain ground rules?

Anything else to consider?

Thanks! I'm sure these job tasks are easily extended to people who are senior devs or technical leads, so feel free to answer at that capacity as well.

答:
A Systems Architect should:

Specify the high-level architecture

Participate in code reviews

Approve technologies used

Assist the developers in their coding effort

Maintain and monitor the development schedule

Produce SA artifacts, such as UML diagrams, Gantt charts and the like.

SA's must know how to code, and should participate in some of the coding work, get their hands wet, so to speak.  This keeps them in touch with the gestalt of the development effort. As Uncle Bob Martin once said, the Architect should do some of the coding himself, so that he can see the pain he is inflicting on others with his designs.

The SA should have the last word on all design, technology and coding style decisions.  But, like all managers, the job of the SA is to clear the path for his people so they can be productive.  That means, for the most part, that the developers get to decide, at their level, how problems are to be solved.  It means that the SA keeps the pointy-haired bosses out of the developers' cubicles.  And it means that the SA pitches in to help, as needed.

Like all human beings, SA's can and do make mistakes.  The good ones learn from those mistakes, and become better SA's.


问:
Java memory management (thunks/lazyness)
If I want to create an infinite list of integers in Java like so:

```<code>ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0;;i++){
    list.add(i);
}
</code>```

I run out of memory. My understanding is that we allocate some memory for i, list, and every time we add i to the list, we allocate more memory for it.

But, by using a thunk, I can create an infinite list which will not eat all of my memory:

```<code>infList(final int start){
    return new InfiniteList (
    start,
    return new InfiniteList.LazyTail(){eval(){return infList(start+1);}}
    );
}
</code>```

(I adapted source from here). How does this work? I know I am delaying the evaluation of the expressions : start+1, start+1, start+1 ... but do I end up with a list of something like this:

[start, eval(){start+1}, eval(){start+1}, eval(){start+1} ... ]

Are the 'eval(){...}' object references? Do they take up space in memory? Will I eventually run out of memory with this implementation (I tried, but memory allocation was not budging)?

Do I only start using memory, say, if I wanted to system.out.print integers, then they would have to be evaluated, and some memory allocated?

答:
The idea behind all simple lists is the following:

Make sure you can tell if you have an empty list or not.

If it's not the empty list, you have 2 parts:

the head of the list

and the tail (rest of the list)

Since Java supports closures (well, kind of), one can implement lazy lists with the following trick: Instead of having a reference directly to the tail, have a reference to an Object which is able to compute the tail. Such an Object could be a Callable<ZList>, say, if ZList is our list type. And yes, such a closure constructed with

```<code> // assuming constructor ZList(int, Callable<ZList>);
 public Callable<ZList> nextNode(final int current) {
   return new Callable<ZList> {
     ZList call() {
          return new ZList(current, nextNode(current+1));
     }
   };
 }
</code>```

takes up some finite amount of memory. Certainly more than a singe list node, but less than many list nodes.

As for the memory requirement: It is posible to go through such an infinite list, and still have constant memory usage as long as the start of the list is stored nowhere. Because, in that case, the head node you're done with can and will be garbage collected.

If, however, you have the head of the infinite list somewhere (in a static variable, say) memory usage will increase as you traverse the list.

Because such things are painful to write in Java, there are new JVM languages like Scala (functional/OO), Clojure (List) or Frege (Haskell like) that make it easy to have such things in the JVM.

Frege may be interesting for you because a) it is non-strict (i.e. lazy) and b) it spits out java source code, hence you could study and play the java sources created by simple functional programs.

Body:
The idea behind all simple lists is the following:

Make sure you can tell if you have an empty list or not.

If it's not the empty list, you have 2 parts:

the head of the list

and the tail (rest of the list)

Since Java supports closures (well, kind of), one can implement lazy lists with the following trick: Instead of having a reference directly to the tail, have a reference to an Object which is able to compute the tail. Such an Object could be a Callable<ZList>, say, if ZList is our list type. And yes, such a closure constructed with

 // assuming constructor ZList(int, Callable<ZList>);
 public Callable<ZList> nextNode(final int current) {
   return new Callable<ZList> {
     ZList call() {
          return new ZList(current, nextNode(current+1));
     }
   };
 }

takes up some finite amount of memory. Certainly more than a singe list node, but less than many list nodes.

As for the memory requirement: It is posible to go through such an infinite list, and still have constant memory usage as long as the start of the list is stored nowhere. Because, in that case, the head node you're done with can and will be garbage collected.

If, however, you have the head of the infinite list somewhere (in a static variable, say) memory usage will increase as you traverse the list.

Because such things are painful to write in Java, there are new JVM languages like Scala (functional/OO), Clojure (List) or Frege (Haskell like) that make it easy to have such things in the JVM.

Frege may be interesting for you because a) it is non-strict (i.e. lazy) and b) it spits out java source code, hence you could study and play the java sources created by simple functional programs.