问:
Why were annotations introduced in Spring and Hibernate?
I would like to know why were annotations introduced in Spring and Hibernate? For earlier versions of both the frameworks book authors were saying that if we keep configuration in xml files then it will be easier to maintain (due to decoupling) and just by changing the xml file we can re-configure the application.

If we use annotations in our project and in future we want to re-configure application then again we have to compile and build the project.

So why were these annotations introduced in these frameworks? From my point of view annotations make the apps dependent on certain framework. Isn't it true?

答:
For earlier versions of both the frameworks book authors were saying that if we keep configuration in xml files then it will be easier to maintain (due to decoupling) and just by changing the xml file we can re-configure the application.

Back then annotations didn't exist. People hated the XML files, and Java got a horrible reputation because of them. Heck, there was a widely used tool (XDoclet) that generated XML config files from special JavaDoc comments, because maintaining them manually was such a pain!

When annotations were introduced in Java 5, everyone quickly realized that they were for most purposes much, much more maintainable than keeping things that configure intimate details of an application (like service dependencies or DB mappings) in a separate XML files. Realistically, most of the "configuration" is really code as far as changes are concerned, i.e. changes will be made as the application is developed (not while it's deployed) and usually together with changes in the code.

If we use annotations in our project and in future we want to re-configure application then again we have to compile and build the project.

Why is that a problem? Is you build process that horrible? Maybe you should work on that then. But note that both Spring and Hibernate still allow you to use XML configuration, even in combination with annotations. You can even override existing  annotations from an XML config file.

So why these annotations were introduced in these frameworks? From my point of view annotations make the apps dependent on certain framework. Isn't it true?

The app depends on the framework anyway, otherwise you wouldn't need it. So why pretend otherwise? Besides, many of the annotations are now official Java standards (such as JPA and CDI) and supported by multiple different frameworks.


问:
Historical origins of Scala implicits
Scala has been called complex with its rich feature set by many of my colleagues and some even blamed all those new features of it. While most programmers are aware of the OO-features, and at least the decent ones also know about functional programming, there is one feature in particular in Scala for which I am not aware of its historical origins.

Given that a major mantra of our profession is to not reinvent the wheel, I am rather confident, that Scala does not have any actual unheard-of-before features, but I stand to be corrected on this one if necessary.

To get to the actual question, while I am aware of the origins of most of Scala's features I have never seen something like its implicit declarations before. Are there other (older!) languages out there which also provide this feature?

Does it make sense to distinguish the different cases of implicits (as they may originate from different sources), namely implict conversions and implicit parameters?

答: I asked a similar question on Stack Overflow. The most voted answer and others suggest that the origins are in Haskell. </p>

ContentLicense: CC BY-SA 3.0

Title: Historical origins of Scala implicits


问:
Why design pattern is not named as implementation pattern?
I find that most of the design patterns are concerned with implementation of a model like mvc, or how to change the implementation with less cost. These are all happened in the implementation phase of a software. So why not call them implementation patterns? </p>

答:
A design pattern is a concept that is more of a high level. How you implement those patterns is up to you and it is more at low-level, internal stuff to the design.

They are a general concept that tends to hide the implementation details, thus the name design pattern.

When you say about change the implementation with less cost, it is a direct side effect of using design pattern. You have all the implementation details encapsulated, so you can change them at will without affecting the clients of your classes.

These are all happened in the implementation phase of a software.

This is not necessarily true, because design patterns might be spotted in the design phase. I agree with you that you should not force design patterns into your design, that they should appear by themselves, but it is a possibility that they appear at the design level, long before you have to worry about the concrete implementation.


答:
I'd argue that what is usually known as 'software implementation phase' is a design phase, possibly low level detailed design, but design none the less. The real 'implementation' is in a sense done by compilers and build scripts and therefore automated and out of sight.

Of course why they were originally called design patterns was because they came from architecture (the bricks and mortar type) which is certainly a design phase rather than implementation. Software design patterns were an analogy to Architectural design patterns

Title: Why design pattern is not named as implementation pattern?

Body: I find that most of the design patterns are concerned with implementation of a model like mvc, or how to change the implementation with less cost. These are all happened in the implementation phase of a software. So why not call them implementation patterns? </p>


问:
exact answer for “what is j2ee?” - job interview
I'd like to ask if someone of you knows the exact meaning of JEE.

That's because a collegue of mine was asked this question in a job interview, and was "unable to answer properly"... to speak with his interwiewer's words. And when he told me what he said to his interviewer I got really surprised, since it was more or less what I would have answered myself - in a concise form, the first paragraph of this article.

J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing typical of large enterprises. Sun Microsystems (together with industry partners such as IBM) designed J2EE to simplify application development in a thin client tiered environment. J2EE simplifies application development and decreases the need for programming and programmer training by creating standardized, reusable modular components and by enabling the tier to handle many aspects of programming automatically.

That seems not to be enough, since the interviewer asked for "more precise and less general definition".

Is there really a more precise definition for JEE? Or did my colleague just find the fussiest-interviewer-ever? :)

答:
First I would have corrected the interviewer by telling him, that since version 5 it's named JavaEE.

Further I would have detailed the parts that make up JavaEE, e.g. JPA, JSF, JSP, etc...


问:
Question about a simple design problem
At work I stumbled uppon a method. It made a query, and returned a String based on the result of the query, such as de ID of a customer. If the query didn't return a single customer, it'd return a null. Otherwise, it'd return a String with the ID's of them. It looked like this:

```<code>String error = getOwners();
if (error != null) {
    throw new Exception("Can't delete, the flat is owned by: " + error);
}
...
</code>```

Ignoring the fact that getCustomers() returns a null when it should instead return an empty String, two things are happening here. It checks if the flat is  owned by someone, and then returns them.

I think a more readable logic would be to do this:

```<code>if (isOwned) {
    throw new Exception("Can't delete, the flat is owned by: " + getOwners());
}
...
</code>```

The problem is that the first way does with one query what I do with two queries to the database.

What would be a good solution involving good design and efficiency for this?

答:
Can you change the getOwners method? If so, I would change getOwners to return an ArrayList. That way you can you just check to see if the list is empty and if not just use the list. Like so.

```<code>public ArrayList<int> getOwners() {
    ArrayList<int> list = ArrayList<int>();
    // Magic...
    return list;
}

// Later...

ArrayList<int> owners = getOwners();
if (!owners.isEmpty()) {
    throw new Exception("Can't delete, the flat is owned by: " + owners.toString());
}
</code>```

I think the above approach is much clearer than any of the other ways.

Title: Question about a simple design problem

Body:
Can you change the getOwners method? If so, I would change getOwners to return an ArrayList. That way you can you just check to see if the list is empty and if not just use the list. Like so.

public ArrayList<int> getOwners() {
    ArrayList<int> list = ArrayList<int>();
    // Magic...
    return list;
}

// Later...

ArrayList<int> owners = getOwners();
if (!owners.isEmpty()) {
    throw new Exception("Can't delete, the flat is owned by: " + owners.toString());
}

I think the above approach is much clearer than any of the other ways.


问:
What design pattern is best suitable with this context?
I have a base class Shape, and drived classes Line Segment, Arc, B-spline,... I want to find the intersection point between these shapes. I would like:

```<code>Shape* a = new LineSegment();
Shape* b = new Arc();

bool did_intersect = a->Intersect(b);
</code>```

I don't like this design in Intersect:

```<code>bool LineSegment(Shape* s) {
  Arc* arc = dynamic_cast<Arc*>(s);
  if (NULL != arc)
    return LineSegmentArcIntersection(this, arc);

  BSpline* bspline = dynamic_cast<BSpline*>(s);
  if (NULL != bspline)
    return LineSegmentBSplineIntersection(this, bspline);
  ...
}
</code>```

So, What design pattern is best suitable with this context?

答:
I think you are looking for double dispatch or multiple dispatch.

Btw., this question is better suited for StackOverflow.

ContentLicense: CC BY-SA 2.5


问:
Are More Comments Better in High-Turnover Environments?
I was talking with a colleague today. We work on code for two different projects. In my case, I'm the only person working on my code; in her case, multiple people work on the same codebase, including co-op students who come and go fairly regularly (between every 8-12 months). She said that she is liberal with her comments, putting them all over the place. Her reasoning is that it helps her remember where things are and what things do since much of the code wasn't written by her and could be changed by someone other than her. Meanwhile, I try to minimize the comments in my code, putting them in only in places with a unobvious workaround or bug. However, I have a better understanding of my code overall, and have more direct control over it. </p>

<p>My opinion in that comments should be minimal and the code should tell most of the story, but her reasoning makes sense too. Are there any flaws in her reasoning? It may clutter the code but it ultimately could be quite helpful if there are many people working on it in the short- to medium-run. </p>

答:
Comments are more helpful in some scenarios than others. This is so fundamental that I worry about how to explain it in the midst of so many answers that I perceive to be "anti-comment".

If your code might not be read for years, comments are more important than if you have frequent code refactoring, strong code ownership, and copious code reviews. If your application is complex and uses techniques that are not immediately obvious to an observer proficient in that language, comments are more important than if the system is a glorified "Hello World." If the code base isn't as strict with standards as it could be, comments are more important than if you're working with six layers of QA. If you're working on a team with eight people just learning the language, comments are more important than if your team has eight programming Pulitzers. If you got a sprawling application dropped in your lap, comments are more important than if you were able to build it clean from scratch.

