答:
Been there, got burned. Creating things that look like iterator but have different or extra requirements will lead to a mess. Basically many ranges are not copyable or at least not cheaply so, but that's what one normally expects of an iterator (it is a requirement of the iterator concept).

You should not have iterators that know of their own end. But chaining works with ranges. There are two ways to define ranges:

As forward-iterable "containers", which you can make of simple pair of iterators. This is a C++ way (and Boost.Range1 has some useful utilities for these), but sometimes it is quite a bit of extra work to make various objects that provide sequences fit the interface.

Define your interface for "generators". It will probably be similar to the python one, but since exceptions are less convenient in C++ than python, it will probably have different method of detecting end. I settled for following interface for my own needs2:

```<code>template <typename T> concept Generator {
    bool valid();
    void next();
    T get();
};
</code>```

where the iteration looks like:

```<code>while(g.valid()) {
    auto item = g.get();
    do_anything_with(item);
    g.next();
}
</code>```

the generator conceptually starts on first item in the sequence, but may only be accessed after valid is called. I found this allows distributing the hard work between constructor, valid and next as is fit for each case and it can be easily wrapped in iterator similarly to how istream_iterator is done. Other variations of the interface are possible including following the istream one (but it has disadvantage that it returns default element when the iteration fails).

Basically you should probably combine the approaches. If you use the later concept, you can adapt any such implementation to fit the (quite complex) Range concept from Boost.Range e.g. using "mixin" and Curiously Recurring Template Pattern. Something like:

```<code>template <typename GeneratorT, typename ValueT>
class GeneratorIterator :
    boost::iterator_facade<GeneratorT, ValueT, boost::single_pass_traversal_tag> {
    GeneratorT *g;
    GeneratorIterator() : g() {}
    GeneratorIterator(GeneratorT *g) g(g) {}
    ValueT &dereference() {
        if(!g || !g.valid())
            throw std::runtime_error("...");
        return g->get();
    }
    bool equal(GeneratorIterator const &l) {
        return g == l.g || ((!g || !g.valid()) && (!l.g || !l.g.valid()));
    }
    void increment() {
        if(g)
            g.next();
    }
}

template <typename GeneratorT, typename ValueT>
class GeneratorFacade {
  public:
    typedef GeneratorIterator<GeneratorT, ValueT> iterator;
    typedef GeneratorIterator<GeneratorT, ValueT> const_iterator;
    const_iterator begin() const {
        return const_iterator(this);
    }
    const_iterator end() const {
        return const_iterator();
    }
}
</code>```

The advantage of the indirection is that the ranges now don't have to be copyable at all or not cheaply while the iterator is just a pointer and therefore is cheaply copyable as required. And defining generators is simple and easy to understand while they still end up conforming to the hairy standard C++ interface.

(Disclaimer: I wrote it off top of my head, not tested)

1 Boost.Range includes concatenating ranges. Don't reinvent the wheel and reuse or at least inspire yourself.

2 The Iterators Must Go talk linked in Ylisar's answer comes up with the same interface, just different names. Note that many languages combine the next/popFront and valid/empty to one next that returns a boolean, but that approach is much more difficult to wrap in iterators and conceptually somewhat more complex, because then the iterators start out in special "uninitialized" state.

Title: Is it bad practice to make an iterator that is aware of its own end

Body:
For some background of why I am asking this question here is an example. In python the method chain chains an arbitrary number of ranges together and makes them into one without making copies. Here is a link in case you don't understand it. I decided I would implement chain in c++ using variadic templates. As far as I can tell the only way to make an iterator for chain that will successfully go to the next container is for each iterator to to know about the end of the container (I thought of a sort of hack in where when != is called against the end it will know to go to the next container, but the first way seemed easier and safer and more versatile).

My question is if there is anything inherently wrong with an iterator knowing about its own end, my code is in c++ but this can be language agnostic since many languages have iterators.

```<code>#ifndef CHAIN_HPP
#define CHAIN_HPP

#include "iterator_range.hpp"

namespace iter {
   template <typename ... Containers>
       struct chain_iter;
   template <typename Container>
       struct chain_iter<Container> {

        private:
           using Iterator = decltype(((Container*)nullptr)->begin());
           Iterator begin;
           const Iterator end;//never really used but kept it for consistency

        public:
           chain_iter(Container & container, bool is_end=false) :
               begin(container.begin()),end(container.end()) {
                   if(is_end) begin = container.end();
           }
           chain_iter & operator++()
           {
               ++begin;
               return *this;
           }
           auto operator*()->decltype(*begin)
           {
               return *begin;
           }
           bool operator!=(const chain_iter & rhs) const{
               return this->begin != rhs.begin;
           }
       };
   template <typename Container, typename ... Containers>
       struct chain_iter<Container,Containers...>
       {

        private:
           using Iterator = decltype(((Container*)nullptr)->begin());
           Iterator begin;
           const Iterator end;
           bool end_reached = false;
           chain_iter<Containers...> next_iter;

        public:
           chain_iter(Container & container, Containers& ... rest, bool is_end=false) :
               begin(container.begin()),
               end(container.end()),
               next_iter(rest...,is_end) {
                   if(is_end)
                       begin = container.end();
               }
           chain_iter & operator++()
           {
               if (begin == end) {
                   ++next_iter;
               }
               else {
                   ++begin;
               }
               return *this;
           }
           auto operator*()->decltype(*begin)
           {
               if (begin == end) {
                   return *next_iter;
               }
               else {
                   return *begin;
               }
           }
           bool operator !=(const chain_iter & rhs) const {
               if (begin == end) {
                   return this->next_iter != rhs.next_iter;
               }
               else
                   return this->begin != rhs.begin;
           }
        };
   template <typename ... Containers>
       iterator_range<chain_iter<Containers...>> chain(Containers& ... containers)
       {
           auto begin =
               chain_iter<Containers...>(containers...);
           auto end =
               chain_iter<Containers...>(containers...,true);
           return
               iterator_range<chain_iter<Containers...>>(begin,end);
       }
}

#endif //CHAIN_HPP
</code>```

Body:
Been there, got burned. Creating things that look like iterator but have different or extra requirements will lead to a mess. Basically many ranges are not copyable or at least not cheaply so, but that's what one normally expects of an iterator (it is a requirement of the iterator concept).

You should not have iterators that know of their own end. But chaining works with ranges. There are two ways to define ranges:

As forward-iterable "containers", which you can make of simple pair of iterators. This is a C++ way (and Boost.Range1 has some useful utilities for these), but sometimes it is quite a bit of extra work to make various objects that provide sequences fit the interface.

Define your interface for "generators". It will probably be similar to the python one, but since exceptions are less convenient in C++ than python, it will probably have different method of detecting end. I settled for following interface for my own needs2:

template <typename T> concept Generator {
    bool valid();
    void next();
    T get();
};

where the iteration looks like:

while(g.valid()) {
    auto item = g.get();
    do_anything_with(item);
    g.next();
}

the generator conceptually starts on first item in the sequence, but may only be accessed after valid is called. I found this allows distributing the hard work between constructor, valid and next as is fit for each case and it can be easily wrapped in iterator similarly to how istream_iterator is done. Other variations of the interface are possible including following the istream one (but it has disadvantage that it returns default element when the iteration fails).

Basically you should probably combine the approaches. If you use the later concept, you can adapt any such implementation to fit the (quite complex) Range concept from Boost.Range e.g. using "mixin" and Curiously Recurring Template Pattern. Something like:

template <typename GeneratorT, typename ValueT>
class GeneratorIterator :
    boost::iterator_facade<GeneratorT, ValueT, boost::single_pass_traversal_tag> {
    GeneratorT *g;
    GeneratorIterator() : g() {}
    GeneratorIterator(GeneratorT *g) g(g) {}
    ValueT &dereference() {
        if(!g || !g.valid())
            throw std::runtime_error("...");
        return g->get();
    }
    bool equal(GeneratorIterator const &l) {
        return g == l.g || ((!g || !g.valid()) && (!l.g || !l.g.valid()));
    }
    void increment() {
        if(g)
            g.next();
    }
}

template <typename GeneratorT, typename ValueT>
class GeneratorFacade {
  public:
    typedef GeneratorIterator<GeneratorT, ValueT> iterator;
    typedef GeneratorIterator<GeneratorT, ValueT> const_iterator;
    const_iterator begin() const {
        return const_iterator(this);
    }
    const_iterator end() const {
        return const_iterator();
    }
}

The advantage of the indirection is that the ranges now don't have to be copyable at all or not cheaply while the iterator is just a pointer and therefore is cheaply copyable as required. And defining generators is simple and easy to understand while they still end up conforming to the hairy standard C++ interface.

(Disclaimer: I wrote it off top of my head, not tested)

1 Boost.Range includes concatenating ranges. Don't reinvent the wheel and reuse or at least inspire yourself.

2 The Iterators Must Go talk linked in Ylisar's answer comes up with the same interface, just different names. Note that many languages combine the next/popFront and valid/empty to one next that returns a boolean, but that approach is much more difficult to wrap in iterators and conceptually somewhat more complex, because then the iterators start out in special "uninitialized" state.


问:
What are the pros and cons for the employer of code questions during an interview?
The Joel Test question #11 is: "Do new candidates write code during their interview?". What are arguments for and against to ask new candidates to write code during the interview and to make a decision upon it?</p>

