问:
Memento with optional state?
EDIT:
As pointed out by Steve Evers and pdr, I am not correctly implementing the Memento pattern, my design is actually State pattern.

Menu Program

I built a console-based menu program with multiple levels that selects a particular test to run.  Each level more precisely describes the operation. At any level you can type back to go back one level (memento).

```<code>Level 1: Server Type?
             [1] Server A [2] Server B
Level 2: Server environment?
          [1] test [2] production
Level 3: Test type?
          [1] load [2] unit
Level 4: Data Collection?
          [1] Legal docs [2] Corporate docs
Level 4.5 (optional): Load Test Type
          [2] Multi TIF [2] Single PDF
Level 5: Command Type?
          [1] Move [2] Copy [3] Remove [4] Custom
Level 6: Enter a keyword
          [setup, cleanup, run]
</code>```

Design

States

PROBLEM:

Right now the STATES enum is the determining factor as to what state is BACK and what state is NEXT yet it knows nothing about what the current memento state is.

Has anyone experienced a similar issue and found an effective way to handle mementos with optional state?

```<code>static enum STATES {
    SERVER, ENVIRONMENT, TEST_TYPE, COLLECTION, COMMAND_TYPE, KEYWORD, FINISHED
}
</code>```

Possible Solution (Not-flexible)

In reference to my code below, every case statement in the Menu class could check the state of currentMemo and then set the STATE (enum) accordingly to pass to the Builder.  However, this doesn't seem flexible very flexible to change and I'm struggling to see an effective way refactor the design.

```<code>class Menu extends StateConscious {
    private State state;
    private Scanner reader;
    private ServerUtils utility;

    Menu() {
        state = new State();
        reader = new Scanner(System.in);
        utility = new ServerUtils();
    }

    // Recurring menu logic
    public void startPromptingLoop() {

        List<State> states = new ArrayList<>();
        states.add(new State());

        boolean redoInput = false;
        boolean userIsDone = false;

        while (true) {
            // get Memento from last loop
            Memento currentMemento = states.get(states.size() - 1)
                    .saveMemento();
            if (currentMemento == null)
                currentMemento = new Memento.Builder(0).build();

            if (!redoInput)
                System.out.println(currentMemento.prompt);
            redoInput = false;

            // prepare Memento for next loop
            Memento nextMemento = null;
            STATES state = STATES.values()[states.size() - 1];

            // get user input
            String selection = reader.nextLine();

            switch (selection) {

            case "exit":
                reader.close();
                return; // only escape

            case "quit":
                nextMemento = new Memento.Builder(first(), currentMemento,
                        selection).build();
                states.clear();
                break;

            case "back":
                nextMemento = new Memento.Builder(previous(state),
                        currentMemento, selection).build();
                if (states.size() <= 1) {
                    states.remove(0);
                } else {
                    states.remove(states.size() - 1);
                    states.remove(states.size() - 1);
                }
                break;

            case "1":
                nextMemento = new Memento.Builder(next(state), currentMemento,
                        selection).build();
                break;

            case "2":
                nextMemento = new Memento.Builder(next(state), currentMemento,
                        selection).build();
                break;

            case "3":
                nextMemento = new Memento.Builder(next(state), currentMemento,
                        selection).build();
                break;

            case "4":
                nextMemento = new Memento.Builder(next(state), currentMemento,
                        selection).build();
                break;

            default:
                if (state.equals(STATES.CATEGORY)) {
                    String command = selection;
                    System.out.println("Executing " + command + " command on: "
                            + currentMemento.type + " "
                            + currentMemento.environment);
                    utility.executeCommand(currentMemento.nickname, command);
                    userIsDone = true;
                    states.clear();
                    nextMemento = new Memento.Builder(first(), currentMemento,
                            selection).build();
                } else if (state.equals(STATES.KEYWORD)) {
                    nextMemento = new Memento.Builder(next(state),
                            currentMemento, selection).build();
                    states.clear();
                    nextMemento = new Memento.Builder(first(), currentMemento,
                            selection).build();
                } else {

                    redoInput = true;
                    System.out.println("give it another try");
                    continue;
                }
                break;
            }

            if (userIsDone) {

                // start the recurring menu over from the beginning

                for (int i = 0; i < states.size(); i++) {
                    if (i != 0) {
                        states.remove(i); // remove all except first
                    }
                }
                reader = new Scanner(System.in);
                this.state = new State();
                userIsDone = false;
            }

            if (!redoInput) {
                this.state.restoreMemento(nextMemento);
                states.add(this.state);
            }
        }
    }
}
</code>```

答:
I decided to stick with the state* pattern I had already implemented and I came up with a pretty simple solution that didn't involve a lot of code restructuring.  I added an OPTIONAL state to the STATES enum and gave the StateConscious an optionalFlag boolean.  For the StateConscious.next() and StateConscious.previous() methods I would give the proper next or previous state based on whether optionalFlag was set.

There were additional code changes to support the additional menu prompt but it was easily added.

Thanks to Amy Blankenship, pdr, and Steve Evers for their insight!

*Clarification: After posting question I realized I'm using State pattern not Memento pattern

Title: Memento with optional state?


问:
Should I make a seperate unit test for a method, if it only modifies the parent state?
Should classes, that modify the state of the parent class, but not itself, be unit tested separately? And by separately, I mean putting the test in the corresponding unit test class, that tests that specific class.

I'm developing a library based on chained methods, that return a new instance of a new type in most cases, where a chained method is called. The returned instances only modify the root parent state, but not itself.

Overly simplified example, to get the point across:

```<code>    public class BoxedRabbits
    {
        private readonly Box _box;
        public BoxedRabbits(Box box)
        {
            _box = box;
        }

        public void SetCount(int count)
        {
            _box.Items += count;
        }
    }

    public class Box
    {
        public int Items { get; set; }
        public BoxedRabbits AddRabbits()
        {
            return new BoxedRabbits(this);
        }
    }

var box = new Box();
box.AddRabbits().SetCount(14);
</code>```

Say, if I write a unit test under the Box class unit tests:

```<code>box.AddRabbits().SetCount(14)
</code>```

I could effectively say, that I've already tested the BoxedRabbits class as well. Is this the wrong way of approaching this, even though it's far simpler to first write a test for the above call, then to first write a unit test for the BoxedRabbits separately?

答: My rule of thumb is if it has flow control then it has a unit test. That may not always be true but simple code usually has simple unit tests.  Therefore testing simple code usually isn't that big a burden. So why not make sure you didn't accidentally think less than and type greater than?</p>

ContentLicense: CC BY-SA 3.0


问:
What would you choose for your project between .NET and Java at this point in time?
You are just starting a new project and you have these two technologies to choose from, Java and .NET. The project you are working doesn't involve having features that would make it easy to choose between the two technologies (e.g. .NET has this that I need and Java does not) and both of them should work just fine for you (though you only need one of course). Take into account:

Performance

Tools available (even 3rd party tools)

Cross platform compatibility

Libraries (especially 3rd party libraries)

Cost (Oracle seems to try and monetize Java)

Development process (Easiest/Fastest)

Also keep in mind that Linux is not your main platform but you would like to port your project to Linux/MacOs as well. You should definitely keep in mind the trouble that has been revolving around Oracle and the Java community and the limitations of Mono and Java as well.
It would be much appreciated if people with experience in both can give an overview and their own subjective view about which they would choose and why.

答:
The single most important (edit: technical) decision is:

Will you at this point in time commit 100% to use Windows as your future deployment platform?

If no, then you should go with Java.

The conclusion from Mono is frequently used to say "Yes, .NET is cross-platform". How valid is that claim? was that Mono is only an option IFF you develop against it!

You cannot expect .NET-applications to work out of the box.

@Basic said that this was more a comment than an answer.  To be precise I consider it a question to go on top of the list, because this is perhaps the most important technical decision you need to do when dealing with .NET.  As Basic says he will test against Mono, then that is out of the way, and I would consider Java and .NET to be pretty equally well suited.  I have very little experience with .NET, but quite a bit in Java.

Performance - Java runs pretty well, but still has quite a bit of startup time.  This is because a JVM starts from scratch when being initialized, and the random access of the runtime library jar file is rather slow when needing to be read in from disk.  Recent Java 6's have a background process to try to keep the runtime library jar files in the disk cache so access is fast when needed.

Tools available.  Plenty of tools exist, and there is a lot available as high quality Open Source.  IBM has some very advanced tooling available, but they also take quite a bit of money for them.  You may want to have a look at MyEclipse who make a living from putting together the best parts in the Java world and make them accessible for a low cost, to see what is available.  Netbeans has a very nice GUI editor.  JDeveloper has a nice Swing debugger.  The Sun 6 JDK has VisualVM which is a nice entry level profiler which can analyze already running programs (which is a killer feature).

Cross platform compatibility.  Very good, tending to excellent.  The JVM is very, very reliable and predictable.  Issues only show when operating system differences seep in - like file separators, file name case sensitivity and menu behaviour.

Libraries.  There are many and many of them are freely available and usable, but primarily written in Java as it is rather difficult to pull in code written in non-JVM languages.

Cost.  Java is basically freely available.  What Oracle is indicating is that the power tools - most likely coming from JRocket - will be at a cost.  Also note that exended support ("Java for Business") also comes for a price.   Non-x86 platforms are a dying breed, but IBM has plenty and IBM provides an excellent Java implementation for them.  This is priced as  being a part of the operating system - most likely for better adoption.

