答:
Yes, that's a fair assessment and really isn't too far from Rails' Active Record pattern. MVC is a UI pattern, and doesn't really care how you structure your domain layer - just that you keep it separate from your View and the UI action handlers (the Controller).

With that said, what you're describing would probably fall under an anemic domain anti-pattern - that's fine for an awful lot of applications, but you should watch out for the pitfalls as well. The main one being the tendency for the Controller to pick up the slack and start absorbing logic that should belong to the domain (such as validation or orchestration). Or the growth of a service layer that lives beside the domain and contains all of the logic.

Title: Is it fair to call a database or a document a "Model", as in Model/View/Controller?

Body:
Part of my job is working on line-of-business applications built around client-side databases, such as Access or FoxPro.  Other times these local LOBA's have direct document access, such as an exact one-to-one mapping between a logical object an an XML node or references to bookmarks in Word Documents or ranges Excel spreadsheets.

While the code is about as messy as one would expect, it's usually fairly stable and the platforms these applications are built upon all have one thing in common: they translate program data to physical storage directly and transparently, from the programmer's point of view.

Would it be fair to refer to the database or document in one of these LOBA's as a "Model", when referring to the Model/View/Controller separation of concerns?  Or would it be improper to call separation of UI and business-logic MVC unless we make intermediate objects that in turn map to either the UI or the database?


问:
Should Junior Programmers be involved as code reviewers in the projects of Senior Programmers?
One of my team members, a junior programmer, has impressive programming skills for his level of experience.

And during code reviews, I believe in emphasizing learning, not pointing out mistakes.

But should junior programmers be involved in code reviews for more senior programmers? Or should code reviews be attended only by programmers with corresponding experience?

答:
Junior programmers should absolutely be performing code reviews for their senior colleagues!

However, they shouldn't be the only reviewer.  Pair them up with a more experienced developer per code review.

There are a myriad of benefits:

The author will be forced to explain more of their code.  Talking through your code is one of the best ways to find issues with it, or better ways of doing it.

The author will find weaknesses in their code.  The junior dev is more likely to be confused by some of the more advanced chunks.  Frequently, these are "too tricky" for their own good, and could benefit from simplification.

The junior dev will learn better coding practices.  Code reviews are an opportunity to teach by example.

The junior dev will be a more effective code reviewer.  Code reviewing is hard.  The more experienced everyone is with code reviews, the faster and more effective code reviews become.

The junior dev will have deeper knowledge of the code base.  Be selfish!  By pulling the junior devs on early, you will be able to hand it off to them sooner.

The junior dev will feel more involved.  The junior dev will start to see "senior" code (and their colleagues) as less foreign and intimidating.  This is a tremendous and often overlooked benefit of code reviews.

The junior dev is a fresh set of eyes.  They're not as indoctrinated as someone who has been working on the code base for a long period of time.  The junior dev is more likely to point out different ways of accomplishing things as they ask questions.  Don't shrug off their wilder comments without at least some consideration!

The senior devs are held accountable.  I've frequently seen situations where senior devs tend to gloss over each others' code (trust, laziness, etc).  An extra set of eyes helps discourage it.

The downside to consider is that all parties involved will spend a fair amount of time performing code reviews.  Thus, it can be a bit of a difficult sell to management.  The benefits completely outweigh the slower pace, though.

ContentLicense: CC BY-SA 3.0


问:
Internal exposure of implementation details on inheritance
I'm reading the "Effective Java" book which suggests to favor composition over inheritance. The example it gives shows something like this:

```<code>public class InstrumentedHashSet<E> extends HashSet<E> {
     // The number of attempted element insertions
     private int addCount = 0;

     public InstrumentedHashSet() { }

     public InstrumentedHashSet(int initCap, float loadFactor) {
         super(initCap, loadFactor);
     }

     @Override public boolean add(E e) {
         addCount++;
         return super.add(e);
     }

     @Override public boolean addAll(Collection<? extends E> c) {
         addCount += c.size();
         return super.addAll(c);
     }

     public int getAddCount() {
         return addCount;
    }
}
</code>```

This presents a problem because the implementation of addAll in HashSet uses the method add. So, when calling addAll each new elements is counted twice - once in addAll and once in add.
In the next chapter it is explained that if we choose to allow extending our class we should explicitly explain the inner working of our methods that use overridable methods (meaning - in the addAll documentation we should specify its use of add and commit to this implementation forever).

I think that a better practice would be to decide that each method that is both an overridable, API method and also used by inner implementation should be extracted to an inner, private method. So Our ideal HashSet would have these methods:

```<code>public class HashSet<E> implements Set<E> {
     // Ignore irrelevant code

     @Override public boolean add(E e) {
         // The new add implementation only wraps the innerAdd method
         return innerAdd(e);
     }

     @Override public boolean addAll(Collection<? extends E> c) {
        // Do the same logic as before but use innerAdd instead of add
     }

     private boolean innerAdd(E e) {
         // The original add logic will be moved to here
     }
}
</code>```

This way we encapsulate inner implementation and allow extending the class without fearing to override a method which is used by inner implementation. Of course that we can use the original add as before because by calling super.add(e) we de-facto use the innerAdd so that's not a problem.

I would like to know whether this might be a good practice (not for HashSet<E> which is already committed to the code that use it, but to new classes that are meant to be overriden)?

答:
Yes, they could have done that, but I think you forget the crucial part: The fact that "addAll" does not rely on "add" has to be explicitly documented in the class' public interface . The problem is that doing this wouldn't too elegant. If you add implementation details to your public interface you break the abstraction principle in that class.

Look at this relevant excerpt from that particular chapter:

"This 'self-use' is an implementation detail, not guaranteed to hold
  in all implementations of the Java platform and subject to change from
  release to release".

In my opinion the takeaway here is that inheritance can easily break encapsulation and lead to insidious issues like this one, hence his opinion that Java classes should haven been made final by default. That way you would need to make a conscious decision when making a class inheritable.


问:
Why is asynchronization so popular in Javascript?
Asynchronized programming seems to be natural in Javascript - it is the "first choice" to do many things.

But in most other programming languages, asynchronization is more like a second choice rather than first choice.

What makes asynchronizated programming so popular and natural to Javascript?