答:
You really want to have the person write code in the interview - even better, get them to pair program with a member in your team for X amount of time (whatever you can comfortably afford in time/manpower).

It's pretty much one of the only ways you can tell if that person can code or not.

I slightly prefer the pair programming as it'll show their team work, gives them a real IDE to work with and lets them work on a 'real' problem (the other person in the pair can guide them past any environmental specifics that the interviewee could never reasonably know about).

We've started using this hiring policy and we're really happy with the results.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Exposing domain models over API
I'm building a simple RESTful API for a web-based application I'm working on, and I'm wondering about the best way to go about exposing my domain models.

Let's say I have a User class and I want to provide a JSON response with the various user properties. I obviously don't want to publicly expose every property of my model (things such as DateCreated, PasswordHash etc) due to security and bandwidth issues.

I've read into Data Transfer Objects and I'm wondering if this is the way to go. If I'm right I could pass, for example, a User model to my User DTO and ensure said DTO only allows exposure of the User properties I choose (which would also help decouple my models from my public API).

Is this solution appropriate or are there better ways to go about this?

Thanks.

答:
That's exactly one of the reasons why DTOs exists.

The tradeoff here is that adding DTOs makes your implementation a bit more complex, and thus prone to errors - such as a mismatch in mapping the domain object to a DTO. Use unit tests for this!

Another thing that you could do with your DTO and tends to be highly overlooked in RESTful services is treating hypertext data for references, nested objects and possible operations.

Refer to Martin Fowler's PoEAA:
"[...] it's worth mentioning that another advantage is to encapsulate the serialization mechanism for transferring data over the wire. By encapsulating the serialization like this, the DTOs keep this logic out of the rest of the code and also provide a clear point to change serialization should you wish."

http://martinfowler.com/eaaCatalog/dataTransferObject.html

TL;DR: I like the idea of separating the concerns of domain logic and "RESTful wiring" through DTOS, albeit introducing a more complex design.

Title: Exposing domain models over API


问:
Writing my problem solving approach on paper?
I'm a freshman Computer Science student and we just started doing some actual projects in Python. I have found I'm very efficient when I use the pen and paper method that my professor suggested in class. But when I can't write my problem down and work my algorithms out on paper I am really slow. During labs, I always seem to have to take the assignment back to my dorm. When I get there and write it out I solve the problem that took me the whole class in like 5 minutes.

Maybe it's because I get stressed seeing people solving labs before me. Or maybe it's the pen and paper method.

I was browsing through forums and someone wrote that if you have to write your programs on paper then you shouldn't be a programmer. I'm really worried because I'm so much better when I can see what the program is doing and track my way through it before typing actual code. Am I doing something wrong?

Edit: Sorry for being unclear, but when I said writing on paper I meant my problem solving approach (e.g writing examples, making tables with values, etc.) not my actual code. I just use the paper to get my ideas out.

答:
I don't put actual code down on paper, but for anything non-trivial I almost always start out on a whiteboard or a notebook. I usually sketch out:

Algorithms/process/control flow

Data structures

Relationships

Components (how do I break this problem down)

It's usually a combination of sketches, pseudocode and English.

I find that by doing this, it's easier to visualize as I start coding. I also will spot flaws before I start into the code because I can see everything in front of me (instead of incessant scrolling and window-hopping). Not only that, once it's written out I can let things form in the back of my mind as I'm working on other tasks. I can also work in a non-linear fashion, committing an idea to paper when it hits me and then come back to it when I reach the point where I need it.

Committing something to paper is a tremendous help for memory retention. The tagline for the Field Notes brand of notebooks is this:

I’m not writing it down to remember it later, I’m writing it down to remember it now.

After taking a more focused approach to writing things down on paper, even if I make an entry in the ToDo app on my phone a moment later, I find that the thought is cemented in my head far better than just making the electronic note. IOW, by planning my coding on paper/whiteboard, the ideas stay in my head better.

It also serves as a handy reference when it's time to document what I've written.


问:
Using Java Reflection to decouple code modules
I'm involved in a project with several modules. I found that programmers have designed one module to be easily decoupled from its dependent modules using Java Reflection. If other modules need to call a method in this module, the programmers are expecting them to use reflection to call it. This has resulted in a lot of places with hard-coded reflection calls. By hard-coded, I mean the class and method names are permanently fixed as Strings, which kind of defeats the purpose of reflection which is supposed to be for dynamic programming.

How can this be justified? I feel they are being novice about it and misusing the reflection API. I think polymorphism is the right way to decouple a module from another without breaking functionality. (Unfortunately, changing the entire code base to polymorphism is way too much maintenance.)

答:
If the sole purpose of the use of reflection is to decouple modules (in an abstract sense), then (IMO) it cannot be justified.

Why?

Because in reality it is NOT decoupling them.  Rather it is replacing one form of coupling with another form.  What is more, the second form of coupling (i.e. the hard-wired class and method name strings) is harder to spot, and more susceptible to breakage.

OTOH, if the use of reflection is intended to achieve other things, then it may well be justifiable on that basis.  For instance, the examples in the other Answers all have more specific purpose than just "reducing coupling".


问:
Advantage or disadvantages between recursive functions and for-loops
Whats the difference between the two procedures?
When should I be using a recursive function instead of a normal for-loop?</p>

答:
When function itself calls repeatedly until some specific condition is met.

Drawbacks:

recursion is slower in terms of speed and execution time.

recursion requires extra amount of runtime overload.


问:
How common is string manipulation, really?
I've noticed a lot of programming introductions (almost any language) usually include a heavy barrage of string manipulation quite early, such as:

Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".

Reverse the given string and remove all vowels from it.

Not just online courses, but even in degree programmes.

But the thing is, I've never encountered a situation in "real life" where you had to do anything like that. Is it just luck, or do you really need to do heavy manipulation in the above manner in some fields of programming? Can you give a description or an example where it is needed?

Edit:

Just to clarify, not necessarily string processing itself as in echoing variables to a html template, or other basic stuff like that, but the more arcane type of processing, like reading every second character? But yes, perhaps it is just for training purposes instead of direct needs. The file format conversion is a good note, though.

答:
These are very specific examples, really just given as training for string manipulation.

And it is more common than you think - mostly in parsing and UI code.

For example - parsing dates out of strings - this requires extensive string manipulation.

Or parsing HTML into a DOM - same kind of thing.

You will also need to manipulate strings for UI purposes - constructing strings based on specific data and conditions.


答:
Is it just luck, or do you really need to do heavy manipulation in the above manner in some fields of programming?

There are domains where string manipulation is not a necessity, or it is a marginal problem. There are also domains where it is a critical requirement.

For example, web technologies depend critically on text manipulation (web and mail servers and clients); so do most software development tools (IDEs, editors, compilers, etc).

Title: How common is string manipulation, really?

Body:
I've noticed a lot of programming introductions (almost any language) usually include a heavy barrage of string manipulation quite early, such as:

Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".

Reverse the given string and remove all vowels from it.

Not just online courses, but even in degree programmes.

But the thing is, I've never encountered a situation in "real life" where you had to do anything like that. Is it just luck, or do you really need to do heavy manipulation in the above manner in some fields of programming? Can you give a description or an example where it is needed?

Edit:

Just to clarify, not necessarily string processing itself as in echoing variables to a html template, or other basic stuff like that, but the more arcane type of processing, like reading every second character? But yes, perhaps it is just for training purposes instead of direct needs. The file format conversion is a good note, though.


答:
Text files and text data are everywhere.

Converting .csv to .xml, reading .py for execution or .f90 for compilation, building and sending spam from a list of mail addresses, building a database of keywords for indexing the web: all of that is string manipulation.

Do computers do something else than manipulating strings?


答:
String manipulation actually is fairly common when you're doing I/O, which includes most network programming. Unicode complicates things, of course, but text remains the closest thing we have to a universal interface.

But where it really shines is as a metaphor. Working with individual characters in strings is, in many ways, not unlike working with cells in memory. At the lowest levels, the operations can be almost identical. This makes strings a less abstract way of learning the very basics of working with data at low levels, and that makes it valuable to learn early.


问:
How to deal with pointers from child to parent?
I have a class that represents a file in specific binary format on disk (the parent in the title) and another class that represents an object inside that file (child). When the object changes, it sometimes needs to relocate to a new position in the file and the file class has to be notified about this new position.

To do this, I have added a weak_ptr field to object, which points to the file. Except that means there has to be a shared_ptr for file, so I'm using a static factory method instead of public constructor for it. And object now can't be initialized in the constructor, so I'm using unique_ptr for it.

In code, it looks something like this:

```<code>class File;

class Object
{
private:
    std::weak_ptr<File> file;

public:
    Object(std::weak_ptr<File> file)
        : file(file)
    {}

    void modify();
};

class File
{
private:
    std::unique_ptr<Object> object;
    std::shared_ptr<File> self;

    File()
    {}

public:
    void setObjectPosition(std::uint64_t newPosition);

    static std::shared_ptr<File> create();
};

void Object::modify()
{
    std::uint64_t newPosition = …;

    file.lock()->setObjectPosition(newPosition);
}

void File::setObjectPosition(std::uint64_t objectPosition)
{
    // store objectPosition
}

std::shared_ptr<File> File::create()
{
    auto file = std::shared_ptr<File>(new File());

    file->self = file;
    file->object = std::unique_ptr<Object>(new Object(file));

    return file;
}
</code>```