Would it be better in most of those scenarios to fix the underlying cause instead of increase the use of comments? Absolutely. But sometimes you're stuck with a code base that has more fingerprints on it than the town smartphone, and the best way to improve it is to make your changes as readable as possible and comment the heck out of it.

To your specific problem: comments shouldn't be strewn about so much as to clutter the code. A well-written paragraph at the top of a subroutine, describing why a function exists and maybe why it uses that approach, is often the best bet to help the next programmer get their bearings.


答:
I find that most of the design patterns are concerned with
  implementation of a model like mvc, or how to change the
  implementation with less cost.

Design obviously has a big impact on implementation -- every design has to be implemented, after all. But design patterns are fundamentally about design, not implementation. Any given design pattern can be implemented in more than one way, but the concept remains the same. To take that a step further, if you have a project that uses some design pattern, you should be able to replace the implementation of that pattern in the project with a different one, and doing so shouldn't cause any major changes in how the objects relate to each other.

If a pattern such as MVC were an implementation pattern, any projects that use MVC would implement that pattern in substantially the same way. That is, the code would look more or less the same. There are a LOT of MVC frameworks out there, and you can bet that they don't all share the same implementation. Nevertheless, if you've worked with any one of them, you'll find it easy to understand others at a conceptual level because they share the same design.


答:
Because their design-level aspects matter, not the implementation-level aspects.

Take, for example, the Factory Pattern.

The key concept is that you provide a central entry point to transparently produce various instances of an abstract data type, with the goal of exposing only the factory and the ADT, but not the implementations themselves.

The factory can be a class, a static method, or a free function, and the ADT it instantiates can be returned by interface, by base class, or, dynamic-programming style, as an unspecified type (but documented to contain certain members). Factories can be used to instantiate pure data, classic data-with-code classes, classes that merely wrap a method, or even just functions (lambdas, function pointers, or whatever mechanism the language provides). Those are implementation details though, while the design principle remains the same - make a polymorphic data type abstract by providing only a common interface and a factory mechanism to create instances transparently.


问:
What is the equivalent word for "compile" in an interpreted language?
(I was encouraged to ask this question here.)

In C, we say:

GCC compiles foo.c.

For interpreters (such as Lua), what is the equivalent verb?

The Lua interpreter ____________ foo.lua.

When I write instructions for users of my Lua script, I often say:

Run the interpreter on foo.lua.

I think this can be said more succinctly:

Interpret (or Translate) foo.lua.