Development process.   Much time with Java is spent researching and choosing the appropriate technology and learning it, but when that is done I think there are plenty of technologies which are quite fast to develop with.  The latest version of Java EE provides for writing very powerful web pages using Facelets which can be reloaded at least as fast as PHP pages.

I think that unless you are not skilled in neither Java or .NET, you will save time and money by choosing the technology you and your organization are the most familiar with.

OwnerDisplayName: Basic

ContentLicense: CC BY-SA 2.5


问:
Sharing business logic between server-side and client-side of web application?
Quick question concerning shared code/logic in back and front ends of a web application.

I have a web application (Rails + heavy JS) that parses metadata from HTML pages fetched via a user supplied URL (think Pinterest or Instapaper). Currently this processing takes place exclusively on the client-side. The code that fetches the URL and parses the DOM is in a fairly large set of JS scripts in our Rails app.

Occasionally want to do this processing on the server-side of the app. For example, what if a user supplied a URL but they have JS disabled or have a non-standard compliant browser, etc. Ideally I'd like to be able to process these URLS in Ruby on the back-end (in asynchronous background jobs perhaps) using the same logic that our JS parsers use WITHOUT porting the JS to Ruby.

I've looked at systems that allow you to execute JS scripts in the backend like execjs as well as Ruby-to-Javascript compilers like OpalRB that would hopefully allow "write-once, execute many", but I'm not sure that either is the right decision.

Whats the best way to avoid business logic duplication for apps that need to do both client-side and server-side processing of similar data?

答:
Trying to interpret one language into another is going to add too much complexity for not enough benefit.

If the amount of logic is small, just duplicate it on the client side using Javascript.

If the logic is extensive, and your architecture allows it, create a layer of REST services in Ruby that you can call using AJAX.


问:
SOLID Principles and code structure
At a recent job interview, I couldn't answer a question about SOLID -- beyond providing the basic meaning of the various principles. It really bugs me. I have done a couple of days worth of digging around and have yet to come up with a satisfactory summary.

The interview question was:

If you were to look at a .Net project that I told you strictly followed SOLID principles, what would you expect to see in terms of the project and code structure?

I floundered around a bit, didn't really answer the question, and then bombed out.

How could I have better handled this question?

答:
S = Single Responsibility Principle

So I'd expect to see a well organised folder/file structure & Object Hierarchy. Each class/piece of functionality should be named that its functionality is very obvious, and it should only contain logic to perform that task.

If you saw huge manager classes with thousand of lines of code, that would be a sign that single responsibility wasn't being followed.

O = Open/closed Principle

This is basically the idea that new functionality should be added through new classes that have a minimum of impact on/require modification of existing functionality.

I'd expect to see lots of use of object inheritance, sub-typing, interfaces and abstract classes to separate out the design of a piece of functionality from the actual implementation, allowing others to come along and implement other versions along side without affecting the original.

L = Liskov substitution principle

This has to do with the ability to treat sub-types as their parent type. This comes out of the box in C# if you are implementing a proper inherited object hierarchy.

I'd expect to see code treating common objects as their base type and calling methods on the base/abstract classes rather than instantiating and working on the sub-types themselves.

I = Interface Segregation Principle

This is similar to SRP. Basically, you define smaller subsets of functionality as interfaces and work with those to keep your system decoupled (e.g. a FileManager might have the single responsibilty of dealing with File I/O, but that could implement a IFileReader and IFileWriter which contained the specific method definitions for the reading and writing of files).

D = Dependency Inversion Principle.

Again this relates to keeping a system decoupled. Perhaps you'd be on the lookout for the use of a .NET Dependency Injection library, being used in the solution such as Unity or Ninject or a ServiceLocator system such as AutoFacServiceLocator.

OwnerDisplayName: S-Unit

Title: SOLID Principles and code structure

OwnerDisplayName: Eoin Campbell


答:
There's probably a number of ways that this can be answered with varying amounts of time.  However, I think this is more along the lines of "Do you know what SOLID means?"  So answering this question probably just boils down to hitting the points and explaining it in terms of a project.

So, you expect to see the following:

Classes have a single Responsibility (e.g. a data access class for customers will only get customer data from the customer database).

Classes are easily extended without effecting existing behavior.  I don't have to modify properties or other methods in order to add additional functionality.

Derived classes can be substituted for base classes and functions that use those base classes do not have to unwrap the base class to the more specific type in order to handle them.

Interfaces are small and easy to understand.  If a class makes use of an interface, it does not need to depend on several methods to accomplish a task.

Code is abstracted enough such that high-level implementation is not concretely dependent on specific low-level implementation. I should be able to switch the low-level implementation without effecting the high-level code.  For example, I can switch my SQL data access layer for a Web-service based one without effecting the rest of my application.

Title: SOLID Principles and code structure

Body:
At a recent job interview, I couldn't answer a question about SOLID -- beyond providing the basic meaning of the various principles. It really bugs me. I have done a couple of days worth of digging around and have yet to come up with a satisfactory summary.

The interview question was:

If you were to look at a .Net project that I told you strictly followed SOLID principles, what would you expect to see in terms of the project and code structure?

I floundered around a bit, didn't really answer the question, and then bombed out.

How could I have better handled this question?

OwnerDisplayName: villecoder


答:
A lot of small classes and interfaces with dependency injection all over the place. Probably in a big project you would also use a IoC framework to help you construct and manage the lifetimes of all those small objects. See https://stackoverflow.com/questions/21288/which-net-dependency-injection-frameworks-are-worth-looking-into

Note that a big .NET project that STRICTLY follows SOLID principles does not necessarily mean a good codebase to work with to everybody. Depending on who the interviewer was, he/she may have wanted you to show that you understand what SOLID means and/or check how dogmatically you follow design principles.

You see, to be SOLID, you need to follow:

S ingle responsibility principle, so you will have many small classes each of them doing one thing only

O pen-closed principle, which in .NET is usually implemented with dependency injection, which also requires the I and the D below...

L iskov substitution principle is probably inmpossible to explain in c# with a one-liner. Luckily there are other questions addressing it, e.g. https://stackoverflow.com/questions/4428725/can-you-explain-liskov-substitution-principle-with-a-good-c-sharp-example

I nterface Segregation Principle works in tandem with the Open-Closed principle. If followed literally it would mean preferring a big number of very small interfaces rather that few "big" interfaces

D ependency inversion principle high-level classes should not depend on low-level classes, both should depend on abstractions.

Title: SOLID Principles and code structure

OwnerDisplayName: Paolo Falabella


答:
This is an excellent question, although I think it is a tough interview question.

SOLID principles really govern classes and interfaces and how they related to each other.

This question is really one that has more to do with files and not necessarily classes.

A brief observation or answer I would give is that generally you will see files that hold just an interface, and often the convention is that they start with a capital-I. Beyond that, I would mention that the files would not have duplicated code (especially within a module, application, or library), and that code would be shared carefully across certain boundaries between modules, applications, or libraries.

Robert Martin discusses this topic in the realm of C++ in Designing Objected Oriented C++ Applications Using the Booch Method (see the sections on Cohesion, Closure, and Reusability) and in Clean Code.

Title: SOLID Principles and code structure

OwnerDisplayName: J. Polfer


问:
Is it correct to fix bugs without adding new features when releasing software for system testing?
This question is to experienced testers or test leads.
This is a scenario from a software project:

Say the dev team have completed the first iteration of 10 features and released it to system testing. The test team has created test cases for these 10 features and estimated 5 days for testing. The dev team of course cannot sit idle for 5 days and they start creating 10 new features for next iteration. During this time the test team found defects and raised some bugs. The bugs are prioritised and some of them have to be fixed before next iteration. The catch is that they would not accept the new release with any new features or changes to existing features until all those bugs fixed. The test team says that's how can we guarantee a stable release for testing if we also introduce new features along with the bug fix. They also cannot do regression tests of all their test cases each iteration. Apparently this is proper testing process according to ISQTB.

This means the dev team has to create a branch of code solely for bug fixing and another branch where they continue development. There is more merging overhead specially with refactoring and architectural changes.

Can you agree if this is a common testing principle. Is the test team's concern valid. Have you encountered this in practice in your project.

答: The test team definitely has a valid concern, but I would question the need for multiple iterations of testing for each release. Why go through an entire round of testing on a version of code that users will never see? </p>


问:
Why nginx's http parser doesnt use regular expressions?
I see the http parser written by Igor Sysoev for nginx does not use regular expressions

https://github.com/joyent/http-parser

What could be the main reason for such design decision? I guess I could write few regular expressions to parse HTTP req & res this would be a lot less complex than Igor's version of the parser.

What am I missing here?

答:
I asked this question over the mailing list of nginx. The following was the response:

Regular expressions isn't something readily available when you
code in C, nor something which can be easily used to parse data
available in chunks.  It's also highly unlikely that even
carefully coded regular expressions will be able to beat C code in
terms of performance.

Of course if you are coding some simple http server in perl or
javascript - using regular expressions is a way to go.  But it's
unlikely a good choise if you are coding high performance web
server in C.

-- Maxim Dounin (member of nginx dev mailing list)


问:
Monitoring C++ applications
We're implementing a new centralized monitoring solution (Zenoss). Incorporating servers, networking, and Java programs is straightforward with SNMP and JMX.

The question, however, is what are the best practices for monitoring and managing custom C++ applications in large, heterogenous (Solaris x86, RHEL Linux, Windows) environments?

Possibilities I see are:

Net SNMP

Advantages

single, central daemon on each server

well-known standard

easy integration into monitoring solutions

we run Net SNMP daemons on our servers already

Disadvantages:

complex implementation (MIBs, Net SNMP library)

new technology to introduce for the C++ developers

rsyslog

Advantages

single, central daemon on each server

well-known standard

unknown integration into monitoring solutions (I know they can do alerts based on text, but how well would it work for sending telemetry like memory usage, queue depths, thread capacity, etc)

simple implementation

Disadvantages:

possible integration issues

somewhat new technology for C++ developers

possible porting issues if we switch monitoring vendors

probably involves coming up with an ad-hoc communication protocol (or using RFC5424 structured data; I don't know if Zenoss supports that without custom Zenpack coding)

Embedded JMX (embed a JVM and use JNI)

Advantages

consistent management interface for both Java and C++

well-known standard

easy integration into monitoring solutions

somewhat simple implementation (we already do this today for other purposes)

Disadvantages:

complexity (JNI, thunking layer between native C++ and Java, basically writing the management code twice)

possible stability problems

requires a JVM in each process, using considerably more memory

JMX is new technology for C++ developers

each process has it's own JMX port (we run a lot of processes on each machine)

Local JMX daemon, processes connect to it

Advantages

single, central daemon on each server

consistent management interface for both Java and C++

well-known standard

easy integration into monitoring solutions

Disadvantages:

complexity (basically writing the management code twice)

need to find or write such a daemon

need a protocol between the JMX daemon and the C++ process

JMX is new technology for C++ developers

CodeMesh JunC++ion

Advantages

consistent management interface for both Java and C++

well-known standard

easy integration into monitoring solutions

single, central daemon on each server when run in shared JVM mode

somewhat simple implementation (requires code generation)

Disadvantages:

complexity (code generation, requires a GUI and several rounds of tweaking to produce the proxied code)

possible JNI stability problems

requires a JVM in each process, using considerably more memory (in embedded mode)

Does not support Solaris x86 (deal breaker)

Even if it did support Solaris x86, there are possible compiler compatibility issues (we use an odd combination of STLPort and Forte on Solaris

each process has it's own JMX port when run in embedded mode (we run a lot of processes on each machine)

possibly precludes a shared JMX server for non-C++ processes (?)

Is there some reasonably standardized, simple solution I'm missing?

Given no other reasonable solutions, which of these solutions is typically used for custom C++ programs?

My gut feel is that Net SNMP is how people do this, but I'd like other's input and experience before I make a decision.

答:
i am not familiar with these products you name but for windows i monitor memory consumption using perfmon, there are some special counters, like non paged pool faults, who show you if your program contains memory leaks, they might be little and thus take a long time to monitor but in my opinion this a simple checking method.

On windows you can do a lot using perfmon, even remotely
Or make use of WMI to attach to the same counters, and do some automation on it (in wmi) to perform actions.

Title: Monitoring C++ applications


答:
In general, I'd say either using Node, ExecJS or the like would be the way to accomplish this - I'm wary of any cross-compilers like that.

That being said, I wonder why the client-side parsing is important in this particular case.  You're going to need some API to do cross-domain requests anyway (ahem jsonp.jit.su), so why not just have it do the parsing as well, and just give you some structured JSON that you can work with on either end?

Title: Sharing business logic between server-side and client-side of web application?

Body:
Quick question concerning shared code/logic in back and front ends of a web application.

I have a web application (Rails + heavy JS) that parses metadata from HTML pages fetched via a user supplied URL (think Pinterest or Instapaper). Currently this processing takes place exclusively on the client-side. The code that fetches the URL and parses the DOM is in a fairly large set of JS scripts in our Rails app.

Occasionally want to do this processing on the server-side of the app. For example, what if a user supplied a URL but they have JS disabled or have a non-standard compliant browser, etc. Ideally I'd like to be able to process these URLS in Ruby on the back-end (in asynchronous background jobs perhaps) using the same logic that our JS parsers use WITHOUT porting the JS to Ruby.

I've looked at systems that allow you to execute JS scripts in the backend like execjs as well as Ruby-to-Javascript compilers like OpalRB that would hopefully allow "write-once, execute many", but I'm not sure that either is the right decision.

Whats the best way to avoid business logic duplication for apps that need to do both client-side and server-side processing of similar data?


问:
How do you deal with over-the-head APIs/technology
I guess most people have been in this situation.

The initial project planning begins. The requirements are outlined. After architectural review and sorting through APIs/Frameworks the fitting technology is picked. The development starts.

And then it starts. As soon as you need to do some supposedly simple supporting things, framework/API start to backfire, and instead of doing any work you end up fighting against the technology. The research time skyrockets, forums are silent, nothing seems to be done, and even when you get something to work, you're not really sure it's done right.

How do you manage in these situations? Do you go for hacks, do you research further, what do you say to management?

答:
Managing external dependencies is the bane of many an IT project. Many years ago the experienced programmers I worked with always made sure they had control over their dependencies - Usually by insisting that source code licenses were bought.

Personally, that has not been my approach.  I tend to be of the under promise, over deliver school of thought.  There are times when I have had to stick my neck out, but I do private research beforehand to be 99% sure - usually doing a private project often in my own time to make sure the technology can deliver. In effect prototype, test, validate then promise.

There are situations where I do get caught out - and have to either backtrack or be inventive.  Having a creative mind with plenty of broad experience helps here, but so does talking to other people. - and not always programmers. Sometimes the solutions come from really strange places.

As for dealing with management, the key is honesty.  Talk early, and often.  Don't leave it to the last minute as letting down managers/customers the day before a big delivery just makes you look like amateurs.  Being able to say 2 months before the deadline that the managers need to choose between dropping a few features and/or delaying the shipping might not be popular at the time, but it does allows the rest of the organisation to do their jobs and to plan.  The key to being able to do this is having a good task management system that tracks times and task estimates.  Having solid evidence to back up your point of view makes it much more likely for you to be listened to.


答:
If you're on Windows you tend to write to the event log, and then use a WMI or similar process to read the events. If you want monitoring, you add performance monitor counters to your app and let perfmon read them. Both are system services in Windows.

On Linux, it obviously tends to be more flexible, but I've always seen nagios style monitors implemented, with a custom socket sending data to a nagios style server.

That all said, I have seen several places where SMNP is used, and frankly, I can't see a reason why you wouldn't use it - especially if you're running a completely heterogenous environment.

Title: Monitoring C++ applications

Body:
We're implementing a new centralized monitoring solution (Zenoss). Incorporating servers, networking, and Java programs is straightforward with SNMP and JMX.

The question, however, is what are the best practices for monitoring and managing custom C++ applications in large, heterogenous (Solaris x86, RHEL Linux, Windows) environments?

Possibilities I see are:

Net SNMP

Advantages

single, central daemon on each server

well-known standard

easy integration into monitoring solutions

we run Net SNMP daemons on our servers already

Disadvantages:

complex implementation (MIBs, Net SNMP library)

new technology to introduce for the C++ developers

rsyslog

Advantages

single, central daemon on each server

well-known standard

unknown integration into monitoring solutions (I know they can do alerts based on text, but how well would it work for sending telemetry like memory usage, queue depths, thread capacity, etc)

simple implementation

Disadvantages:

possible integration issues

somewhat new technology for C++ developers

possible porting issues if we switch monitoring vendors

probably involves coming up with an ad-hoc communication protocol (or using RFC5424 structured data; I don't know if Zenoss supports that without custom Zenpack coding)

Embedded JMX (embed a JVM and use JNI)

Advantages

consistent management interface for both Java and C++

well-known standard

easy integration into monitoring solutions

somewhat simple implementation (we already do this today for other purposes)

Disadvantages:

complexity (JNI, thunking layer between native C++ and Java, basically writing the management code twice)

possible stability problems

requires a JVM in each process, using considerably more memory

JMX is new technology for C++ developers

each process has it's own JMX port (we run a lot of processes on each machine)

Local JMX daemon, processes connect to it

Advantages

single, central daemon on each server

consistent management interface for both Java and C++

well-known standard

easy integration into monitoring solutions

Disadvantages:

complexity (basically writing the management code twice)

need to find or write such a daemon

need a protocol between the JMX daemon and the C++ process

JMX is new technology for C++ developers

CodeMesh JunC++ion

Advantages

consistent management interface for both Java and C++

well-known standard

easy integration into monitoring solutions

single, central daemon on each server when run in shared JVM mode

somewhat simple implementation (requires code generation)

Disadvantages:

complexity (code generation, requires a GUI and several rounds of tweaking to produce the proxied code)

possible JNI stability problems

requires a JVM in each process, using considerably more memory (in embedded mode)

Does not support Solaris x86 (deal breaker)

Even if it did support Solaris x86, there are possible compiler compatibility issues (we use an odd combination of STLPort and Forte on Solaris

each process has it's own JMX port when run in embedded mode (we run a lot of processes on each machine)

possibly precludes a shared JMX server for non-C++ processes (?)

Is there some reasonably standardized, simple solution I'm missing?

Given no other reasonable solutions, which of these solutions is typically used for custom C++ programs?

My gut feel is that Net SNMP is how people do this, but I'd like other's input and experience before I make a decision.


问:
How to refactor to cleaner version of maintaing states of the widget
Backstory

I inherited a bunch of code that I'd like to refactor. It is a UI application written in javascript.

Current state:

We have main application which consist of several UI components. And each component  has entry fields, textboxes, menus, etc), like "ticket", "customer information", etc. Based on input, where the application was called from, who is the user, we enable/disable, hide, show, change titles.

Unfortunately, the app grew to the point where it is really hard to scale, add new features. Main the driver (application code) calls set/unset functions of the respective components. So a lot of the stuff look like this

Main app unit

```<code>function1() {
   **call_function2()**
   component1.setX(true);
   component1.setY(true);
   component2.setX(false);
}

call_function2() {
       // it may repeat some of the code function1 called
}
</code>```

and we have a lot of this in the main union.

I am cleaning this mess. What is the best way to maintain the state of widgets?
Please let me know if you need me to clarify.

答:
I just did a similar refactor.  The approach I took was instead of storing the state inside the components, store it in a semantically meaningful state variable, which is published to the components, who then manage their individual UI state accordingly.

For example, you could have a userState variable with values of unauthenticated, untrusted, trusted, or admin.  Your controller functions then just have to call something like changeUserState(trusted), which in turn calls a userStateChanged(trusted) on all subscribed components, who change their UI state accordingly.

What that does for you is decentralize your UI state logic.  Instead of every controller function needing to track the low-level state of every UI component, the controller functions handle high-level state, and the individual components translate the high-level state into their own low-level state.


问:
PayPal proof of payment - is there a need to store it at our server?
I am developing an iPhone app, which I am integrating with PayPal.

I did it successfully using PayPal library. I am testing it on sandbox mode. When I transfer money from one account to the other account, it displays a message "send to server for verification".

Is there a real need to store this PayPal transaction id and other details on our server?

答:
While Apple will provide the user with their transaction (payment) history, your program will need to know when a user has paid, in order to make decisions such as allowing them access, or renewing their subscription (if it isn't one-time).

However, I don't know enough about iPhone API to know whether you should store the PayPal information yourself, or make calls to the API in order to make the above decisions.


问:
Is argument or parameter considered more appropriate for a function/method argument/parameter?
Hopefully the topic is not too confusing, I am curious though as lately I have seen more and more use of the word parameter to denote a function's passed in values, whereas during my studies I feel as if argument was used almost exclusively.

Is parameter more appropriate as argument is more specific to a programs arguments specific at runtime whereas when a function is called, the values passed to it are parameters to the function itself?

From a curious programmer.

答:
I found this definition very simple to explain:

a parameter is a "hole" in your function definition

an argument is what the client uses to fill that "hole"


问:
Ubiquitous Language and Custom types
Note that my question is referring to those attributes that even on their own already represent a concept ( ie on their own provide a cohesive meaning ). Thus such attribute needs no additional functional support and as such is self-contained.

I'm also well-aware that even with self-contained attributes the custom types may prove beneficial ( for example, they  give the ability to add new behavior later, when business requirements change ). Thus, my question focuses only on whether custom types for self-contained attributes really enrich Ubiquitous Language UL

a) I've read that in most cases, even simple, self-contained attributes should have custom, more descriptive types rather than basic value types ( double, string ... ),  because among other things, descriptive types add to the UL, while the use of basic types instead weakens the language.

I understand the importance of UL, but  how does having a basic type for a self-contained attribute weaken the language, since with self-contained attributes the name of the attribute already adequately describes the concept and thus contributes to the UL vocabulary?

For example, the term person_age already adequately explains the concept of quantifying the number of years a person has:

```<code>class Person
{
       string person_age;
}
</code>```

so what could we possibly gain by also introducing the term ThingAge to the UL:

```<code>class person
{
      ThingAge person_age;
}
</code>```

thanks

答:
If you have a system that considers ages of different "things", then having a ThingAge type could be useful. For example, an insurance software system considers the age of drivers and the age of vehicles (for automobile), the age of buildings (for home and commercial property). It might be useful to have further subtypes such as DriverAge for drivers, which has logic particular to drivers (such as related to being above/below regional minimum driving ages), and other types such as HouseAge that has logic related to regional heritage structure rules.  EquipmentAge might relate to mechanical/industrial equipment that might be relevant for underwriting.

Of course, in such a system you don't need to have ThingAge, DriverAge, HouseAge, EquipmentAge types; it's just one way to do it that may be legitimate in some systems. In others, it might not be a good way to do it.

If your system will only ever consider "people" as having an "age" attribute, then having a ThingAge type might not be very useful.

Title: Ubiquitous Language and Custom types


问:
Make a flowchart to demonstrate closure behavior
I saw below test question the other day in which the authors used a flowchart to represent the logic of loops, and I got to thinking it would be interesting to do this with some more complex logic. For example, the closure in this immediately-invoked function expression (IIFE) sort of boggles me:

```<code>while (i <= qty_of_gets) {
    // needs an IIFE
    (function(i) {
        promise = promise.then(function(){
            return $.get("queries/html/" + product_id + i + ".php");
        });
    }(i++));
}
</code>```

I wonder if seeing a flowchart representation of what happens in it could be more elucidating. Could such a thing be done? Would it be helpful, or just messy? I haven't the foggiest clue where to start, but thought maybe someone would like to take a stab. Probably all the ajax could go and it could just be a simple return within the IIFE.

答:
Unfortunately, I don't think a flowchart would be very helpful for this problem, because the code takes advantage of certain Javascript language details that I think would be quite hard to represent effectively in a flowchart, such as first-class functions and variable scope.  I expect that you would find it easy to use flowcharts to represent some subset of Javascript code, but painful and unhelpful (because the flowchart would be complex) to represent other code.  You could probably create a clear flowchart for what the code is supposed to be doing, though (ignoring the details of how it works around Javascript).

Although textual forms create a number of problems (such as yours), they seem to be the most efficient way of writing programs.  I say this not because I hope it's true (I don't) or that I think it will always be this way, but because I've never really seen a better way to represent programming, in its full complexity, but through plain text.  Unfortunately, neat projects like this don't seem to have caught on.  Maybe that will change soon.

Let me mention that I'm not an expert -- my only experience on this matter is from using LabView, with which I eventually became disgusted due to the difficulty of implementing even simple logic and functions, let alone actual substantial abstractions.

That said, the code is extremely hard to understand, because:

you have to think about whether the closures are "by reference" or "by value" (I put those in quotes because I'm not sure what the correct terms are).  This is something that Javascript programmers often have trouble with.  I believe the outer function is there specifically to deal with this issue, since it's immediately executed.

You can investigate this issue by comparing the following two code snippets:

```<code>var fs = [],    i = 0;
while (i <= 4) {
    (function(i) {
        fs.push(function(){
            return i;
        });
    }(i++));
}

var gs = [],    j = 0;
while (j <= 4) {
    gs.push(function(){
        return j;
    });
    j++;
}
</code>```

Then execute some of the functions in fs and gs.  Why are the results what they are?

nested anything is relatively hard to understand, and typically obscures the solution.  For comparison, nested loops are relatively hard to understand, as are nested objects/classes, nested tables, etc.  The nested closures means there's multiple scopes and execution times to think about.

i is shadowed, and I don't really see any good reason for that.  Now, in every scope, you have to figure out which i is being referred to.  Ouch.  Poor kittens.

Body:
Unfortunately, I don't think a flowchart would be very helpful for this problem, because the code takes advantage of certain Javascript language details that I think would be quite hard to represent effectively in a flowchart, such as first-class functions and variable scope.  I expect that you would find it easy to use flowcharts to represent some subset of Javascript code, but painful and unhelpful (because the flowchart would be complex) to represent other code.  You could probably create a clear flowchart for what the code is supposed to be doing, though (ignoring the details of how it works around Javascript).

Although textual forms create a number of problems (such as yours), they seem to be the most efficient way of writing programs.  I say this not because I hope it's true (I don't) or that I think it will always be this way, but because I've never really seen a better way to represent programming, in its full complexity, but through plain text.  Unfortunately, neat projects like this don't seem to have caught on.  Maybe that will change soon.

Let me mention that I'm not an expert -- my only experience on this matter is from using LabView, with which I eventually became disgusted due to the difficulty of implementing even simple logic and functions, let alone actual substantial abstractions.

That said, the code is extremely hard to understand, because:

you have to think about whether the closures are "by reference" or "by value" (I put those in quotes because I'm not sure what the correct terms are).  This is something that Javascript programmers often have trouble with.  I believe the outer function is there specifically to deal with this issue, since it's immediately executed.

You can investigate this issue by comparing the following two code snippets:

var fs = [],    i = 0;
while (i <= 4) {
    (function(i) {
        fs.push(function(){
            return i;
        });
    }(i++));
}

var gs = [],    j = 0;
while (j <= 4) {
    gs.push(function(){
        return j;
    });
    j++;
}

Then execute some of the functions in fs and gs.  Why are the results what they are?

nested anything is relatively hard to understand, and typically obscures the solution.  For comparison, nested loops are relatively hard to understand, as are nested objects/classes, nested tables, etc.  The nested closures means there's multiple scopes and execution times to think about.

i is shadowed, and I don't really see any good reason for that.  Now, in every scope, you have to figure out which i is being referred to.  Ouch.  Poor kittens.


问:
State Pattern - should a state know about its context?
I am referring to the state pattern as described in this link.

In the example class diagram, a context has numerous states. However, it does not show how does a state communicates with a context (perhaps an input in a state has impact on a setting in the context).

The two examples on the page shows either passing the context to the state via a function, or storing a reference to the context. Are those advisable?

Are there other ways for a state to communicate with a context?

Update to an edit:

For instance, I am doing a remote control which can have several states. Say, the context has a setting for Volume, and I am in one of the states which allow  me to tweak the volume. How should the state communicates with the context that the volume is being changed?

答:
That's one of the most complicated and apparently pointless design patterns I've come across. It very tightly couples the components in a way that would make change or extensibility difficult.

In that link, the example shows a bank account class whose behaviour changes depending on the available balance. The behaviour is changed by assigning completely new types to the account 'state' object, except each 'state' is responsible for assigning each other to an account. The control flow is not clear; simply calling 'account.deposit' ends up reassigning internal members to new classes.

When a new rule is invented (e.g; we include a 'platinum' account, which simply has a higher interest rate); we now have to modify 4 classes; 3 x existing state types and the original account, plus create a completely new implementation of 'state' which needs to fully implement the behaviours of a bank account, simply to alter one 'rule'.

There might be a good case to use this pattern intentionally, but that doesn't seem to be it, to me.

And I cannot see how you could sensibly apply this pattern to the concept of a remote control. A remote control has no state (apart from perhaps on/off), it simply sends instructions to another device. That device may have a state (e.g; volume is maxed) in which case a particular instruction could be ignored (cannot increase volume when maxed) but you'd be massively over-engineering the solution trying to squeeze it into this pattern.


问:
Does having Master's degree in Computer Science help your career?
I am curious about experiences of programmers who have gone beyond college or university and now work in the industry. I am not talking about academia (you need PhD there anyway). Do you have a Master's degree? Has it helped your career? Are there any other benefits besides the knowledge one gains while pursuing the degree?</p>

答:
I'm also thinking about a degree in computer science and I'm coming from what you might call the exact opposite end of the educational spectrum (B.A. in Speech Communication W/ some emphasis' - also unrelated to anything in the fields classified as "hard sciences".

One thing I've noticed a lot is an emphasis on experience trumping education, to an even greater degree than seems to be the trend in most every sector since the job market took a fall. I honestly feel like education has been getting a bad wrap.

I'm sure a lot of my reasoning is biased as I have the degree without experience and a job incapable of allowing me to achieve economic independence. Still, I think there are enough grounds for employers to give a little more weight to education than most seem to. Maybe its because of these stupid "online adult education - be a doctor in 6 months" new "universities", which seem more like business organizations (that somehow received accreditation) with primarily financial objectives as opposed to educational. Maybe they're graduates are giving education a bad wrap. Or, maybe the influx of Zuckerbergs and Gates' are overshadowing the value of education. One thing I do know, however, is that I know how to learn (in the truest sense of the word) and how to do so in a much more systematic manner than I could before attending a Cal State. And while my initial work experience (limited, but I do have some) has shown me that I lack some of the professional skills displayed by those with extensive experience and limited education, the quick manner in which I've been able to attain a good chunk of professionalism is definitely faster than what it takes the experience guys to increase their capabilities (But then again, I work at RadioShack, so...lol).

I think learning things you don't need to apply in the workforce teaches you how to be more effective at learning things you do.


问:
user's requirements verification, howto?
My question is: How can you verify the users' requirements early in the software creation process?

I show the user specifications, prototypes, demos... but still users forget to share some "insignificant details" about the process or business rules and data. Which pops up after the final test as some "really small and rare exceptions" - which are turned into change request and accumulate a lot of work.

So how do you prototype (or verify) users requirements early in the project?

答:
I remember being in a business meeting and having one of the business analysts saying that it must be great being a developer always having a fixed specification to work to.

In the real world, there are a few things that greatly help with this.  The first one, is to accept that these last minute details are a fact of life. the only 100% complete specification of the final product is the source code. If the customer already has this, then they have no need for you to write it do they?

The second thing to do is to actively try to flush out the missing specification details.  now you could try getting the customer to sign off 300 page Use Case documents and other contractual mechanisms, but in the end, I can say with 100% confidence, the best way is to deliver software to your customers. Get them to review it, use it, actively encourage them to change the specification to their needs (and when appropriate to charge them for the work).  Even when only some of the features are implemented, customer feedback is key.

The third, when reading the specification, think about what would cause this requirement to change and how you could handle variations.  its often not sensible to over engineer for changes that may not appear, but having a plan, and just as importantly not designing in extra difficulties will make your life much easier - and the extra brownie points for keeping your cool and being confident when you say 'we can handle that by ....  and it will take about 4 days to do.' will inspire others to have confidence in you.


问:
Is imposing the same code format for all developers a good idea?
We are considering to impose a single standard code format in our project (auto format with save actions in Eclipse). The reason is that currently there is a big difference in the code formats used by several (>10) developers which makes it harder for one developer to work on the code of another developer. The same Java file sometimes uses 3 different formats.

So I believe the advantage is clear (readability => productivity) but would it be a good idea to impose this? And if not, why?

UPDATE

We all use Eclipse and everyone is aware of the plan. There already is a code format used by most but it is not enforced since some prefer to stick to their own code format. Because of the above reasons some would prefer to enforce it.

答:
One format to rule them all... is it really optimal?

It's like driving someone else's car...

Sure you can hop in and drive any car, but you will be safer, more comfortable, and less likely to crash if you take the time to adjust the seat, steering wheel and mirrors to YOUR preference.

With code, the formatting does affect your comfort in reading and understanding the code.  If it is too far from what you are used to it will require more mental effort.  Is it necessary to inflict this on the developers?

+1 to all the benefits mentioned so far, but...

Automatic enforcement comes with costs that need to be considered:

-1 to the fact that code formatters don't understand aesthetics of code formatting.
How many times have you had a code formatter destroy a comment block that was nicely aligned in a tabular form?
How many times did you purposely align a complex expression a certain way to increase readability, only to have automatic formatting mangle it into something that "follows the rules", but is far less readable?

Sometimes there are workarounds to these things, but developers have more important things to put their mind to than how to keep the automatic formatter from mangling the code.

Have formatting rules, but allow some freedom to apply common sense.


问:
Best option for PDF viewer embedded in web app
I have a web app that needs to be able to display a PDF.  It needs to allow the user to page through the PDF, and my application needs to be able to know which page is currently being viewed, because other aspects of the web app will change based on the current page.  Ideally it would not be dependent on the client having Adobe Reader but I could probably support that dependency.

What are my best options for this?  My application stack consists of ASP.NET 4 along with optionally Silverlight 5.  Also, I could use something that is client-side based as well using JavaScript / HTML if such a thing exists.

I found ComponentOne's offering for this and that seems like the leading candidate at this point, but I want to know if there are other options I should consider.

Edit: Per Fosco's comment, converting the PDF to another format (such as HTML) might be an option, as long as I could tie back parts of the converted document to the original PDF page #s.

Another note: this has to run entirely on our servers.  It would not be acceptable to use a third-party service to view the PDFs.

答:
PDF.JS is not exactly a plug and play operation, you're better off converting the PDFs to HTML. There's also things you can pay for.

What I reccomend to anyone looking to embed a PDF in a webpage with minimal configuarion is Google Docs Viewer.

Advantage: Easy like Sunday Morning, beautiful

Disadvantage: Hosted by Google


答:
To answer the question more directly, having an MSc is better than not having one.  Speaking as someone who hires technical staff, if you take 2 very similar candidates, but the only difference is that one has an MSc, pending their performance in an interview, the MSc person will get the job.  Also, on a related note, doing a degree (at least a recognised Computer Science degree for example) involves doing presentations, communications skills and various standard things that you would expect an employee to do.

Just by doing a degree and attaining one, a candidate proves something and provides a tick in a box which someone without a degree does not have.  It is less relevant where candidates have a many years of professional experience.

Title: Does having Master's degree in Computer Science help your career?

Body: I am curious about experiences of programmers who have gone beyond college or university and now work in the industry. I am not talking about academia (you need PhD there anyway). Do you have a Master's degree? Has it helped your career? Are there any other benefits besides the knowledge one gains while pursuing the degree?</p>


问:
Achieving Zero Downtime Deployment
I am trying to achieve zero downtime deployments so I can deploy less during off hours and more during "slower" hours - or anytime, in theory.

My current setup, somewhat simplified:

Web Server A (.NET App)

Web Server B (.NET App)

Database Server (SQL Server)

My current deployment process:

"Stop" the sites on both Web Server A and B

Upgrade the database schema for the version of the app being deployed

Update Web Server A

Update Web Server B

Bring everything back online

Current Problem

This leads to a small amount of downtime each month - about 30 mins.  I do this during off hours, so it isn't a huge problem - but it is something I'd like to get away from.

Also - there is no way to really go 'back'.  I don't generally make rollback DB scripts - only upgrade scripts.

Leveraging The Load Balancer

I'd love to be able to upgrade one Web Server at a time.  Take Web Server A out of the load balancer, upgrade it, put it back online, then repeat for Web Server B.

The problem is the database.  Each version of my software will need to execute against a different version of the database - so I am sort of "stuck".

Possible Solution

A current solution I am considering is adopting the following rules:

Never delete a database table.

Never delete a database column.

Never rename a database column.

Never reorder a column.

Every stored procedure must be versioned.

Meaning - 'spFindAllThings' will become 'spFindAllThings_2' when it is edited.

Then it becomes 'spFindAllThings_3' when edited again.

Same rule applies to views.

While, this seems a bit extreme - I think it solves the problem.  Each version of the application will be hitting the DB in a non breaking way.  The code expects certain results from the views/stored procedures - and this keeps that 'contract' valid.  The problem is - it just seeps sloppy.  I know I can clean up old stored procedures after the app is deployed for awhile, but it just feels dirty.  Also - it depends on all of the developers following these rule, which will mostly happen, but I imagine someone will make a mistake.

Finally - My Question

Is this sloppy or hacky?

Is anybody else doing it this way?

How are other people solving this problem?

答:
You could potentially do it like this for a bit of extra effort.

Back up database by taking an export

Import the back up but rename it with a release version e.g. myDb_2_1

Execute database release on myDB_2_1

"Stop" the app pool on Web Server A or take it out of the load balancer

Update Web Server A, run post implementation tests and rollback if necessary

Session bleed Web Server B and put Web Server A back in loop

Upgrade Web server B and then put back in load balancer

Naturally the web updates would need new config entries to point to the new Db schema. Thing is if you're doing releases once a month and it's a small team how many DB changes are you really making that aren't backwards compatible? If you can control that by testing you could go for getting an automated deployment with no down time or maybe at worst only 5 mins down time.

Title: Achieving Zero Downtime Deployment


问:
OOP concept: is it possible to update the class of an instantiated object?
I am trying to write a simple program that should allow a user to save and display sets of heterogeneous, but somehow related data. For clarity sake, I will use a representative example of vehicles. The program flow is like this:

The program creates a Garage object, which is basically a class that can contain a list of vehicles objects

Then the users creates Vehicles objects, these Vehicles each have a property, lets say License Plate Nr. Once created, the Vehicle object get added to a list within the Garage object

--Later on--, the user can specify that a given Vehicle object is in fact a Car object or a Truck object (thus giving access to some specific attributes such as Number of seats for the Car, or Cargo weight for the truck)

At first sight, this might look like an OOP textbook question involving a base class and inheritance, but the problem is more subtle because at the object creation time (and until the user decides to give more info), the computer doesn't know the exact Vehicle type.

Hence my question: how would you proceed to implement this program flow? Is OOP the way to go?

Just to give an initial answer, here is what I've came up until now. There is only one Vehicle class and the various properties/values are handled by the main program (not the class) through a dictionary. However, I'm pretty sure that there must be a more elegant solution (I'm developing using VB.net):

```<code>Public Class Garage
    Public GarageAdress As String
    Private _ListGarageVehicles As New List(Of Vehicles)

    Public Sub AddVehicle(Vehicle As Vehicles)
        _ListGarageVehicles.Add(Vehicle)
    End Sub
End Class

Public Class Vehicles
    Public LicensePlateNumber As String
    Public Enum VehicleTypes
        Generic = 0
        Car = 1
        Truck = 2
    End Enum
    Public VehicleType As VehicleTypes
    Public DictVehicleProperties As New Dictionary(Of String, String)
End Class
</code>```

NOTE that in the example above the public/private modifiers do not necessarily reflect the original code

答:
probably you are looking for this pattern

you have to tweak this code to your exact requirement.

```<code>public interface IVehicle
{
    string VehicleType{get;}
    int NumberOfSeets{set;get;}
    int Corgosize{set;get;}
}

public class Car:IVehicle
{
    private int _numseets;
    private int _corgo;
    public string VehicleType{
        get{return "CAR";}
    }

    public int NumberOfSeets
    {
       get{return _numseets;}
       set{_numseets = value;}
    }

    public int Corgosize
    {
        get { return _corgo; }
        set { _corgo = value; }
    }
}

public class Truck : IVehicle
{
    private int _numseets;
    private int _corgo;
    public string VehicleType
    {
        get { return "Truck"; }
    }

    public int NumberOfSeets
    {
        get { return _numseets; }
        set { _numseets = value; }
    }

    public int Corgosize
    {
        get { return _corgo; }
        set { _corgo = value; }
    }
}

public class Vehicle : IVehicle
{
    private IVehicle _vehicle;
    public Vehicle(IVehicle refVehicle)
    {
        _vehicle = refVehicle;
    }
    public string VehicleType
    {
        get { return _vehicle.VehicleType; }
    }

    public int NumberOfSeets
    {
        get { return _vehicle.NumberOfSeets; }
        set {  }
    }

    public int Corgosize
    {
        get { return _vehicle.Corgosize; }
        set {  }
    }

}

public class MainClass
{
    public static void Main()
    {
        Vehicle car, truck;
        car = new Vehicle(new Car());
        truck = new Vehicle(new Truck());
        Console.WriteLine("Car type ->{0}",car.VehicleType);
        Console.WriteLine("truck type ->{0}", truck.VehicleType);
        Console.ReadKey();

    }

}
</code>```

Body:
probably you are looking for this pattern

you have to tweak this code to your exact requirement.

public interface IVehicle
{
    string VehicleType{get;}
    int NumberOfSeets{set;get;}
    int Corgosize{set;get;}
}

public class Car:IVehicle
{
    private int _numseets;
    private int _corgo;
    public string VehicleType{
        get{return "CAR";}
    }

    public int NumberOfSeets
    {
       get{return _numseets;}
       set{_numseets = value;}
    }

    public int Corgosize
    {
        get { return _corgo; }
        set { _corgo = value; }
    }
}

public class Truck : IVehicle
{
    private int _numseets;
    private int _corgo;
    public string VehicleType
    {
        get { return "Truck"; }
    }

    public int NumberOfSeets
    {
        get { return _numseets; }
        set { _numseets = value; }
    }

    public int Corgosize
    {
        get { return _corgo; }
        set { _corgo = value; }
    }
}

public class Vehicle : IVehicle
{
    private IVehicle _vehicle;
    public Vehicle(IVehicle refVehicle)
    {
        _vehicle = refVehicle;
    }
    public string VehicleType
    {
        get { return _vehicle.VehicleType; }
    }

    public int NumberOfSeets
    {
        get { return _vehicle.NumberOfSeets; }
        set {  }
    }

    public int Corgosize
    {
        get { return _vehicle.Corgosize; }
        set {  }
    }

}

public class MainClass
{
    public static void Main()
    {
        Vehicle car, truck;
        car = new Vehicle(new Car());
        truck = new Vehicle(new Truck());
        Console.WriteLine("Car type ->{0}",car.VehicleType);
        Console.WriteLine("truck type ->{0}", truck.VehicleType);
        Console.ReadKey();

    }

}


问:
General questions regarding open-source licensing
I'm looking to release an open-source iOS software project but I'm very new to the licensing side of the things. While I'm aware that the majority of answers here will not lawyers, I'd appreciate it if anyone could steer me in the right direction.

With the exception of the following requirements I'm happy for developers to largely do whatever they want with the projects source code. I'm not interested in any copyleft licensing schemes, and while I'd like to encourage attribution in derivative works it is not required.

As such, my requirements are as follows:

Original source can be distributed and re-distributed (verbatim) both
commercially and non-commercially as long as the original copyright
information, website link and license is maintained.

I wish to retain rights to any of the multi-media distributed as part
of the project (sound effects, graphics, logo marks, etc). Such
assets will be included to allow other developers to easily execute
the project, but cannot be re-distributed in any manner.

I wish to retain rights to the applications name and branding.

Futher to selecting an applicable license, I have the following questions:

The project makes use of a number of third-party libraries (all licensed under variants of the MIT license). I've included individual licenses within the source (and application) and believe I've met all requirements expressed in these licenses, but is there anything else that needs to be done before distributing them as part of my open-source project?

Also included in my project is a single proprietary, close-sourced library that's used to power a small part of the application. I'm obviously unable to include this in the source release, but what's the best way of handling this? Should I simply weak-link the project and exclude it entirely from the Git project?

答:
Honestly, you have a mess of licensing requirements.  And by mess, I mean too many conflicting requirements.

At first glance, the GPL looks like it would fit your requirements for attribution & re-distribution of source.  It also is pretty good at absorbing other licenses like MIT & BSD.

Your requirements regarding the media though will essentially require a different licensing scheme than GPL.  It's at this point in your req's list that you've painted yourself into a corner without a solution.

However, you really nail things shut by relying upon a closed source, proprietary application.  Generally, closed source licenses don't mesh together with the GPL.

There are some Creative Commons licenses that you could consider, but honestly, they're not going to be able to resolve your conflicting requirements either.

And I would encourage you to take a step back and ask who would actually want to pick up your project? From an outsider's point of view, this is what I see.

I might be able to extract everything and compile

That assumes I can find a copy of the proprietary engine that your app relies upon

If I ever want to redistribute it, I have to come up with all of my own media

And then I have to consider the long chain of licenses that you've released things under.

Nothing personal, but it better be one helluva application to make me want to go through those hoops.


答:
It sorts of varies from one deployment to another.

Sure, you could never delete a table or a column.  You could never change anything that broke interface compatibility.  You can always add a layer of abstraction.  But then you have to version that abstraction and the version the versioning.

The question you need to ask yourself is, does every single release change the schema in such a way that it is not backwards compatible?

If very few releases change the schema in that way, then the database issue is mute.  Just do a rolling deploy of the application servers.

The two things that I have seen help the most with minimal-downtime deployment are:

Strive for backward compatibility - at least within a single release.  You won't always achieve it, but I can bet you can achieve it on 90% or more of your releases, especially if each release is small.

Have a pre-release and post-release database script.  This allows you to handle renames  or interface changes by creating your new object before your app code is deployed, then dropping the old one after the app code is deployed.  If you add a new non-nullable column, you could add it as nullable in your pre-release script with a trigger that fills a default value.  Then in your post-release, you can drop the trigger.

Hopefully the rest of your deploys can be saved for maintenance windows.

Other ideas that may help deal with the few deploys which require downtime:

Can you build backward compatibility into your code?  For example, is there any way your code can support multiple types of result sets?  If you need to change a column from an int to a double, your app code could read it as a string and parse it.  Kind of hacky, but if it's temporary code to get yourself through the release process, it may not be the end of the world.

Stored procedures can help insulate your app code from schema changes.  This can only go so far, but does help a bit.

Title: Achieving Zero Downtime Deployment

Body:
I am trying to achieve zero downtime deployments so I can deploy less during off hours and more during "slower" hours - or anytime, in theory.

My current setup, somewhat simplified:

Web Server A (.NET App)

Web Server B (.NET App)

Database Server (SQL Server)

My current deployment process:

"Stop" the sites on both Web Server A and B

Upgrade the database schema for the version of the app being deployed

Update Web Server A

Update Web Server B

Bring everything back online

Current Problem

This leads to a small amount of downtime each month - about 30 mins.  I do this during off hours, so it isn't a huge problem - but it is something I'd like to get away from.

Also - there is no way to really go 'back'.  I don't generally make rollback DB scripts - only upgrade scripts.

Leveraging The Load Balancer

I'd love to be able to upgrade one Web Server at a time.  Take Web Server A out of the load balancer, upgrade it, put it back online, then repeat for Web Server B.

The problem is the database.  Each version of my software will need to execute against a different version of the database - so I am sort of "stuck".

Possible Solution

A current solution I am considering is adopting the following rules:

Never delete a database table.

Never delete a database column.

Never rename a database column.

Never reorder a column.

Every stored procedure must be versioned.

Meaning - 'spFindAllThings' will become 'spFindAllThings_2' when it is edited.

Then it becomes 'spFindAllThings_3' when edited again.

Same rule applies to views.

While, this seems a bit extreme - I think it solves the problem.  Each version of the application will be hitting the DB in a non breaking way.  The code expects certain results from the views/stored procedures - and this keeps that 'contract' valid.  The problem is - it just seeps sloppy.  I know I can clean up old stored procedures after the app is deployed for awhile, but it just feels dirty.  Also - it depends on all of the developers following these rule, which will mostly happen, but I imagine someone will make a mistake.

Finally - My Question

Is this sloppy or hacky?

Is anybody else doing it this way?

How are other people solving this problem?


问:
Finding duplicate files?
I am going to be developing a program that detects duplicate files and I was wondering what the best/fastest method would be to do this? I am more interested in what the best hash algorithm would be to do this? For example, I was thinking of having it get the hash of each files contents and then group the hashes that are the same. Also, should there be a limit set for what the maximum file size can be or is there a hash that is suitable for large files?</p>

答:
If you are optimising for developer time, you are along the right tracks; if you choose a decent enough hashing algorithm, collisions should be extremely unlikely (see Yanis' link; but aside from those, people typically use MD5 or SHA1 for hashes, although MD5 is not recommended if you are security conscious).  I would go with  something that's available out of the box in your programming environment, since implementing and maintaining a hashing algorithm might not be worthwhile.

If you are worried about runtime performance, there are some things you can do to optimise the process.  There are likely to be two areas which are slow - the reading in of all the data, and the actual hashing process itself.  To give you an idea, most hash algorithms (even the slower, cryptographic ones) can typically go through a few hundred MB per second.  So, unless you are using a (very fast) SSD, the bottleneck is more likely to be disk IO, so you should try to minimise that first.

One idea would be to group files by size first, and exclude any files with unique sizes.  Then hash the first few kB of each remaining file, and using that to produce a list of potential matches (again, only compare against files of the exact same size).  You would then only need to get the full hash of these potential matches, as opposed to every file on the drive.  Depending on the exact characteristics of the drive, this may be faster than simply reading everything in (unless there are a very large number of duplicates, and we're wasting our time trying to exclude them - a worst case scenario).  This should work fairly well for typical workloads, with more knowledge about the actual environment, you could probably tune it much more.

Title: Finding duplicate files?


问:
Why do certain sites don't allow Back / Forward / Refresh?
This has been a cause of frustration for me on many sites like IRCTC, Online Banking sites which wont allow Back, forward or refresh. If you do you would be logged out and you have to login again. What I don't understand is what concern had there been in their mind to have such terrible "feature".</p>

答:
A common reason for this "feature" is that a site tries to keep some state of the current session on the server side.

That desire to track "conversation" state on the server side often comes from trying to write a Desktop-like "rich client" on the web (as opposed to embracing the web as the chaos it is). To be fair, this mostly happened in a time when the concept of a rich web application wasn't as well-understood as it is these days.

For example if a site provides a multi-page wizard and tracks where exactly you are and what answers you have given, then supporting back/forward in a sane manner becomes complicated (because some operations don't get communicated to the server at all).

This complication sometimes goes so far that sites outright ban forward/back. As you noted, that has obvious usability problems.


问:
What's with the aversion to documentation in the industry?
There seems to be an aversion to writing even the most basic documentation. Our project READMEs are relatively bare. There aren't even updated lists of dependencies in the docs.

Is there something I'm unaware of in the industry that makes programmers dislike writing documentation? I can type out paragraphs of docs if needed, so why are others so averse to it?

More importantly, how do I convince them that writing docs will save us time and frustration in the future?

答: A minor point, but one that seems to be important with some developers who write obnoxiously little documentation: they can't type. If you have some approximation of the 10 finger system you tend to write more documentation just because it's easy. But if you are stuck with hunting and pecking you are lost. If I'd be responsible for hiring this is actually something I'd check.</p>


问:
CppUnit for unit-testing executable files?
I am not sure if anyone has done it. I am trying to do something that is in general, uncommon i.e. unit-testing executable (Windows) or ELFs (Linux). I know that CppUnit provides a good unit testing facility, but I have never used it for unit-testing (used UnitTest++). I hear rumours that you can unit-test executables too. Does anyone have the experience in this?

A relevant post regarding the philosophy of it was here

答:
You can use almost any xUnit test tool for automatic testing of executables (however, this will not result in unit tests, but integration or system tests). This assumes your executable can be run in some batch mode without user interaction, and it will produce some machine-readable output for which you can check if it is the expected output or not.

Just write a test which runs your executable in a separate process (see, for example,  here), pipes the output into a file and add a function to your test lib which compares the content of the file with a second "expected output" file. You may have to add additional safety measures like time-out testing if you expect your executables to crash or leave batch-mode in case of a bug.

Running the separate process is easy, testing the output, however, can be arbitrary complex, dependent on your program-under-test and the complexity if its output. But the latter part is nothing you can expect any xUnit tool to help you with.


问:
What would you choose for your project between .NET and Java at this point in time?
You are just starting a new project and you have these two technologies to choose from, Java and .NET. The project you are working doesn't involve having features that would make it easy to choose between the two technologies (e.g. .NET has this that I need and Java does not) and both of them should work just fine for you (though you only need one of course). Take into account:

Performance

Tools available (even 3rd party tools)

Cross platform compatibility

Libraries (especially 3rd party libraries)

Cost (Oracle seems to try and monetize Java)

Development process (Easiest/Fastest)

Also keep in mind that Linux is not your main platform but you would like to port your project to Linux/MacOs as well. You should definitely keep in mind the trouble that has been revolving around Oracle and the Java community and the limitations of Mono and Java as well.
It would be much appreciated if people with experience in both can give an overview and their own subjective view about which they would choose and why.

答:
OK, lets try to break this down:

Take into account:

Performance Tools available (even 3rd party tools)

Both the Java and .NET platforms have plenty of good performance testing tools available, I know that in the Java space that there are plenty of free open source tools that are adequate for most scenarios.  I can't speak for the .NET side.

Cross platform compatibility

Java has an advantage here - project Mono (or similar) is required to get .NET running on some platforms.  I'm not sure with Mono is 100% bullet-proof and performant, something hopefully someone else can chime in on.

Libraries (especially 3rd party libraries)

Both have strong support here.  Initially the Java eco-system lead the way (there's literally a a free open source library for just about anything you could think of) but I'd say that .NET has certainly caught up where it matters (NHiberante for persistence, NUnit for unit testing to name two basic ones + I'm sure there's a metric truckload more).

Cost (Oracle seems to try and monetize Java)

All companies try to monetize to some degree, but in the case of Java I think your statement is a little misleading.  Java was open sourced as of version 6 (the OpenJDK project) and Oracle has shown no inclination to monetize Java beyond what Sun was doing.  So yes they sell App servers and extensions to the JVM (management extensions in particular), but core Java itself?  Nope and they never will (this has been publicly stated plenty of times).

I think both MS and Oracle benefit massively due to indirect revenue with their repsepctive platforms.

Total Cost of Ownership (TCO)?  I'm not even going to get into this debate as there's no way to prove it (programming is a creative human activity after all).  I personally think that Java based systems tend to have a lower initial cost as you can utilise a free open source stack from top to bottom in most cases.  However, large enterprises tend to prefer having support contracts so that can nullify that particular benefit.

Development process (Easiest/Fastest)

Depends on what you're trying to build!  I'd personally argue that they're pretty much even, although C# has some extra features in the core language over Java at the moment.  However with (multiple inter-operable with Java) languages on the JVM (Groovy, Scala, Clojure etc) you can have all of the langauge features you want.

.NET had a distinct advantage for building web front end 'stuff' for awhile (Rapid Application Development if you will), but I think JEE6 and/or Spring and other web/app frameworks have pretty much closed that gap.

Also keep in mind that Linux is not
  your main platform but you would like
  to port your project to Linux/MacOs as
  well. You should definitely keep in
  mind the trouble that has been
  revolving around Oracle and the Java
  community and the limitations of Mono
  and Java as well. It would be much
  appreciated if people with experience
  in both can give an overview and their
  own subjective view about which they
  would choose and why.

If you want to port to Linux, UNIX and in particular Mac OS then as stated above Java has an edge there.

Hope that helps!


问:
Unit-Testing functions which have parameters of classes where source code is not accessible
Relating to this question, I have another question regarding unit testing functions in the utility classes:

Assume you have function signatures like this:

```<code>public function void doSomething(InternalClass obj, InternalElement element)
</code>```

where InternalClass and InternalElement are both Classes which source code are not available, because they are hidden in the API. Additionally, doSomething only operates on obj and element. I thought about mocking those classes away but this option is not possible due to the fact that they do not implement an interface at all which I could use for my Mocking classes.

However, I need to fill obj with defined data to test doSomething.

How can this problem be solved?

答:
What you are looking for is the adapter pattern: http://www.dofactory.com/Patterns/PatternAdapter.aspx

Using this pattern you can create a wrapper around the external class.

Lets take the following external class:

```<code>public sealed class SomeExternalClassWithoutInterface
{
    private readonly string _someValue;

    public SomeExternalClassWithoutInterface(string someConstructorValue)
    {
        _someValue = someConstructorValue;
    }
    public string Method1()
    {
        return _someValue;
    }

    public int Method2()
    {
        return _someValue.Length;
    }
}
</code>```

We can now easily create our own class as a wrapper around this external class, and Implement an interface:

```<code>public class ExternalClassAdapter : IExternalClassAdapter
{
private readonly SomeExternalClassWithoutInterface _someExternalClassWithoutInterface;

// DI implementation, this is not neccesary
public ExternalClassAdapter(SomeExternalClassWithoutInterface someExternalClassWithoutInterface)
{
    _someExternalClassWithoutInterface = someExternalClassWithoutInterface;
}

// Constructor Without Depedency Injection, this is not preferable.
public ExternalClassAdapter(string someValue)
{
   _someExternalClassWithoutInterface = new SomeExternalClassWithoutInterface(someValue);
}

public string Method1()
{
    return _someExternalClassWithoutInterface.Method1();
}

public int Method2()
{
    return _someExternalClassWithoutInterface.Method2();
}
</code>```

}

This is our interface, which is implementing all the methods used in the external class. (If alot of methods are available, seperate the interfaces according to the Interface Segregation principle)

```<code>public interface IExternalClassAdapter
    {
        string Method1();
        int Method2();
    }
</code>```

Now, when this Adapter class is used in your application instead of the external class, you should be able to mock any other implementation pretty easy.

You should never use non interfaced external classes in your code.

Pastebin link (since the code outlining is not working well here): http://pastebin.com/2qN7u3u6

If, for any reason, you also need a facade pattern... You can still wrap these 2 adapters in a single facade! But do not create a single facade on 2 external classes!

Body:
What you are looking for is the adapter pattern: http://www.dofactory.com/Patterns/PatternAdapter.aspx

Using this pattern you can create a wrapper around the external class.

Lets take the following external class:

public sealed class SomeExternalClassWithoutInterface
{
    private readonly string _someValue;

    public SomeExternalClassWithoutInterface(string someConstructorValue)
    {
        _someValue = someConstructorValue;
    }
    public string Method1()
    {
        return _someValue;
    }

    public int Method2()
    {
        return _someValue.Length;
    }
}

We can now easily create our own class as a wrapper around this external class, and Implement an interface:

public class ExternalClassAdapter : IExternalClassAdapter
{
private readonly SomeExternalClassWithoutInterface _someExternalClassWithoutInterface;

// DI implementation, this is not neccesary
public ExternalClassAdapter(SomeExternalClassWithoutInterface someExternalClassWithoutInterface)
{
    _someExternalClassWithoutInterface = someExternalClassWithoutInterface;
}

// Constructor Without Depedency Injection, this is not preferable.
public ExternalClassAdapter(string someValue)
{
   _someExternalClassWithoutInterface = new SomeExternalClassWithoutInterface(someValue);
}

public string Method1()
{
    return _someExternalClassWithoutInterface.Method1();
}

public int Method2()
{
    return _someExternalClassWithoutInterface.Method2();
}

}

This is our interface, which is implementing all the methods used in the external class. (If alot of methods are available, seperate the interfaces according to the Interface Segregation principle)

public interface IExternalClassAdapter
    {
        string Method1();
        int Method2();
    }

Now, when this Adapter class is used in your application instead of the external class, you should be able to mock any other implementation pretty easy.

You should never use non interfaced external classes in your code.

Pastebin link (since the code outlining is not working well here): http://pastebin.com/2qN7u3u6

If, for any reason, you also need a facade pattern... You can still wrap these 2 adapters in a single facade! But do not create a single facade on 2 external classes!


答:
External processes can be tested (as Doc Brown already mentioned, it will not be unit tests) by test tools in any language. So I recommend using a language where running external tools is easy, so some scripting language rather than C++. Some options are:

CTest is part of CMake. It runs external processes with specified parameters and checks their output and return value. The capabilities are rather limited, but it is useful to eventually combine tests written with various tools. And integrate them in the build if you use CMake.

Unix Shell (using cygwin or msys on Windows). You can use ShUnit or write a bit of custom glue, in shell it is simple.

Expect is a tool specially designed for testing command-line programmes. It supports emulating terminal to the tested application, so it can be used for testing applications that require terminal interaction, which can't be tested with ctest or shell.

There is a Perl version of Expect and a wrapper to make simple uses simpler, Expect::Simple, or you can use Perl with just it's standard Test::Harness.

Python also has pexpect module for the same purpose and has the advantage of being better integrated in Windows.

I am sure Ruby will have such tool as well.

There are even some tools that can automate interaction with GUI applications, like the Linux Desktop Testing Project (which since learned to control applications using native Windows and MacOS GUI toolkits too).

You will likely use respective "xUnit" framework with the above mentioned languages and you could equally well do it with C++. It will handle running the tests in sequence for you, but the testing tools it provides won't be of much use for you. You'll have to write your own assertions for checking the output or use of the expect modules.

Note, that some of the above tools exist much longer than any xUnit. First version of expect was created in 1987 and DejaGNU (testing framework on top of expect used by GCC and some other GNU projects) changelog goes back to 1992 while I could only trace SUnit (Smalltalk, apparently first unit-testing framework) back to 1997.

Good example of project with extensive functional tests over command-line interface is gcc. It has a huge collection of code snippets that should compile and a huge collection of code snippets that should not compile and the test suite tries to compile them with the compiler that was just built and verifies whether the results work where they should and that appropriate diagnostics is given for those that shouldn't compile. Most other compilers and interpreters have similar test suites.

Another example would be git, where the primary interface is also command-line and tests are done using custom shell framework utilizing the runner from perl Test module, while it does not have much toward C-level API that would allow running tests in unit-test style.

Title: CppUnit for unit-testing executable files?

Body:
I am not sure if anyone has done it. I am trying to do something that is in general, uncommon i.e. unit-testing executable (Windows) or ELFs (Linux). I know that CppUnit provides a good unit testing facility, but I have never used it for unit-testing (used UnitTest++). I hear rumours that you can unit-test executables too. Does anyone have the experience in this?

A relevant post regarding the philosophy of it was here


问:
Choosing the right language for the job
I'm currently working for a company on the engineering team of about 5-6 people and have been given the job of heading up the redesign of an embedded system tester. We've decided the general requirements and attributes that would be desirable in the system, and now I have to decide on a language to use for the system, or at the very least come up with a list of languages with pros and cons to present to the team.

The general idea of the project is that we currently have a tester written in c++, which was never designed to be a tester, but instead has evolved to be such over the course of 3-4 years due to need. Writing tests for a new product requires modifying the 'framework' and writing code that is completely non-human readable or intuitive due to the way the system was originally designed. Now, we've decided that the time to modify this tester for each new product that we want to test has become too high and want to partially re-write the system so that we can program the actual tests in a scripting language that would then use the modified c++ framework on the back end to test the actual systems. The c++ framework would be responsible for doing all the actual work and the scripting language would just integrate with that to tell the framework what to do.

Never having programmed in a scripting language (we program embedded systems), I've run into a wall where I have no experience with any of the languages that we could possibly use, but must somehow give pros and cons of each language so that we can choose the best one for the job.

Currently my short list of possibilities includes:

Python

TCL

Lua

Perl

My question is this: How can a person evaluate a language that he/she has never used before? What criteria are good indicators for a languages potential usability on a project?

While helpful suggestions for my particular case are appreciated, I feel that this is a good skill to possess and would like to be able to apply this to many different projects if at all possible

答:
I am not sure if you have the budget for this, but you can hire people who can evaluate products/technologies for you.
Solution architects -normally give you sound advice backed with data.

But if you dont have the budget for this or you are the solution architect, its better you learn about the languages you are evaluating. There are forums which will advocate various languages but best bet would be to try out few tutorials and get a feel of it.
Also you might want to consider things pertaining to post production (installation, maintenance, version upgrade etc)

Title: Choosing the right language for the job


答:
People who dislike reading documentation dislike writing documentation. Plenty of programmers will do all they can to avoid reading a document thoroughly.

Don't focus on the writing, focus on the reading. When programmers read documentation and assimilate things from it, they will see the value and be much more inclined to write some.

Title: What's with the aversion to documentation in the industry?

Body:
There seems to be an aversion to writing even the most basic documentation. Our project READMEs are relatively bare. There aren't even updated lists of dependencies in the docs.

Is there something I'm unaware of in the industry that makes programmers dislike writing documentation? I can type out paragraphs of docs if needed, so why are others so averse to it?

More importantly, how do I convince them that writing docs will save us time and frustration in the future?