Is this this the right approach to do this? Or is there a better/more idiomatic solution? I feel like I'm using *_ptr too much, but I can't think of anything better.

答:
In these cases I think it's better to use a naked pointer from the child, if you can't guarantee that the parent out lives its child just let the destructor set it to 0 to signify that a child has no parent. This way you don't need 2 phase construction, and you don't pay the overhead of weak_ptr<>::lock at every turn.

You should probably also take a look at boost::enable_shared_from_this<>, in fact with the approach you're using now with File keeping an explicit reference to itself you defeat the purpose of using it in the first place.

Furthermore it's usually a good idea to use boost::make_shared<>, as it both uses fewer allocations ( saving you memory & cycles ), and just have better cache behavior all around ( since you usually poke the ref count when you poke the object ).


答:
Real life programming will almost certainly involve string manipulation at one point or another. Your example is a very specific case and may or may not appear in a real life scenario (In reality, I'm sure somebody, somewhere has had to tackle that problem in real life).

However, the real life applicability of a particular use case is not necessarily the point of those exercises when introducing a new language or teaching someone brand new to programming. The point of those exercises are likely to be any of the following (depending on context):

To teach a programmer the basic syntax of a given language using an easily understood problem.

To provide an exercise allowing novice programmers to learn basic programming logic without having to understand a complex problem.

To express a languages ability to solve a particular string manipulation problem.


答: When I interviewed for my current job, I was given a list of questions to write code for by the recruiter. I was very impressed because the questions were obviously written by someone who had a deep knowledge of SQL, so it works both ways.</p>

Title: What are the pros and cons for the employer of code questions during an interview?

Body: The Joel Test question #11 is: "Do new candidates write code during their interview?". What are arguments for and against to ask new candidates to write code during the interview and to make a decision upon it?</p>


问:
Are Nested Static Library dependencies possible?
I am working in QT .

Can a static library depend on another static library?(Static Lib is made by linking another static lib)

If yes, is it possible that after linking to  lib2, the generated lib(lib1) would not contain all the codes of lib2?

In my Qt Project I am using a static library, which depends on multiple libraries. I had to add all the libraries (with all their headers in my project), although I need only one lib (and one .h of that class) in my code.

Please explain the scenario.

答:
When you declare something you just promise that during linking it will be available and uniquely identified. Static libs are nothing more than containers for definitions in a format which is outside the standard. So, this has the following implications:

1 ) I don't quite get what you're asking here, but one static library can very much depend on another static library. Either you promise that the definitions of that library be available during the final linking stage of your executable ( by providing it as link dependency ). Or you "merge" it during linking of the static lib.

2 ) The answer to this then becomes that the only thing you need to do is simply to not link in lib2 during linking of lib1.

Overall the best approach in my experience is to only merge libs which are private, the reason being that otherwise clients will run into multiply defined symbols violations when other parts of their project shares dependencies with you.


问:
How do I support interfaces for different devices in the same input scenario?
I asked this question on SO but someone pointed out that I would be better off here. He's most likely right. So here I go!

So I just wanted an opinion. I have 2 different ways to approach the problem. Okay so I have a system that I wanna design toward the future. I have some types of objects wich takes as parameters an object implementing an Interface wich can itself contain another object Implementing another interface and so on.

In this way i have

```A(InterfaceB B)->B(InterfaceC C)->C(InterfaceD D) ...```

Until i get to a point where the object does not contain another one. Every interfaces implement a common interface. So I have

```Parent->InterfaceB   ---   Parent->InterfaceC   ---   Parent->InterfaceD```

But InterfaceD does not necessarily implement InterfaceB. Because an interface does not have only one implemention, I have multiple possible trees.

```A(InterfaceB B)->B(InterfaceC C)->C(InterfaceD D)->...```

and

```A(InterfaceB B)->B(InterfaceC Y)->Y(InterfaceZ Z)->...```

So my question is this : If i want to manage the possible trees, Am I better off using reflection to generate the possible trees on startup? Or would I be better off to hold the different trees in a xml file that I would parse on startup? I have to keep in mind that those Interface types and their implementations will keep coming on. So every time I add a new type, it has to be managed. I know both solution will work. My question is more like this : What would be the best approach to orient the system toward the future.

To add some context to the situation, here's an example of a case

All those interfaces expose an adaptor. Each adaptor may need another one to do its task. For instance, I have an adaptor wich parse some data. But then this data has to be communicated with a remote target. To do this it can use ethernet, serial port, etc... So I could have a generic parser wich takes a generic communicator. That's one of the different possibilities.

If you need some clarifications dont hesitate!

答:
I've been giving this some thought, and I believe your approach with interfaces is counter-intuitive.  If you really need this kind of flexibility, interfaces are the opposite of what you want, because interfaces establish specificity, not generality.

Unless, of course, you have a single interface that looks something like this:

```<code>public interface ICommand
{
    void Execute(string command);
}
</code>```

Which is actually what I suggest you do.  You can make that string anything you want; no need for any additional interfaces.

If you want to make it a bit more sophisticated, you can pass XML to your command, and deserialize it to an instance of a type.  You can even make it polymorphic by adding a parameter that specifies the type you want to deserialize to.

My point is that trying to specify your command interface using Interfaces is de-generalizing, which is the opposite of what you want.

Body:
I've been giving this some thought, and I believe your approach with interfaces is counter-intuitive.  If you really need this kind of flexibility, interfaces are the opposite of what you want, because interfaces establish specificity, not generality.

Unless, of course, you have a single interface that looks something like this:

public interface ICommand
{
    void Execute(string command);
}

Which is actually what I suggest you do.  You can make that string anything you want; no need for any additional interfaces.

If you want to make it a bit more sophisticated, you can pass XML to your command, and deserialize it to an instance of a type.  You can even make it polymorphic by adding a parameter that specifies the type you want to deserialize to.

My point is that trying to specify your command interface using Interfaces is de-generalizing, which is the opposite of what you want.


问:
Could ChromiumOS be re-written in Go from the ground up?
As Go seems able to performance match C and with Google obviously biased towards Go, I feel that it would be great way for Go to gain more traction.

The way ChromiumOS/Chrome has jumped from an Ubuntu base to a Gentoo base, while they have the ability to avoid both and create exactly what they need from scratch, leads me to believe it could be something in the works.

Time would of course be a factor, as would the lack of existing libraries as compared to C and Linux, but done in parallel whilst the current Linux based machines gain traction would mitigate any time to market issues for them.

I'm a rank amateur when it comes to low-level programming though, are there any technical limitations in the language to prevent this from happening?