but that sounds awkward for some reason (perhaps because I'm unsure of its correctness). I can't really say compile because users may confuse it with the usage of the Lua compiler when I actually mean the Lua interpreter.

答:
I have always thought along these lines:

A compiler compiles code.

An interpreter interprets code.

So I would say interprets.


问:
Are breadcrumbs still a viable way to navigate web sites and web apps?
I'm currently working on the following types of web sites and apps:

ecommerce like Amazon

Reservation system (think of a hotel receptionist checking rooms availability)

Invoice management like Freshbook

On Amazon, I didn't notice any breadcrumbs, just facets from the left panel.  However, newegg is using both breadcrumbs and facets.

In a management system like hotel reservations or invoice management, you usually have unique reservation or customer number that you search through your system.  Each reservation can then expand to more sections, for instance:

```<code>Reservations
    > Reservation #123456
        > Guests
        > Room
        > Airport pickup
        > Payment
</code>```

In each unique reservation page, I'm using breadcrumbs to show the location of the current page relative to the site.  Is that a good method to present that kind of information?  Should I use tabs or other techniques?

答:
Breadcrumbs are used in Windows 7 Explorer, in a highly effective manner.

I actually think breadcrumbs are underused in web sites.  It's an extremely effective technique for moving around in the website tree, especially if the website is large and complex.


答:
It sounds awkward because compilers and interpreters are really different things.

You can say "run the compiler" to get the binary and maybe deploy the application but you cannot say "run the interpreter" to produce binary and deploy it. So you cannot compare them.

Interpret is the right word.

Title: What is the equivalent word for "compile" in an interpreted language?

Body:
(I was encouraged to ask this question here.)

In C, we say:

GCC compiles foo.c.

For interpreters (such as Lua), what is the equivalent verb?

The Lua interpreter ____________ foo.lua.

When I write instructions for users of my Lua script, I often say:

Run the interpreter on foo.lua.

I think this can be said more succinctly:

Interpret (or Translate) foo.lua.

but that sounds awkward for some reason (perhaps because I'm unsure of its correctness). I can't really say compile because users may confuse it with the usage of the Lua compiler when I actually mean the Lua interpreter.


答: In addition to the obvious interprets, you could say that the interpreter runs or executes some code.


答: "Interprets" or "runs" are, I think, the two most natural verbs. Maybe "executes".</p>


问:
Web standards or risk avoidance?
My company is building an App Engine application. The app encounters a bug (possibly due to an issue with App Engine itself, as per our research) on IE9, but it cannot be reliably reproduced and is experienced by a small percentage of users.

The workaround is to force IE9 to use IE8 mode. As a lazy front end developer (who doesn't like CSS hacks, shims and polyfills) I think it's OK to at least try going back to IE9 mode and see what happens, while we're still in private beta. The senior engineer (being more pragmatic) would rather that we continue forcing IE9 users to use the older IE8 mode. Who is right?

答:
If your code is standards-compliant, but IE9 breaks unless put in IE8 mode, I'd say keep it as it is. Just make sure you're not breaking anything for other browsers for the sake of salvaging IE. You may get into trouble when you try to use standard functionality that isn't available on IE until version 9 though; if that happens, you should re-assess and decide what is more important - the bug not appearing, or full functionality when it doesn't appear.

If you can pinpoint the problem to a documented bug in IE, you may want to implement a workaround (again, one that doesn't affect other browsers) or just switch back to IE9 mode once the bug is fixed (plus a bit of a grace period, because not everyone updates their systems on a daily basis).

Title: Web standards or risk avoidance?


问:
Why do some programmers think there is a contrast between theory and practice?
Comparing software engineering with civil engineering, I was surprised
to observe a different way of thinking: any civil engineer knows that
if you want to build a small hut in the garden you can just get the
materials and go build it whereas if you want to build a 10-storey house
(or, e.g., something like this) you need to do quite some maths
to be sure that it won't fall apart.

In contrast, speaking with some programmers or reading blogs or forums
I often find a wide-spread opinion that can be formulated more or less as follows: theory and formal methods are for mathematicians / scientists
while programming is more about getting things done.

What is normally implied here is that programming is something very
practical and that even though formal methods, mathematics, algorithm theory,
clean / coherent programming languages, etc, may be interesting topics,
they are often not needed if all one wants is to get things done.

According to my experience, I would say that while you do not need much
theory to put together a 100-line script (the hut), in order to develop
a complex application (the 10-storey building) you need a structured
design, well-defined methods, a good programming language, good text
books where you can look up algorithms, etc.

So IMO (the right amount of) theory is one of the tools
for getting things done.

My question is why do some programmers think that there is a contrast
between theory (formal methods) and practice (getting things done)?

Is software engineering (building software) perceived by many as
easy compared to, say, civil engineering (building houses)?

Or are these two disciplines really different (apart from mission-critical
software, software failure is much more acceptable than building failure)?

I try to summarize, what I have understood from the answers so far.

In contrast to software engineering, in civil engineering it is much clearer what amount of theory (modelling, design) is needed for a certain task.

This is partly due to the fact that civil engineering is as old as mankind while software engineering has been around for a few decades only.

Another reason is the fact that software is a more volatile kind of artefact, with more flexible requirements (it may be allowed to crash), different marketing strategies (good design can be sacrificed in order to get it on the market quickly), etc.

As a consequence, it is much more difficult to determine what the right amount
of design / theory is appropriate in software engineering (too little -> messy code, too much -> I can never get finished)
because there is no general rule and only (a lot of) experience can help.

So if I interpret your answers correctly, this uncertainty about how much
theory is really needed contributes to the mixed love / hate feelings
some programmers have towards theory.

答:
Bear with me on this one. I have a point.

I had a professor tell me once that procrastinating leads to more procrastinating, even though most people after a night of harried paper writing/cramming/programming say to themselves, "I'll never do that again. Next time, I'll start early and get done early." In my experience as the consummate procrastinator, I've found this to be true, and here's the professor's explanation why: no matter how unpleasant the experience of procrastinating is, in most cases, you get done having achieved relative success. This is high risk/high reward behavior. After a while, you forget about all of the unpleasantness, and only remember the reward. Thus, the next temptation to procrastinate is all the more enticing, because you succeeded the last time.

I think an analogy can be made here to the "get things done" programming technique we all too often see. A programmer or team of programmers, maybe out of ignorance, laziness, or perhaps a genuine time constraint, takes the "get things done" approach to programming, throwing all of your theory and maths and good practices out the window. And you know what? They get things done. It's not elegant, pretty, or maintainable, but it gets the job done. Maybe a non-technical superior who doesn't know a semicolon from a semaphore gives them some high praise for "getting things done". Thus, the next time the programmer is tempted to take this slack approach to programming, it's all the easier, because hey, it worked last time didn't it? It's the "easy" way out, unless your the poor, unfortunate soul who inherits such an application years later and has to maintain it.

I've been that poor, unfortunate soul, and so have many of you probably. I implore you all. Don't take the easy way out! :)

ContentLicense: CC BY-SA 4.0


答:
I think the main difference is that with civil engineering, real world physics act as a constant, powerful reality check that keeps theory sane and also limits bad practices, whereas in software engineering there is no equally strong force to keep impractical ivory tower concepts as well as shoddy workmanship in check.

Many programmers have had bad experiences with runaway theory becoming an active impediment to getting things done (e.g. "executable UML", super-bureaucratic development processes). Conversely, dirty hacks and patches can get you pretty damn far, albeit slowly in the end. And as you observe in your last paragraph: failures are usually not as final and thus not as problematic.

Title: Why do some programmers think there is a contrast between theory and practice?

Body:
Comparing software engineering with civil engineering, I was surprised
to observe a different way of thinking: any civil engineer knows that
if you want to build a small hut in the garden you can just get the
materials and go build it whereas if you want to build a 10-storey house
(or, e.g., something like this) you need to do quite some maths
to be sure that it won't fall apart.

In contrast, speaking with some programmers or reading blogs or forums
I often find a wide-spread opinion that can be formulated more or less as follows: theory and formal methods are for mathematicians / scientists
while programming is more about getting things done.

What is normally implied here is that programming is something very
practical and that even though formal methods, mathematics, algorithm theory,
clean / coherent programming languages, etc, may be interesting topics,
they are often not needed if all one wants is to get things done.

According to my experience, I would say that while you do not need much
theory to put together a 100-line script (the hut), in order to develop
a complex application (the 10-storey building) you need a structured
design, well-defined methods, a good programming language, good text
books where you can look up algorithms, etc.

So IMO (the right amount of) theory is one of the tools
for getting things done.

My question is why do some programmers think that there is a contrast
between theory (formal methods) and practice (getting things done)?

Is software engineering (building software) perceived by many as
easy compared to, say, civil engineering (building houses)?

Or are these two disciplines really different (apart from mission-critical
software, software failure is much more acceptable than building failure)?

I try to summarize, what I have understood from the answers so far.

In contrast to software engineering, in civil engineering it is much clearer what amount of theory (modelling, design) is needed for a certain task.

This is partly due to the fact that civil engineering is as old as mankind while software engineering has been around for a few decades only.

Another reason is the fact that software is a more volatile kind of artefact, with more flexible requirements (it may be allowed to crash), different marketing strategies (good design can be sacrificed in order to get it on the market quickly), etc.

As a consequence, it is much more difficult to determine what the right amount
of design / theory is appropriate in software engineering (too little -> messy code, too much -> I can never get finished)
because there is no general rule and only (a lot of) experience can help.

So if I interpret your answers correctly, this uncertainty about how much
theory is really needed contributes to the mixed love / hate feelings
some programmers have towards theory.


答:
If I cut a corner on most software, and do something that's not the best design, but will get the job done, nobody is going to die.  It's the same reason a hut in the garden doesn't need the same standards as a 10 story building.  However, I can build a very large app like facebook, and if it screws up and loses some data, or whatever, it's not really that big of a deal.  It's also simpler to fix the foundation of a large app after the fact, than it is to replace the foundation of a 10 story building.  It all comes down to context, and calculating risk.

I can also, safely and simply keep adding to an app.  You can't easily toss in a new third floor of a 10 story building (making it 11).  I can toss in a new feature to a large app every day if I want to.

Now, good design makes all this easier in programming.  But it's not impossible with poor design, and the risks, are...buggy software.  Not usually death.


答:
Your perception may be wrong here, or it includes many resources from people who haven't written sufficiently complex software.

Your experience is inline with what most people I know of (who have designed and written sufficiently complex software) would say.

That said, when it comes to most programmers, when the task of writing something gets to them the design ("the maths" as you put it) has already been done by the architect/lead/etc. before the task of writing it gets to them. So it may appear that way from the front-line level.


答:
Software engineering and civil engineering have little in common.  Civil engineering efforts are limited by the physical properties of their materials and the environment.  Civil engineers spend a lot of time learning about soil properties and material characteristics.  Software development is physically limited only by the speed of the processors and the available storage.  Both of these are easy to understand, and we don't spend much time studying them.  The major limitation to software development is the human intellect.  And no two developers are alike.  Is this code maintainable?  By whom?  A three-line implementation of quicksort in Haskell may be obviously correct to some, but incomprehensible to others.  A team of two may complete an application in a month, while another team of ten struggles to deliver in a year.

Software development is all design, the artifacts being designed are orders of magnitude more complex than any manufactured article, and each one is unique.


答:
So my question is why do some programmers think that there is a
  contrast between theory (formal methods) and practice (getting things
  done)?

Building software is unlike building a bridge.  In software, there are many objects to be built which may or may not be defined at the onset.  Standards exist to increase ease of maintenance and developer collaboration, not to adhere to arbitrary mathmatical formulas or other such ideals. For example, when selecting behavior based upon a variable sometimes it makes sense to use a switch, other times a factory pattern.  It depends on the ease of maintenance and identified pain points such as performance problems.

Another example can be made with data manipulation.   It often makes sense to use delegates in the context of .NET.  It is not so easy in Java because it does not have the framework support for functional programming style that .NET has.  In other words, in the general case it simply is not possible to do X in situation Y.  This is due to the fact that X and Y depend on N number of variable factors.

Is software engineering (building software) perceived by many as easy
  compared to, say, civil engineering (building houses)?

I'm not sure "easy" is the correct term.  A lack of tangible evidence can lead to the perception that no work is being done. Or, similarly, that existing work is easily changed.

Or are these two disciplines really different (apart from
  mission-critical software, software failure is much more acceptable
  than building failure)?

Traditional Engineering and Software Engineering are very different for the reasons I already stated.


问:
How do you deal with the anxiety of not knowing enough?
I just finished college a couple of months ago and I'm taking time out to improve my knowledge. I love programming but I feel like I don't know enough to be confident if I went for an interview. Last night I was browsing through questions and came across a question that asks interviewees how to work out a linked list. I learned these at college but if I was asked on the spot how to do it I wouldn't know. So that's another thing added to the list of what to learn.

This is when the anxiety hit me because I have so much to learn in so little time (at least it feels that way). Upon introspection, I think this anxiety is related to my perfectionism even though being perfect isn't rational e.g. Shakespeare and Einstein failed 80% of the time.

So the questions are, have you felt this anxiety of not knowing enough? If so, how did you deal with it? I suppose there's a point in time when you begin to feel comfortable in your abilities?

答:
Making a linked list is something you should have learned in college.  The Java programmers never have to do so, because the standard runtime library provides a set of list implementations with different characteristica.

I would suggest that you - if you have gotten a job yet - dig into what you can learn of what is expected of you in your current job.  For Java programmers that would be "Effective Java" you should learn by heart.  The ecosystem these days is so great that there is PLENTY to learn just for the standard runtimes.


答:
Your premise is flawed. The main reason civil engineers use engineering when designing large buildings, bridges, tunnels, etc. is to ensure that they are using minimum amount of material (concrete, structural steel, etc) which satisfies the required safety standards. It is entirely possible to build a tall building without much in the way of mathematics (e.g. the pyramids of the ancient Egyptian and Mayan civilizations) if costs of material and of labour is no object, but once built, there is usually no point in modifying them to make them use material more efficiently.

There is a somewhat different dynamic in designing large software systems. If anything, they are usually under-designed, but this is because the design can be changed dynamically as work proceeds, which simply cannot be done so easily with civil engineering projects.

The common factor is cost. Design on a traditional civil engineering project reduces costs (both actual, in terms of material, and potential in terms of liability), whereas there comes a point in software development where the cost of design increases beyond the value returned.


答:
I think the reason for this contrast is that the life cycle of a software project and hardware or architecture project is different. Most software evolves gradually, it is not planned from the beginning to the end. Software developers can apply an iterative approach to development: plan, implement and listen to feedback. If the feedback is positive, carry on, it not - take a step back and reconsider your strategy. That's why software developers have things like agile development, minimum viable product and so on.

Civil engineers don't have such luxury. For them, once something is planned, you cannot change it as easily, as with software, because the cost of such changes can be dire. For software development, on the other hand, it's doesn't cost that much, and this can be used for their advantage.

But not every branch of software development can afford such approach. Making software, for instance, for aviation or medical services require very careful planning and a lot of prior calculations.


答:
An architect's/civil engineer's blueprints are virtually never identical to the "as built" plans. Something ALWAYS changes. Why? Because there are, and will always be, "unknown unknowns". There are things that you know and so can plan for, things that you know are unknown and so you can research and estimate, and then there are things that you don't know you don't know; "surprises". You aim to eliminate these in most systems by learning all you can, but all it takes is one little building code violation (which may be based on a rule that didn't exist 2 years ago when your building was being conceptualized) and your all-encompassing master plan has to change, sometimes quite drastically.

Software is very much like this; there's always an unknown unknown. However, unlike civil or structural engineering, software development is inherently much more tolerant of change based on the problems the unknown unknowns create. If you're building a 10-story building and you overestimated the load-bearing capacity of the foundation you put in your design, you either can't build the building to 10 stories or you have to tear out a significant amount of work to get back down to the foundation and reinforce or rebuild it. However, in software, if you underestimated the demands on a particular tier of the overall solution structure, there are many options for fixing that tier that don't involve invalidating all the other work. You can replace a single DB server with a more powerful one, or a replication/failover cluster, or a load-balancing/distributed cluster. Same for the webserver. If you coded an algorithm that is inefficient but simple based on faulty assumptions of input size, you can almost always simply remove and rewrite the implementation in a relatively surgical manner, without affecting other code that has knowledge of the algorithm (calls and passes input to it, or expects an output from it).

This relative ease of change allows a software engineer to code based on what he knows without worrying unduly about what he doesn't know. This allows for laxer application of theory and up-front conceptual design; you dive in and get it done, and along the way you find the things you coded that need to change, and change them. You must still know the concepts and theory, because when a problem is uncovered it's those things that will help you identify the cause and create a solution. But, you're allowed to make a snap decision without succumbing to "analysis paralysis", because if it turns out you made the wrong decision based on something you didn't know or didn't factor in to your "calculations", the mistake is easier to correct.


答:
The difference is primarily because of the known requirements:

On the theory side, everything is defined up-front, so you can know exactly what you need before you start.

In practice, they're often not all there, or you discover something midway through the implementation that causes you to have to redesign something.  So it's much better to jump with at least rudimentary designs, so you can discover these problems early on.

Additionally, when talking about "theory", it usually means the theory side of computer science, rather than software engineering.  This is the part of computer science that's largely about finding better and more efficient algorithms, proving whether something is or is not possible (P and NP, for example), and so on.  While it's good to have these in the back of your mind, they don't come up in software development very often.

We use libraries for that kind of thing as much as possible.


问:
is it a bad practice to call a View from another View in MVC?
I have some plain Views, they don't have any logic behind them (there is no action or controller behind them), their only propouse is to alert the user about something like "We have sent you an email to confirm your account", "You have no access to this resource", etc...

These views are really simple, and calling them through a Controller/Action seems to be too much overhead, but somehow I feel like it is not quite correct. What do you think? How do you handle this kind of situations??

I guess this question will apply to any MVC Framework, but in my case I'm using the ASP.NET MVC 3 framework.

答:
They do have logic "behind" them.

They only came up as the result of certain actions, like "Done, email me and send me a confirmation."  As that email action is being done in a controller, the controller then directs to the final view.

If you just want pop-ups for acknowledgment messages, like the ones that appear and then disappear automatically, that's different and you can use Javascript and libraries like jQuery for that.


答: I would also point out, in addition to several other excellent responses that mankind has been doing the equivalent of "civil engineering" since easily the time of the Egyptians so we've had a lot of time to perfect the general theory of how things should be done.  We've been building software for somewhere around 70 years or so (depending on what you consider the first "software"); I mean that we've not had the same amount of time to develop the same sort of body of experience.  </p>


答:
In my 'view' everything needs to go through the controller. When you break the design pattern, even for something simple, you're asking for chaos as the app evolves over time. Ask anyone who's still having to work on 10-12 year old apps where a 'simple' change in 2002 is now a nightmare to deal with in 2012.

In .NET MVC3 you can use partial views to handle some informational widgets as well as JQuery. Which to use will depend on where you want to separate server and client side interaction.

To take it further, you might want to use an Alert view model and have your view (or partial) adjust accordingly. For example, I use a LinkSelectList viewmodel to hold values for a list of links matching search criteria. I use this in several places in an app where the user can search for different items.

Title: is it a bad practice to call a View from another View in MVC?

Body:
I have some plain Views, they don't have any logic behind them (there is no action or controller behind them), their only propouse is to alert the user about something like "We have sent you an email to confirm your account", "You have no access to this resource", etc...

These views are really simple, and calling them through a Controller/Action seems to be too much overhead, but somehow I feel like it is not quite correct. What do you think? How do you handle this kind of situations??

I guess this question will apply to any MVC Framework, but in my case I'm using the ASP.NET MVC 3 framework.


答: I find breadcrumbs a very useful feature.  I particularly like it on ecommerce sites where I might be in and out of a lot of different category products.  Its a wonderful tool that should be used more often and doesn't require a lot of screen real estate to implement.</p>

Title: Are breadcrumbs still a viable way to navigate web sites and web apps?

Body:
I'm currently working on the following types of web sites and apps:

ecommerce like Amazon

Reservation system (think of a hotel receptionist checking rooms availability)

Invoice management like Freshbook

On Amazon, I didn't notice any breadcrumbs, just facets from the left panel.  However, newegg is using both breadcrumbs and facets.

In a management system like hotel reservations or invoice management, you usually have unique reservation or customer number that you search through your system.  Each reservation can then expand to more sections, for instance:

```<code>Reservations
    > Reservation #123456
        > Guests
        > Room
        > Airport pickup
        > Payment
</code>```

In each unique reservation page, I'm using breadcrumbs to show the location of the current page relative to the site.  Is that a good method to present that kind of information?  Should I use tabs or other techniques?


问:
When module calling gets ugly
Has this ever happened to you?  You've got a suite of well designed, single-responsibility modules, covered by unit tests.  In any higher-level function you code, you are (95% of the code) simply taking output from one module and passing it as input to the next.  Then, you notice this higher-level function has turned into a 100+ line script with multiple responsibilities.

Here is the problem.  It is difficult (impossible) to test that script.  At least, it seems so.  Do you agree?  In my current project, all of the bugs came from this script.

Further detail: each script represents a unique solution, or algorithm, formed by using different modules in different ways.

Question: how can you remedy this situation?

Knee-jerk answer:  break the script up into single-responsibility modules.

Comment on knee-jerk answer:  it already is!

Best answer I can come up with so far:  create higher-level connector objects which "wire" modules together in particular ways (take output from one module,  feed it as input to another module).  Thus if our script was:

```<code>Foo.Input fooIn = new Foo.Input(1, 2);
Foo.Output fooOutput =  fooModule.operate(fooIn);
Double runtimevalue = getsomething(fooOutput.whatever);
Bar.Input barIn = new Bar.Input( runtimevalue, fooOutput.someOtherValue);
Bar.Output barOut = barModule.operate(barIn);
</code>```

It would become with a connector:

```<code>FooBarConnectionAlgo fooBarConnector = new fooBarConnector(fooModule, barModule);
Foo.Input fooIn = new Foo.Input(1, 2);
Bar.Output barOut = fooBarConnector.operate(fooIn);
</code>```

So the advantage is, besides hiding some code and making things clearer, we can test FooBarConnectionAlgo.

I'm sure this situation comes up a lot.  What do you do?

答: In isolation, I think you are on the right track. I am not sure I would bother writing "connectors" that join modules for each specific case. However, it does make sense to create objects that perform the logic and can have its dependencies injected into it. Why not just do that for the entire "script" itself? Then the script itself is testable. You can then inject mocks or "doubles" to ensure things happen the way you expect. After all, I expect that it is the script as whole that you care about, rather then each individual interaction between the modules.

Title: When module calling gets ugly


答:
I think what you're referring to is an integration test.  Typically you would have a set of test data and known results, just like for a unit test, but in this case you're testing the whole integrated work, instead of only one module in isolation.

An integration test can't get into every nook and cranny of every bit of code, but it'll give you pretty good confidence that you've wired everything up correctly.

Title: When module calling gets ugly

Body:
Has this ever happened to you?  You've got a suite of well designed, single-responsibility modules, covered by unit tests.  In any higher-level function you code, you are (95% of the code) simply taking output from one module and passing it as input to the next.  Then, you notice this higher-level function has turned into a 100+ line script with multiple responsibilities.

Here is the problem.  It is difficult (impossible) to test that script.  At least, it seems so.  Do you agree?  In my current project, all of the bugs came from this script.

Further detail: each script represents a unique solution, or algorithm, formed by using different modules in different ways.

Question: how can you remedy this situation?

Knee-jerk answer:  break the script up into single-responsibility modules.

Comment on knee-jerk answer:  it already is!

Best answer I can come up with so far:  create higher-level connector objects which "wire" modules together in particular ways (take output from one module,  feed it as input to another module).  Thus if our script was:

```<code>Foo.Input fooIn = new Foo.Input(1, 2);
Foo.Output fooOutput =  fooModule.operate(fooIn);
Double runtimevalue = getsomething(fooOutput.whatever);
Bar.Input barIn = new Bar.Input( runtimevalue, fooOutput.someOtherValue);
Bar.Output barOut = barModule.operate(barIn);
</code>```

It would become with a connector:

```<code>FooBarConnectionAlgo fooBarConnector = new fooBarConnector(fooModule, barModule);
Foo.Input fooIn = new Foo.Input(1, 2);
Bar.Output barOut = fooBarConnector.operate(fooIn);
</code>```

So the advantage is, besides hiding some code and making things clearer, we can test FooBarConnectionAlgo.

I'm sure this situation comes up a lot.  What do you do?


答:
But your controller must first find out if those messages are valid.

"We have sent you an email to confirm your account" makes only sense, if an email was sent without errors.

"You have no access to this resource" is something the view can't and should not know. It needs to ask the controller to send the resource. Even the controller should know nothing about access permissions, but has to ask the model. Only after the model found this out, i can respond either with the resource or the error message.


答:
You've got it right.  This is called "Structured Programming".  It works well when you have a problem to be solved with a series of sequential steps.  You just break each problem into a few sub-problems, then break down the sub-problems, then break down the sub-sub-problems, then....  You seem to be at the point where you have a top-level subroutine--er, method, and a bunch of bottom level ones.  The top one's getting big, so you need an middle layer, as it were.  If your problem (I'd like to call it a program, but it's really a part of a program) gets big enough, you could end up with many levels of methods.

Each method's actions should be determined solely by the parameters passed to it.  I say this to be complete; with your focus on testing, you understand this as well as any old-time Structured Program evangelist.  Ideally, each method would be called from more than one place, showing that it is generally useful, but it's better that methods use sub-methods that only they call, and that they only call once, than that the main method get large and unweildy.

I'm not sure how Sructured Programming and OOP relate.  They seem to blend nicely, and it's always obvious when to use what.  OO seems more for tracking and maintaining a program's state, for handling periodic input from users and such.  SP is more for crunching numbers.  I have found that when I've written big number-crunchers, classes start to creep in at the lower levels of my SP hierarchy.

Title: When module calling gets ugly


答:
It seems the same to me. You build a large building out of standard blocks, standard strength concrete, standard steel. You build a big app out of standard libraries.

You don't try and mathematically formally prove a large app correct in the same way you don't try and write the wavefunction for a 100storey building


问:
Review quality of code
I have been asked to quality review two code bases. I've never done anything like that, and need advice on how to perform it and report it.

Background

There are two providers of code, one in VB and one in C (ISO 9899:1999 (C99)). These two programs do not work so well together, and of course, the two suppliers blames  each other. I will therefore as a independent person review both codes, on a comprehensive level review the quality of the codes to find out where it is most likely that the problem lies. I will not try to find problems, but simply review the quality and how simple it is to manage and understand the code.

Edit:
I have yet not received much information about what the problem consists of. I've just been told that I will examine the code in terms of quality. Not so much more. I do not know the background to why they took this decision.

答:
Doing code reviews in a way which is acceptable for all parties involved is hard. A good process will help, as well as an objective standard, which together ensure the review is verifiable and repeatable. Also, analysis and getting the technical facts is one, reporting in a way that resolves the problem situation, including managing the different perspectives, positions, feelings, is another.

Visual inspection and making a list of all things that are wrong with the code is typically only a good idea there are no time and budget constraints or the code base is really small. Otherwise, the inspections themselves might just be too much work, or the corrections that you would suggest could be too time consuming to perform. Please keep this in mind when you come with recommendations.

What research questions does your client have for the code review and what will be done with the results?

OwnerDisplayName: magol

Title: Review quality of code


问:
Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?
The coding standards for the code hosted in drupal.org suggest to use two spaces to indent the code; other sites suggest to use tabs to indent the code.

What is the proper indentation character for everything, and in every situation? Please explain the answer you give.

答: Tabs for the win.</p>

Body: Tabs for the win.


答:
Interview anxiety is natural. You're going to be under a spotlight in the interview. If they're doing their jobs, the interviewers will ask you questions you don't know the answer to. That's the only way to test the boundaries of what you know and also to gauge how you react when faced with a problem where you don't have the information. This will be true regardless of how much you study.

Knowing that, there's only one thing to do: take the interview. What's the worst that can happen? They'll hire someone else (which is what they're going to do if you don't apply) and you will have interview experience to build on.

Remember, the interviewers are not trying to embarrass or belittle you (if they are, they're not doing their job). They have better things to do with their time. In fact, the reason they're hiring is because they have more work than they can handle without someone. They just want to find the right person to do that work.

Title: How do you deal with the anxiety of not knowing enough?

Body:
I just finished college a couple of months ago and I'm taking time out to improve my knowledge. I love programming but I feel like I don't know enough to be confident if I went for an interview. Last night I was browsing through questions and came across a question that asks interviewees how to work out a linked list. I learned these at college but if I was asked on the spot how to do it I wouldn't know. So that's another thing added to the list of what to learn.

This is when the anxiety hit me because I have so much to learn in so little time (at least it feels that way). Upon introspection, I think this anxiety is related to my perfectionism even though being perfect isn't rational e.g. Shakespeare and Einstein failed 80% of the time.

So the questions are, have you felt this anxiety of not knowing enough? If so, how did you deal with it? I suppose there's a point in time when you begin to feel comfortable in your abilities?


答:
As a more-or-less honest-to-gosh mechanical engineer (with some civil) turned programmer, then CS (AI) PhD, then teacher, then programmer again (excuse me, Software Engineer), I've got a rant on this general subject.

In traditional engineering

you gotta know your math and science because everything you do is based on it

the "heroes" in the field are people who invent new things, discover new ideas, solve problems considered unsolvable

There is a "physics" that applies to software - information theory, but software engineers get little exposure to it, and certainly nothing applied.
The most theory they get is computability and big-O.

Also I'm continually amazed at people who think knowing programming is enough, and they don't need to understand the subject matter of what their programs are about.

What's more, inventiveness is not encouraged. It is discouraged, in favor of least-common-denominator group-think methods, disguised as "readability".
(Imagine if aeronautical or nuclear engineers were encouraged not to do anything that might be hard to understand for their junior peers.)

The things they do learn, like how to program web apps, are of great value.
So is the skill of a plumber or electrician,
but it is not engineering.


问:
What are the alternatives to "overriding a method" when using composition instead of inheritance?
If we should favor composition over inheritance, the data part of it is clear, at least for me.

What I don't have a clear solution to is how overwriting methods, or simply implementing them if they are defined in a pure virtual form, should be implemented.

An obvious way is to wrap the instance representing the base-class into the instance representing the sub-class. But the major downsides of this are that if you have say 10 methods, and you want to override a single one, you still have to delegate every other methods anyway. And if there were several layers of inheritance, you have now several layers of wrapping, which becomes less and less efficient. Also, this only solve the problem of the object "client"; when another object calls the top wrapper, things happen like in inheritance. But when a method of the deepest instance, the base class, calls it's own methods that have been wrapped and modified, the wrapping has no effect: the call is performed by it's own method, instead of by the highest wrapper.

One extreme alternative that would solve those problems would be to have one instance per method. You only wrap methods that you want to overwrite, so there is no pointless delegation. But now you end up with an incredible amount of classes and object instance, which will have a negative effect on memory usage, and this will require a lot more coding too.

So, are there alternatives (preferably alternatives that can be used in Java), that:

Do not result in many levels of pointless delegation without any changes.

Make sure that not only the client of an object, but also all the code of the object itself, is aware of which implementation of method should be called.

Does not result in an explosion of classes and instances.

Ideally puts the extra memory overhead that is required at the "class"/"particular composition" level (static if you will), rather than having every object pay the memory overhead of composition.

My feeling tells me that the instance representing the base class should be at the "top" of the stack/layers so it receives calls directly, and can process them directly too if they are not overwritten. But I don't know how to do it that way.

[EDIT] It seems that many people reading this question think that I am debating if I should use Composition or Inheritance, and that "guiding" me to the one or the other will solve my problem. This is not the case. I always use inheritance when I can, for the simple fact that composition requires more coding, and also more memory. No need to convince me that inheritance is not evil.

I have a very good reason to want to use composition. I want to create a system that model domain objects that can "change nature" over time. That is they can both gain and loose functionality/properties over time, as a result of some actions. This is a lot more natural when modeled as composition.

If the components that can be dynamically added and removed where composed only of properties, it would be easy. In fact I have already found 14 different possible designs that support that case, with varying compromise on code complexity, memory usage, and speed.

The real problem comes when all those components need to be aware of each other, and talk to each other. This is not required when they are just "beans" (in the Java sense). I want to know if there are any, and hopefully several, ways of allowing the components to talk to each other, and more specifically how to have several components of the same type, where one serves as base-class and the others progressively override some of it's methods.

I can see two ways to simulate the overriding present in inheritance.

The first is to have a base component, and all overriding components are built as wrapper on top of another component of the same type. Like that, you can choose at runtime which hierarchy of components you want. This is like pipes and filters. But the problem is that with inheritance, not only can the derived class call methods of the base class, but it works the other way around too. A base class can declare a pure virtual method, which is implemented by the sub-class, and the base class can call this method. I don't see how to accomplish that using whole component wrapping. Also, if we have N inheritance/wrapping layers, then calls to method of the base component then gets N level of delegation, even if the method was not overwritten by any of the wrapping components.

The other alternative, like I said in "One extreme alternative ...", is to do it like above, but forcing each component to contain a single method. In that case we solve the problem of the base-class not seeing/calling the methods of the derived classes, for all methods, except it's own method. So it works now correctly for all cases except for recursion. But the price we pay in memory consumption is high, at least in Java. And Java isn't "functional", so there is a lot of syntax overhead to turn every object method into an individual object.

If there any better alternatives then the two mentioned above, I would like to know about it.

答:
Delegation

Its very used in Java in the Streams classes, but , applies to other programming languages, and frameworks, as well.

In the following "dummy" example, there are several interfaces,
and several classes that support those interfaces.

One of that clases, its composed by another classes, delegates their functuonality, by using their composite fields methods.

```<code>public interface StreamInterface
{
  bool canRead();
  bool canWrite();
  bool canSeek();
}

public interface ReaderInterface extends StreamInterface
{
  void read(byte[] Buffer, int MaxSize);
}

public interface WriterInterface extends StreamInterface
{
  void write(byte[] Buffer, int MaxSize);
}

public class ReaderClass extends ReaderInterface
{
  bool canRead() { ... }
  bool canWrite() { ... }
  bool canSeek() { ... }

  void read(byte[] Buffer, int MaxSize) { ... }
} // class ReaderClass

public class WriterClass extends WriterInterface
{
  bool canRead() { ... }
  bool canWrite() { ... }
  bool canSeek() { ... }

  void write(byte[] Buffer, int MaxSize) { ... }
} // class WriterClass

public class ReaderWriterStreamClass
  extends
    ReaderInterface,
    WriterInterface
{
  public ReaderInterface Reader;
  public WriterInterface Writer;

  void read(byte[] Buffer, int MaxSize)
  {
     Reader.read(Buffer, MaxSize);
  }

  void write(byte[] Buffer, int MaxSize)
  {
     Writer.write(Buffer, MaxSize);
  }
} // class ReaderWriterStreamClass
</code>```

In this example, we can use "ReaderClass" & "WriterClass", to support the required methods, but, can also be replaced by other classes.

Cheers.

Body:
Delegation

Its very used in Java in the Streams classes, but , applies to other programming languages, and frameworks, as well.

In the following "dummy" example, there are several interfaces,
and several classes that support those interfaces.

One of that clases, its composed by another classes, delegates their functuonality, by using their composite fields methods.

public interface StreamInterface
{
  bool canRead();
  bool canWrite();
  bool canSeek();
}

public interface ReaderInterface extends StreamInterface
{
  void read(byte[] Buffer, int MaxSize);
}

public interface WriterInterface extends StreamInterface
{
  void write(byte[] Buffer, int MaxSize);
}

public class ReaderClass extends ReaderInterface
{
  bool canRead() { ... }
  bool canWrite() { ... }
  bool canSeek() { ... }

  void read(byte[] Buffer, int MaxSize) { ... }
} // class ReaderClass

public class WriterClass extends WriterInterface
{
  bool canRead() { ... }
  bool canWrite() { ... }
  bool canSeek() { ... }

  void write(byte[] Buffer, int MaxSize) { ... }
} // class WriterClass

public class ReaderWriterStreamClass
  extends
    ReaderInterface,
    WriterInterface
{
  public ReaderInterface Reader;
  public WriterInterface Writer;

  void read(byte[] Buffer, int MaxSize)
  {
     Reader.read(Buffer, MaxSize);
  }

  void write(byte[] Buffer, int MaxSize)
  {
     Writer.write(Buffer, MaxSize);
  }
} // class ReaderWriterStreamClass

In this example, we can use "ReaderClass" & "WriterClass", to support the required methods, but, can also be replaced by other classes.

Cheers.


问:
Alternatives for comparing data from different databases
I have two huge tables on separate databases. One of them has the information of all the SMS that passed through the company's servers while the other one has the information of the actual billing of those SMS.

My job is to compare samples of both of these tables (for example, the records between 1 and 2 pm) to see if there are any differences: SMS that were sent but not charged to the user for whatever reason that may be happening.

The columns I will be using to compare are the remitent's phone number and the exact date the SMS was sent. An issue here is that dates usually are the same on both sides, but in many cases differ by 1 or 2 seconds.

I have, so far, two alternatives to do this:

(PL/SQL) Create two tables where i'm going to temporarily store all the records of that 1hour sample. One for each of the main tables. Then, for each distinct phone number, select the time of every SMS sent from that phone from both my temporary tables and start comparing one by one using cursors. In this case, the procedure would be ran on the server where one of the sources is so the contents of the other one would be looked up using a dblink.

(sqlplus + c++) Instead of storing the 1hour samples in new tables, output the query to a text file. I will have two text files, one for each source. Then, open the first file and load all of it's content on a hash_map (key-value) using c++, where the key will be the phone number and the value a list of times of SMS sent from that phone. Finally, open the second file, grab each line (in this format: numberX timeX), look for numberX's entry on the hash_map (wich will be a list of times) and then check if timeX is on that list. If it isn't, save it somewhere to finally store it on a "uncharged" table (this would also be the final step on case 1)

My main concern is efficiency. These samples have about 2 million records on each source, so just grabbing one record on one side and looking it up on the other would not be possible. That's the reason I wanted to use hash_maps

Which do you think is a better option?

答:
If the databases are on the same server, you can simply run a query against both databases.

If not, you could use Oracle Database Gateways (if you have it) to connect to both, and similarly do the comparison.


问:
How common are generic-case exponential time algorithms in production software?
I know that exponential time algorithms should generally be avoided but are sometimes necessary. A case being the Traveling Salesman. How common are such algorithms in production software? Are these cases typically necessary or a result of rush jobs? I understand that many can be solved with a good heuristic. What is typically done with those that cannot?</p>

答: Programming language interpreters are worse than exponential time (in the length of their input, i.e. in the length of the program they're interpreting), and they are quite common. Another example is automatic theorem proving / constraint solving / sat solving / integer linear programming. And yet another example is symbolic differentiation as implemented in e.g. Maple/Mathematica (although it is possible to do symbolic differentiation in linear time if you're allowed to share subexpressions between nodes).</p>


问:
Where do you turn for code base improvement on a multi-project scale?
Are there resources out there for a programmer with a large code base to have professional alalysis performed for the goal of finding the areas of most needed improvement?

Logic/Reason tells me there's a limit to what a code review question can absorb, and also that the amount of work involved is not something that should need be free.

答:
While 5 years old, this article is a great start:

http://msdn.microsoft.com/en-us/library/bb896741.aspx

If you want a professional review of your code base, you can find many consulting groups that will do software reviews for you.  Such services tend to not be cheap by any means, but they can save you a lot of trouble in the long run by pointing out potential issues that will later cause you extra work or maintenance headaches.


答:
My perspective on this is to understand that what I need to know to do a task is often going to be a combination of research and applying it.  I may not know all of what to do but I can figure it out usually.  At least that is my perspective though there is something to be said for understanding how to play the game that can exist in some cases like interviews.  Some people may memorize a hundred answers to try to handle various programming problems but others may just remember what the heuristic was and the general outline of what to do and correct themselves as they go.  Technology changes enough that as I get comfortable with one thing up comes something new to add to my list of things to learn.

If you believe you are too much of a perfectionist, it may be worthwhile to see a therapist or counselor to try to work through this.  I'm not saying all perfectionists need help, but for those that want it, it could be a very good idea.


答: Does any part of your code cause you pain when you see it again or change it? If so, then I suggest you take those portions of your code and research how people have solved the problems you are having with it. If you keep doing this over and over again you'll eventually get better at spotting weak points as you are designing and developing the code. Over time you'll have a dramatically improved code-base that you'll (hopefully) feel better about, regardless of how you feel about it right now.</p>

Title: Where do you turn for code base improvement on a multi-project scale?

Body:
Are there resources out there for a programmer with a large code base to have professional alalysis performed for the goal of finding the areas of most needed improvement?

Logic/Reason tells me there's a limit to what a code review question can absorb, and also that the amount of work involved is not something that should need be free.


答:
Here's a very efficient way to compare two queries (generalized solution for the problem of comparing two tables efficiently):

```<code>SELECT * FROM
(
  SELECT foo1 col1, foo2 col2 FROM ...
  UNION ALL
  SELECT bar1 col1, bar2 col2 FROM ...
) t
GROUP BY col1, col2
HAVING COUNT(*) = 1
</code>```

This query takes two sub-queries that are expected to be identical, and the output is the rows that are only in one of the queries. In other words, if the two sub-queries return identical rows, the output should be empty.

I needed to compare two large data sets in the past, where performance was an important concern, and this was by far the fastest method I found.

You mentioned the timestamps may have a few seconds difference. To hide that noise, I recommend to use some kind of date rounding, but I don't know the syntax for that.

Title: Alternatives for comparing data from different databases

Body:
I have two huge tables on separate databases. One of them has the information of all the SMS that passed through the company's servers while the other one has the information of the actual billing of those SMS.

My job is to compare samples of both of these tables (for example, the records between 1 and 2 pm) to see if there are any differences: SMS that were sent but not charged to the user for whatever reason that may be happening.

The columns I will be using to compare are the remitent's phone number and the exact date the SMS was sent. An issue here is that dates usually are the same on both sides, but in many cases differ by 1 or 2 seconds.

I have, so far, two alternatives to do this:

(PL/SQL) Create two tables where i'm going to temporarily store all the records of that 1hour sample. One for each of the main tables. Then, for each distinct phone number, select the time of every SMS sent from that phone from both my temporary tables and start comparing one by one using cursors. In this case, the procedure would be ran on the server where one of the sources is so the contents of the other one would be looked up using a dblink.

(sqlplus + c++) Instead of storing the 1hour samples in new tables, output the query to a text file. I will have two text files, one for each source. Then, open the first file and load all of it's content on a hash_map (key-value) using c++, where the key will be the phone number and the value a list of times of SMS sent from that phone. Finally, open the second file, grab each line (in this format: numberX timeX), look for numberX's entry on the hash_map (wich will be a list of times) and then check if timeX is on that list. If it isn't, save it somewhere to finally store it on a "uncharged" table (this would also be the final step on case 1)

My main concern is efficiency. These samples have about 2 million records on each source, so just grabbing one record on one side and looking it up on the other would not be possible. That's the reason I wanted to use hash_maps

Which do you think is a better option?

Body:
Here's a very efficient way to compare two queries (generalized solution for the problem of comparing two tables efficiently):

SELECT * FROM
(
  SELECT foo1 col1, foo2 col2 FROM ...
  UNION ALL
  SELECT bar1 col1, bar2 col2 FROM ...
) t
GROUP BY col1, col2
HAVING COUNT(*) = 1

This query takes two sub-queries that are expected to be identical, and the output is the rows that are only in one of the queries. In other words, if the two sub-queries return identical rows, the output should be empty.

I needed to compare two large data sets in the past, where performance was an important concern, and this was by far the fastest method I found.

You mentioned the timestamps may have a few seconds difference. To hide that noise, I recommend to use some kind of date rounding, but I don't know the syntax for that.


问:
Why has the accessor methods from the JavaBean specification become the standard for Java development?
The JavaBeans Specification describes a JavaBean as

A Java Bean is a reusable software component that can be manipulated visually
  in a builder tool

Since the majority of the lines of code that are written seem to have nothing to do with being manipulated visually in a builder tool, why has the JavaBean specification been the "way" to write object oriented code?

I would like to forgo the traditional getter/setter in favor of Fluent Interfaces all throughout the code, not just in builders but fear doing so since this is traditionally not the way way object oriented code is written in Java.

答:
JavaBean style accessors have proven to be a good match for all kinds of scenarios that are similar to the original "builder tool" scenario in one core point: components are being passed around and manipulated by generic containers and tools as well as application code. In an app server you have service components to which an EJB or Spring container adds transactions and dependency injections, persistent domain models to which an ORM adds lazy loading and change detection, and which can be serialized to XML by a library without any specific code.

Accessors provide a common API that is very flexible in how the component can be used - it does not proscribe an order of operations. Each accessor call is independant of others and they all follow the same pattern, so you can easily add generic layers that add functionality without disrupting the intended usage pattern.

In contrast, fluent interfaces are often designed for one-shot use: the object is created, a chain of methods is called that ends with a method that produces a final result, and the object is then abandoned. There is much less flexibility (mostly in methods being optional) and genericality, but this is exactly the advantage: the interface forces you into an intended usage pattern, making it very easy to use.

So JavaBeans and fluent interfaces have advantages in different scenarios, and which you should use depends. And you could even combine both.


答:
Well, because the JavaBeans Specification you link to defines a convention for accessing properties, folks decided to take advantage of the convention and built frameworks around it.  Some of these frameworks, such as Hibernate, were quite useful and so became very popular.  So, because people used frameworks that were based on the JavaBeans spec, javaBeans became more and more ubiquitous, and more and more frameworks were built around them.

Fluent Interfaces are a great idea, but do they play well with Spring or Struts 2?  Beats me.

Title: Why has the accessor methods from the JavaBean specification become the standard for Java development?

Body:
The JavaBeans Specification describes a JavaBean as

A Java Bean is a reusable software component that can be manipulated visually
  in a builder tool

Since the majority of the lines of code that are written seem to have nothing to do with being manipulated visually in a builder tool, why has the JavaBean specification been the "way" to write object oriented code?

I would like to forgo the traditional getter/setter in favor of Fluent Interfaces all throughout the code, not just in builders but fear doing so since this is traditionally not the way way object oriented code is written in Java.


答:
There are actually quite a few levels of software engineering depending upon what the software you are building is doing.

NASA needs software to control manned shuttles in space so naturally the level of engineering process is much stricter than that of building a website to show pictures of rockets.

One of my co-workers that worked for NASA previously described their software engineering process as writing hundreds of pages of justification and hundreds of hours of meetings to justify writing a single line of code!

Don't misunderstand me because I'm not trying to sound disrespectful when I say this but even after all that cost of time, resources, and billions of dollars the space shuttle still blew up.

Even civil engineers know that no matter how much theory they put into a design something will eventually break it so they also need to develop contingency plans.

When building software the cost of it crashing rarely causes loss of life so it is much easier to quickly throw stuff out there and test drive it.  Let's agree that getting things done quickly results in weak code.  Even if this is always the case, seeing software in action is the best way for a developer to see where it is weak and needs to be made stronger versus where it is weak and still many times stronger than it needs to be to keep up with the load.

To sum up, Premature optimization is the root of all evil
or as my boss would always say Shipping is a feature!


答:
Lots of good answers here, but I think the comparison between Computer Science and Civil Engineering is flawed.

Strictly speaking, what professional software developers do is more like Software Engineering than Computer Science. A better analogy is that Computer Science is the Physics for Software Engineering. Similarly, Civil Engieering is a collection of simplifications and approximations of Physics for practically building stuff.

I imagine that Civil Engineers rarely have to take into account general relativity when going about their job. Much of Civil Engineering can be safely built in Newtonian Mechanics. Similarly, Software Engineering can be accomplished very successfully with a roughly approximate understanding of theoretical computer science.

The big difference is that bridges, skyscrapers, and other products of Civil Engineering are reasonably well understood things. Software engineers are often building novel constructs, or using novel methods to build well understood things. Software Engineering is FAR less mature than Civil Engineering, and that will likely continue to be true for the foreseeable future.

TL;DR: Theory and practice are different in Software Engineering just like they are everywhere else. The proper analogy is Software Engineering : Civil Engineering :: Computer Science : Physics. But in practice, it is a little more complex than that :)


问:
Strategy/algorithm to divide fair teams based on history
We are a group of people playing floorball together on a regular basis. Every session starts with the daunting task of dividing teams...

So what would be better than an application to pick teams automatically?

So, given a history of team-combinations and results, and a list of people showing up for this particular session, what would be a good strategy to find the optimal teams? By optimal, I mean teams as equal as possible.

Any ideas?

Edit: To make it clear, the data that I have to base the picking on, would be something like this:

```<code>[{ team1: ["playerA", "playerB", "playerC"],
   team2: ["playerD", "playerE", "playerF"],
   goals_team1: 10,
   goals_team2:  8
 },
 { team1: ["playerD", "playerB", "playerC"],
   team2: ["playerA", "playerE", "playerG"],
   goals_team1:  2,
   goals_team2:  5
 },
 { team1: ["playerD", "playerB", "playerF"],
   team2: ["playerA", "playerE", "playerC"],
   goals_team1:  4,
   goals_team2:  2
 }]
</code>```

答:
Depending on how much time you have, start the first few sessions by randomly selecting team captains, and have a draft before each game. Keep track of which pick a players goes. Earlier picks get higher ratings:

Round #1 = 8 pts, Round #2 = 6 pts, Round #3 = 4 pts, etc

Winning a game = 5 pts

All of this will depend on number of players per team. The total points may need to be converted to a daily or game average if there is a large discrepancy in participation. You may also award a team for a larger margin of victory.

Players who were selected early and played on a winning team get the most power points.

Then let the computer do the drafting (selecting of teams) by balancing the power points for each team and putting teams with near equal ratings against one another. Players who get selected early, but continue to play on losing teams will drop in the rankings.


答:
Two million records shouldn't be that big a deal, especially if phone number is indexed.  So your time is probably more important than the query time.  Heck, I would probably create a table and import all the records from one database to the other if I couldn't otherwise reference both in one query.

So, I'll assume you can reference both tables in one query.

The logic for matching within the 2 second window is somewhat tricky.  For example what if there was an SMS at 12:00:01 and 12:00:05 and a bill for 12:00:03?  Really, one of the two hasn't been billed.

So what you really want as a first step is to match SMS message count and messages billed count for a phone number.  Later you can figure out which one wasn't billed (or possibly not have enough information to do so precisely, as in my example).

We can do that:

```<code>SELECT A.PhoneNumber,SentCount,BilledCount
FROM
     (SELECT SentMessages.PhoneNumber, Count(SentMessages.SentDate) as SentCount
        FROM SentMessage
    GROUP BY SentMessages.PhoneNumber) as A JOIN
      (SELECT BilledMessages.PhoneNumber, Count(BilledMessages.BilledDate) as BilledCount
        FROM BilledMessages
    GROUP BY BilledMessages.PhoneNumber) AS B
          ON A.PhoneNumber=B.PhoneNumber
       WHERE SentCount>BilledCount
</code>```

And we might as well run this on the entire table as a sample - except that maybe some messages aren't actually supposed to have been billed yet, so we don't want those.  That's outside the scope of the question anyway.

Body:
Two million records shouldn't be that big a deal, especially if phone number is indexed.  So your time is probably more important than the query time.  Heck, I would probably create a table and import all the records from one database to the other if I couldn't otherwise reference both in one query.

So, I'll assume you can reference both tables in one query.

The logic for matching within the 2 second window is somewhat tricky.  For example what if there was an SMS at 12:00:01 and 12:00:05 and a bill for 12:00:03?  Really, one of the two hasn't been billed.

So what you really want as a first step is to match SMS message count and messages billed count for a phone number.  Later you can figure out which one wasn't billed (or possibly not have enough information to do so precisely, as in my example).

We can do that:

SELECT A.PhoneNumber,SentCount,BilledCount
FROM
     (SELECT SentMessages.PhoneNumber, Count(SentMessages.SentDate) as SentCount
        FROM SentMessage
    GROUP BY SentMessages.PhoneNumber) as A JOIN
      (SELECT BilledMessages.PhoneNumber, Count(BilledMessages.BilledDate) as BilledCount
        FROM BilledMessages
    GROUP BY BilledMessages.PhoneNumber) AS B
          ON A.PhoneNumber=B.PhoneNumber
       WHERE SentCount>BilledCount

And we might as well run this on the entire table as a sample - except that maybe some messages aren't actually supposed to have been billed yet, so we don't want those.  That's outside the scope of the question anyway.


问:
Is dependency injection by hand a better alternative to composition and polymorphism?
First, I'm an entry level programmer; In fact, I'm  finishing an A.S. degree with a final capstone project over the summer. In my new job, when there isn't some project for me to do (they're waiting to fill the team with more new hires), I've been given books to read and learn from while I wait - some textbooks, others not so much (like Code Complete). After going through these books, I've turned to the internet to learn as much as possible, and started learning about SOLID and DI (we talked some about Liskov's substitution principle, but not much else SOLID ideas). So as I've learned, I sat down to do to learn better, and began writing some code to utilize DI by hand (there are no DI frameworks on the development computers).

Thing is, as I do it, I notice it feels familiar... and it seems like it is very much like work I've done in the past using composition of abstract classes using polymorphism. Am I missing a bigger picture here? Is there something about DI (at least by hand) that goes beyond that? I understand the possibility of having configurations not in code of some DI frameworks having some great benefits as far as changing things without having to recompile, but when doing it by hand, I'm not sure if it's any different than stated above... Some insight into this would be very helpful!

答:
I am not an expert as I only started using DI in the past couple of years, but a few of the useful themes/functionalities of DI containers that I've noticed are (which I don't  think of as products of composition/polymorphism (but I may stand to be corrected on that):

central hub of object creation

provide singletons on a per thread basis

aspect oriented techniques such as interception


问:
Is comparing cloud computing to main frames a bad analogy?
They both can be seen as centralized processing, but from a developer's perspective is it returning us to the days when access to computers you could program yourself were limited and expensive? To me that was the problem the PC solved.

Heard this on http://thisdeveloperslife.com/ 1.0.6 Abstraction.

答:
The whole thing about the cloud is that it should be decentralised- one datacentre goes down? No problem, the app is running in five other places too. It really doesn't care about physical hardware.

The "traditional" model for serving websites is that you pay for a server or a bunch of servers in a datacentre somewhere. You give the hosting company money and they give your computers a home and/or provide some maintenance. Every user who accesses your site does so by going to that server.

That is a fairly centralised situation right there.

The advantage of a cloud setup is that your site or service is now hosted on virtual machines wherever you need them to be. To me that is less centralised. Admittedly the code isn't running on your local machine and the data isn't being stored on your local machine, but if that is the only place you're running code or storing data then that's a kind centralisation too.

The way it is perhaps more like mainframes is the pay-as-you-use approach. Again if you compare that with traditional web hosting approach you aren't paying the background running and rental costs of having a server at someone's server farm, so actually relative to that it can represent fairly good value.

On the whole I would say that the cloud is neither centralising nor particularly similar to a mainframe. Maybe the approach of storing your data on a server far from your own machine is more mainframe-like, but that isn't really something to do with cloud computing, that's more to do with how developers design applications now. They could be doing that with a few physical servers of their own as easily as using one of the cloud storage services.


答:
At first blush, your second option is probably going to be superior.

Here's my line of thinking and assumptions.

0) I'm assuming you don't have a massive DB system sitting idly by waiting for a query like this to justify its purpose.

1) You're likely going to have run this multiple times.  If nothing else, once discrepancies in the bill processing have been resolved, this audit process will be needed to validate the fixes.

2) Parallel operations will be key in getting reasonable run times.  The second option you suggest will allow you to break things out into chunks of individual "sent" listings and "billed" mappings.  Those chunks can be farmed out to distributed clients for faster processing time.

3) C++ code will give you more options in handling the time discrepancies and subsequent (re-)processing of those entries.