答:
Especially when used in a browser environment, there are no threads (let's ignore the rather new WebWorkers for now) available - all JS runs in a single thread which is usually the same one that also handles e.g. rendering of the page.

So performing actions in a blocking manner is simply not an acceptable option - especially since most actions that involve IO in JavaScript usually cause network IO which, unlike disk IO, is usually rather slow and thus blocking everything until a request finished is not acceptable.


问:
Defining work days and work time
I'm working on development of SMS parking software, and I'm stuck at one point for a month... I need to implement periods of payment (or work time, of a work day, if you will). Here's the problem:

For an example, traffic wardens work from Monday to Saturday. From Monday to Friday, the work times are from 07:00 to 21:00, and on Saturday, the work time is from 07:00 to 14:00. The project request was, that the customer can pay parking by SMS unlimited, which I did, but didn't implement this logic. I started with making a table for this periods of payment, it consists of: dayofweek (INT, for use with mysql function DAYOFWEEK, to tell me which day in week is the current date), work_start and work_stop (DATETIME, for defining starting and ending the work day), but I'm unsure if I should use DATETIME, beacuse of the date, or should I use only TIME.

The idea is this:

If you send an SMS, at 20:50, Monday, it should be valid until 07:50, Tuesday (it's payed by the hour). Extending the time of payment, regarding the work time in week. Currently, it works with extending time by the hour without this rule. Really would use some help, or some ideas, I'm stuck with this for quite some time...

答:
You need your program code logic to implement paid time periods.  If you allow for payment on one day to carry over to the next, you really want to have two records of "paid time."

(After all, what happens when someone pays on Friday Dec 29th, and doesn't pick up their car until Tuesday Jan 2nd, after two weekends and a holiday in a separate year?  And the car park wants to know their revenue by month, quarter, and year?)

When you serialize the information to a database, you'll want two tables anyway.  "SMS payments" and "parking time", which allows for future payments for other things (i.e., SMS to pay the higher rate for a ticket) as well as legal parking for other reasons (employee/resident guests, promotional coupons, etc.)

Alternately, if the parking garage has a slick system for tracking what times cars enter and leave, you can just record the events, extract a bill, and compare it to the record of payments, be they by SMS or not.  One "SMS payment" would give a credit for 60 minutes (or 3600 seconds, depending on your resolution), and if the car has recorded time without payments they get the second, higher, rate for not paying on time.

Title: Defining work days and work time


问:
Explanation of the definition of interface inheritance as described in GoF book
I am reading the first chapter of the Gof book. Section 1.6 discusses about class vs interface inheritance:

Class versus Interface Inheritance

It's important to understand the difference between an object's class
  and its type. An object's class defines how the object is
  implemented.The class defines the object's internal state and the
  implementation of its operations.In contrast,an object's type only
  refers to its interface--the set of requests on which it can respond. An
  object can have many types, and objects of different classes can have
  the same type.

Of course, there's a close relationship between class and type. Because
  a class defines the operations an object can perform, it also defines
  the object's type . When we say that an object is an instance of a
  class, we imply that the object supports the interface defined by the
  class.

Languages like c++ and Eiffel use classes to specify both an object's
  type and its implementation. Smalltalk programs do not declare the
  types of variables; consequently,the compiler does not check that the
  types of objects assigned to a variable are subtypes of the variable's
  type. Sending a message requires checking that the class of the
  receiver implements the message, but it doesn't require checking that
  the receiver is an instance of a particular class.

It's also important to understand the difference between class
  inheritance and interface inheritance (or subtyping). Class inheritance
  defines an object's implementation in terms of another object's
  implementation. In short, it's a mechanism for code and representation
  sharing. In contrast,interface inheritance(or subtyping) describes when
  an object can be used in place of another.

I am familiar with the Java and JavaScript programming language and not really familiar with either C++ or Smalltalk or Eiffel as mentioned here. So I am trying to map the concepts discussed here to Java's way of doing  classes, inheritance and interfaces.

This is how I think of of these concepts in Java:

In Java a class is always a blueprint for the objects it produces and what interface(as in "set of all possible requests that the object can respond to") an object of that class possess is defined during compilation stage only because the class of the object would have implemented those interfaces. The requests that an object of that class can respond to is the set of all the methods that are in the class(including those implemented for the interfaces that this class implements).

My specific questions are:

Am I right in saying that Java's way  is more similar to C++ as described in the third paragraph.

I do not understand what is meant by interface inheritance in the last paragraph. In Java interface inheritance is one interface extending from another interface. But I think the word interface has some other overloaded meaning here. Can some one provide an example in Java of what is meant by interface inheritance here so that I understand it better?

答:
For your 2nd question about interface inheritance:
Interface inheritance is logically similar to class inheritance, but the real reason it is provided is for providing flexibility. For example, consider interfaces of concurrent utility package in java. At top level we have executor interface which has method execute exposed and another interface named executorService extends executor interface. Now if you are not interested in features provided by executorService then you can go for implementing executor Interface, otherwise you just need to implement executorService interface and you will have all features of parent interface. This design can be observed in most of the java packages, be it Collection framework or Concurrent utilities.


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答: A high SO score can get your foot in the door at plenty of jobs.  But it's always the interview that makes or breaks you.  If you're bad at interviewing (like me), then a high SO score will get you the interview but not the job.</p>

ContentLicense: CC BY-SA 2.5


问:
How should I deal with problems with completed stories in agile
I am new to Agile and scrum and want to ask few things.

Suppose I havetwo user stories 1, 2

Suppose I finished story 1 in sprint 1 but while doing sprint 2 I did something which breaks something so that my things in user story 1 broken and I need to spend more time on that again.

What do I need to do for that case?

答:
Either:

1. You knew you needed to modify Story 1 as part of implementing Story 2. No problem. Add tasks (under Story 2) as needed to do that work, and consider it part of the Story 2 scope.

2. You accidentally broke Story 1 during Story 2 works. Stuff happens. File it as a bug and follow through as you would any other bug.


问:
Which child process will inherit threads of parent process?
What happens when one process has child threads and a child process, will child process inherit all child threads of parent process?

Assume OS is Linux. Let it be Java Threading model.

答:
The short answer is that the child process inherits one thread from the parent, namely the thread that had called fork.

This is from the Posix/Pthreads point of view. Linux usually tries to stay close to Posix so this also mostly applies to Linux, although Linux may have some features outside of Posix that behave differently.

One might ask why just one thread is inherited instead of all. Apparently an alternative call forkall was considered and rejected for Posix. At first glance this seems like it might be useful. Actually, though, it's easy to see how it could lead to intractable bugs. Consider a case where thread A has opened a file and is about to issue a write to it. At that precise moment, thread B calls forkall. Since thread A is duplicated in the child process, and (in general) all open files are duplicated in the child process, thread A and its clone in the child both write to the open file. This is most likely an error.

Even having the child process inherit just a single thread is problematic. See this stackoverflow question and a good blog article that it links to. The upshot is that there are issues but they can be dealt with.

The Solaris Threads model, which predates Pthreads, had a different policy regarding fork and threads. By default the fork system call cloned all threads whereas the fork1 system call cloned just the calling thread. Worse, when Pthreads was implemented in Solaris, the way the program was linked defined whether it was using Solaris threads or Pthreads semantics, which determined the semantics of fork. Very confusing.

Finally, you had asked about Java threads. The way a new process is forked in Java is using the java.lang.Runtime.exec() method. This fuses the functions of Posix fork and exec. In general, the subprocess need not be running a Java Virtual Machine (JVM), so none of the Java threads from the parent exist in the child. Even if the child does end up running a JVM, that JVM starts fresh by running the main() method of the start-class, and it doesn't inherit any threads from the parent.


问:
Do pointers really exist in Java?
I read quite a few resources on the internet and now I am quite confused about the existence of pointers in Java.

Some claim that there are pointers and some claim that there is no such concept. So what is the truth?

答:
Java does have pointers. Any time you create an object in Java, you're actually creating a pointer to the object; this pointer could then be set to a different object or to null, and the original object will still exist (pending garbage collection).

What you can't do in Java is pointer arithmetic. You can't dereference a specific memory address or increment a pointer.

If you really want to get low-level, the only way to do it is with the Java Native Interface; and even then, the low-level part has to be done in C or C++.

Title: Do pointers really exist in Java?


问:
In an MVC architecture, how closely coupled are the Model and View to the Controller?
I've got an app which uses MVC, but I'm struggling a little as to how the controller should be architected. For example, the View is only viewing some subset of the model's data at once. However, I'm unsure as to exactly how this should be arranged. Is it normal for the View or Model to directly call functions on the Controller, for example? Through some sort of interface? Or are they totally encapsulated and never know about the Controller or each other?

Just as an edit; this is a custom app not written in any web framework, so I'm not looking for framework-specific details here and have the freedom to make my own choice.

答:
Here is a simple example of how MVC can be used in a typical Java Swing application ...

Let's say you have a Panel containing a Button and a TextField. When the Button is pressed, an event is fired, leading to some state change in the application. Once the state change is registered, the TextField becomes disabled.

This, then, would be the typical approach taken by a simple MVC application ...

The Controller registers itself as the listener of the View's events. When the Button is clicked, the View itself does not handle the event; the Controller does. The Controller is Swing specific as it must deal with Swing related events.

The Controller receives this notification and must decide who must handle it (The View or the Model). Since this event will change the state of the application, it decides to forward the information to the Model who is responsible for data and program logic. Some make the mistake of placing program logic in the Controller but in OOP, Models represent both data AND behavior. Read Martin Fowler on his take of this.

The message is received by the Model in the proper context. That is, it is completely void of any reference to Swing or any other GUI specific references. This message speaks to the Model and ONLY the model. If you find yourself importing javax.swing statements in the Model, you are not coding the Model correctly.

The Model then sets its state to 'disabled' and proceeds to notify any interested parties of this model change. The View, being interested in this event has already registered itself as an Observer of any model changes. Once the Model state change event is picked up by the View, it proceeds to disable its TextField. It is also legal for the View to get Read-Only information directly from its Model without having to go through the Controller (usually through a specific interface exposed by the Model for such activity)

By promoting such loose coupling between the Presentation and Business Logic and Data Layers, you will find your code is much more maintainable. As systems grow, so too will your approach to MVC. For example, Hierarchical MVC is an extension often used to link MVC triads together to form large enterprise wide systems without coupling subsystems together


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
That there is some mythical source of absolute best practices.

No deviation can ever be justified.

No document claiming to define something as a best-practice can ever be questioned.


问:
Pattern to use for different Stages in a software
I am developing a software for a laboratory to test some devices. To test each device there are multi subtests which should be done to reach to the final result.To perform a complete test, the software must pass Stage1 then automatically goes to Stage2 then Stage3 and so on until the whole test is finished. meanwhile the user can select to just have the Stage3 or Stage2 or any other Stages independently to be performed (which she selects that at runtime).
this is the thing I have done so far:

```<code>public class IronTestWorkFlow:ITestWorkFlow
    {
        private readonly List<ITestStages> _testStageses;

        public IronTestWorkFlow(List<ITestStages> testStageses )
        {
            if (testStageses == null)
            {
                throw new ArgumentNullException("testStageses");
            }
            _testStageses = testStageses;
        }
    }
</code>```

I am useing a DI container. But I don't know how to change the list of Stages in ITestWorkFlow at runtime.

Questions:

1- Am I designing this right?

2- If yes which pattern shall I follow to obey the principles and change the stages at runtime? and how can I do that?

答:
It would appear there are a myriad of patterns that may be employed here. One to consider is the State pattern if you must transition from one test to another automatically (each State must know how to transition its context to the next state, in your case, these states would be your specific lab tests if I understood the problem correctly)

or even some variant of Chain of Responsibility might be useful.

OwnerDisplayName: Mehrdad Kamelzadeh


问:
Programming to interface in Java
What is the real use of interfaces in Java? What is meant by programming to interfaces?

I heard these things several times but I don't know what it is and why it is used.

答:
One day, a junior programmer was instructed by his boss to write an application to analyze business data and condense it all in pretty reports with metrics, graphs and all that stuff. The boss gave him an XML file with the remark "here's some example business data".

The programmer started coding. A few weeks later he felt that the metrics and graphs and stuff were pretty enough to satisfy the boss, and he presented his work. "That's great" said the boss, "but can it also show business data from this SQL database we have?".

The programmer went back to coding. There was code for reading business data from XML sprinkled throughout his application. He rewrote all those snippets, wrapping them with an "if" condition:

```<code>if (dataType == "XML")
{
   ... read a piece of XML data ...
}
else
{
   .. query something from the SQL database ...
}
</code>```

When presented with the new iteration of the software, the boss replied: "That's great, but can it also report on business data from this web service?" Remembering all those tedious if statements he would have to rewrite AGAIN, the programmer became enraged. "First xml, then SQL, now web services! What is the REAL source of business data?"

The boss replied: "Anything that can provide it"

Title: Programming to interface in Java

Body:
One day, a junior programmer was instructed by his boss to write an application to analyze business data and condense it all in pretty reports with metrics, graphs and all that stuff. The boss gave him an XML file with the remark "here's some example business data".

The programmer started coding. A few weeks later he felt that the metrics and graphs and stuff were pretty enough to satisfy the boss, and he presented his work. "That's great" said the boss, "but can it also show business data from this SQL database we have?".

The programmer went back to coding. There was code for reading business data from XML sprinkled throughout his application. He rewrote all those snippets, wrapping them with an "if" condition:

if (dataType == "XML")
{
   ... read a piece of XML data ...
}
else
{
   .. query something from the SQL database ...
}

When presented with the new iteration of the software, the boss replied: "That's great, but can it also report on business data from this web service?" Remembering all those tedious if statements he would have to rewrite AGAIN, the programmer became enraged. "First xml, then SQL, now web services! What is the REAL source of business data?"

The boss replied: "Anything that can provide it"


答:
An interface is a simple contract.

The interface defines methods and you can call methods on any object that implements this interface. It does not matter which object this is.

Also an object can implement multiple interfaces and therefore you can see this as implementing different contracts.

By programming against the interfaces you do not depend on a certain class and can replace the implementation without changing the rest of you code.

As example:

If you use List in your application you can switch between LinkedList and ArrayList without changing your code.

Title: Programming to interface in Java

Body:
What is the real use of interfaces in Java? What is meant by programming to interfaces?

I heard these things several times but I don't know what it is and why it is used.


答:
You program to an interface because it's easier to handle. The interface encapsulates the behavior of the underlying class. This way, the class is a blackbox. Your whole real life is programming to an interface. When you use a tv, a car, a stereo, you are acting on its interface, not on its implementation details, and you assume that if implementation changes (e.g. diesel engine or gas) the interface remains the same. Programming to an interface allows you to preserve your behavior when non-disruptive details are changed, optimized, or fixed. This simplifies also the task of documenting, learning, and using.

Also, programming to an interface allows you to delineate what is the behavior of your code before even writing it. You expect a class to do something. You can test this something even before you write the actual code that does it. When your interface is clean and done, and you like interacting with it, you can write the actual code that does things.

Title: Programming to interface in Java


问:
MVC shared model different required fields on different type
I have a model called Car and depending on what type of Car the user select the view is presented differently. For example the user selects from a grid of different cars and depending if it is a Volvo or a Kia or a Ford the view must allow different fields to be editable. For example with a Volvo the color is editable and is mandatory but with a Kia it is not.

I would like to use the one Car class to bind the view but want the client side validation to pick up the required fields based on what type of car.

I want to go only to one Action method for the Update

what is a good way to approach this problem...? create a base class and inherit from it? will this give me binding problems..?

答:
The state of the fields are the domain of your model. The view should have absolutely no "smarts" within it in determining the enabled or disabled state of its widgets. All "logic" must be provided by the model itself. Binding should be done polymorphically within the model, not the view.

The view must be able to request this information in such a way that a polymorphic response is returned by the model.

for example, this method is fired by the Model when its state has changed. It provides its Observers information about the selected Car in a polymorphic manner ...

Class View {

```<code>// view registers itself as a listener of model changes ...
Model.addModelStateListener(this);

// model has changed ...
// Car instance can be a KIA, Ford or Volvo. Car is simply a common interface
// and each instance defines its state differently

public void modelChanged(Car instance){
    ColorWidget.value = instance.getColorState();
}
</code>```

}

Body:
The state of the fields are the domain of your model. The view should have absolutely no "smarts" within it in determining the enabled or disabled state of its widgets. All "logic" must be provided by the model itself. Binding should be done polymorphically within the model, not the view.

The view must be able to request this information in such a way that a polymorphic response is returned by the model.

for example, this method is fired by the Model when its state has changed. It provides its Observers information about the selected Car in a polymorphic manner ...

Class View {

// view registers itself as a listener of model changes ...
Model.addModelStateListener(this);

// model has changed ...
// Car instance can be a KIA, Ford or Volvo. Car is simply a common interface
// and each instance defines its state differently

public void modelChanged(Car instance){
    ColorWidget.value = instance.getColorState();
}

}


答: If you spend time getting 5-digit reputation on Stack Overflow then you probably know what you're doing. That, more than any numerical value, is what get you the jobs.</p>

Title: Will high reputation in Stack Overflow help to get a good job?

Body:
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?


问:
Is it fair to call a database or a document a "Model", as in Model/View/Controller?
Part of my job is working on line-of-business applications built around client-side databases, such as Access or FoxPro.  Other times these local LOBA's have direct document access, such as an exact one-to-one mapping between a logical object an an XML node or references to bookmarks in Word Documents or ranges Excel spreadsheets.

While the code is about as messy as one would expect, it's usually fairly stable and the platforms these applications are built upon all have one thing in common: they translate program data to physical storage directly and transparently, from the programmer's point of view.

Would it be fair to refer to the database or document in one of these LOBA's as a "Model", when referring to the Model/View/Controller separation of concerns?  Or would it be improper to call separation of UI and business-logic MVC unless we make intermediate objects that in turn map to either the UI or the database?

答:
I don't think it's really important how you would call this or that, as long as you get MVC separation of concerns in a correct way.

In my opinion, MVC as a term is only related to code, not to data it's processing. In your example, DB would be storage, while model is whatever in your code "opens" and "exposes" this storage to other parts of your program (ie. controller).


答:
At face value, since the official Java language specification specifically mentions pointers, then the answer is YES, pointers exist in Java.

So how do we explain the apparent contradictory opinions here?  Well, like many issues, the disagreement comes down to semantics.

The term "pointer" is strongly associated with the C/C++ concept of pointers, which are variables which explicitly store memory addresses, and which can be modified arithmetically to point to any arbitrary address.  In Java, pointers exist, but not as a first-class language concept.  Rather, pointers only exist as an implementation detail for References.  The spec says:

An object is a class instance or an array.

The reference values (often just references) are pointers to these
  objects, and a special null reference, which refers to no object.

It's also telling that accessing a null reference throws a NullPointerException, not a NullReferenceException.  So, clearly the Java designers were at least thinking in terms of pointers when they wrote the Java language spec.  (Although really it should be called a NullReferenceException; in my opinion the name of that exception leaks through the abstraction)

So, the answer is that Java References are "pointer-ish", in the sense that they are implemented in terms of pointers (just like most implementations of C++ references), but Java References provide a higher-level abstraction which restricts the programmer from manipulating the actual memory address.  Syntactically, a Java reference only gives you access to the members or methods of the pointed-to Object - not the memory location of the Object.

So yes, pointers exist in Java, for a certain value of "exist".  But it's probably not helpful to speak in terms of "pointers" when discussing Java language concepts.

Title: Do pointers really exist in Java?

Body:
I read quite a few resources on the internet and now I am quite confused about the existence of pointers in Java.

Some claim that there are pointers and some claim that there is no such concept. So what is the truth?


问:
Does MVC pattern negate other design patterns?
So usually when working with the MVC you have a controller that controls the input a model that process it and makes it ready for the user and a view that display the "result" to the user.

Now when creating this pattern you seperate the code into their relevant place. for instance the controller code goes into the controller, the gui code goes into the view and so on.

Now my question is if we look at all of the design patterns out there for instance the observer pattern. How would you apply such pattern to a code structure that already implements the MVC pattern? for that case many of the other patterns aswell such as composite, factory and command pattern?

Doesnt the structure of the MVC pattern make it harder to implement other good pratice design patterns?

答:
The MVC pattern is a composed pattern consisting of multiple patterns:

The Model uses the Observer pattern to keep the view(s) and controller updated.

You can find the strategy pattern in the view and the controller as the view is only concerned with the visual aspects and delegates all the interface behaviour to the controller

And you can find the composite pattern in the view if working with nested windows etc.

So to answer your question, the MVC already almalgamates quite a few design patterns and this raises the complexity as is not even mentioning adding more patterns.

** edit **

Kind of started reading up a little and found a little more information on the subject.

If you do need some more patterns or a different approach to MVC patterns their seems to be a whole family of patterns that either adapt, replace or add patterns to the existing MVC for all sorts of situations:

MVC,

MVA,

MVP,

PAC,

Model-Delegate


答:
No, because most design patterns don't dictate how the code should be organised. Instead they describe the roles that classes can have in a particular interaction and give common names to those roles to ease communication with other developers.

The fact that the MVC pattern suggests a certain organisation of the classes does not mean that you can't apply other design patterns within or across that organisation.

For example, within an MVC triad, you can use the Observer pattern to let Model classes inform the relevant View classes about updates to the Model. This is entirely within the structure of the MVC pattern, because the Model does not have any knowledge about which View classes it needs to inform, only that it should inform those classes that are registered (and they can be View classes, but equally well, they can be other Model classes).

In a similar way, you can also use the Abstract Factory pattern to create specific View classes based on parameters that the Controller should not care about (for example, if you have a separate View class for each supported language).

Title: Does MVC pattern negate other design patterns?

Body:
So usually when working with the MVC you have a controller that controls the input a model that process it and makes it ready for the user and a view that display the "result" to the user.

Now when creating this pattern you seperate the code into their relevant place. for instance the controller code goes into the controller, the gui code goes into the view and so on.

Now my question is if we look at all of the design patterns out there for instance the observer pattern. How would you apply such pattern to a code structure that already implements the MVC pattern? for that case many of the other patterns aswell such as composite, factory and command pattern?

Doesnt the structure of the MVC pattern make it harder to implement other good pratice design patterns?


答:
First thing you should note, that MVC is a UI-related pattern. It took me several years to get this pattern understood correctly. MVC also, is not a real pattern, it is more like a general approach, because various implementations exist.

For example, the Model-View-Presenter is an incarnation on MVC pattern with slightly changed responsibilities, very suitable for desktop applications. In any case, the presenter in this approach would implement an observer pattern, and the view is observable object. Moreover, usually, when the view is somehow complex, I would introduce a ViewData object, or so-called ViewModel, which contains the data being displayed and inputted by the user. That case view also becomes an observer for this ViewModel object.

In case of large desktop application, you couldn't stay with good code using only MVC pattern. There will be too much responsibility for each layer. That case MVC is just a top of the whole application. I would say a small example from own experience.

All business logic implemented by Commands, Commands returned by CommandFactory (factory pattern). There also orthogonal logic for commands, like checking access rights, and logging of business actions executed. This orthogonal part intensively uses Decorator pattern. In the middle of application there is a model of current data state, which is not a simply database-mapped model, but model that have behaviour related to business processes under the hood. This model is a bunch of Observable objects, which observer by the UI layer (MVP pattern). Exact object creation and lifetime is controlled by ServiceLocator/Dependency Injection patterns.

That said, when an application grows larger and larger and become more complex - you have to split it in parts, that are as independent as possible, so you could involve more people on a project. To reduce the complexity, and do not suffer from a NIH syndrome (Not-Invented-Here) there are plenty of patterns which give you a way if implementing a solution for typical design problems that is well understandable by other programmers.


问:
Reading CSV files located on a Linux server and updating the tables in a SQL Server database
I was wondering how we could ingest CSV files located on a Red Hat Linux server into SQL Server database tables.

I know we can write a stored procedure/bulk insert to read the files that are located on the same Windows server as SQL Server and update the database, but not sure how to do it when the files are present on a Linux server.

Any help would be greatly appreciated.

答:
The key for connecting to a MS SQL Server from arbitrary places is ODBC.

You are looking for some language that can handle reading a csv easily, and inserting the data back across ODBC.

There are several choices for ODBC.  If you are a Java shop, one can go and get the jdbc for SQL Server and connect to the database that way.  Have that .jar be part of your class path and connect away. This should probably be the option if you have people on high dictating technologies (java is a fairly safe one and you can always find or hire a java programmer).

Me?  I'm a perl guy at heart.  Crunching one data file and exporting it into another is a classic perl solution domain.

WIth perl, one would get DBI (docs) for the interface to a database layer, and then DBD::CSV (tutorial) to read the data from the csv file as if it was a database itself, and then DBD::ODBC to write out to an ODBC connection.  Installing perl modules through CPAN is fairly easy (though I do admit that I say that after having done it many, many times).

This could be done with Text::CSV instead.  However, there is a certain elegance in the DBD approach of writing a program to read from one arbitrary database (do any appropriate transforms on the data) and write to another arbitrary database.  If done right, and you find yourself wishing to copy data from another database at some point, it becomes a fairly minor change to the code (install the appropriate DBD driver for the database and read the data.

Taking a completely different approach that bends more into the sysadmin world than the programmer domain, one could move the data from the linux machine to the windows machine on a regular basis.

You could put the files on a samba share and mount them from windows.

Similar option to above, you could make the file available on a web server and then fetch and process it on windows.

With the appropriate packages, one could mount a windows share on linux (something along the line of mount -t cifs -o guest,uid=client_user,gid=users //192.168.1.100/share /path_to/mount  or //192.168.44.100/share   /path_to/mount   cifs   guest,_netdev   0 0 in /etc/fstab)

Instead of sharing linux to windows, or windows to linux, NAS (network attached storage) is an easy way to have a single server (not linux or windows) that serves files to each.

Set up an ftp server on linux and have a scheduled job to pull the file from windows.

Have an automated job on linux (cron) ftp the file to windows (this assumes you've set up an ftp server on some windows machine).

Create a web app on windows that can insert a csv file into a database, call this web app via curl from windows.

These options take a greater degree of synchronization between the machines.  Making the file available requires that both machines can access each other.  This may be difficult if one is say, in the dmz and another is not.  Having two sets of programs to do the work on different machines (copy file, process file) requires that clocks be synced reasonably and multiple sets of scheduled processes be able to run.


问:
JQuery / JSON + .Net Service Layer - to WCF or Not to WCF?
I Recently had a discussion with a colleague of mine about the pros / cons of WCF. He mentioned about how much code is generated to support WCF, and also the overhead required. It was mentioned that a simple jQuery /Ajax post to a .aspx page (or a handler for that matter) that returns JSON would work more efficiently and takes much less code to implement. I am also aware of the new WCF Web API and feel that technology may solve the "bloated"-ness required in attaining a proxy etc... by just outputting JSON.

So when developing a relational DB (MSSQL) storage model, with a fairly complex Business Layer (C#) and Data Access Layer (EntityFW)..  what's a good technology for creating a "service layer" which will spit out View Models represented in JSON, with a CQRS(Command Query..) approach in mind.. The app would use the service layer to support it's required UI, as well as provide an available subset of services (outputting JSON data) for service subscribers..

In other words an admin panel to support the admin UI, and service endpoints that return JSON to access the configurations made from the administration UI.

What are some potential technologies to use as the transport / communication layer. I'd like to use a pure RESTful approach, but am not against doing some URL rewriting with IIS.

Obviously some of the available technologies are:
WCF

WCF Web API (should this even be separate?)

Straight request / response (query string to .aspx / handler)

Would using MVC .Net solve this entire problem? maybe their single page app approach?

any suggestions / feedback from developing this type of application?

Thanks,

答:
Well, I've decided not to use WCF, if an alternative could be found. Here are the reasons:

Hard to develop (learning curve guys, basic to medium developers)

Messy configuration (all those bindings, endpoints, etc.)

Client knows about data types of the server (contract attributes)

SOAP is not as handy as JSON (readability for developers)

SOAP is MUCH more verbose than JSON

Unfriendly URLs, which can't be called directly from the browser (SOAP envelopes)

WctTestClient sucks, because it doesn't have a simple alphabetical sort for functions

You gotta suffer to make it RESTful

Your models are not POCO, because of [DataContract], [DataMember], etc. attributes

No method overloading (which some consider to be a form of polymorphism)

I personally have the experience of working with WCF in two mid-sized projects, and in both of them I wish I could be the decision-maker so that I could decide to use something else.


问:
Agile in a multidisciplinary environment
I work for an engineering consultancy who do a combination of industrial design, mechanics, electronics and software. By their nature - or perhaps simply by history - the overall development philosophy has been waterfall. But when I joined I was surprised that Agile, which I would now say is an industry standard, had barely been heard of. For me, whilst I remain skeptical of Agile, I recognize its benefits for both developers and clients, and have been keen to promote its use.

It seems clear to me that you can't build hardware in an Agile fashion. It's just too time-consuming and expensive to "refactor" a physical thing. This means we are moving towards being software-Agile and hardware-Waterfall, and the Project Manager is struggling to make the two work together. Worse, it becomes difficult when we are faced with providing clients with a definitive cost for a project. Agile doesn't do uber-plans, and velocity projections require a project to be up, running and a few sprints to have passed to be meaningful. This means we tend to over-estimate as contingency, driving up our prices and our competitiveness goes down.

Seems to me then that either

We sell Agile explicitly to the client, and get their buy-in to receiving new software iterations per sprint, being able to add to the backlog and prioritize the next tranche of work. We persuade them that this is a no-bullshit way of working, and that waterfall is unrealistic and results in overspend. The Product Owner is from the client in this model. How then do we approach contracts, saying how much we charge for the software? How do we avoid the impression that this is an open-ended revenue stream in which it is in our interests to take as long as we like?

We adopt Agile internally only. The Product Owner is one of our guys / girls. The client just gets an alpha/beta/release version of the software as in waterfall. If we're over time, do we then fudge the slippage in the final phases? Is this even Agile?

In short, having a contract between us and a client seems a very un-Agile way of doing things. And yet waterfall is doomed to fail in an environment where we see every day that not only do we not understand the problem domain on day 1 of a project, neither does the client. And how do we do Agile for software and waterfall for hardware - is there software that can handle both under one umbrella? How do we marry these worlds?

答:
The model of Agile you use should always be tailored to the environment, so that the process delivers tangible value to the client. A key benefit of Agile is that value is delivered early, and clients like that. After seeing it in action, they start to accept the approach.

In your case, the hardware guys will only deliver working kit on day X. What happens before day X? If you were working on a waterfall approach, when do you start code design and construction? How do you test code before the h/w is built? Do you use an emulator?

Go slowly, using Agile internally. Not every client will want to be part an Agile "experiment" (as they would see it). Build up a track record of sprints and velocity. With known velocity, new projects can be estimated more accurately than previously. Then the company can sell the Agile approach to interested clients. Agile requires extra commitment from the client, and not all clients will want to be in it, until they see what the cost difference will be.


答:
"If you only have a hammer, then every problem looks like a nail".

Agile is a very good methodology that has gained (with good reason) wide acceptance within the developer community.

However, it's not the only game in town and it's not always the right answer.  (Code for deep space probes and avionics come to mind).

Is Agile an industry standard in your industry? (Not development in general, but the specific business you're in).  It sounds like that may not be the case.  Your customers aren't asking for it and the hardware guys don't want it or need it.  (Agile requires additional effort from the client that may or may not be available).

If you're going to adopt it, make sure you're doing it for the right reasons & not just because all the kids on SO or P.SE are doing it.

If you decide to move forward anyway, take it slow, start using it internally only, and build up a track record.  Adopting a methodology is a corporate culture change and those never happen quickly.

Be patient.

Title: Agile in a multidisciplinary environment

Body:
I work for an engineering consultancy who do a combination of industrial design, mechanics, electronics and software. By their nature - or perhaps simply by history - the overall development philosophy has been waterfall. But when I joined I was surprised that Agile, which I would now say is an industry standard, had barely been heard of. For me, whilst I remain skeptical of Agile, I recognize its benefits for both developers and clients, and have been keen to promote its use.

It seems clear to me that you can't build hardware in an Agile fashion. It's just too time-consuming and expensive to "refactor" a physical thing. This means we are moving towards being software-Agile and hardware-Waterfall, and the Project Manager is struggling to make the two work together. Worse, it becomes difficult when we are faced with providing clients with a definitive cost for a project. Agile doesn't do uber-plans, and velocity projections require a project to be up, running and a few sprints to have passed to be meaningful. This means we tend to over-estimate as contingency, driving up our prices and our competitiveness goes down.

Seems to me then that either

We sell Agile explicitly to the client, and get their buy-in to receiving new software iterations per sprint, being able to add to the backlog and prioritize the next tranche of work. We persuade them that this is a no-bullshit way of working, and that waterfall is unrealistic and results in overspend. The Product Owner is from the client in this model. How then do we approach contracts, saying how much we charge for the software? How do we avoid the impression that this is an open-ended revenue stream in which it is in our interests to take as long as we like?

We adopt Agile internally only. The Product Owner is one of our guys / girls. The client just gets an alpha/beta/release version of the software as in waterfall. If we're over time, do we then fudge the slippage in the final phases? Is this even Agile?

In short, having a contract between us and a client seems a very un-Agile way of doing things. And yet waterfall is doomed to fail in an environment where we see every day that not only do we not understand the problem domain on day 1 of a project, neither does the client. And how do we do Agile for software and waterfall for hardware - is there software that can handle both under one umbrella? How do we marry these worlds?


问:
Are there legitimate reasons for returning exception objects instead of throwing them?
This question is intended to apply to any OO programming language that supports exception handling; I am using C# for illustrative purposes only.

Exceptions are usually intended to be raised when an problem arises that the code cannot immediately handle, and then to be caught in a catch clause in a different location (usually an outer stack frame).

Q: Are there any legitimate situations where exceptions are not thrown and caught, but simply returned from a method and then passed around as error objects?

This question came up for me because .NET 4's System.IObserver<T>.OnError method suggests just that: exceptions being passed around as error objects.

Let's look at another scenario, validation. Let's say I am following conventional wisdom, and that I am therefore distinguishing between an error object type IValidationError and a separate exception type ValidationException that is used to report unexpected errors:

partial interface IValidationError { }

abstract partial class ValidationException : System.Exception
{
    public abstract IValidationError[] ValidationErrors { get; }
}
```

<p>(The <code>System.Component.DataAnnotations</code> namespace does something quite similar.)</p>

<p>These types could be employed as follows:</p>

<pre class="lang-csharp prettyprint-override"><code>partial interface IFoo { }  // an immutable type

partial interface IFooBuilder  // mutable counterpart to prepare instances of above type
{
    bool IsValid(out IValidationError[] validationErrors);  // true if no validation error occurs
    IFoo Build();  // throws ValidationException if !IsValid(…)
}
</code>```

Now I am wondering, could I not simplify the above to this:

partial class ValidationError : System.Exception { }  // = IValidationError + ValidationException

partial interface IFoo { }  // (unchanged)

partial interface IFooBuilder
{
    bool IsValid(out ValidationError[] validationErrors);
    IFoo Build();  // may throw ValidationError or sth. like AggregateException<ValidationError>
}
```

Q: What are the advantages and disadvantages of these two differing approaches?

答:
Returning exceptions instead of throwing them can make semantical sense when you have a helper-method for analyzing the situation and returning an appropriate exception which is then thrown by the caller (you could call this an "exception factory"). Throwing an exception in this error analyzer function would mean that something went wrong during the analysis itself, while returning an exception means that the kind of error was analyzed succesfully.

One possible use-case could be a function which turns HTTP response codes into exceptions:

```<code>Exception analyzeHttpError(int errorCode) {
    if (errorCode < 400) {
         throw new NotAnErrorException();
    }
    switch (errorCode) {
        case 403:
             return new ForbiddenException();
        case 404:
             return new NotFoundException();
        case 500:
             return new InternalServerErrorException();
        …
        default:
             throw new UnknownHttpErrorCodeException(errorCode);
     }
}
</code>```

Note that throwing an exception means that the method was used wrong or had an internal error, while returning an exception means that the error code was identified succesfully.

Body:
Returning exceptions instead of throwing them can make semantical sense when you have a helper-method for analyzing the situation and returning an appropriate exception which is then thrown by the caller (you could call this an "exception factory"). Throwing an exception in this error analyzer function would mean that something went wrong during the analysis itself, while returning an exception means that the kind of error was analyzed succesfully.

One possible use-case could be a function which turns HTTP response codes into exceptions:

Exception analyzeHttpError(int errorCode) {
    if (errorCode < 400) {
         throw new NotAnErrorException();
    }
    switch (errorCode) {
        case 403:
             return new ForbiddenException();
        case 404:
             return new NotFoundException();
        case 500:
             return new InternalServerErrorException();
        …
        default:
             throw new UnknownHttpErrorCodeException(errorCode);
     }
}

Note that throwing an exception means that the method was used wrong or had an internal error, while returning an exception means that the error code was identified succesfully.


问:
How do I manage the technical debate over WCF vs. Web API?
I'm managing a team of like 15 developers now, and we are stuck at a point on choosing the technology, where the team is broken into two completely opposite teams, debating over usage of WCF vs. Web API.

Team A which supports usage of Web API, brings forward these reasons:

Web API is just the modern way of writing services (Wikipedia)

WCF is an overhead for HTTP. It's a solution for TCP, and Net Pipes, and other protocols

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

SOAP is not as readable and handy as JSON

SOAP is an overhead for network compared to JSON (transport over HTTP)

No method overloading

Team B which supports the usage of WCF, says:

WCF supports multiple protocols (via configuration)

WCF supports distributed transactions

Many good examples and success stories exist for WCF (while Web API is still young)

Duplex is excellent for two-way communication

This debate is continuing, and I don't know what to do now. Personally, I think that we should use a tool only for its right place of usage. In other words, we'd better use Web API, if we want to expose a service over HTTP, but use WCF when it comes to TCP and Duplex.

By searching the Internet, we can't get to a solid result. Many posts exist for supporting WCF, but on the contrary we also find people complaint about it. I know that the nature of this question might sound arguable, but we need some good hints to decide. We're stuck at a point where choosing a technology by chance might make us regret it later. We want to choose with open eyes.

Our usage would be mostly for web, and we would expose our services over HTTP. In some cases (say 5 to 10 percent) we might need distributed transactions though.

What should I do now? How do I manage this debate in a constructive way?

答:
Assuming both sides are 100% correct in all of their arguments, which ones matter?

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

Do you care?  Are you planing on doing something that requires POCO?

WCF supports distributed transactions

Again is this something you are going to use and need to build if you don't have it because you took the other path?

Basically get to the heart of which one:

Offers everything you need (If neither offer everything you need which makes you have to do the least amount of work).

Offers the least amount of junk you aren't going to use but have to put up with anyway.

Any argument put forth that isn't in the path of what you need to accomplish is irrelevant and should not factor in to your decision, with some wiggle room for considering future expansion.


答:
Conceptually, if the exception object is the expected result of the operation, then yes. The cases I can think of, however, always involve throw-catch at some point:

Variations on the "Try" pattern (where a method encapsulates a second exception-throwing method, but catches the exception and instead returns a boolean indicating success). You could, instead of returning a Boolean, return any Exception thrown (null if it succeeded), allowing the end user more information while retaining the catch-less success or failure indication.

Workflow error processing. Similar in practice to "try pattern" method encapsulation, you might have a workflow step abstracted in a chain-of-command pattern. If a link in the chain throws an exception, it's often cleaner to catch that exception in the abstracting object, then return it as a result of said operation so the workflow engine and the actual code run as a workflow step don't require extensive try-catch logic of their own.

Title: Are there legitimate reasons for returning exception objects instead of throwing them?

Body:
This question is intended to apply to any OO programming language that supports exception handling; I am using C# for illustrative purposes only.

Exceptions are usually intended to be raised when an problem arises that the code cannot immediately handle, and then to be caught in a catch clause in a different location (usually an outer stack frame).

Q: Are there any legitimate situations where exceptions are not thrown and caught, but simply returned from a method and then passed around as error objects?

This question came up for me because .NET 4's System.IObserver<T>.OnError method suggests just that: exceptions being passed around as error objects.

Let's look at another scenario, validation. Let's say I am following conventional wisdom, and that I am therefore distinguishing between an error object type IValidationError and a separate exception type ValidationException that is used to report unexpected errors:

partial interface IValidationError { }

abstract partial class ValidationException : System.Exception
{
    public abstract IValidationError[] ValidationErrors { get; }
}
```

<p>(The <code>System.Component.DataAnnotations</code> namespace does something quite similar.)</p>

<p>These types could be employed as follows:</p>

<pre class="lang-csharp prettyprint-override"><code>partial interface IFoo { }  // an immutable type

partial interface IFooBuilder  // mutable counterpart to prepare instances of above type
{
    bool IsValid(out IValidationError[] validationErrors);  // true if no validation error occurs
    IFoo Build();  // throws ValidationException if !IsValid(…)
}
</code>```

Now I am wondering, could I not simplify the above to this:

partial class ValidationError : System.Exception { }  // = IValidationError + ValidationException

partial interface IFoo { }  // (unchanged)

partial interface IFooBuilder
{
    bool IsValid(out ValidationError[] validationErrors);
    IFoo Build();  // may throw ValidationError or sth. like AggregateException<ValidationError>
}
```

Q: What are the advantages and disadvantages of these two differing approaches?


问:
Does Scrum lend itself to multi-project environments?
I will be moving workplace in the near future and I believe they will be very interested in my experience of Scrum and how it may relate to their business. I am trying to understand if it will work in their environment.

My current place of work we have a 2 products/2 backlogs/2 separate teams. These backlogs are obviously prioritised based on what the business thinks it most needs for a platform that we develop. The place I will be moving to however has many projects on the go all at the same time with (2/3 individuals working on each), small bits of work come in and are fixed on a daily basis and I imagine all the customer deliverables are roughly equally as important.

So I'm wondering if anyone has experience of Scrum in a similar environment, what real examples have you got of things that worked? What didn't work? What considerations need to there for Scrum to work in this situation?

There are a few aspects that I'm not sure how would work out well:

I believe people in teams will work across projects, and therefore potentially across scrum teams if broken down.

How do you go about handling priority on so many moving parts which are probably changing frequently and have their own timescales?

If you have a scrum team that works on several projects (some many only require 1 Dev) then how do you understand the context of the stand-up?

答:
I work as a Development Manager in exactly this environment, and have inplemented Scrum extremely successfully with a team of 4 over the past year, from what was a horrible mess. It took a bit of time to get to where we are now, but it works great. I will try to summarise the most important actions, but feel free to enquire further.

I acted as both Product Owner and Scrum Master. I worked to create a backlog for each product, with the associated stakeholder.

I then prioritised across ALL of the backlogs, so I efectively had my own backlog spanning projects.  This was using Fogbugz, so I could filter to each one by project for that stakeholder to work with me and shuffle items.

Plan sprints from this, encapsulating all projects and all team members, so some team members will be working on their own specific tasks, but encourage cross functional working and learning. All stand up discussions are useful, because if someone is talking about something no-one else knows, they had to elaborate enough for us to understand.  This aided the learning.

At this point, the team was lacking cohesion, but we were at least getting things done on all projects, keeping the business happy, and improving quality by adding source control / automated tests. It was a HUGE improvement of the mess that was before, but it was also hard to maintain focus, with no goal other than completing the sprint. We also didn't have demo's as they would not be particularly relevant to any one stakeholder.  Because I was both PO and SM, I was relatively gentle on comitting the team to too much.  It's worth noting we were still delivering a LOT more than prior to my arrival.

I then tried to slowly shift focus of sprints more to a single product, so we would have a sprint say 60% on one product, but still with other tasks.  Eventually, sprints were 90% focussed on one task, and stakeholders learnt to 'wait their turn' - after all, we were still achieving a whole lot more than they ever got before. This made Demo's possible for one product at a time.

Once the sprints were focussed, I began to train the stakeholders in Scrum, and turn some of them into Product Owners.  This is the stage I am at now, I work with 3 product owners, and still have 2 products I effectively own.  Sprints may have 1 or 2 tasks for 'other' projects, but we have a enough focus for a sprint demo with the main stakeholders of the sprint demonstrating only their products new features.

I hope this helps, this is the journey I have been on with my current employer, and so far the Dev team, business units, and (most importantly) my boss are very happy.

ContentLicense: CC BY-SA 4.0


答:
Are there any legitimate situations where exceptions are not thrown and caught, but simply returned from a method and then passed around as error objects?

If it is never thrown then it's not an exception. It is an object derived from an Exception class, though it does not follow the behavior. Calling it an Exception is purely semantics at this point, but I see nothing wrong with not throwing it. From my perspective, not throwing an exception is the exact same thing as an inner-function catching it and preventing it from propagating.

Is it valid for a function to return exception objects?

Absolutely. Here is a short list of examples where this may be appropriate:

An exception factory.

A context object that reports if there was a previous error as a ready to use exception.

A function that keeps a previously caught exception.

A third-party API that creates an exception of an inner type.

Is not throwing it bad?

Throwing an exception is kind of like: "Go to jail. Do not pass Go!" in the board game Monopoly. It tells a compiler to jump over all source code up to the catch without executing any of that source code. It doesn't have anything to do with errors, reporting or stopping bugs. I like to think of throwing an exception as a "super return" statement for a function. It returns execution of the code to somewhere much higher up than the original caller.

The important thing here is to understand that the true value of exceptions is in the try/catch pattern, and not the instantiation of the exception object. The exception object is just a state message.

In your question you seem to be confusing the usage of these two things: a jumping to a handler of the exception, and the error state the exception represents. Just because you took an error state and wrapped it in an exception does not mean you are following the try/catch pattern or its benefits.


答:
When both sides have good arguments and the opinions on the issue are too strong to come to a consensus, you as a manager need to make a decision and end the debate. Otherwise it will just turn in circles and fortify the positions of all participants even more. The longer you wait, the harder will it be for the "losing" side to admit defeat and work productively with the outcome.

Write down all the arguments, value their importance for the project, and then make your decision. When you can't, flip a coin. Your project can likely be completed succesfully with either technology, and wasting valuable time with unnecessary debates will just cost unnecessary money.

Title: How do I manage the technical debate over WCF vs. Web API?

Body:
I'm managing a team of like 15 developers now, and we are stuck at a point on choosing the technology, where the team is broken into two completely opposite teams, debating over usage of WCF vs. Web API.

Team A which supports usage of Web API, brings forward these reasons:

Web API is just the modern way of writing services (Wikipedia)

WCF is an overhead for HTTP. It's a solution for TCP, and Net Pipes, and other protocols

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

SOAP is not as readable and handy as JSON

SOAP is an overhead for network compared to JSON (transport over HTTP)

No method overloading

Team B which supports the usage of WCF, says:

WCF supports multiple protocols (via configuration)

WCF supports distributed transactions

Many good examples and success stories exist for WCF (while Web API is still young)

Duplex is excellent for two-way communication

This debate is continuing, and I don't know what to do now. Personally, I think that we should use a tool only for its right place of usage. In other words, we'd better use Web API, if we want to expose a service over HTTP, but use WCF when it comes to TCP and Duplex.

By searching the Internet, we can't get to a solid result. Many posts exist for supporting WCF, but on the contrary we also find people complaint about it. I know that the nature of this question might sound arguable, but we need some good hints to decide. We're stuck at a point where choosing a technology by chance might make us regret it later. We want to choose with open eyes.

Our usage would be mostly for web, and we would expose our services over HTTP. In some cases (say 5 to 10 percent) we might need distributed transactions though.

What should I do now? How do I manage this debate in a constructive way?


问:
Implementing scrum-but for first time: how to deal with technical pre-requisites?
After working Scrum(ish) in a previous workplace, I am trying to implement it in my new place of work for a brand new project (I am no scrum expert). We have some pre-requisites to code before we can begin working on the stories (which are being groomed in the mean time). Things like database design, api design, etc. We plan to use two week iterations and it's just not clear to me how the first one (or two) can provide something useful to the customer and "potentially shippable" if we first have to "lay down some groundwork" ? Any ideas on how to treat this?

-----edit / rephrase-----

How do we incorporate initial non client-visible preliminary work (e.g., database design, api, etc) into the Scrum process?

答:
I'm worried that you have separated the design / API from user stories - it is a good idea to consider how things are going to evolve, but I feel this work should be incorporated into the stories, not segragated from it.

It sounds to me like you are scared of the words 'potentially shippable'.  This does NOT mean that what  you build can be shipped to the customer to use, merely that the result of the sprint is actually 'Done' - that is tested and production quality.

It can be the case in larger projects that the first sprint/s the result has absolutely no meaning to the customer, but if you can at least say 'This database has been built so that we can do X' or something similar, or even run unit tests that show 100 little green lights, they should understand the usefulness will follow soon enough.


问:
In-Memory Debugger for .NET?
I don't know if "In-Memory debugger" is really what I mean, or if it's even possible to produce, but it's the best name I could come up with...  Here's the tool I'm looking for:

Given a variable name, resolve that name to a reference

Given that reference, be able to watch the object referenced

Given the watch, be able to visualise it in a useful way, e.g.

browse the properties of the object as you can in Visual Studio

be notified when the object referenced is changed.

Here's a use case for this hypothetical tool.  I have spent all of today trying to track down an ObjectDisposedException in my C# web app.  The object being disposed is the WindowsIdentity of the current user, and there would appear to be a race condition causing the WindowsIdentity to be disposed before it is used.  If I could watch a particular memory reference in an intelligent way, rather than a variable in some given scope, I think it would help me pin down the source of this sort of bug more easily.

Does such a tool exist for .NET?

答:
If I understand correctly you want to know when a reference is changed. Well, just add a break point on the lines where the reference might be changed and you will break the execution when this happens (or before, depending on where you put the breakpoint).

About seeing variables in other contexts: you can see any variable as long as it exists in one context. Use the threads drop down to select different threads and the call stack to navigate between different frames.

Title: In-Memory Debugger for .NET?


答:
I think you need to investigate the "type" of Agile you need to adopt. Scrum is one form of agile that adapts well to software development when there are new features to be developed.  Kanban is another form of Agile that sometimes applies better to groups who can't commit to a fixed interval to solve problems like maintaining developed code with mostly bugfixes.  That's only two types of "agile" and there are more you can investigate.  From what others have answered before, agile is designed to help you adapt a flexible process to your company's needs.

Our company has put both software and hardware teams on scrum. I can't comment on how it's going for the hardware team, but it helps the software guys on scrum to line up their schedules.


答:
What should I do now? How do I manage this debate in a constructive way?

First, keep subjectivity away. In your WebAPI team's arguments, I find "Web API is just the modern way"*, "WCF models are not POCO, because of those attributes" and "SOAP is not as readable and handy as JSON" pretty opinionated, if not plain wrong, and will not help make a decision.

So, what to do: decide what you want to do with your service(s), then choose a technique that accommodates that goal and its maintainability and extensibility with the least amount of pain. You can do this by simply researching whether any given aspect is supported by the framework to use.

Interesting reading material:

Mvc 4 vs. Wcf Web Api

WCF or ASP.NET Web APIs? My two cents on the subject

WebAPI or WCF?

*: note you refer to Wikipedia for this, where the citation is: "Web 2.0 web applications have moved away from a service-oriented architecture (SOA) with SOAP-based web services towards more cohesive collections of RESTful web resources". That's an example of use for when your service is to be consumed from a webpage. This can also easily be done with WCF, using the WebHttpBinding. It does not say "Use WebAPI for this".

If this question stretches beyond the "how to manage the discussion": I would use WCF if the services are to be consumed by non-web-clients, because its metadata allows for astonishingly easy strongly-typed client generation.


问:
Heavy use of static methods in a Java EE web application?
Generally I am asking if this is a norm. The application architecture includes spring and the zk framework. I personally can't help but think this introduces a number of problems. I mean...this is a lot of non synchronized functionality. On top of that we are using an Apache project that, through my browsing of source, appears to use a singleton which has methods that are not thread safe. Changed in a newer version however we are not free to migrate the library at this time.

My real question is, is there a justifiable reason for using a large quantity of static methods in a JavaEE application? I was an ASP.NET dev before this and never encountered this. Instincts dictate this is bad architecture but I am unfamiliar with the stack. There are other warning signs such as a lack of conventional generic convention use. Is this the norm?

What is foreign in one platform may not be in another.

答:
Statics should be used when you don't want to have varying behavior for different objects.

Statics should be used when data is not instance dependent and for all existing instances of static member you want to apply same state.

Statics should not be used at all If they are not actually required as they create dependencies and references to other classes and class loader in JVM and stay in memory for long time. So they are not considered for garbage collection once they are done with current work Instead they are de-referenced with their loading classes as they maintain a reference to static classes.
Read more-
http://efectivejava.blogspot.in/2013/08/when-to-use-static-members-in-java.html


答:
Lets say you enqued some task to be executed in some thread pool. If this task throw exception, it is different thread so you don't catch it. Thread where it was executed just die.

Now consider that something (either code in that task, or the thread pool implementation) catches that exception store it along with task and consider task finished (unsucessfully).
Now you can ask whether task is finished (and either ask whether it threw, or it can be thrown again in your thread (or better, new exception with original as cause)).

If you do it manually, you can notice that you are creating new exception, throwing it and catching it, then storing it, in different thread retrieving throwing, catching and reacting on it. So it can make sense to skip throw and catch and just store it and finish task and then just ask whether there is exception and react on it.
But this can lead in more complicated code if in the same place there can be really thrown exceptions.

PS: this is written with experience with Java, where stack trace information is created when exception is created, (unlike C# where it is created when throwing). So not thrown exception approach in Java will be slower than in C# (unless its precreated and reused), but will have stack trace info available.

In general, I would stay away from creating exception and never throwing it (unless as performance optimalization after profiling point it out as bottleneck). At least in java, where exception creation is expensive (stack trace). In C# it is possibility, but IMO its surprising and thus should be avoided.


问:
What should a proper Ready for Sprint definition contain?
Teams in our company deal with Product Owners who are in such a position that they cannot spend as much time with us, as we would like, to do proper Backlog Grooming.

Thus in order to alleviate some of the time constraints we have begun implementing the art of getting stories "Ready for Sprint" or in other words getting them into a state where we know/understand enough to take them into a sprint.

Unfortunately we are still new to what would be a proper definition of 'Ready For Sprint' and so the question of what would be good to keep in mind when getting a story in the backlog Ready for Sprint?

[EDIT]

In response to answers and comments by Ryathal and Donal Fellows i would like to try explain that we do not intend to actually build the stories. We would like to apply the practice of getting existing stories "Ready for Sprint" as explained by this Blog Post. Product owners should probably be adding to this but as mentioned we are not in a prime position with our product owners (as yet).

We have read that you can make definitions such as a story is in Ready state if its effort points are 5 or less, or the story must have Minimum Acceptance Criteria defined, or it must have a Balsamiq Mockup etc.

My question is geared towards finding what others have used in their definitions and what has worked for them. :)

答:
I think the definition of ready is pretty self explanitory, and not really worth explicitly defining.

If the PO disappears until the end of the sprint (which may happen), and the team build what the story says, is there any way the Product Owner can say 'This isn't what we agreed on'? If not, it is ready.

Depending on PO involvement in the sprint, and the type of story this can be very detailed, or very simple.


答:
The answer is yes.  See http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Exceptions and open up the arrow for Google's C++ style guide on exceptions.  You can see there the arguments that they used to decide against, but say that if they had to do it over again, they would have likely decided for.

However it is worth noting that the Go language does not idiomatically use exceptions either, for similar reasons.


答:
If you're working on something like choosing and setting up source code control, I would say that you are not open for business yet. An analogy would be that a restaurant has to set up its kitchen before it serves customers. You could still use the scrum process, but the focus would be getting ready to start instead of meeting customer needs.

"We have some pre-requisites to code before we can begin working on the stories." The previous sentence cuts to the heart of the problem. You are planning to work on something for the customer, but what you are working on is not a story.

It is important to work on what the customer needs.

I suggest that you validate with the product owner that you are correct in thinking that they do not expect something in two weeks. Whether they say yes or not, what is important is that you are aligned with the customer.

Based on what the product owner says, I suggest one of two options

If the project needs something done quickly or is likely to change requirements in the future, I would suggest only doing enough design to meet the current iteration's story.

If the project has fairly high (3 months of work or more) amount of stories to be useful, or is not likely to change requirements in the future, treat the database design as a spike. The risk to the customer is that you might design something that the customer decides not to implement.

Title: Implementing scrum-but for first time: how to deal with technical pre-requisites?

Body:
After working Scrum(ish) in a previous workplace, I am trying to implement it in my new place of work for a brand new project (I am no scrum expert). We have some pre-requisites to code before we can begin working on the stories (which are being groomed in the mean time). Things like database design, api design, etc. We plan to use two week iterations and it's just not clear to me how the first one (or two) can provide something useful to the customer and "potentially shippable" if we first have to "lay down some groundwork" ? Any ideas on how to treat this?

-----edit / rephrase-----

How do we incorporate initial non client-visible preliminary work (e.g., database design, api, etc) into the Scrum process?


答:
Put my two cents in.

As a manager, you should ask your teammates to keep in mind the Yagni principle. This will help to reduce the list of reasons brought forward by both Teams.

Our usage would be mostly for web, and we would expose our services
  over HTTP. In some cases (say 5 to 10 percent) we might need
  distributed transactions though.

Rather than diving into distributed transaction, you should consider working with compensation instead.

Last thing to take into account is the learning curve. Depending on the deadline of your project, as a manager, you should be able to decide whether it's ok to start learning a new technology or not.

If you have plenty of time to waste, then go for some kind of Innovation Day where Team A and B would have a day to produce proof of concepts based on the same requirements.

By the way, to the guy that says "WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes", tell him that POCOs are generaly meant to be domain entities and that it's not a best practice to expose your domain object to any kind of clients, this is what DTO's are for.


问:
Do I need a database to implement AJAX functionality for my app?
I am new to the construction and design of a web app so I'd like some advice please (Django is my framework).  I'm trying to code up a "how-to" website instructing users the step-by-step process for doing a certain task.  I'd like the navigation of the website to be something like this...

http://technet.microsoft.com/en-us/library/aa991542.aspx

...in which there is a tree-like navigation on the left-pane that lists each step (e.g. Step 1, Step 2, etc...) that expands and loads the instructions for each step into the right-pane.            I don't want to reload the page each time so that leads me into AJAX.  At this point, I'm not sure how to implement this.  Do I store the HTML/CSS into a database to be pulled when the user clicks on certain links?  Or do I write the HTML/CSS into my template files with display: hidden to be changed to display: block when corresponding links are clicked?

答:
No, you don't need a database to implement AJAX.  Flat xml or JSON files stored on the server will work just fine.

However, you may want to just make a single-document solution instead, or even use a frames-based setup.


问:
Best way to handle nulls in Java?
I have some code that is failing because of NullPointerException.  A method is being called on the object where the object does not exist.

However, this led me to think about the best way to fix this.   Do I always code defensively for nulls so that I future proof code for null pointer exceptions, or should I fix the cause of the null so that it won't occur downstream.

What are your thoughts?

答:
Adding null checks may make testing problematic. See this great lecture ...

Check out Google Tech talks lecture: "The Clean Code Talks - Don't Look For Things!" he talks about it around minute 24

http://www.youtube.com/watch?v=RlfLCWKxHJ0&list=PL693EFD059797C21E

Paranoid programming involves adding null checks everywhere.
Seems like a good idea at first however from a testing perspective,
it makes your null check type testing hard to deal with.

Also, when you create a precondition for the existence of some object
such as

```<code>class House(Door door){

    .. null check here and throw exception if Door is NULL
    this.door = door
}
</code>```

it prevents you from creating House since you will be throwing an exception. Assume your test cases are creating mock objects for testing something other than Door, well, you can't do this because door is required

Those who have suffered through Mock creation hell are well aware of these types of annoyances.

In summary, your test suite should be robust enough to test for Doors, Houses ,Roofs
or whatever without having to be paranoid about it. Seroiusly, how difficult is it to add a null check test for specific objects in your testing :)

You should always prefer applications that work because you have several tests that PROVE it works, rather than HOPING it works simply because you have a whole bunch of preconditional null checks all over the place

Title: Best way to handle nulls in Java?

Body:
Adding null checks may make testing problematic. See this great lecture ...

Check out Google Tech talks lecture: "The Clean Code Talks - Don't Look For Things!" he talks about it around minute 24

http://www.youtube.com/watch?v=RlfLCWKxHJ0&list=PL693EFD059797C21E

Paranoid programming involves adding null checks everywhere.
Seems like a good idea at first however from a testing perspective,
it makes your null check type testing hard to deal with.

Also, when you create a precondition for the existence of some object
such as

class House(Door door){

    .. null check here and throw exception if Door is NULL
    this.door = door
}

it prevents you from creating House since you will be throwing an exception. Assume your test cases are creating mock objects for testing something other than Door, well, you can't do this because door is required

Those who have suffered through Mock creation hell are well aware of these types of annoyances.

In summary, your test suite should be robust enough to test for Doors, Houses ,Roofs
or whatever without having to be paranoid about it. Seroiusly, how difficult is it to add a null check test for specific objects in your testing :)

You should always prefer applications that work because you have several tests that PROVE it works, rather than HOPING it works simply because you have a whole bunch of preconditional null checks all over the place


答:
AJAX has nothing to do with the backend of the website.  You don't need anything "backing" it - not a database, not xml, not JSON... just some way to determine which page should be sent.

AJAX, at its core, is just a way of making a request to the server without posting back the entire page, and getting something back.  That something could be JSON, which then gets parsed into new values to display.  It could be HTML which just overwrites something else already being displayed.  It could just be a true to represent something completed successfully.

So the simplest form of AJAX would be to have a site with main.html, menu/menu1.html, menu/menu2.html.  On main.html, you use your AJAX framework to post a request for menu/menu1.html when the user clicks on the first menu option, and for menu/menu2.html when they click on the second.  In both cases, you'd probably want to overwrite a menu element with the data you got back (or something) to display it.  You'd do that with javascript if django doesn't handle it for you.

Title: Do I need a database to implement AJAX functionality for my app?

Body:
I am new to the construction and design of a web app so I'd like some advice please (Django is my framework).  I'm trying to code up a "how-to" website instructing users the step-by-step process for doing a certain task.  I'd like the navigation of the website to be something like this...

http://technet.microsoft.com/en-us/library/aa991542.aspx

...in which there is a tree-like navigation on the left-pane that lists each step (e.g. Step 1, Step 2, etc...) that expands and loads the instructions for each step into the right-pane.            I don't want to reload the page each time so that leads me into AJAX.  At this point, I'm not sure how to implement this.  Do I store the HTML/CSS into a database to be pulled when the user clicks on certain links?  Or do I write the HTML/CSS into my template files with display: hidden to be changed to display: block when corresponding links are clicked?


答:
AJAX implies that you are making a server call for the data, but there is no reason for the server to fetch the data from a database - it could handle it using property files or even constants within a Java servlet or PHP/JSP page, without any involvement of a DB.

As for your use case, unless the menu is really long and has complex use cases, why not just follow your own comment on hiding the sub menus with CSS until they are needed? If the problem is loading the content in the right hand pane, it can also be done by using target on the menu and having a named frame or iframe for contents.


答:
I would propose using Option/Some/None pattern from functional languages. I am not a Java specialist, but I intensively use my own implementation of this pattern in my C# project, and I am sure it could be converted into Java world.

The idea behind this pattern is: if it is logically to have situation when there is possibility of absense of a value (for example when retreiving from database by id) you provide an object of type Option[T], where T is a possible value. I case of absense of a value object of class None[T] returned, in case if existence of the value - object of Some[T] returned, containing the value.

In this case, you must handle possibility of value absence, and if you do code review you could easily found placec of incorrect handling. To get an inspiration from C# language implementation refer to my bitbucket repository https://bitbucket.org/mikegirkin/optionsomenone

If you return a null value, and it is logically equivalent an to error (for example no file exists, or could not connect) you should throw an exception, or use another error-handling pattern. The idea behind this, again, you end up with solution, when you must handle the situation of value absence, and could easily find the places of incorrect handling in the code.

Title: Best way to handle nulls in Java?

Body:
I have some code that is failing because of NullPointerException.  A method is being called on the object where the object does not exist.

However, this led me to think about the best way to fix this.   Do I always code defensively for nulls so that I future proof code for null pointer exceptions, or should I fix the cause of the null so that it won't occur downstream.

What are your thoughts?