答:
Could it? Almost, though not quite. There are still a few things very deep in the boot process where pretty much nothing but assembly language will do (the problem isn't so much speed as having ultra-low-level access). Go doesn't have any implementations that integrate cleanly with assembly, so you'd have to write those parts in a language that integrates with both assembly and Go. But you could use Go for the rest of the system.

Still, just because it could be done, should it? Probably not. Sometimes there are compelling reasons for ground-up rewrites, but doing it just to use a different language is generally not a good idea. You lose a robust and well-tested code base, and if you're just trying to port the code straight across, you don't gain anything in the exchange. If you're trying to go idiomatic, or do things that the new language makes easier, then you're generally better off designing something completely new.


答:
I think you're thinking about it in too much of a top down matter. This is a signal processing problem. The route I'd follow is to have a message bus that your inputs (or let's call them producers) send messages to and that your adaptors (or consumers) listen to. Your consumers can be responsible for transforming the messages so that another consumer can understand it. To make it highly adaptable, the consumers should be responsible for one thing and one thing only. So one consumer would be responsible for transforming a message, another would be responsible for taking a specific message and generating output. </p>

<p>A great book to read for pointers on how to create such a system would be Enterprise Integration Patterns. </p>

Title: How do I support interfaces for different devices in the same input scenario?

Body:
I asked this question on SO but someone pointed out that I would be better off here. He's most likely right. So here I go!

So I just wanted an opinion. I have 2 different ways to approach the problem. Okay so I have a system that I wanna design toward the future. I have some types of objects wich takes as parameters an object implementing an Interface wich can itself contain another object Implementing another interface and so on.

In this way i have

```A(InterfaceB B)->B(InterfaceC C)->C(InterfaceD D) ...```

Until i get to a point where the object does not contain another one. Every interfaces implement a common interface. So I have

```Parent->InterfaceB   ---   Parent->InterfaceC   ---   Parent->InterfaceD```

But InterfaceD does not necessarily implement InterfaceB. Because an interface does not have only one implemention, I have multiple possible trees.

```A(InterfaceB B)->B(InterfaceC C)->C(InterfaceD D)->...```

and

```A(InterfaceB B)->B(InterfaceC Y)->Y(InterfaceZ Z)->...```

So my question is this : If i want to manage the possible trees, Am I better off using reflection to generate the possible trees on startup? Or would I be better off to hold the different trees in a xml file that I would parse on startup? I have to keep in mind that those Interface types and their implementations will keep coming on. So every time I add a new type, it has to be managed. I know both solution will work. My question is more like this : What would be the best approach to orient the system toward the future.

To add some context to the situation, here's an example of a case

All those interfaces expose an adaptor. Each adaptor may need another one to do its task. For instance, I have an adaptor wich parse some data. But then this data has to be communicated with a remote target. To do this it can use ethernet, serial port, etc... So I could have a generic parser wich takes a generic communicator. That's one of the different possibilities.

If you need some clarifications dont hesitate!

Body:
I think you're thinking about it in too much of a top down matter. This is a signal processing problem. The route I'd follow is to have a message bus that your inputs (or let's call them producers) send messages to and that your adaptors (or consumers) listen to. Your consumers can be responsible for transforming the messages so that another consumer can understand it. To make it highly adaptable, the consumers should be responsible for one thing and one thing only. So one consumer would be responsible for transforming a message, another would be responsible for taking a specific message and generating output.

A great book to read for pointers on how to create such a system would be Enterprise Integration Patterns.


答:
Though it is not the primary intent of Data Transfer Objects, DTOs can be used to satisfy this concern in a similar manner to the data portion of a Presentation Model.

As it has been pointed out, this may bloat your design and something as simple as an added field may require changes to bubble up through the additional layers. Because of this, it is advisable to see if you can provide metadata to describe the serialization of the object. In many languages, this takes the form of specialized annotations that can be applied to your domain objects to avoid the tedious translation to DTOs. Packages like Jackson (through the use of Mixins) often take this idea a bit farther to completely separate your metadata from your domain model.

Title: Exposing domain models over API

Body:
I'm building a simple RESTful API for a web-based application I'm working on, and I'm wondering about the best way to go about exposing my domain models.

Let's say I have a User class and I want to provide a JSON response with the various user properties. I obviously don't want to publicly expose every property of my model (things such as DateCreated, PasswordHash etc) due to security and bandwidth issues.

I've read into Data Transfer Objects and I'm wondering if this is the way to go. If I'm right I could pass, for example, a User model to my User DTO and ensure said DTO only allows exposure of the User properties I choose (which would also help decouple my models from my public API).

Is this solution appropriate or are there better ways to go about this?

Thanks.


问:
How can I consolidate data from a group of remote SQL Server instances?
I work for a company whose point-of-sale service uses IIS servers tied to static IP addresses at each of our stores. My boss wants a better real-time stat tracker than what the point-of-sale service provides.

I would like to connect to these servers from a central location and retrieve the data. If possible, I'd like to be able to do so from Python, PHP, or Ruby. What are some recommended approaches for doing so.

答:
The simplest way to expose a MS SQL Database to a remote client is to use WCF Data Services. Using Visual Studio, you can walk through a wizard that looks at the database and creates the service for you in minutes.

WCF Data Services exposes your data using an open protocol called OData. There is a consumer library for Ruby that will consume an OData service and allow you to do whatever you want with it.


问:
How do web APIs work?
I have heard of many web APIs like that of Facebook, Twitter, etc., which helps third party access data and manipulate it.  I would like to know how a web API works. What are the basics of a web API?

If I want to create an API for my site, so that people can access or update it, what will I need to start with?

答:
That's actually a very broad question. In the most basic sense, a web API works when a client (like a Web browser) makes an HTTP request of some kind to a Web server. The server examines that request to figure out what the user wants, and then returns data in some format (like a page) that the client then examines to get what it wants. These are just about the only things that Web APIs have in common; I realize that this doesn't really answer your question, but I wanted to give a reason why the question is so broad.

There are all sorts of ways that a client could format its request, or that a server could format its response, and so in order for any of it to make sense, the client and server have to agree on some basic rules. Generally speaking, nowadays there are two very general styles that get used for this sort of thing.

Remote Procedure Call (RPC)

In an RPC style API, there's usually just one URL for the whole API. You call it by POSTing a document of some kind which contains information about what you want to do, and the server returns the document that has what you want. In general computing terms, the request document typically has a function name and some arguments.

Some standards for this style of API include XML-RPC and SOAP. These standards attempt to create a format that can be used to describe the function calls you're making, or even to describe the whole API.

REpresentational State Transfer (REST)

In a REST style API, you don't so much have a URL for the API as a name space: a server, or a folder inside of a server, where a lot of different objects reside, and every URL within this namespace becomes part of the API. Rather than telling the server that you want to use the API, the URL tells the server what you want to use the API on. You then use the HTTP method, and possibly the request body, to explain what you want to do to that object: GET (retrieve something that's already there), POST (create something new), PUT (replace something that's already there), or DELETE (get rid of something that's already there). There are a few other verbs you can use, but those are by far the most common.

So far, I haven't mentioned standard formats for REST. In theory, you could use just about any format. HTTP already provides for saying what you want to do and what you want to do it to, so the format of the request body could be just about anything: some representation of the object you want to create or replace. But in practice, REST authors tend to agree on a format anyway, because it would be difficult to make sense of every possible format.

Title: How do web APIs work?


问:
Is Dependency Injection worth it outside of UnitTesting
Given a constructor that will never, ever, have to use any different implementations of several objects that it initializes, is it still practical to use DI? After all, we might still want to unit test.

The class in question initializes a few other classes in its constructor and the classes it uses are pretty specific. It will never use another implementation. Are we justified in avoiding trying to program to an interface?

答:
I agree with both camps here and the matter is still open for debate in my opinion. YAGNI demands that I not tackle changing my code to fit supposition. Unit testing is not a problem here because I firmly believe that the dependency will never, ever change. But if I was Unit testing as intended to begin with, I would have never reached this point anyway. As I would have slimed my way into DI eventually.

Let me offer another alternative for my scenario specifically

With a factory pattern I can localize dependencies in one place. When testing I can change implementation based on context, and that's good enough. This doesn't go against YAGNI because of the benefits of abstracting several class constructions.


问:
Determining if language/framework/technology is 'Future-proof'
I'm a PHP developer and I recently started to work with CodeIgniter. It seems that whenever I search for something related to CodeIgniter, the blog posts and what not are usually from '09 or '10, so it got me thinking, is CodeIgniter still relevant and is it going to be in the future? Is there another framework that is taking it's place?

The same goes for other languages and frameworks as well. At what point do you abandon learning certain languages or frameworks? Is there any easy way to find those that are emerging and worth picking up?

答:
Mikeras answer is pretty nice. I'll add that future-proofing is a kind of security or risk management really. It often requires you to give up certain conveniences and cost/productivity benefits now to avoid problems later. I've been making nearly future-proof tech for quite a while now. There are certain patterns that can help. Here's a few.

Data should be stored in an open format that's easy to extract or transform later. Odd file formats are a big lockin technique & trap area in general. Also, prefer simpler approaches such as CSV, ASN.1, or JSON over complicated crap such as XML or, say, Word 97 format ;). The idea is that it's simple enough to throw a parser together yourself and the low-level format parser is reusable across your apps.

Applications ideally should have vendor- and tech-neutral interfaces built into them, plus a precise description of what they do. You should design stuff where you can change or throw away the implementation without breaking anything. Also, moving to a new platform is easy if your method of calling procedures or processing data works across platforms. So, the interfaces are the most important thing to get correct. The simpler, faster, and more open the interface implementation method the better.

The stack should be entirely open source and free to modify. GPL, LGPL, BSD, MIT, etc licenses are fine on this angle. The idea is that, if community starts dying off, then the stack might need to be moved to new [hardware/OS/protocol/etc]. And you need the code to do that.

The stack's design should be extremely modular with each piece being understandable by one person. This makes it easier for a new group to pick it up and maintain it. Having even the lowest levels of the runtime, libraries and compiler factored out nicely can have a huge payoff if it needs to be ported. Often, just that one part can be ported and all your old code will work.

Your app should be made in a modular way that factors out platform details to minimize rework in that area. It helps to structure functions into input/processing/output blocks where possible too. This can aid an analysis of what will be affected by a port (and correctness analysis in general a la' Cleanroom methodology). Lowest risk approach platform wise is to use lowest common denominator features that are supported about universally with one interface that lets you use them, further reducing porting. (I said you'd be loosing something...)

Dynamic typing, type inference or other flexible typing approaches help. A port to a new platform might change the definitions of the base types. Languages that do strong typing internally mean you worry less with this stuff.

Keep the concurrency model simple. Event-driven, message passing through clear interfaces is portable to... basically everything. There's also coroutines. You just want to avoid routes that are prone to both errors and portability problems.

Look at Mozilla and Apache's portable runtimes. They factor out many platform specific issues with certain interface and implementation choices. They can clue you in on what to worry about, along with providing good solutions to many problems.

Perfect example: Tcl. I know, plenty of people hate it and I rarely use it myself. Yet, Tcl is an extremely easy language to understand, implement (12 main rules), and code in. It's small, fast enough, integrates with Web servers, embeds in native apps, has been ported to tons of stuff, has certain safety features, and has been updated regularly since the 80's when it was made. You or I could implement a whole TCL runtime in no time for the core language. If we had to port the standard library, it would be easier than porting .NET or Java. And there's quite a bit of useful code written for it. And it's been used in web tech as far back as "mobile agent" craze that Java applets also aimed at. For instance, OpenACS web framework goes back to 1998 with server older than that.

Other examples: BASIC, COBOL and LISP (Scheme or CL). These languages all go back toward the 50's or 60's. They are simple enough to ease understanding, implementation and mechanical translation. Yet, you can build useful stuff with them. COBOL still powers most of world's transaction processing, has been updated a few times, & runs on .NET even. Old QBasic/QuickBASIC apps still run today with open/free tools on modern platforms, along with porting possibilities to better tools like GAMBAS or RealBASIC. LISP coders naturally make their systems modular and functional, easing porting. There's been a steady stream of implementations for it over decades, open and commercial.

So, interfaces, openness, simplicity, modularity, and platform-neutral architecture/design/coding. THESE will get you the future-proofing you require. Most of the time, anyway.


问:
How should modules access data outside their scope?
I run into this same problem quite often. First, I create a namespace and then add modules to this namespace. Then issue I always run into is how best to initialize the application? Naturally, each module has its own startup procedure so should this data(not code in some cases, just a list of items to run) stay with the module? Or should there be a startup procedure in the global namespace which has the startup data for ALL the modules.

Which is the more robust way of organizing this situation? Should some things be made centralized or should there be strict adherence to modules encapsulating everything about themselves?

Though this is a general architecture questions, Javascript centric answers would be really appreciated!

答:
OSGi is a framework used for inter-module communication. You can set up your modules to write/read from/to the osgi service, and hence setting up a channel to exchange data between modules.

Can this be done in Java script ? I am not sure but a google search does throw up a few interesting links which can be further explored


问:
Making a business case for a future proof Silverlight application
I have recently started working for a pretty big bank writing internal apps. I am being subcontracted out by the company I work for (who I have also recently started working for).

This bank has recently upgraded to Windows XP, they previously used Windows 2000.

I have been tasked with re-writing a report viewing application, which I am currently doing in MVC4 (Windows XP == Visual Studio 2010). The original app was written in .net 2 with webfoms, and is a bit of a mess.

The whole application seems to rely on state, where MVC is all about embracing the stateless nature of the web, as in the data you input to form A, affects the options you see in form B, options you select in form B affect form C etc etc (I love MVC and think that it is an awesome thing in the right context).

The whole maintaining models between states thing is starting to get pretty messy, and I can't help but thinking that I am either doing it wrong, or not using the right tool for the job.

My thoughts are that WPF would be perfect for this but the Computers are controlled by an external agency and are pretty locked down. We have slightly more control over the servers hosting the applications. The obvious next option is Silverlight(I think, maybe I'm horribly wrong!)

A couple of questions.

First: Is MVC ASP actually the best option here, or am I doing it wrong?

Second: What argument would you present to management if you agreed with me and thought a Silverlight based application was the way to go?

Using non MS based technologies is a no go. MVC4 is controversial.

答:
First off, there isn't a "future proof" application.  It just doesn't exist.  An application can be designed to handle change more easily and therefore better adapt to the future, but it's not future proof.

Since you're at a technology decision point, and you're constrained to the Microsoft stack, this is my recommendation based upon my experience.

Leave Silverlight alone.  Microsoft has not provided any information regarding updates or a roadmap in well over a year's time.  Cynics and critics have declared the language dead, but the reality is we don't know.  With Microsoft technology, don't know == don't use assuming you have the choice, which you do.  In short, I wouldn't use Silverlight at this point because you don't know how long it will be around.  But I like the MVVM pattern it provides.

Windows XP is slated to officially retire on April 8, 2014.  That having been said, nothing will force your current employer to upgrade their systems to Windows 7 or 8.  However, you can make future changes to the application easier by avoiding technologies that are more closely tied to the underlying OS.  To me, this means avoiding WPF.  Not because there is anything wrong with WPF, but because the environment your application will be running in will soon be in end-of-life legacy support.  Your worst case scenario is your application needing a security patch for WPF that isn't available on XP.

ASP.NET has the best chances of providing a technology that will work within your environment and has an active roadmap from Microsoft.

Many of the problems with winForms applications come from poorly structured code.  Even if using MVC4 is controversial, you can still use the underlying principles and patterns it presents.  Separating the view from the business logic (controller) from the data access logic (model) is a "good thing" and will make the application easier to change in the future.  There's quite a bit written on the MVC pattern as well as many variants such as MVVM and MVP.  Have a read over that information and you'll be well on your way to encapsulating responsibility within the appropriate layers of the new application.


答:
If you were going to hire a juggler, you'd be insane not to have him juggle for you. Or a musician you'd have audition. Otherwise you get stuff like the awesome yo-yo "master" K-strass. </p>

<p>Walking through something on a whiteboard is the programmers equivalent of a quick demo juggle. </p>

Body:
If you were going to hire a juggler, you'd be insane not to have him juggle for you. Or a musician you'd have audition. Otherwise you get stuff like the awesome yo-yo "master" K-strass.

Walking through something on a whiteboard is the programmers equivalent of a quick demo juggle.


问:
What are some possible alternatives for providing an 'Admin Password' for a desktop application?
I'm currently managing and re-factoring a piece of software that has been used at my company for over a decade now.  One of the elements of this application is a sort of admin or power-user mode which provides things like some additional/internal input as well as the ability to turn off input limits.

Historically this mode has been turned on by placing a specifically named file in a specific place in the windows system directory (both of which were hard coded into the application), the file being named 'something.DLL', even though it was an empty ASCII file and not a dll.

So I recently added some code and a little modal form that allows the user to enter an admin password to turn this functionality on.  It is a set password, not user specific.  When the correct password is entered, it does sort of the same thing by creating a 'key file' in the applications root directory so that the program can start in admin mode if that file is present.

Now the manager of the department that this software is mostly for doesn't like that idea so much.  He thinks that if we have just a simple, preset password that it will easily 'get out', and he doesn't want inexperienced users accessing those extra features.

So my question is, what other methods are there for providing this kind of access that would be somewhat more secure?  It's pretty much just me when it comes to maintaining and managing this software, so anything that isn't almost completely built in or automated wouldn't help (such as sending requests for 'license keys' or something similar to that).

Notes:  This application is written in VB.NET (.NET 4.0), and I am currently planning on using click-once deployment when the new version is done.

答:
Use Access Control Lists.

The quick and dirty way to do this is to remove all permissions from the application directory (including read permission), then add these permissions for any users who are permitted to run the application.  Of course, a user with permission could just as easily copy the application directory to a public location, but this is unlikely to happen accidentally, whereas password sharing can easily happen accidentally.

This assumes, of course, that the computers involved are secured (hopefully with active directory).


答:
If you have Active Directory, you can test for membership in an Active Directory Group:</p>

```<code>public bool IsInADGroup(string ADGroupName)
    {
        bool result = false;
        List<string> myGroups = new List<string>();

        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, SystemInformation.UserDomainName))
        {
            using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(pc, SystemInformation.UserName).GetGroups(pc))
            {
                src.ToList().ForEach(sr => myGroups.Add(sr.SamAccountName));
            }
        }
        result = myGroups.Contains(ADGroupName);
        return result;
    }
</code>```

Title: What are some possible alternatives for providing an 'Admin Password' for a desktop application?

Body:
I'm currently managing and re-factoring a piece of software that has been used at my company for over a decade now.  One of the elements of this application is a sort of admin or power-user mode which provides things like some additional/internal input as well as the ability to turn off input limits.

Historically this mode has been turned on by placing a specifically named file in a specific place in the windows system directory (both of which were hard coded into the application), the file being named 'something.DLL', even though it was an empty ASCII file and not a dll.

So I recently added some code and a little modal form that allows the user to enter an admin password to turn this functionality on.  It is a set password, not user specific.  When the correct password is entered, it does sort of the same thing by creating a 'key file' in the applications root directory so that the program can start in admin mode if that file is present.

Now the manager of the department that this software is mostly for doesn't like that idea so much.  He thinks that if we have just a simple, preset password that it will easily 'get out', and he doesn't want inexperienced users accessing those extra features.

So my question is, what other methods are there for providing this kind of access that would be somewhat more secure?  It's pretty much just me when it comes to maintaining and managing this software, so anything that isn't almost completely built in or automated wouldn't help (such as sending requests for 'license keys' or something similar to that).

Notes:  This application is written in VB.NET (.NET 4.0), and I am currently planning on using click-once deployment when the new version is done.

Body:
If you have Active Directory, you can test for membership in an Active Directory Group:

public bool IsInADGroup(string ADGroupName)
    {
        bool result = false;
        List<string> myGroups = new List<string>();

        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, SystemInformation.UserDomainName))
        {
            using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(pc, SystemInformation.UserName).GetGroups(pc))
            {
                src.ToList().ForEach(sr => myGroups.Add(sr.SamAccountName));
            }
        }
        result = myGroups.Contains(ADGroupName);
        return result;
    }