答:
I was a mechanical and manufacturing engineer before I discovered some 20 years ago that my aptitudes lay in software. I sympathise with many of the elements which you have laid out.

I suspect that the true nature of the problem is about how we get things done. We've now got ten or so years of agile development under our collective belts, and the message is clear. Don't progress by layers; progress by features. Sure - there will be projects when you need to progress by layers (e.g. build your network stack before your web server) but for the vast majority of real-world projects, we have learned the lesson that delivering working features, one or a few at a time, is much more effective building huge untested theories, and then trying to implement them.

So let's take your hut example (I usually talk of making a bridge by throwing a log across a stream vs. a kilometer long suspension bridge... whatever!), and bring it to the world of software engineering. The main difference I see is that in software, most of the work is of a scale that it doesn't need big up-front modelling to succeed. The beginner's mistake is often to assume that things need more of this than they actually do, and for most of us, having made that mistake a few times, we're chary of making it again too often.

No argument - there are projects that need to begin with a committee of 17 software architects. In truth they are about as rare as 20 carat diamonds.


答:
Formal theory assumes that you can accurately plan everything in advance like a manufactured product, that software will exist indefinitely within the same environment, and that solving a general abstract problem is always the goal.  It assumes a 4D software-as-a-product lifecycle: design, develop, deploy, done.  Formal theory is about solving the problem of software design using analysis, abstraction, generalization, and predicting future change.  This is good if you have a well-defined problem in a straightforward domain that's easily analyzable, predictable, and fairly static.