问:
Client-side javascript: How to include third party frameworks?
When developing web apps you often build your app on top of some frameworks like Twitter's bootstrap. These frameworks come with less/sass/stylus, javascript, images and sometimes webfonts.

I'm wondering how to embed these frameworks in my app. Most of my apps are build using some grunt tasks that compile my coffeescript and stylus to javascript respectively css.
Because I'm not shipping third party code (e.g. frameworks) with my app I add them as a dependency. This allows me to install e.g. frameworks using a package manager like npm or volo.

Handling small javascript libraries (which consist only of one file, no assets) is easy. I install them in a vendor dir and update my require.js conf. But if the library has images or less/sass/stylus/css files attached I'm always struggling how to handle them:

Paths to assets in the css files or javascript files of these libraries are often hardcoded (relative)

less/sass/stylus has to be compiled (which I can do with a grunt task)

Copy all third party assets into my folder structure?

Should I include third party assets (stylesheets, javascript) in my own files and minimize them together?

If I use stylus and the framework uses sass I have to install a lot of further dependencies

I think I'm not the only one who has these problems so I'm looking for solutions, best practices or some general tips.

答:
I'm wondering how to embed these frameworks in my app.

Short answer:

Use aliases?

If it can be automated, I don't see any harm in copying.

Long answer:

Listed below are some of the tools and techniques I use.

Bower

Bower is a package manager for the web. It offers a generic, unopinionated solution to the problem of front-end package management, while exposing the package dependency model via an API that can be consumed by a more opinionated build stack. There are no system wide dependencies, no dependencies are shared between different apps, and the dependency tree is flat.

Grunt.js

Grunt: The JavaScript Task Runner.

grunt-bower-task

Install Bower packages. Smartly.

... Also worth mentioning:

Git submodules

Submodules allow you to keep a Git repository as a subdirectory of another Git repository.

Real world example ...

Within my Gruntfile.js, I have a bower task:

```<code>bower : {

    install : {

        options : {

            targetDir : './files/plugins', // A directory where you want to keep your Bower packages.
            cleanup : true,                // Will clean target and bower directories.
            layout : 'byComponent',        // Folder structure type.
            verbose : true,                // Debug output.

        },

    },

},
</code>```

... the above requires a bower.json (next to the Gruntfile):

```<code>{
  "name": "simple-bower",
  "version": "0.0.0",
  "dependencies": {
    "normalize-css": "2.1.3",
    "foo": "https://github.com/baz/foo.git"
  },
  "exportsOverride": {
    "foo": {
      "scss": "foo/scss/",
      "css": "foo/*.css"
    }
  }
}
</code>```

When the above bower task is run, I get a folder structure that looks like (organized by "component"):

plugins/

normalize-css/ (component)

normalize.css

foo/ (component)

css/

foo.css

foo.min.css

scss/

foo.scss

partials/

_variables.scss

_functions.scss

_mixins.scss

_other.scss

Note: Using exportsOverride option, I was able to "grab" resources other than the main resource that was specified via the endpoint's (foo, in this case) bower.json.

Based on the above setup, I now have a folder called plugins/ (like, I assume, your vendor/ folder) and I can now point my Gruntfile tasks at said directory and/or files.

But if the library has images or less/sass/stylus/css files attached I'm always struggling how to handle them ...

Alias technique #1:

Question: Based on the above Bower install, how does one include normalize.css as a SASS partial?

One solution is to create an alias (cwd = my project's scss/ folder):

```<code>$ ln -s ../plugins/normalize-css/normalize.css _normalize.scss
</code>```

From there, I can treat the alias as an SCSS partial and @import into my scss files as I please.

Alias technique #2:

Question: Based on the above Bower install, how does one include foo's scss partials?

Assuming foo.scss includes all of the partials, it's not going to work as a direct alias because the @imports are relative.

Why not alias the whole folder then?

```<code>$ ln -s ../plugins/foo/scss ./foo
</code>```

Now I can easily include the 3rd party dependency's scss partials (or just foo.scss) in my project's build process without having to do much leg work.

Copying technique ...

Copy all third party assets into my folder structure?

I see no problems with this approach either. Optimally, you'd automate the copy with a task like:

grunt-contrib-copy

One approach could be a copy target that runs via an init task which would copy source files to the locations you specify in your build directory. From there, you'd run your other/process tasks to generate/build/copy the development/production files like you would normally.

Here's the copy task from one of my latest projects:

```<code>copy : {

    // Copies `normalize.css` from `plugins/` into the root-level `/demo/` folder:
    dev : {

        filter : 'isFile',
        expand : true,
        cwd : './files/plugins/',
        src : '**',
        dest : '../demo/',
        flatten: true,

    },

    // Copies source `scss` files into my distribution folder:
    prod : {

        filter : 'isFile',
        expand : true,
        cwd : './files/styles/',
        src : [
            '**/*',
            '!demo.scss',
        ],
        dest : '../<%= pkg.name %>/scss/',

    },

    // Copies images into the root-level `/demo/` folder:
    all : {

        expand : true,
        cwd : './files/images/',
        src : '**',
        dest : '../demo/',

    },

},
</code>```

Direct linking technique?

Depending on your needs, there's not much stopping you from relatively linking to 3rd party assets in your vendor/ folder. I'd say if direct linking doesn't work (due to some sort of relative import or something), then the above two aliasing options are good alternatives. Personally, I find that aliasing is nice because it keeps my path strings clean.

Minimize and/or uglify?

Should I include third party assets (stylesheets, javascript) in my own files and minimize them together?

I say, for production environment, definitely yes.

My personal approach is to have two build processes, one for "dev" and one for "prod". The former links to source files whereas the latter links to the min/uglified files.

I've given a basic outline of my build process here:

Have Grunt generate index.html for different setups

For me, the goal is to have a "dev" build for development (where I can easily use to hunt for bugs) and a "prod" build for production (keeping in mind, that new bugs may get introduced when the source files have been combined/minified/uglified).

Grunt tasks I use on a regular basis to generate my min/ugly files:

grunt-contrib-jshint

grunt-contrib-uglify

grunt-contrib-sass

grunt-contrib-less

grunt-contrib-htmlmin

Note: I always strive to include un-minified/uglified versions of 3rd party code in my builds; if I decide to use already compressed files, I skip the compression step (for these files) in my build process and just do the file concatenation instead.

3rd party uses different preprocessor/other?

If I use stylus and the framework uses sass I have to install a lot of further dependencies.

That's definitely a predicament. A few solutions I can think of:

Just prepare yourself for these eventualities. It's usually not too hard to install packages (homebrew helps), so once you're system is setup it should be easier the next time you encounter this type of situation. From there, it shouldn't be hard to find a Grunt task to incorporate the source files into your build. A lot of times I'll use a temp/ folder to store "inbetween" build files, and then I'll use other tasks to combine/minify/uglify said code with other code (for example, let's say I want to combine the sass/less generated files ... just slap them into /temp and combine them at some point during my build process).

Find a version of that framework that's using the tools you prefer. For example, Twitter's Bootstrap uses less; well, luckily, there happens to be a sass version. Problem solved (hopefully). :)

If it exists, and if you can get away with it, use the "generated" version of the framework. For example, I try to include a generated source file for every project I create ... I dunno about you, but I like having the option of viewing/using an already generated version of a plugin, especially if said plugin can work out-of-the-box in my project.

Other? I'm currently out of ideas on this one.

With all that said, I am by no means an authority on this topic ... The above is just what works for me. My personal preference for when it comes to this stuff is to strike a balance between simple and complex.

Body:
I'm wondering how to embed these frameworks in my app.

Short answer:

Use aliases?

If it can be automated, I don't see any harm in copying.

Long answer:

Listed below are some of the tools and techniques I use.

Bower

Bower is a package manager for the web. It offers a generic, unopinionated solution to the problem of front-end package management, while exposing the package dependency model via an API that can be consumed by a more opinionated build stack. There are no system wide dependencies, no dependencies are shared between different apps, and the dependency tree is flat.

Grunt.js

Grunt: The JavaScript Task Runner.

grunt-bower-task

Install Bower packages. Smartly.

... Also worth mentioning:

Git submodules

Submodules allow you to keep a Git repository as a subdirectory of another Git repository.

Real world example ...

Within my Gruntfile.js, I have a bower task:

bower : {

    install : {

        options : {

            targetDir : './files/plugins', // A directory where you want to keep your Bower packages.
            cleanup : true,                // Will clean target and bower directories.
            layout : 'byComponent',        // Folder structure type.
            verbose : true,                // Debug output.

        },

    },

},

... the above requires a bower.json (next to the Gruntfile):

{
  "name": "simple-bower",
  "version": "0.0.0",
  "dependencies": {
    "normalize-css": "2.1.3",
    "foo": "https://github.com/baz/foo.git"
  },
  "exportsOverride": {
    "foo": {
      "scss": "foo/scss/",
      "css": "foo/*.css"
    }
  }
}

When the above bower task is run, I get a folder structure that looks like (organized by "component"):

plugins/

normalize-css/ (component)

normalize.css

foo/ (component)

css/

foo.css

foo.min.css

scss/

foo.scss

partials/

_variables.scss

_functions.scss

_mixins.scss

_other.scss

Note: Using exportsOverride option, I was able to "grab" resources other than the main resource that was specified via the endpoint's (foo, in this case) bower.json.

Based on the above setup, I now have a folder called plugins/ (like, I assume, your vendor/ folder) and I can now point my Gruntfile tasks at said directory and/or files.

But if the library has images or less/sass/stylus/css files attached I'm always struggling how to handle them ...

Alias technique #1:

Question: Based on the above Bower install, how does one include normalize.css as a SASS partial?

One solution is to create an alias (cwd = my project's scss/ folder):

$ ln -s ../plugins/normalize-css/normalize.css _normalize.scss

From there, I can treat the alias as an SCSS partial and @import into my scss files as I please.

Alias technique #2:

Question: Based on the above Bower install, how does one include foo's scss partials?

Assuming foo.scss includes all of the partials, it's not going to work as a direct alias because the @imports are relative.

Why not alias the whole folder then?

$ ln -s ../plugins/foo/scss ./foo

Now I can easily include the 3rd party dependency's scss partials (or just foo.scss) in my project's build process without having to do much leg work.

Copying technique ...

Copy all third party assets into my folder structure?

I see no problems with this approach either. Optimally, you'd automate the copy with a task like:

grunt-contrib-copy

One approach could be a copy target that runs via an init task which would copy source files to the locations you specify in your build directory. From there, you'd run your other/process tasks to generate/build/copy the development/production files like you would normally.

Here's the copy task from one of my latest projects:

copy : {

    // Copies `normalize.css` from `plugins/` into the root-level `/demo/` folder:
    dev : {

        filter : 'isFile',
        expand : true,
        cwd : './files/plugins/',
        src : '**',
        dest : '../demo/',
        flatten: true,

    },

    // Copies source `scss` files into my distribution folder:
    prod : {

        filter : 'isFile',
        expand : true,
        cwd : './files/styles/',
        src : [
            '**/*',
            '!demo.scss',
        ],
        dest : '../<%= pkg.name %>/scss/',

    },

    // Copies images into the root-level `/demo/` folder:
    all : {

        expand : true,
        cwd : './files/images/',
        src : '**',
        dest : '../demo/',

    },

},

Direct linking technique?

Depending on your needs, there's not much stopping you from relatively linking to 3rd party assets in your vendor/ folder. I'd say if direct linking doesn't work (due to some sort of relative import or something), then the above two aliasing options are good alternatives. Personally, I find that aliasing is nice because it keeps my path strings clean.

Minimize and/or uglify?

Should I include third party assets (stylesheets, javascript) in my own files and minimize them together?

I say, for production environment, definitely yes.

My personal approach is to have two build processes, one for "dev" and one for "prod". The former links to source files whereas the latter links to the min/uglified files.

I've given a basic outline of my build process here:

Have Grunt generate index.html for different setups

For me, the goal is to have a "dev" build for development (where I can easily use to hunt for bugs) and a "prod" build for production (keeping in mind, that new bugs may get introduced when the source files have been combined/minified/uglified).

Grunt tasks I use on a regular basis to generate my min/ugly files:

grunt-contrib-jshint

grunt-contrib-uglify

grunt-contrib-sass

grunt-contrib-less

grunt-contrib-htmlmin

Note: I always strive to include un-minified/uglified versions of 3rd party code in my builds; if I decide to use already compressed files, I skip the compression step (for these files) in my build process and just do the file concatenation instead.

3rd party uses different preprocessor/other?

If I use stylus and the framework uses sass I have to install a lot of further dependencies.

That's definitely a predicament. A few solutions I can think of:

Just prepare yourself for these eventualities. It's usually not too hard to install packages (homebrew helps), so once you're system is setup it should be easier the next time you encounter this type of situation. From there, it shouldn't be hard to find a Grunt task to incorporate the source files into your build. A lot of times I'll use a temp/ folder to store "inbetween" build files, and then I'll use other tasks to combine/minify/uglify said code with other code (for example, let's say I want to combine the sass/less generated files ... just slap them into /temp and combine them at some point during my build process).

Find a version of that framework that's using the tools you prefer. For example, Twitter's Bootstrap uses less; well, luckily, there happens to be a sass version. Problem solved (hopefully). :)

If it exists, and if you can get away with it, use the "generated" version of the framework. For example, I try to include a generated source file for every project I create ... I dunno about you, but I like having the option of viewing/using an already generated version of a plugin, especially if said plugin can work out-of-the-box in my project.

Other? I'm currently out of ideas on this one.

With all that said, I am by no means an authority on this topic ... The above is just what works for me. My personal preference for when it comes to this stuff is to strike a balance between simple and complex.


问:
What mistakes in managing software products must be avoided to keep people from hating the vendor?
A previous question about why people hate Microsoft was closed. This is an attempt at a somewhat more constructive question along the same general line. This one is both broader and narrower though. It's more general by being about software vendors in general, not just Microsoft. It's narrower by dealing only with management of software products.

So, what steps should be taken (and/or avoided) in managing individual software products to assure that not only the individual products, but the company as a whole is respected/liked/seen in a positive light?

答:
Let me discuss this from the angle of the commercial software I've used that has driven me crazy.

Too much flexibility - this is critical. Do not let your desire to offer flexibility mean that you give up on designing the features most people would want. I have never used a "flexible" product that users actually liked using. They don't want to have to figure out how to fix your design errors. We have "flexible" project management software from a well-know vendor that shall remain nameless. It's so flexible it doesn't have things like a field for the client who requested the project (Just how many companies big enough to need a product that costs tens of thousands of dollars don't need to be able to sort projects by client? That would be zero.). When you convert an idea or an incident to a project, the information doesn't automatically move to the project, making searching for details about what was wanted or who wanted it extremely annoying because the devs didn't really design the system, since it was so "flexible". The complexity of trying to add fields and then fix all the forms so you can see those fields means that pretty much everyone has given up using the product for all the "great" features it was sold to us as having and only use it to document time.  In general, the more flexible a system is, the more people will hate it.

Lack of consideration for performance by wanting to be database neutral instead of writing the better performing code that might be database specific.

Lack of testing in an environment with hundreds of simultaneous users and a large data set in the database. Database queries that work fine for small data sets are often disatrous for large databases. I worked at a call center once that had a well-know call center software program, it could take ten minutes to move from one screen to the next. You can imagine how much both the call takers and the users liked this. Our most common error was a timeout on the database.

Change for change sake. Nothing annoys users more than getting a new version of something that rearranges how to do everything and yet adds no features that they wanted or needed (see Office 2007 and the crappy Ribbon they added and the menu structure they removed). I don't want to have to relearn the stuff I depend on day-to-day evey year or two years and neither do most users. It's one thing to learn new techiniques to better solve problems and it's another thing to just reaarrange the GUI so that you can't find all the stuff you already knew how to do.

Customer service. If I have a problem, I want you to help me fix it quickly and without it costing too much, especially if I paid a huge amount for the software.

Ridiculously buggy software. Come on, I shouldn't be able to break it doing common tasks in an ordinary way. You did test this stuff didn't you? It is especially anoying when you hit bugs in installation or the first couple of days using the product. It is even more annoying when the stuff that worked great in the last version no longer works.  Sure all code has bugs, we know that, but the most obvious ones should be tamed before shipping.

Now as to a company that does it right - I submit that Red-Gate is that company. Their stuff just works, it does what it says it should do without a lot of trouble on my part to use it, it's fast and their customer service is great. Pretty much every experienced SQl Server dba I have ever known recommends buying their tools.


问:
Clarity over Python and Jython
I'm a Java programmer, but I want to program in Jython. I've never coded in Python before, but have been looking through some tutorials and I'm fairly confident I can grasp it. </p>

<p>My question is clarity over Jython. I understand with Jython you have the joys of writing Python code with the added bonus of accessing Java libraries. Does this mean, all aspects and coding practices of Python can be applied, such as creating animation, input out structures, or is there a whole new structure which needs to be learned to code Jython? </p>

答:
Jython is Python implemented in Java.  Unfortunately, if you want the latest and greatest, you won't get it.  The Jython implementation is several versions behind, so some newer features are not available.

As you noted, you can import from Java libraries and use the features you want from Java.

Coding style is radically different from Java.  Indentation is important, as is choice of tabs or spaces for indentation.

Variable usage and typing is also significantly different.  Variables are not declared, but must be assigned before use.

The ability to prototype at the command line is a great feature.

The static code analysis you are used to in Java is not a feature of the language.  Some IDEs do provide the some checks, and can save debugging time.

Any real-time animation will have the same issues with garbage collection that a Java program would have.

Title: Clarity over Python and Jython


答:
My preference is as @Dan suggested - use active directory. If this is not possible, then a password generator based on time can be useful. In a similar situation, (very distant past) one my company I worked for used 9999-MMDD. This did get out after a couple of years. If you threw in hhmm and mixed it up a bit you might get a year or two out of it before someone lets the cat out the bag.

You could always write a program that generates a password using a similar, but more complex strategy. Throw in the used name an machine name as well. You manager can run that program to get the current password for just that machine. Store some information in the file so its not valid if copied to another machine or if a different user is logged in. Its then up to you manager to keep the program secure and if the cat gets out, its his fault.

This scheme is considered weak and unreliable from a cyrpto perspective, but is adequate for the problem you have.


答: Jython is an implementation of Python, just like OpenJDK is an implementation of Java. And just like with Java, it doesn't matter which implementation you use (provided that you don't use any implementation-specific features, obviously).</p>

Title: Clarity over Python and Jython

Body:
I'm a Java programmer, but I want to program in Jython. I've never coded in Python before, but have been looking through some tutorials and I'm fairly confident I can grasp it. </p>

<p>My question is clarity over Jython. I understand with Jython you have the joys of writing Python code with the added bonus of accessing Java libraries. Does this mean, all aspects and coding practices of Python can be applied, such as creating animation, input out structures, or is there a whole new structure which needs to be learned to code Jython? </p>


答:
Either way you go, you're putting a different peg in the same hole; you're just saying well this peg is a little rounder than the other one, is it better?

There is no reason an ASP.NET MVC app cannot appear to function the same way as an ASP.NET WebForms app. This will require different approaches because the two frameworks have radically different philosophies. Ultimately WebForms managed more state for you, but the state capabilities are identical.

Make sure you ask, and consider why ASP.NET MVC was chosen before making a proposal to management that a client dependent technology be considered