Practical programming is about solving the right problem (not that of software design) in the right way right now, so that your coworkers can do their jobs better/faster/at all, or so that revenues can flow in to the company.  Much software is not like a product, never 'done', but more like a living thing, that begins highly-specialized for one ecological niche, and may have a widely-variable lifespan during which it needs to solve new, unforseen problems in a wide variety of ever-changing environments.  In the business world, with politics and legalities and competition and ever-changing organizations, structures, and trends, the requirements are often ambiguous, convoluted with all kinds of special cases, poorly-defined, and subject to rapid unexpected change.  They're not analyzable, predictable, or static, and often not logical or reasonable.  The software is as likely to be irrelevant in 2 weeks as to be still in use in 20 years.  It comes into the world not knowing much or able to do much, and needs to be nurtured, groomed, and trained throughout its lifetime to grow up strong, flexible, and able to adapt to its ever-changing environments and new problems.  If you neglect it after birth, it will go feral if it survives long enough, and cause pain and suffering, solving problems with blunt force.

Formal theory doesn't address the needs of much real-world business software.  It tricks us into believing that software can be designed and done.  That it's a product that can be occassionally fixed, polished, or have things tacked on, but not a living thing that needs to be raised properly with constant care and attention throughout its lifetime.  So we end up with really ugly feral legacy code, but formal theory probably wouldn't have helped with that.