Title: Making a business case for a future proof Silverlight application

Body:
I have recently started working for a pretty big bank writing internal apps. I am being subcontracted out by the company I work for (who I have also recently started working for).

This bank has recently upgraded to Windows XP, they previously used Windows 2000.

I have been tasked with re-writing a report viewing application, which I am currently doing in MVC4 (Windows XP == Visual Studio 2010). The original app was written in .net 2 with webfoms, and is a bit of a mess.

The whole application seems to rely on state, where MVC is all about embracing the stateless nature of the web, as in the data you input to form A, affects the options you see in form B, options you select in form B affect form C etc etc (I love MVC and think that it is an awesome thing in the right context).

The whole maintaining models between states thing is starting to get pretty messy, and I can't help but thinking that I am either doing it wrong, or not using the right tool for the job.

My thoughts are that WPF would be perfect for this but the Computers are controlled by an external agency and are pretty locked down. We have slightly more control over the servers hosting the applications. The obvious next option is Silverlight(I think, maybe I'm horribly wrong!)

A couple of questions.

First: Is MVC ASP actually the best option here, or am I doing it wrong?

Second: What argument would you present to management if you agreed with me and thought a Silverlight based application was the way to go?

Using non MS based technologies is a no go. MVC4 is controversial.


问:
When using an ORM should mappings be defined in the code file?
Doctrine offers three ways to define the object mapping properties: in XML, in YAML and as inline docblock annotations in the code.  The Doctrine documentation doesn't give any advice on choosing among them, but I'm specifically wondering if there is a generally accepted for best practice with regard to keeping mapping metadata for an ORM system in the file where the objects are defined versus keeping it in a separate data file.  Is there?</p>

答:
I don't think so.

The different options are there to satisfy developers' personal preferences.  Some people don't like XML, preferring something a bit simpler and more straightforward like YAML.  Annotations are a nice way to add ORM capability to code that already exists.

It certainly seems to be in keeping with PHP's philosophy of "There's more than one way to do it, and the more ways the better."


问:
How should I create a combined interface for two logically independent modules?
I'm having trouble coming up with a good way to structure the interfaces for two modules that are logically independent but whose implementations may be combined for the purposes of performance or efficiency.

My specific situation is the replacement of the separate queuing and logging modules in a message routing application with a combined database-backed implementation (let's call it DbQueueLog).  It's easy enough for DbQueueLog to implement both the IQueue and ILogger interfaces so clients of the old queuing and logging modules can use it seamlessly.  The challenge is that the most efficient and performant implementation of DbQueueLog involves combining the EnqueueMessage(Message m) and LogMessage(Message m, List<LogParams> p) methods into an EnqueueAndLogMessage(Message m, List<LogParams> p) method that minimizes the number of cross-process database calls and the amount of data written to disk.  I could create a new IQueueLog interface with these new methods, but I'm uncomfortable with what that would mean if a future iteration of the application moved back to separate queuing and logging modules.

Are there any design approaches to this situation that would allow me to build the efficient, performant DbQueueLog implementation now without permanently coupling together the application's queuing and logging modules?

Edit: The application is built on Windows using C# in case any there are any platform-specific techniques that might be available.

答:
It sounds like EnqueueAndLogMessage is a pretty typical Service. My suggestion is to expose an interface to EnqueueAndLogMessage. Then, in the concrete implementation of the service, use two instance variables for your EnqueueMessage and LogMessage interfaces. This will allow you to provide one service which handles both the queing and logging capabilities, without tying you to the implementation of either. If you no longer need the combined service, it's as simple as calling a different service.

Psuedo-code:

```<code>Interface EnqueueAndLogMessageService {
   public void queAndLogMessage(Message message);
}

Class EnqueueAndLogMessageServiceImpl {
   EnqueueMessage enqueueMessageSvc;
   LogMessage logMessageSvc;

   public void queAndLogMessage(Message message) {
      enqueueMessageSvc.queMessage(message);
      logMessageSvc.logMessage(message);
   }
}
</code>```

Body:
It sounds like EnqueueAndLogMessage is a pretty typical Service. My suggestion is to expose an interface to EnqueueAndLogMessage. Then, in the concrete implementation of the service, use two instance variables for your EnqueueMessage and LogMessage interfaces. This will allow you to provide one service which handles both the queing and logging capabilities, without tying you to the implementation of either. If you no longer need the combined service, it's as simple as calling a different service.

Psuedo-code:

Interface EnqueueAndLogMessageService {
   public void queAndLogMessage(Message message);
}

Class EnqueueAndLogMessageServiceImpl {
   EnqueueMessage enqueueMessageSvc;
   LogMessage logMessageSvc;

   public void queAndLogMessage(Message message) {
      enqueueMessageSvc.queMessage(message);
      logMessageSvc.logMessage(message);
   }
}


问:
AS2 vs AS3 communication protocol difference. Server requirement
I'm researching what's needed for EDI as far as protocols and server/application setup.
This is transportation industry and I'm interested in X12 format for transactions like 204, 210, 214.

Specific question is:
Do BOTH trading partners have to run servers? With AS3 it seems like SFTP server and it seems like one partner can run it and another partner can push/pull.

What about AS2? Can it have server only on one side? Or both partners should be able to push?

答:
Yes, for AS2 both sides run HTTP server. Here is good explanation on how this works:

http://as2integration.org/display/AS2/AS2+Protocol+Operation

I also was able to develop our own AS2 server and sender based on IIS WCF stack + EldoS EDIBlackBox


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

答:
"Structure and Interpretation of Computer Programs", Abelson & Sussman.

"Structured Programming", Dahl, Dijkstra & Hoare.

"GOTO Statement Considered Harmful", Dijkstra.


答:
Since Active Directory is not an option, I would hash the current date. Use elements with the most entropy first (day of month) and those with least entropy last (year). If need be, add a domain-specific salt (a customer ID, company name, etc. since it is used outside your company). This should produce a very different password each day that is practically impossible for end users to guess, and it can be different for different companies that use the software.

This is essentially a chicken and egg problem since the software needs to be able to authenticate the user without phoning home. So make an egg with a really obscure cracking mechanism: while security through obscurity is not real security, this is the best you have given the parameters of your problem.

This is also better than placing a text file somewhere: that is no better than a static password because once the secret gets out, game over.


答:
The manager is right about the password getting out. Its not a matter of if, but when.

Since Active Directory isn't an option for some users, you could create a signed text file with a list of windows login names that are allowed super user access. This assumes that people are not sharing computers or logins.

The user names would just go in an easily distributed text file that would be put in the application's folder. The important part is to sign the list of user names. Keep it very simple. One user name per row and put the hash on the last line. Embed some sort of secret key in your program binary and hash it with the usernames. The secret key will prevent people from modifying the file and then calculating the hash themselves (which is probably far-fetched to start with).

```<code>UserName1
UserName2
.
.
.
UserName34
<HashOfUserNamesAndSecretKey>
</code>```

This, of course, requires someone somewhere to act as the admin of the list of authorized users. The admin should have a program (written by you!) that generates the file and hash. If nothing else, it could just take an text file of user names and add the hash.

In the interest of being thorough, someone who has been revoked access could grab the copy of the file that still has their login name in it. Whenever they wanted access, they could just put their copy in place. Probably not something to worry about, though.

Body:
The manager is right about the password getting out. Its not a matter of if, but when.

Since Active Directory isn't an option for some users, you could create a signed text file with a list of windows login names that are allowed super user access. This assumes that people are not sharing computers or logins.

The user names would just go in an easily distributed text file that would be put in the application's folder. The important part is to sign the list of user names. Keep it very simple. One user name per row and put the hash on the last line. Embed some sort of secret key in your program binary and hash it with the usernames. The secret key will prevent people from modifying the file and then calculating the hash themselves (which is probably far-fetched to start with).

UserName1
UserName2
.
.
.
UserName34
<HashOfUserNamesAndSecretKey>

This, of course, requires someone somewhere to act as the admin of the list of authorized users. The admin should have a program (written by you!) that generates the file and hash. If nothing else, it could just take an text file of user names and add the hash.

In the interest of being thorough, someone who has been revoked access could grab the copy of the file that still has their login name in it. Whenever they wanted access, they could just put their copy in place. Probably not something to worry about, though.


问:
Distributing a data access solution across multiple solutions
I have 3 solutions, one of them is a dataccess solution with all the repositories etc. At the moment when a change is made to it, the others have to go get the latest nuget version locally, we have a nuget server on the LAN. Its a pain to debug though.

Would a git submodule work here to enable debugging and not worry about updating nuget packages?

答: It sounds like you're looking for something to handle your dependency management. In that case, I'd recommend looking into Maven. You can integrate Maven into your builds so that new revisions of library code are automatically downloaded and incorporated (using SNAPSHOTS). </p>


答:
Why do you have a data access solution? You act as if that's a best practice.

Data Access is a layer, not its own initiative.

You should refactor your code so that the data access projects are used by the other solutions. Data access shouldn't be implemented as its own solution.

Title: Distributing a data access solution across multiple solutions

Body:
I have 3 solutions, one of them is a dataccess solution with all the repositories etc. At the moment when a change is made to it, the others have to go get the latest nuget version locally, we have a nuget server on the LAN. Its a pain to debug though.

Would a git submodule work here to enable debugging and not worry about updating nuget packages?