That all sounds pretty negative, but in reality I love using formal theory.  A beautiful design always brings a smile to my face.  However, that's mostly in my hobbyist programming that isn't subject to the vicissitudes of business.  At work, I mostly deal with organic code and just hope that I can give it enough attention that it will grow up right, make me proud, and not be obnoxious and rude to others who have to deal with it.


答:
The fundamental idea in DI is simply to push dependencies into objects, rather than letting them pull dependencies from outside. This was also called "inversion of control" earlier. This allows one to control dependencies much better, and - last but not least - to write code which is easy to unit test.

DI frameworks only build on top of this idea, and (partly) automate the often tedious part of wiring object dependencies together. This may otherwise require a significant amount of code in a larger project when done by hand.

To define dependencies, apart from external configuration files, it is also possible to use code annotations nowadays, e.g. in languages like Java and C#. These may bring the best of both worlds: wiring dependencies in a declarative style, but right within the code itself, where it logically belongs to. To me, the possibility of changing dependencies without having to recompile is not that valuable, as it is rarely done in real life (apart from some special cases), but introduces an often artifical separation of dependencies from the classes and objects defined within the code.

To return to your title question, DI is not an alternative to composition nor polymorphism; after all, it is made possible by these two.

Title: Is dependency injection by hand a better alternative to composition and polymorphism?

Body:
First, I'm an entry level programmer; In fact, I'm  finishing an A.S. degree with a final capstone project over the summer. In my new job, when there isn't some project for me to do (they're waiting to fill the team with more new hires), I've been given books to read and learn from while I wait - some textbooks, others not so much (like Code Complete). After going through these books, I've turned to the internet to learn as much as possible, and started learning about SOLID and DI (we talked some about Liskov's substitution principle, but not much else SOLID ideas). So as I've learned, I sat down to do to learn better, and began writing some code to utilize DI by hand (there are no DI frameworks on the development computers).

Thing is, as I do it, I notice it feels familiar... and it seems like it is very much like work I've done in the past using composition of abstract classes using polymorphism. Am I missing a bigger picture here? Is there something about DI (at least by hand) that goes beyond that? I understand the possibility of having configurations not in code of some DI frameworks having some great benefits as far as changing things without having to recompile, but when doing it by hand, I'm not sure if it's any different than stated above... Some insight into this would be very helpful!