问:
Best design pattern for library with data model
I am refactoring an old Codeigniter library to be php framework agnostic. There are these core parts:

the connection object - this will come from the "user"; ie, the framework's connection, or their own connection library. My library will not want to "know about it" except that (at first) it will be a PDO conn object (but things should be written to handle a native driver type)

the model object - runs the queries & returns results array (or error array) to the main lib. As it is now, it is very "thin" and only has transactions, query building & the actual db query

the model interface - I'm a big fan of interfaces, and I see this model as being swappable for a NoSQL model, for example

the main library - in my current CI library, this 1) receives the function request, 2) validates the params passed to it, 3) requests from the model, 4) creates a response array that includes the data & error codes and messages (multilingual configurable, but not really part of this question)

So, in summary, the way it works NOW is in your controller or calling page:

1) call main lib function
2) main lib calls model
3) model returns to main lib
4) main lib returns to controller

NOW starts my real design pattern question:

I would like to pass my conn object via DI to my main library, but I'd also like to pass my model via DI to the main library to keep things flexible. The flexibility goal I'm after would be to allow people to create their own Native DB or NoSQL models & pass non-PDO conns into this, so keeping them decoupled seems optimal.

BUT to do this, the only thing I can think of would end up as:

(controller - where I might actually execute the query in the lib, not model)

```<code>$conn //from the user
$model = new MyModel();
$lib = new MyLib($conn, $model);
</code>```

or

```<code>$conn //from the user
$model = new MyModel($conn);
$lib = new MyLib($model);
</code>```

which feels more "natural" since the query & conn tend to work together

Either case feels pretty clumsy for the user, and I can't help but wonder if I'm not either overdoing this whole DI thing or just have picked the wrong design pattern to go about this.

Any guidance as to how to best set this up would be greatly appreciated - spent more time thinking about this than it will take me to refactor the actual code!

TIA

答:
I could be waaaaaay off, but...

It seems that a model is necessary to use the library, you just don't care which one, right? Further, the library doesn't care how the model gets its data, or where the data comes from, it just wants an object that meets the criteria of the interface.

If the library doesn't need the connection object, then make that the responsibility of the model.

```<code>interface MyFooModelInterface
{
    public function getItem($id);
    public function addItem($item);
    ...
}
</code>```

And here is a simple class example:

```<code>class MyLib
{
    protected $model;

    public function __construct(MyFooModelInterface $model)
    {
        $this->model = $model;
    }

    public function getItemById($id)
    {
        return $this->model->getItem($id);
    }
}
</code>```

And a Model example:

```<code>class MyModel implements MyFooModelInterface
{
    protected $conn;

    public function __construct(\PDO $conn)
    {
         $this->conn = $conn;
    }

    public function getItem($id)
    {
        ...
    }
    public function addItem($item)
    {
        ...
    }
}
</code>```

And here is an example of using it:

```<code>// the model is responsible for handling the data retrieval, not the library
$model = new Model($conn);

$lib = new MyLib($model);
return $lib->getItem($id);
</code>```

Now, if I decide that I want a file-based solution, I can easily swap the model.  To test the model, the connection obj is injected, so that's easy.  To test the library, the model is also injected, so, again, that's easy.

In this case, the model is only responsible for getting the data, while the library is responsible for handling and processing the data.  Neither cares what or how the other one does it.

EDIT

the library with a factory method to create the model if none was given...

```<code>class MyLib
{
    protected $model;

    public function __construct(MyFooModelInterface $model = null, $conn = null)
    {
        // if we have a model, use it
        if (!is_null($model)) {
            $this->model = $model;
        }

        // if we don't have a model, but have a connection obj, make a model
        if (is_null($model) && !is_null($conn)) {
            $this->model = $this->factoryModel($conn);
        }

        // if we don't have either, quit and go home
        if (is_null($model) && is_null($conn)) {
            throw new Exception('need moar inputs');
        }
    }

    protected factoryModel($conn)
    {
        $this->model = new MyModel($conn);
    }

    public function getItemById($id)
    {
        return $this->model->getItem($id);
    }
}
</code>```

Body:
I could be waaaaaay off, but...

It seems that a model is necessary to use the library, you just don't care which one, right? Further, the library doesn't care how the model gets its data, or where the data comes from, it just wants an object that meets the criteria of the interface.

If the library doesn't need the connection object, then make that the responsibility of the model.

interface MyFooModelInterface
{
    public function getItem($id);
    public function addItem($item);
    ...
}

And here is a simple class example:

class MyLib
{
    protected $model;

    public function __construct(MyFooModelInterface $model)
    {
        $this->model = $model;
    }

    public function getItemById($id)
    {
        return $this->model->getItem($id);
    }
}

And a Model example:

class MyModel implements MyFooModelInterface
{
    protected $conn;

    public function __construct(\PDO $conn)
    {
         $this->conn = $conn;
    }

    public function getItem($id)
    {
        ...
    }
    public function addItem($item)
    {
        ...
    }
}

And here is an example of using it:

// the model is responsible for handling the data retrieval, not the library
$model = new Model($conn);

$lib = new MyLib($model);
return $lib->getItem($id);

Now, if I decide that I want a file-based solution, I can easily swap the model.  To test the model, the connection obj is injected, so that's easy.  To test the library, the model is also injected, so, again, that's easy.

In this case, the model is only responsible for getting the data, while the library is responsible for handling and processing the data.  Neither cares what or how the other one does it.

EDIT

the library with a factory method to create the model if none was given...

class MyLib
{
    protected $model;

    public function __construct(MyFooModelInterface $model = null, $conn = null)
    {
        // if we have a model, use it
        if (!is_null($model)) {
            $this->model = $model;
        }

        // if we don't have a model, but have a connection obj, make a model
        if (is_null($model) && !is_null($conn)) {
            $this->model = $this->factoryModel($conn);
        }

        // if we don't have either, quit and go home
        if (is_null($model) && is_null($conn)) {
            throw new Exception('need moar inputs');
        }
    }

    protected factoryModel($conn)
    {
        $this->model = new MyModel($conn);
    }

    public function getItemById($id)
    {
        return $this->model->getItem($id);
    }
}


问:
What is this programming style? "Monoid-ic"?
In a moderately old blog post, Conal Elliot makes an interesting (if less than serious) argument that C is a purely functional language, by drawing a parallel between the combination of the C preprocessor and C itself, and that of Haskell's pure expression language and its impure IO action values. It's observed further down that the phase separation between C's components actually makes what cpp does quite different from Haskell, though, so cpp+C is not monadic after all.

In real programming projects, C programmers prefer to minimize their use of cpp as far as possible. The macro language may be capable of amazing things, but it's a fairly hostile programming environment. So as far as I can tell this concept is mostly unexplored from a C perspective.

However, building on the example of C, we could envisage a language where the primary way of programming is for the developer to write a purely functional program which builds a fixed sequence of action values and strings them together into a finished program. Distinct from Haskell's model in that the functional program only exists at "compile time", with a clear separation between the two stages of evaluation and execution; distinct from C's model (or Lisp's) mainly in the emphasis on the "macro" stage as the primary programming tool (and with a macro stage that isn't.. y'know, horrible - rather, it looks and runs like the full-fledged language), with the end program consisting of a fixed sequence of "action" building-blocks that the developer is discouraged (or even prevented) from authoring directly.

Does this programming paradigm exist? If so, what is it called and what are existing examples of it? Is there any literature on this topic?

("Metaprogramming" is the obvious answer, but that seems too broad and off-target: cpp or C++ templates as they're currently lightly-used also fall under that, while Haskell IO doesn't.)

答:
Turns out the paradigm described (badly) in the question does exist, and is known as "multi-staged programming", "staged metaprogramming", or similar words to that effect. According to this taxonomy, the question is envisaging the "static generator" (as opposed to those systems that use staging for dynamic code generation).

Staged programming is distinct from classic macros in that it implies a deeper understanding by the compiler of the code being processed: macros are traditionally syntactic, the code-as-data being a simple structure of atoms, whereas "MSP" maintains and checks type and scope information, and handles only valid, whole expressions as single values; from these it's able to build well-typed and syntactically valid output. (One could certainly write Lisp/Scheme macros to do this - it's been done - but it's not part of their core functionality.) Staging therefore appears to be more closely related to partial evaluation than to macros.

Knowing what it's called, there are many examples and papers to look at:

MetaOCaml (OCaml with staging annotations), tutorial introduction

MetaML (similar work for SML), example

an explanation courtesy of CS.se

Mint, an example of MSP working with an imperative output language (in this case, Java)

tickc, a runtime/dynamic MSP system extending C (not to be confused with the more well-known tcc compiler)

(Hindsight note: in effect, what the question envisaged was using something like MetaML for the metalanguage with C as the output language, running the metalanguage only at compile-time.)

ContentLicense: CC BY-SA 3.0


问:
What does C++ do better than D?
I have recently been learning D and am starting to get some sort of familiarity with the language. I know what it offers, I don't yet know how to use everything, and I don't know much about D idioms and so on, but I am learning.

I like D. It is a nice language, being, in some sort of ways, a huge update to C, and done nicely. None of the features seem that "bolted on", but actually quite well thought-out and well-designed.

You will often hear that D is what C++ should have been (I leave the question whether or not that is true to each and everyone to decide themselves in order to avoid unnecessary flame wars). I have also heard from several C++ programmers that they enjoy D much more than C++.

Myself, while I know C, I can not say that I know C++. I would like to hear from someone knowing both C++ and D if they think there is something that C++ does better than D as a language (meaning not the usual "it has more third-party libraries" or "there are more resources" or "more jobs requiring C++ than D exists").

D was designed by some very skilled C++ programmers (Walter Bright and Andrei Alexandrescu, with the help of the D community) to fix many of the issues that C++ had, but was there something that actually didn't get better after all? Something he missed? Something you think wasn't a better solution?

Also, note that I am talking about D 2.0, not D 1.0.

答:
The most important thing that C++ "does better" than D is interfacing with legacy libraries. Various 3D engines, OpenCL and alike. As D is new, it has far smaller amount of different libraries to choose from.

Another important difference between the C++ and the D is that the C++ has multiple financially independent vendors, but as of 2014 the D has practically only one, the 2-man team that created it. It's interesting that the "second source principle" that says that projects should never depend on technology, components, that have only one, single, vendor, seems to hold even for software.

For comparison, the first version of the Ruby interpreter was written by the inventor of Ruby, the Yukihiro Matsumoto, but the 2014 era mainstream Ruby interpreter has been written practically from scratch by other people. Therefore, Ruby can be seen as a language that has more than one financially independent vendor. D, on the other hand, can be an awesome technology, but it depends on the few developers that develop it.

The history of Java shows that even if a technology, in this case, Java, has a fine, but single, financier, there is a great risk that the technology is essentially dumped, regardless of the huge corporate user base. A citation of the Apache Software Foundation, where the EC stands for "Executive Committee":

Oracle provided the EC with a Java SE 7 specification request and license that are self-contradictory, severely restrict distribution of independent implementations of the spec, and most importantly, prohibit the distribution of independent open source implementations of the spec.

As a historical note, it can be said that Java applets had hardware accelerated 3D canvas years before the HTML5 WebGL got developed. The Java applets start-up speed issue could have been solved, if the Java had been a community project, but the executives of the sole financier of the Java, the Sun Microsystems, did not find it important enough to have the Java implementation fixed. The end result: HTML5 canvas by multiple vendors as a "poor man's replica" of the Java GUI frameworks (Swing, etc.). Interestingly enough, on the server side the Python programming language has the same advantages that the Java promised: write once, run on every server, regardless of hardware, provided that the Python application is not compiled to machine code. The Python is about as old/young as the Java is, but unlike the Java, it's backed up by more than one independently financed team of developers (the PyPy and the main stream Python interpreter).

Summary:

When evaluating technology for production use, the most important properties of technologies are the people, who develop it, the social process, where the development takes place, and the number of financially independent development teams.

Whether it's more advantageous to use technology T1 over technology T2 depends on the vendors of the technologies and whether technology T1 allows to solve project related problems more cheaply than T2. For example, if the single supplier issue were ignored, then for information systems the Java would be a "better" technology than the C++, because Java binaries do not need recompilation at deployment to new hardware and the amount of memory management related software development work is smaller for the Java than it is for the C++. Projects that are developed from scratch, e.g. projects that do not depend on other libraries, might be cheaper to develop in D than C++, but, on the other hand, the C++ has more than one vendor and therefore is less risky in the long run. (The Java example, where the Sun Microsystems was almost OK, but the Oracle practically made Java the "new COBOL".)

A Possible Workaround to some of the C++ Limitations

One of the possible workarounds to some of the limitations of the C++ is to use a design pattern, where the initial task is taken to pieces and the pieces are "sorted" (classified, clustered, divided, other-nice-words-for-the-same-thing) to 2 classes: control logic related tasks, where memory access patterns do not allow locality; signal processing-like tasks, where locality is easily achieved. The signal processing "like" tasks can be implemented as a set of relatively simplistic console programs. The control logic related tasks are placed all to a single script that is written in Ruby or Python or otherwise something, where software development comfort has higher priority than speed.

To avoid expensive operating system process initialization and data copying between operating system processes, the set of small C++ console applications might be implemented as a single C++ program that is booted as a "servlet" by the Ruby/Python/etc. script. The Ruby/Python/etc. script shuts the servlet down before exit. Communication between the "servlet" and the Ruby/Python/etc. script takes place over a Linux named pipe or some similar mechanism.

If the initial task does not lend itself to be easily divided to pieces that can be classified to the 2 aforementioned classes, then a thing to try might be to re-phrase the problem so that the initial task changes.

Title: What does C++ do better than D?


问:
Which features of shell scripting are relevant for PHP/Python development?
I'm a PHP/Python programmer learning Java and C#(.NET).

My main development OS is windows 7 but I've used Linux and I currently dual-boot with Ubuntu. My Linux knowledge however, is pretty limited. I can work with the command line on simple tasks but that's pretty much it. I don't do any shell scripting and I don't know many important commands.

My interests are web development, mobile apps and maybe some embedded stuff in the future.  Will shell scripting skills be useful for these interests and if so, how?

答:
There is a certain degree of 80/20 thinking you can apply here. It doesn't actually take very long to learn the basics of how Linux works and the core commands you need to know about from the Shell. Likewise basic Apache configuration is very convenient to have if you need it. You don't need to dedicate years of your life to it, but it is certainly worth learning enough of the basics that you could get by running your own server if you had to.

It's a fine line though. If you aren't careful you can quickly find Windows begins to really tick you off as you get used to what Linux offers...

ContentLicense: CC BY-SA 2.5


问:
How important is it to clean up someone else's code when faced with a tight deadline?
(I'm talking about HTML / CSS code (not programming languages) but I think we also face the same issue as with programmers.)

I am the senior front-end designer in a team and I often have to re-work my juniors' output in tight deadlines.

I am faced with 2 problems:

Their coding style is a bit of a mess.

The aesthetics are not good.

Their coding style, I find, is a mixed bag with no proper convention / standard. I am torn between cleaning up the code or just dealing with their code (even copying how they do things).

I do find it frustrating to follow their coding style as I feel I might learn bad habits. But then, that is the fastest way of meeting the deadline.

For those with much more experience, which is more effective? Should I save the clean-up for later? Or clean-up along the way as I make the changes?

(I don't want to sound arrogant though but such is the reality. It will take them more years to write better code. I know, I wrote messy code when I was starting.)

答:
I can see the reason in the "don't fix what's working" and "don't waste your time on what's not important to the client" answers. PMs are worried about risks and this is fine.

Also I understand most people don't take this kind of fix well. I understand this too.

Said that, I believe that most deadlines are artificial. Real systems live ever more than the deadlines and the bad design you do today will fight you back forever and ever. People run to deliver something in a few months and spend years after this fixing some bad decisions in a code that is being run in production.

Tech debt is the word. It will come back someday and someone will pay for it.

So IMO, I think you are just right fixing the broken design, and being professional (specially for the juniors) also means that you must know how to take criticism and how to learn from it, even if it's not polite. In fact, most of life is not polite anyway.

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
Do Design Patterns Stifle Creativity
Many years ago, I was talking with an Economics professor about design patterns, how they were establishing a common language for programmers and how they were solving well known problems in a nice manner, etc etc.

Then he talked back to me that this is exactly the opposite approach he would use to his Economics students. He usually presented a problem and asked them to find a solution first, so they could think about it first and try to find ways to solve the problem first, and only after that, he presented the "classical" solution.

So I was thinking if the "design pattern" approach is really something that makes programmers smarter or dumber, since they're many times just getting the "right solution for this problem" instead maybe of using creativity and imagination to solve some problem in a new and innovative way.

What do you think?

答:
The way Design Patterns people want you to look at Design Patterns is as a set of solutions that you can apply if similar problems come up.  They do not want you to think of them as the only possible solutions, given by God to Moses carved in stone tablets upon the mountain.

Unfortunately, some people take them as something closer to holy writ than to a bunch of example designs that could be learned from.  That does kill creativity, and sets up a cargo cult.

Your economics professor mentioned presenting students with the problem and having them try to solve it first, which is a good educational technique, but he did have a solution to show them.  Having a bunch of solutions to lots of different problems in your head a good thing, and it's something Design Patterns tries to be.  I think it fails in some ways (Singleton encouraging bad approaches, a myopic focus on imperative OO, etc.), but it could be used well with intelligence and taste.  However, it is a mistake to think that every possible example solution in software Must Be An Official Design Pattern.

If you look at a problem and ask yourself "What is the Design Pattern for this?", then you're doing it wrong, and you'll be less likely to see a solution that's staring you in the face.

If you look at a problem and ask yourself "How can I solve this?", then if there's a non-pattern solution, you'll see it, and if there's a pattern that fits, you'll see that too.

Title: Do Design Patterns Stifle Creativity


答: Know enough that if you intend to deploy to a particular OS, then you can ensure that your application works on it, but otherwise... you don't have to know anything/everything.

Title: Which features of shell scripting are relevant for PHP/Python development?

Body:
I'm a PHP/Python programmer learning Java and C#(.NET).

My main development OS is windows 7 but I've used Linux and I currently dual-boot with Ubuntu. My Linux knowledge however, is pretty limited. I can work with the command line on simple tasks but that's pretty much it. I don't do any shell scripting and I don't know many important commands.

My interests are web development, mobile apps and maybe some embedded stuff in the future.  Will shell scripting skills be useful for these interests and if so, how?


答:
Your economics professor is absolutely correct.

Software Design Patterns are primarily a way for experienced software developers to communicate with each other.  They are a shorthand for established solutions to known problems.

But they should only be used by people who understand how to solve the problem without the pattern, or have come up with a similar pattern on their own.  Otherwise, they will have the same problem as the copy/paste coder; they will have code, but they won't understand how it works, and therefore will be unable to troubleshoot it.

Also, many of the design patterns are enterprise patterns, patterns that are intended to be used in large, corporate software systems.  If you learn the wonders of the Inversion of Control container, you will want to use it in every program you write, even though most programs don't actually need it (there are better ways to inject your dependencies in smaller programs, way that don't require an IoC container).

Learn the patterns.  Understand the patterns, and their appropriate use.  Know how to solve the same problem without the pattern (all software patterns are abstractions over fundamental algorithms).  Then you will be able to use software patterns with confidence, when it makes sense to do so.

Title: Do Design Patterns Stifle Creativity

Body:
Many years ago, I was talking with an Economics professor about design patterns, how they were establishing a common language for programmers and how they were solving well known problems in a nice manner, etc etc.

Then he talked back to me that this is exactly the opposite approach he would use to his Economics students. He usually presented a problem and asked them to find a solution first, so they could think about it first and try to find ways to solve the problem first, and only after that, he presented the "classical" solution.

So I was thinking if the "design pattern" approach is really something that makes programmers smarter or dumber, since they're many times just getting the "right solution for this problem" instead maybe of using creativity and imagination to solve some problem in a new and innovative way.

What do you think?


答:
I also think your economics professor is correct and that's a way to learn anything in the first place; However let's look at like this: Would you keep the Wheel secret and let everyone reinvent it, for the sake of Creativity? I expect you to say No, because not all the people are made/capable of inventing their wheels -- and if they're, they will do it at some point, doesn't matter if they are aware of existence of the wheel or not.

Let's go back to programmers; I am a web-developer by day, so MVC is one of those things that I interact with on a daily basis. Several times I tried to build my own structures, I learned a lot but all of them were basically unsuccessful. I tried my best but what would happen if there were no MVC out there? Well, simple, my source code sucks -- in terms of reliability, maintainability and extendability.

I think that's the same for most of us. If nobody tells you about DI -- as a good practice, then how many enterprise applications should struggle or fail until their developers learn the lesson?

The second point is Industry Standards. If you won't teach MVC to web-developers then are you ready to face all of those non-standard structures that you need to spend some time to learn their way of doing things first, and then you realize that some of those structures might have a nice idea, but most of them will have serious design-flaws that might have serious consequences for your software project -- even well-known frameworks still struggle with design-flaws time to time.

But what would happen if we do have all of those nice ideas and put them all together and those smart developers take the good things from all of those experiments and make a really cool structure that works best for that specific problem? Then you have just created the Design Patterns. If you're a living creature, then there is no other way around; Even animals follow best-practices and design-patterns in their day-to-day life.

Title: Do Design Patterns Stifle Creativity


答:
Commerce and education have different goals. If I were teaching students design patterns, I would take the same approach. But in a production environment, time and efficiency are everything.

Moreover, (macro) economics outside the classroom is a different thing. Do you see governments saying, "Whoa! Now we are super bored with doing the taxes and all the same way, so let's try something super wacky this time"? No, you don't, because such wild experiments can shatter the economy beyond repair. Instead, they tend to stick to tried-and-tested approaches: increase interest rate, announce tax holidays, etc. In other words, they are relying on design patterns.

Title: Do Design Patterns Stifle Creativity


问:
Use of separate threads or singe thread
In my project, on a security system, I was using a socket to get the details of the client and then store it in a database (his IP and port he connected from and service he accessed). I was wondering if the fetching of the details and storing them in a database should be done in separate threads or a single thread. Which is the more advantageous approach?</p>

答:
Quick answer: Is the main socket handler multi-threaded? If not, then definitely hand the processing of the request off to a thread pool executor. If the request handler is already multi-threaded, then it's more of a judgement call (...or a performance enhancement to be borne out with load testing).

...

If the service isn't handling requests with a pool of execution threads, then it probably should. That's a more central issue than getting the client details asynchronously.

The main benefit of using a separate thread is to do the work asynchronously -- that is, in the background while the main thread moves on to the next request. If the fetch will be slow and potentially block handling of incoming requests, then handing off the fetch to a separate thread would be a good idea.

However, if the app already handles requests with a pool of execution threads, and the number of threads is large enough, a separate thread pool might not bring much benefit.

Note: DO NOT spin up a new thread for each request. Instead, look in the currency package for ThreadPoolExecutor or an ExecutorService.

Here's a sample link (the first one in the search) from a quick lookup of ThreadPoolExecutor: http://www.javacodegeeks.com/2011/12/using-threadpoolexecutor-to-parallelize.html.

Title: Use of separate threads or singe thread


答:
The answer is, of course: Yes.

Design patterns are a wonderful learning tool in themselves, as long as one takes the time to figure out how they work and why they bring the value they bring.

They can also be great productivity boosters by fast-tracking a design process, because they provide familiar solutions to problems that pop up all the time.

However, if they short-circuit design too much, or people become dogmatic and over-precise about their use, then they have the opposite effect.

Title: Do Design Patterns Stifle Creativity


问:
Adding to the System namespace in C#
Would it be acceptable for some very generic utilities or classes to be added in the System namespace?

I'm thinking of really basic stuff like a generic EventArgs (EventArgs<T>),

Use case: would be shared in a company's core library (so that it can be recompiled in a new project as-is, without changing the namespace);

答: Fully correct answers here, but no rule without exception: if you create something like LinqBridge (which is a .NET framework 2.0 replacement for .NET fw 3.5 classes in a 100% compatible way), then usage of the System namespace is mandatory. Or to answer this in a more general way: own usage of the System namespace is only a good idea if you have to port some higher version framework classes to a lower version, because you cannot upgrade your production version to the higher framework (and I guess this is the only valid reason for using this namespace).

Title: Adding to the System namespace in C#


问:
When internationalizing texts, should underscores (for keyboard shortcuts) be part of the texts to be translated?
I have a project where I need to translate a lot of words and text fragments in different languages.

In these texts, underscores are currently added in these text (fragment(s)) to be used as keyboard shortcuts (used in Visual Studio).

However, I was wondering if this is the way to go, or if it would be better to remove the underscores and add them AFTER translation.

Is there some guideline to follow?

答: At least, you need to make sure you don't get shortcut collisions within each local context where the shortcuts have to be unique (I guess its some kind of dialog or form). If you can assure this whilst the translation is done, do it. If your translator just gets a naked word list and no information about the context, you can only assure this afterwards, so better add them after translation. The person who places the underscores in the translation should know about the context and the global shortcuts he should not use (like Ctrl-C, Ctrl-X, Ctrl-V). </p>


问:
Does immutability entirely eliminate the need for locks in multi-processor programming?

Part 1

Clearly Immutability minimizes the need for locks in multi-processor programming, but does it eliminate that need, or are there instances where immutability alone is not enough?  It seems to me that you can only defer processing and encapsulate state so long before most programs have to actually DO something (update a data store, produce a report, throw an exception, etc.).  Can such actions always be done without locks?  Does the mere action of throwing out each object and creating a new one instead of changing the original (a crude view of immutability) provide absolute protection from inter-process contention, or are there corner cases which still require locking?

I know a lot of functional programmers and mathematicians like to talk about "no side effects" but in the "real world" everything has a side effect, even if it's the time it takes to execute a machine instruction.  I'm interested in both the theoretical/academic answer and the practical/real-world answer.

If immutability is safe, given certain bounds or assumptions, I want to know what the borders of the "safety zone" are exactly.  Some examples of possible boundaries:

I/O

Exceptions/errors

Interactions with programs written in other languages

Interactions with other machines (physical, virtual, or theoretical)

Special thanks to @JimmaHoffa for his comment which started this question!

Part 2

Multi-processor programming is often used as an optimization technique - to make some code run faster.  When is it faster to use locks vs. immutable objects?

Given the limits set out in Amdahl's Law, when can you achieve better over-all performance (with or without the garbage collector taken into account) with immutable objects vs. locking mutable ones?

Summary

I'm combining these two questions into one to try to get at where the bounding box is for Immutability as a solution to threading problems.

答:
You start with

Clearly Immutability minimizes the need for locks in multi-processor programming

Wrong. You need to carefully read the documentation for every class that you use. For example, const std::string in C++ is not thread safe. Immutable objects can have internal state that changes when accessing them.

But you are looking at this from a totally wrong point of view. It doesn't matter whether an object is immutable or not, what matters is whether you change it. What you are saying is like saying "if you never take a driving test, you can never lose your driving license for drunk driving". True, but rather missing the point.

Now in the example code someone wrote with a function named "ConcatenateWithCommas": If the input was mutable and you used a lock, what would you gain? If someone else tries to modify the list while you try to concatenate the strings, a lock can keep you from crashing. But you still don't know whether you concatenate the strings before or after the other thread changed them. So your result is rather useless. You have a problem that isn't related to locking and cannot be fixed with locking. But then if you use immutable objects, and the other thread replaces the whole object with a new one, you are using the old object and not the new object, so your result is useless. You have to think about these problems at an actual functional level.


问:
How does one become a leader in a team of programmers?
What skills, knowledge and talents should a junior programmer aim to obtain in order to be qualified to become a team leader? </p>

答:
a) Either show through time that you handle the material at hand with no trouble, have the necessary technical skills and are good with people in a way that you motivate them and lead them towards a mutual goal

b) or

ContentLicense: CC BY-SA 4.0


问:
how to manage new private variables introduced into class?
Whenever I want to add a new functionality, I introduce a new private variable into the class. Declare it just above the first method definition. leave a small comment. Set it in a certain method. And then use this set value in another method.

Now the possible problems which arise are, I dont cover all the possible cases when to modify the value of this variable and only notice a bug in it when during trying various possible user flows of the software. Is there any possible way to tie this value to some kinds of triggers so that I know all the possible situations when to modify its value? I am using Javascript.

For e.g. I create a status message for editing an existing DB record. If the updating is failed over REST HTTP I set the status. Now I forgot to reset the status when I dont hit update button and instead select another record for updating.

What is the best way to manage such new private variables? How to mange their state? what is the best software engineering way to prevent such mistakes?

答:
The best way is to follow separation of concerns, which means restricting the scope of your new variable to the smallest possible unit.

If the new information truly has to be a new class member, and the class is too big for you to read it through and easily find all other circumstances in which you have to deal with the new field, then the class is too big, period. Refactor it into more, smaller classes so that only one of them has to deal with the new field.

If you can find a way not to store the information indefinitely, even better is to treat it as a parameter, callback information, session attribute etc.


答:
Don't reinvent a hammer, but don't treat every problem like a nail

Programming patterns are a great time-saver, because they give you ready-to-use solutions, good documented and tested with mean cases you could easily forget about. But you need to learn (and think) when to use them.

Paraphrasing your question: would learning to drive make me move faster, or just walk slower?

Learning how to use programming pattern doesn't mean you shouldn't exercise finding own solutions. There will still be enough problems to exercise your creativity upon. Knowing programming patterns will only let you get quick with well-known problems and concentrate on those, which are less trivial.

Returning to the second part of your question - is your proffesor right?

Yes, he is right. The primary goal of studies is to learn students to think. They need to try to find their own solutions to the problem, and then confront them with the existing solutions. Only in that way they can really understand them. If you learn them the patterns first, you risk they will only learn mechanically to apply them, and not to understand, what is behind.

This is the reason you first teach students to program, and the patterns are introduced in further semesters.

Title: Do Design Patterns Stifle Creativity


问:
When to use python function nesting?
I am writing a program that creates backup of directories.

Which of the following approach is better for code organization?

Create separate class for Backup and Zip logic -

```<code>class BackupUtil:
    def backup(self):
       None

class ZipUtil:
    def archive_dir(self):
       None
</code>```

Or use function nesting like this -

```<code>class BackupUtil:
    def backup(self):
        def archive_dir():
            None
        None
</code>```

答:
Keeping the two separate would be useful for quite a few reasons:

1) You will have more flexibility working with either class (especially Class inheritance)

2) You can transform the two classes into modules that you can use in your other codes independently from each other

3) You will avoid unnecessarily creating a larger class when you maybe only need to use one of the two features

4) Keeping the functions separate also increases code readability when you later call these functions

Hope that helps clarify somethings.

Title: When to use python function nesting?


答: Design patterns are of course less creative. That's the whole idea. Creativity is a scarce resource. You shouldn't waste it on problems that don't need creativity. It is much easier, quicker, and more likely to work, if you solve a problem in the same way as hundreds of developers before you. Boring, unexciting code that does its job is actually good. </p>

Title: Do Design Patterns Stifle Creativity


答:
The best team leaders I've seen have all been dynamite programmers. But they've all had several other qualities, which are harder to define: wisdom, good judgment, good people skills (friendly and pleasant but not a pushover), dedication, commitment, and — most important of all — knowing how to give credit to others. Such people are natural leaders.

The worst qualities you could cultivate are arrogance, always having to be right, always having to have the final say, being a glory hound, one-upmanship, having a huge, bruiseable ego, never admitting you're wrong, deflecting blame onto others while hogging all the credit for yourself, and, worst of all, competing with the people who work for you.

Title: How does one become a leader in a team of programmers?

Body: What skills, knowledge and talents should a junior programmer aim to obtain in order to be qualified to become a team leader? </p>


问:
Isn't MVC anti OOP?
The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data.

In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?

答:
In my Opinion OOPs has a drawback that since the (data and behavior) are moulded as one entity(Class) this shows more coupling effect than cohesion.
Whereas on the other hand MVC it has Model containing...(Beans, DAOs, Other Logic classes),
Controller that specifies how the control must travel and Views to determine how the data should be shown are given in a seperated fashion.
Based on this no matter if the project is Too big to prepare can be easily made as seperate entity other than getting mixed unlike OOPs.
The problem is solved in logical pattern just like divide n conquer strategy and MVC follows this atmost.</p>

Title: Isn't MVC anti OOP?


答:
In general, when the inner function is small and you want to make it clear that it's only useful to the enclosing function. Alternatively, when you need to return a function. The latter scenario is trivial since generally the inner function relies on variables in the enclosing functions's scope, so declaring it anywhere else isn't an option. You might be able to use a lambda in that case, but anything longer than one expression would need a full function declaration.

Without the implementations it's hard to say which one you should choose in this case. I would hasten to add that you don't have to put everything in a class either.

Title: When to use python function nesting?

Body:
I am writing a program that creates backup of directories.

Which of the following approach is better for code organization?

Create separate class for Backup and Zip logic -

```<code>class BackupUtil:
    def backup(self):
       None

class ZipUtil:
    def archive_dir(self):
       None
</code>```

Or use function nesting like this -

```<code>class BackupUtil:
    def backup(self):
        def archive_dir():
            None
        None
</code>```


答:
I would absolutely advise against teaching programming by teaching design patterns. You cannot apply them well without understanding the principles behind them, so teaching those principles are far more important.

I tend to think that design patterns aren't really all that valuable to working programmers either, anyway. If you fully understand the principles involved in a given design pattern, then in a situation where it's a good solution you'll naturally tend to construct it (or something similar) anyway just as a matter of course, even if you didn't know that it was a pattern with a name. Whatever time you'd spend learning patterns could be better spent learning how to think about code in general. If your "problem solving in general" skills aren't up to scratch, then you can't write good code no matter how good you are at applying some set of patterns. And if your "problem solving in general" skills are good, then you can solve problems even if you don't know a single pattern.

I also think that in an ideal world there wouldn't be any design patterns, because ideas common enough to be called a pattern would all be well-implemented in libraries and we'd actually be reusing code instead of constantly rewriting it. Imagine if there was a "regular expression design pattern", that required you to implement a small regex engine every time you wanted to use it. Design patterns are just libraries that can't be written because the language doesn't provide the right abstraction facilities.

That's actually another reason to not care terribly much about them; they're not anywhere near as universal as is sometimes claimed, but are in fact tied very strongly to the particular ways of structuring programs that a particular language allows/encourages. A design patterns book written for Python would be completely different than one written for Java, and even more different than one written for a non-imperative language like Haskell. Better to understand at a deeper level, and you'll be able to discover design patterns yourself in any language you gain familiarity with.

Title: Do Design Patterns Stifle Creativity


问:
Protecting API Keys
Iv'e moved this from SO as it's more of a design question than a code one.

In many applications third party websites/programs can access the website via a key.

For example, a web application hosts applications each of which have a unique API key. These keys are issued to the various developers to ensure they don't make too many requests based on their contract.

However, the 3rd party applications often make requests in the form:

http://www.thewebapplication.com/my.api?key=TheKey&parameter=SomeValue

These can be seen by a myriad of technologies (fiddler, traffic snoopers). Even worse these requests may be placed in Javascript and made available to everyone. How can you design an API system which helps to protect your clients' API keys?

答:
Instead of requiring the actual key, require something that only the key owner can provide, but which doesn't disclose the actual key value.

The usual solution is to expect not the key, but the value of a one-way hash function on the key+something arbitrary. For instance, the developer could generate a nonce value (something that is never sent more than once), combine it with the key, hash the result, and then send the combined hash + the nonce value, but not the key. Your application would then have to check that the hash is correct and that the nonce value wasn't used before (and that the service limit wasn't reached). This allows the client to make as many requests as they want (within their contract), but interceptors can't steal the credentials to spoon services off the contract.

Title: Protecting API Keys


问:
Building an organization-specific XML editor in HTML
I'm building a user friendly XML editor in HTML/JS.

Looking for some general advice on how to build the editor UI and which approach you'd recommend on mapping the data to the UI.

Details about the problem:

Basically I'll fetch a single object as XML from a sever.
The XML objects in question will be a small set of organization-specific XML which can only be structured in a few different ways. (Overall there are only about 15 different types of nodes available.)  So I'll know all kinds of nodes that can appear, so I know which kind of UI to create for each type of node.

Basically, all classes have the same root node (Item). The 1st child node of that class can be a single List, Table, Person or Building node. After that, there are usually about 4 levels of multiple child-nodes, of varying structures. For example:

A Person containing a List of Addresses, where each Address node has two properties; an id and a type="personal address". Anywhere inside the text of each Address there can also be a reference, a kind of internal link to an id in the system.

A Table consists of Header, Footer and a Body with and an optional number of rows and cells

The use case is the following:

The user will always start by loading an existing XML item into the editor. The user is allowed to edit existing values, remove them, and add new values. (Since all items have the same kind of root node, the user will have access to add pretty much any kind of node they want.)  When they are done they hit 'Save' and the editor closes, and a view mode (already completed) shows the saved item.

I have 2 ideas for the editor UI:

A sort of Markup-editor in the style of StackExchange (a single text field with simple markup tags)

A HTML form where you render each node as one or more input fields, and use buttons to move/add/delete the fields.
I'd render Tables as HTML tables, and Lists as an unordered list with every list item containing multiple input fields (one input field for each Address and one dropdown for the type, and stash the id in a data-id parameter).

Which of these UI approaches would you recommend? (Feel free to ask more questions about the XML.)

How would you recommend mapping the data to the UI?
Would you keep all the data inside the HTML during editing and then parsing it back to XML when the user saves his work.
Or store the data as a JavaScript object, work directly with the JS object and just update the UI based on the JS object? Perhaps using some MV* framework with 2-way-binding? (I suppose that method would only be considered if I built the UI as a Form.)
Or would it always be easier to traverse the XML node-by-node and generate UI elements based on that?

答:
In general, I'd expect a good graphical editor to be easier to use and a markup editor to be easier to implement and potentially more powerful, but this is really hard to answer in the general case:

What is your team's skill set?  A StackExchange-style markup editor would probably be easier to implement.  An MV* framework has more of a learning curve.  (I don't have enough experience with JavaScript MV* frameworks myself to give much of an opinion there.)  Etc.

How technically skilled are your users?  To stereotype, I'd expect more technical users to be more willing to edit markup (and might even prefer to), while less technical users would be more comfortable with a graphical approach.

How many resources do you have? For example, even though StackExchange has you type Markdown, they also have a very nifty live preview.  However, your team may not have the resources that StackExchange does.

Have you talked to your users? The answer to the question, "Which is the better UI?", is almost always, "Get some feedback from actual users."  Developers' intuition about what makes a good UI is notoriously bad.  Do a prototype (use paper prototypes if you don't want to build one on the computer), do some hallway usability testing, whatever it takes to get actual feedback from actual users.

Regarding how to implement the mapping of data to UI, any of the approaches that you've described should work. It depends on what your team's comfortable with, how you all prefer to work, and what frameworks or libraries you're using.


答:
Not anti, but also OOP is not required for MVC.

Because controllers, which are usually represented by classess hold no data.
For which pure functions would suffice.

If you go further and separate data from behaviour, for example let's say that models work only on database data, which they fetch every time their function (that is responsible for data manipulation) is called (instead for storing some kind of data in the instance fields) - then you can say the same for the models.

Going further, if you take the view layer of an application and divide it in similar fashion, you will actually end with conclusion that MVC has nothing to do with OOP, and it is completely possible to write MVC implementation without any pain using only procedurall approach.

Title: Isn't MVC anti OOP?

Body:
The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data.

In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?


问:
Under what conditions is the use of MVVM appropriate?
Model View View-Model was developed by Microsoft to target UI development platforms which support event-driven programming, specifically Windows Presentation Foundation (WPF) and Silverlight on the .NET platforms using XAML and .NET languages.  In the years since, many Javascript frameworks such as Angular, Knockout and ExtJS have adopted the pattern.

Like most software patterns, MVVM has its appropriate uses, and its abuses.  Under what conditions is the use of MVVM appropriate?  When is it ill-advised?

答:
I've been a WPF/Silverlight programmer for years building huge applications, such as trading systems, on MVVM.

For me, as the years have gone by, I've learned that strict MVVM eats time and costs money. By strict, I mean rules such as "no code behind".

It's impossible in anything but the most basic form/database app, not to have code-behind.

Your designer will spec something on day one that is not possible with the standard controls, so you must build a series of custom controls, or wrap existing controls, to support the interaction paradigm while working with MVVM.

I've written all kinds of swish UI controls using math, inertia, gestures etc. and its hard work.

But this is all code-behind, it's just not in the view. You have to handle button clicks, scrolling, dragging etc. but its all nicely wrapped up in a set of controls, which somehow makes this code-behind okay.

Its often easier simply to just write the code-behind and clever UI stuff in the view, instead of building up a set of controls just for the sake of it.

The goal of MVVM is to separate application/business logic from UI logic. The binding system and MVVM is a nice way to do this.

The other goals touted, such as XAML designer on one desk, C# programmer on the other, one working in Blend the other in VS, is a fallacy.

Being able to rapidly redesign a UI is another fallacy. It's never happens, its premature optimisation; any major rework needs a lot of work doing to the view models. Tweaking is one thing but quick UI overhauls aren't possible; the view models must fit the interaction paradigm, so the coupling is tighter than you may realise.

For me, I use MVVM to keep my application logic separate (I usually use a testable controller and a set of logicless view models) but whatever code and tricks are needed to make my UI look and act in a sexy way, I don't sweat it.

Else you end up reigning-in your designs, cool animations, etc. just because the idea of how to MVVM-arize it all becomes too mind-boggling.

MVVM, like most things in life, has a sweet spot somewhere between two extremes.

The most important thing in software design is shipping your product early, finding out what features are used, what UI works well, and not writing beautiful code for a product no one uses.


问:
Data structures VS Classes and what happens if they merge?
Alright so I've learned this:

Classes have public methods that perform operations on the class's data and they hide away their implementations.

Data structures on the other hand, completely expose their implementation through properties (getters and setters) and don't usually have methods.

So my question is, let's say that I have customer data structure that looks like this:

```<code>public class Customer
{
   public string FirstName { get ; set; }
   public string LastName { get ; set; }
   public List<Offer> Offers { get ; set; }
}
</code>```

I would assume this to be a data structure.

but what if later during the project, I realize that I need to add some business logic to my customer data structure?

Like a method to add new offers because there's more logic in doing so than just adding it to the list?

It seems to me that this logic would belong inside of the data structure.

What happens then? Does the data structure turn in to a class? Or into some kind of third object type that I'm unaware of?

Is this bad design?

答:
It is not bad design to add a method like that.  This sort of thing's actually very normal when classes are in their infancy.

But classes and data structures are a little bit different than you think, and one doesn't really oppose or exclude the other at all.  Most classes are data structures, and many data structures are classes.  Classes have a lot more to do with the syntax of a language - they're programmed into a language directly - whereas datastructures have more to do with how you personally intend to use certain things.  You tell a program what is and is not a class, but you do not generally tell a program what is and is not a data structure - you keep up with the latter yourself.

A class might involve methods - or it might not.  It also might involve data - or it might not.  Usually they'll involve both (especially in Java-style languages, where both are required), but this is not always true.  You could even have a class with neither methods nor data.

Without getting into any of the details of OOP, a class is mostly just a collection of methods and/or data.  And a class doesn't have to have public members, by the way.  I've used some whose members were all either internal or private, for instance.

A data structure is a little different.  It's basically a grouping of data that has been structured in some particular way for some particular purpose.  This may be a class.  Any time you see a class with more than one piece of data, that is generally a data structure.

Like a class, a data structure may either contain or forgo methods.  Unlike a class, however, it must contain some form of data (even if the data's just a couple of "blank" variables).

You can have data structures that are not classes.  For instance, imagine if you have two arrays: One is a list of people's first names, and one is a list of people's last names.  And if the nth element of the first array is somebody's first name, then the nth element of the second array is that same person's last name.  Even though the program and the programming language may have no idea these two arrays are connected, you do personally, just because you're keeping up with it.  Even though this is not a good example of how you would usually want to set things up, this still constitutes a data structure.

I know that might have been a little long, but hopefully it'll help.


答:
I would assume this to be a data structure.

Specifically, it's a record.

Like a method to add new offers because there's more logic in doing so than just adding it to the list?

Is there some important condition you need to maintain in your Offers list? e.g. It needs to stay sorted? If so, then giving the whole program free access to the list is bad. Either you turn Customer into an abstraction (a class or interface), or you turn Offers into one, but you have to control access to that list somehow. Which one should become the abstraction depends on the rest of the program and what you're trying to do.

If there's no such condition, you can simply add plan ol' functions that take the Customer record as its argument and do whatever things you need to do to it.

The bottom line is that not every user-defined type in your program is going to be an abstraction of something. Sometimes you do have plain old data objects. You do need some abstractions, and your data structures will often be used as the private members of some class, but they could also appear as arguments or return values of a class's methods, especially simple types like tuples or records.

Title: Data structures VS Classes and what happens if they merge?

Body:
Alright so I've learned this:

Classes have public methods that perform operations on the class's data and they hide away their implementations.

Data structures on the other hand, completely expose their implementation through properties (getters and setters) and don't usually have methods.

So my question is, let's say that I have customer data structure that looks like this:

```<code>public class Customer
{
   public string FirstName { get ; set; }
   public string LastName { get ; set; }
   public List<Offer> Offers { get ; set; }
}
</code>```

I would assume this to be a data structure.

but what if later during the project, I realize that I need to add some business logic to my customer data structure?

Like a method to add new offers because there's more logic in doing so than just adding it to the list?

It seems to me that this logic would belong inside of the data structure.

What happens then? Does the data structure turn in to a class? Or into some kind of third object type that I'm unaware of?

Is this bad design?


问:
Does Serialization preclude the use of Dependency Injection?
Simple question: I understand that Serialization in C# requires default constructors. This would eliminate the possibility of using Constructor injected DI (which is generally the favored style of DI, in my reading[citation needed]). So is it really an either-or situation, or am I missing something?

(Side question): Do IoC containers side-step this tradeoff somehow?

答:
It is not possible to de-serialize an object and also inject a dependency to another, already existing object, in one step in C#, using the standard serialization mechanisms. You will have to use property injection instead, first constructing the object using the deserializer, afterwards injecting the dependency. For most real-world applications, I don't consider this beeing a real drawback - if you have a serializeable data model class, which has also dependencies to other, non-data model classes, you should check if your data model class may have too many responsibilities already.

If that really bothers you, you may consider to wrap your serializable object with a decorator class, where you can pass the de-serializer and additional dependencies through the constructor. That wrapper then executes the two steps (de-serialization of the wrapped object and property injection) in its constructor.


答:
It will be tough to be the best programmer you are capable of and be a leader, so accept the fact that you may be spending time doing things you don't like to do when you'd rather be coding. Not that you can't become a really good programmer, but eventually, something in your time constraints will have to give. This does not mean you will be a respected development team leader if your code is crap.

Like everyone in power, you'll be tempted to think of them as your minions, but the best leaders are the ones who have something to offer those who are in their responsibility. Be a resource for programming solutions or at least point them in the right direction. Create an environment conducive to software development by making those on your team responsible for their code and run interference on the outside forces threatening your team.

Get in touch with your natural tenancies. If you have an aversion to the following, think twice about this career move:

Teaching other developers and caring about their career development.

Giving critical feedback; sorry, but one day you will have to fire someone (Or maybe you should be.).

Justifying and standing up for your team to the rest of the company. They won't 'just get it'. You have to sell, persuade, and convince. Just thinking of them as stupid will hinder your team. Eventually, you'll have to toe the company line. Admit it to your team and don't come up with some illogical nonsense excuse why doing something stupid is the right thing to do. Hey, I know it doesn't make sense, but do it anyway.

Stick to what you know is the acceptable workload, time expectations, and code quality without being deluded into thinking you use to be able to program for 100 hours straight with no sleep and zero defects.

If you don't want these confrontations and would rather be coding, just be a great programmer and forget about being a manager. Every project/team/company could use a bus load of those.


问:
Building a serverless p2p CMS/System
I'm thinking about building an Open Source, serverless, offline-replicated p2p CMS, but I'm concerned about it really working in a real environment. How would you go about doing that, reducing the exposition to risks/bugs?

I've thought about this schema for now.

On the local device we have a folder called "cmsfiles" containing the software's files and a subfolder "database-shards", inside this subfolder we have: shard0.sqlite, shard1.sqlite, shard2.sqlite and so on.. each shard has a cap of 50GB. Inside these shards we'll assign the tables in a random way, being: comments, posts, answers, users etc.

If a device visits a portal, it has read-only access and to interact it has to have a locally installed instance, with the same content as explained above.

When he installs the software, he's asked for a nick and a password, that will then be saved on a private key for later verification. When a device does an insert (an answer to a post in this case), it has to send other information as well.

Locally, the request is processed in the following way:

The remote peer is asked for his ip address/proxy/tor-node and hardware UUID. A check is then done to determine if the remote peer is in the blacklist list, if TRUE, the whole operations/negotiations are discarded, but if it evaluate FALSE, a checking is done to see if it's present in the "breaking attempt log" list and if the number is less than 5 && not equal to 0, the number is ++incremented, at the same time all the operations are discarded with the remote peer.

Else, if the number equal 0, we proceed to further verification.

The remote peer's message (answer), private key and files in the "cmsfiles" folder are fetched.

The files are now being compressed locally to cmsfiles.lz, hashing and comparing.

This hash is then compared to the local one and if they're not equal, the number in the "breaking attempt log" list is ++incremented and all the operations being done discarded. But if they match, we proceed signing the remote private key with the public key, if it signs successfully, we check if the post (the answer) already exists.

If it exists (if TRUE), the number in the "breaking attempt log" is ++incremented and any operation discarded, else (if FALSE) we check if post votes equal 0 (a new post cannot have more than 0 votes!), if it doesn't, the number in "breaking attempt log" list is ++incremented and any operations discarded.

Otherwise, if it indeed equals 0 we can finally add the message (answer) to the local database.

I'm including a tree schema representation just in case:

答:
If you are thinking about "50 GB caps", folders and subfolders, etcetera, you should have had the basic architecture nailed down first.

I don't think you are close to that. For instance, you start out by "the remote peer is asked for his IP/...". Which remote peer? How do you ask it for its IP if you don have that IP address yet?

Similarly, "a check is done to determine if the remote peer is in the blacklist".  The blacklist? In a P2P architecture?

The biggest part of your message appears to be about this "breaking attempt log". Yet it doesn't seem to have any solid way of preventing peer spoofing. I can generate new peer identities faster than you can blacklist them.

Title: Building a serverless p2p CMS/System


问:
Too many CS files in a single project
I am working on a ‘brown-field’ project, with a team of programmers. I understand each programmer will have different styles.
I am running into some criticism with my coding style, specifically creating ‘too many class files' (aka too many CS Files, not number of classes).

I have always tried to separate project/business logic into smaller and smaller chunks contained within separate pages (when it is possible).

As an example, a ‘green-field’ project, dealing with an ‘Account’ I might have 5 CS pages (Model, Views, Custom Mappers, Controllers, Presenters, Services…).

The current project has about 40-45 domain specific entities, which means I might have up to 200 CS when the project is all completed.

Of course each would be well separated into an understandable structure.

I was also taught/told that CS files are cheap and don’t worry about the count number of files created as long as it make sense to someone else looking at the code-base.

After the criticism I received, I decided to bend and follow the past code base structures.

As I did this, I can across several CS files, most of which extended beyond 1000 lines of code, and some over 4500 lines of code.

I am having a hard time trying to explain my point of view, which is mainly based on readability and maintainability down the road.

How to explain my point of view to the team OR rather demonstrate the need to follow Single Responsibility principle?

答:
It's hard to say if you're gone too far without seeing more concrete examples, but keep in mind that in one of Bob Martin's treatments of the SRP, he states:

If [...] the application is not changing in ways that cause the two responsibilities to change at different times, then there is no need to separate them. Indeed, separating them would smell of Needless Complexity.

There are of course many reasons to create separate classes besides following the SRP, e.g. reducing coupling, increasing cohesion, separation of concerns, etc; however it's helpful to question yourself as to whether you're actually realizing benefits because of a given design decision.

Title: Too many CS files in a single project


答:
In my experience, the argument against "too many class files" is always perpetuated by people who simply aren't disciplined enough to separate responsibilities well.  Your experience of finding 4500+-line code files is exactly the same experience I have with these teams.  Files will tend to grow, so it's a good practice to start them small anyway.

A common counter-argument I hear is that it's "confusing to debug" code that is passed on from one class to another, etc., but in reality, you shouldn't care about all the implementation details of all the classes involved in a flow, so you shouldn't need to step through all of them in the first place.  Further, if you have proper unit tests set up, you shouldn't need to be stepping through the code incredibly often.

Speaking of unit testing, having many separate classes makes your code much more testable, and that is a good thing.  I am willing to bet that the test coverage on this current project is all but non-existent, since unit testing would reveal the problems with the architecture of this codebase right away.

It sounds like you're in the unfortunate situation of being in a somewhat toxic environment in which popular opinion trumps reason, and it can be frustrating to be the only reasonable voice in a group, but don't stop fighting the good fight.  Point them to resources by professionals, like Robert Martin or Martin Fowler.  It's likely that your team is so rooted in their ways and tied to their ego that they won't budge, but don't stop pushing them in the right direction.

If by some miracle you have an existing unit test solution set up for your project, you might want to try the passive-aggressive introduction of unit-tests-as-guards against bad code that your team may be writing.  On a toxic team I worked on, I found it helpful to refactor code into testable chunks and write unit tests around it, guaranteeing that my coworkers would face pain if they ever tried to change things for the worse.  (Of course, this might just lead them to the conclusion that "unit testing is bad!" so try at your own risk. ;) )

Title: Too many CS files in a single project

Body:
I am working on a ‘brown-field’ project, with a team of programmers. I understand each programmer will have different styles.
I am running into some criticism with my coding style, specifically creating ‘too many class files' (aka too many CS Files, not number of classes).

I have always tried to separate project/business logic into smaller and smaller chunks contained within separate pages (when it is possible).

As an example, a ‘green-field’ project, dealing with an ‘Account’ I might have 5 CS pages (Model, Views, Custom Mappers, Controllers, Presenters, Services…).

The current project has about 40-45 domain specific entities, which means I might have up to 200 CS when the project is all completed.

Of course each would be well separated into an understandable structure.

I was also taught/told that CS files are cheap and don’t worry about the count number of files created as long as it make sense to someone else looking at the code-base.

After the criticism I received, I decided to bend and follow the past code base structures.

As I did this, I can across several CS files, most of which extended beyond 1000 lines of code, and some over 4500 lines of code.

I am having a hard time trying to explain my point of view, which is mainly based on readability and maintainability down the road.

How to explain my point of view to the team OR rather demonstrate the need to follow Single Responsibility principle?


问:
Moving data between databases with XML
I just read this quote online:

XML is a very useful technology for moving data between different databases or between databases and other programs. However, it is not itself a database.

Which is quoted from the book 'Effective XML: 50 Specific Ways to Improve Your XML'.

I don't understand what you would bother moving data between databases in an XML format. Databases usually contain a lot of data, so wouldn't it be verbose to transform it into an XML format?

Is there no way, to just serialize the database data into something less verbose, somehow, instead of bothering with conversions?

答:
XML has two very important attributes that make it attractive for data transfer between heterogenous systems:

You can pass it through firewalls, and

You can usually find reader/writer libraries already written to create and parse it.

If you're looking for something less verbose that still has both of these attributes, you can try using JSON.

If you're simply transferring data between two homogeneous databases on the same network, there are probably easier ways.  For example, Microsoft SQL Server has at least three different ways to transfer data between databases: Bulk Insert, SSIS, and Replication.

Title: Moving data between databases with XML


问:
Should I include myself as an author after modifying 3rd-party code?
It's common practice to make some tweaks or fixes in 3rd-party code (be it a simple gist or an entire library). But it's also common that many of these code have their own licensing rules and eventually a header on every file with copyright informations.

After making those modifications what's the correct thing to do next? Keep the licence info untouchable or try to update it including yourself with something like @author or @revision tags?

Another common problem is changing the 3rd-party namespace/package to fit it to your project conventions. Some license types include these kind of information in their license block, can I change it freely?

I know the answer for these questions depends on each license type, so to make my question more specific...

Considering general license rules (usually they are different in minor aspects, right?), is ethical(or at least allowed) that I freely add information to the license block about my modifications and perhaps also modify how do I refer to it in my code (e.g use YACorp.YALib as Utils.YALib)?

答:
I would add a comment, partly to signal to a reader that the file is not "vanilla", with links to any relevant documentation or an issue tracking system.

Edit: So this situation reminds me of when a Linux distribution packages e.g. a library. Debian has guidelines and standards around how packages should be built and named, which could well vary from how the library is usually distributed pre-built.

I don't think you should be shy about naming / building / modifying a library, since I'm guessing you won't be distributing the result to the wider world? In this case I would include a README along with the source that describes what changes you've made and why. E.g. README.${companyName}.changes


问:
Options for client-side encryption of local web databases
My scenario is as follows:

Web application, run from the browser, designed for mobile devices.

Uses WebSQL storage which may contain sensitive
data.

Uses Application Cache to enable offline use where there is no connectivity.

Can connect to an API where even more sensitive data can be downloaded. Authentication is handled with BASIC Authentication, and unencrypted data is transferred over the wire, as the application shall access the API in the following environments/scenarios:

On a private, secured, local Wi-Fi network.

Over the public internet, over a VPN connection.

Over the public internet, through a HTTPS connection.

So far, based on my limited knowledge, the security of sensitive data transferred over the wire is covered. However, the data 'at-rest' in the local WebSQL storage, and formatted in the HTML pages of the web application, is not secure.

The current concern is if a mobile device contains sensitive data, and it is lost or stolen, how to minimise the risk of the sensitive data being accessed.

As the application needs to be usable without interaction with the server, any software-based encryption would be contained on the client itself. This means that, presumably, attempting to encrypt the WebSQL database will be pointless as if a skilled intruder can bypass the hardware encryption, they can presumably determine the encryption/decryption logic as well?

The proposed solution for encryption of data at rest, is to use the built-in hardware encryption that is part of iOS and Android devices, requiring users to enter a password at the lock screen. There are related 'remote wipe' features as well that could be used.

Q: How 'secure' is the proposed solution? If the built-in hardware encryption is not enough, what are the best strategies for implementing client-side encryption of WebSQL data without need of interaction with a server?

Is the implementation of a software-based, data encryption/decryption solution, only going to give a marginal security benefit, as the encryption/decryption code can be accessed and reverse engineered? Is it just me, or is the main benefit of that merely marketing purposes, i.e. being able to 'say' that it is encrypted?

Interesting links:

https://security.stackexchange.com/questions/10529/are-there-actually-any-advantages-to-android-full-disk-encryption

Also...

Underlying storage mechanisms may vary from one user agent to the
  next. In other words, any authentication your application requires can
  be bypassed by a user with local privileges to the machine on which
  the data is stored. Therefore, it's recommended not to store any
  sensitive information in local storage.

https://www.owasp.org/index.php/HTML5_Security_Cheat_Sheet#Client-side_databases

Does this mean the only secure option is to produce a hybrid application? E.g. using Phonegap. Is this a great deal more secure, could it just be reverse engineered to view the JavaScript that encrypts/decrypts in the same way anyway?

答:
Edited (after comments)

First of all

Save sensitive data on the client is a matter of agreement between the user and the owner of the data. You should get into the details of the software license, and the privacy policy that claims to offer.

Deciding to save data to the client application, without a robust synchronization policy, can create problems of data consistency (apart from safety).

Deciding to save data to the client application, can result in a complex system of synchronization increasing database workload (a hell).

I personally believe that the device should only be used as terminals, not as part of the architecture.

For those reasons, save data locally is not a good option, and +1 to Nikolay for

Caching sensitive data: Don't.

The customer is right, and not listen to reason

Having said that, if the request is mandatory, and there is no way to convince the customer/owner to move towards an on-demand architecture, you must find all the tricks to increase security within the client, protecting the rights, privacy and in general the access and use of data.

The proposal (which is one of opportunity), consider the following key points:

The user must log into the system at least once;

After login, we will carry out the synchronization of local data with the server;

After synchronization, a new encryption key will be generated (see details below) and used throughout the session (including after you disconnect from the server and network);

All information processed by the customer, even after disconnection, will be saved in the device, using an algorithm that considers the "encryption key  currently available";

Two-Factor Auth

The keys to encrypt data during sessions will be generated after the log in process. The 2nd factor is a key element to maximize the safety of a product that can be defined as "unsafe".

This mechanism ensures that if the device is stolen (for example), the data available locally, will be limited to one session, but most important, the remote system will not be accessible using the device.

What about VPN or ...

A product developed specifically to be used within an intranet, where the device does not have ability to connect to other networks, it does not need high security mechanisms, indeed, that kind of products only need to identify the user (you would use identity certificates, LDAP or similar devilry).

If the application must save data locally and can be distributed in any type of device (which has the minimum requirements), the VPN is no longer a security element within the design.


问:
What does Dependency Injection mean by saying it can inject on runtime?
I understand that the dependency injection is something done by coding and its all done at compile time. And that Dependency injection coding is easily done now by helper tools like Ninject.

However this is at compile time that the dependency injection occurs. Then what does it mean that dependency injection also occurs at Runtime?

This is straight from wiki about Dependency Injection

Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time.

I mean I thought about it and came up with the idea that it may refer to multiple interfaces to a single class when a Delegate calls a metho from one of the interfaces, dependency injection decides something like this at runtime, but when I went deeper into it and even discussed it with my boss it sounded like its not that simple as that. And that then, how does the dependency injection makes this decision and assume it the correct one?

Anyone can help me clear out this question?

答:
I'm late to the party, but I noticed that no one else answered the actual question. Here's a simple example of runtime DI:

First you need an object with a dependency:

```<code>public MyRoom(ILightFixture fixture)
{
  this.MyLightFixture = fixture ;
}
</code>```

And then, in your composition root, include a run-time decision:

```<code>public void Main()
{
  // make runtime decision (e.g. input from user); respond dynamically...
  ...
  if (userChoice == "Classy")
     room = new MyRoom(new ClassyChandelier());
  else
     room = new MyRoom(new SubduedSconce());
}
</code>```

Simple as that. Now the mood of your room object is determined dynamically (at runtime).

Body:
I'm late to the party, but I noticed that no one else answered the actual question. Here's a simple example of runtime DI:

First you need an object with a dependency:

public MyRoom(ILightFixture fixture)
{
  this.MyLightFixture = fixture ;
}

And then, in your composition root, include a run-time decision:

public void Main()
{
  // make runtime decision (e.g. input from user); respond dynamically...
  ...
  if (userChoice == "Classy")
     room = new MyRoom(new ClassyChandelier());
  else
     room = new MyRoom(new SubduedSconce());
}

Simple as that. Now the mood of your room object is determined dynamically (at runtime).


问:
What are the principles of open source projects?
Although its generally agreed by organisations like the OSI and the FSF what is and isn't an open source software (basically, the the terms of the source code license) what are the guiding principals for open source projects?

Other software movements have principals like the Agile Manifesto. It seems as though open source share some common values (such as transparency, collaboration, etc.). Are these documented somewhere?

答:
"Open source" is a broad term.  Its approach can be more pragmatic ("this is a useful approach for doing development") than philosophical, and it includes people from a variety of perpsectives, so I doubt you'll find a list of principles for it.

For free software in particular, the Free Software Foundation has an extensive description of the philosophy and principles behind it.

For open source in general, your best source would be something like The Cathedral and the Bazaar, by Eric S. Raymond, which had a lot of influence on the early open source movement.  More recently, there's Producing Open Source Software, by Karl Fogel, and Red Hat and others have put together opensource.com and theopensourceway.org, giving their own perspective on the movement.


答:
As you said, it depends on the particular license of the software. The license really goes a long way in terms of what you're allowed to do or not, and many debates ensue as to which open source license really respects the spirit and ideals of the OSS movement. Even the FSF actively maintains two versions of the GNU License (GPL and LGPL which are very different). As Josh kelley points out, the Free Software Foundation has a whole bunch of stuff related to this philosophies (as Linus Torvalds put in once, Stallman is the philosopher and he's the engineer.

However, the very definition of open source software, as broad as the term can be, is very straight-forward. Can you legally see the source code and modify it? Then it's open source. Is this documented somewhere? I'm very sure it is, be it a dictionary, an encyclopedia or the documentation of an open source license. Take your pick.

Open source licenses deal with distribution details of both the original work and your contributions, they already assume that the source code is open to see and modify.

Title: What are the principles of open source projects?

Body:
Although its generally agreed by organisations like the OSI and the FSF what is and isn't an open source software (basically, the the terms of the source code license) what are the guiding principals for open source projects?

Other software movements have principals like the Agile Manifesto. It seems as though open source share some common values (such as transparency, collaboration, etc.). Are these documented somewhere?


问:
How many programming languages is a programmer expected to be an expert at?
Do most programmers specialize on a single stack, leaving other things be, or are they expert at multiple languages at the same time? If it's more than one, how many is standard?

By expert, I mean more than simply knowing the syntax of a language - an expert knows enough of standard libraries, tools, environments and syntax to be able to write non-trivial programs without having to constantly look things up or read books/tutorials.

答: One, but that doesn't mean you can neglect the others. You have to know enough to justify why you're not using them or know your limitations, so you can ask for help when appropriate. </p>


问:
Unit test JSON parsing code?
In my humble view of unit testing a unit test tests a single unit of code. For me, this means a single class. Every dependency for that class is mocked in the corresponding test class, and passed in the constructor (or injected via a DI container). This allows you to test the class in complete isolation from the rest of the system. I take this as the gospel truth of what a unit test is supposed to be. If you are testing multiple real classes (more than one class in your test class is not a mock) then you don't have a unit test, you have an integration test.

Given this point of view, there are things that seem to fall outside of the realm of unit testing even though it seems as if you are testing a single class. One of these types of tests is data parsing tests. For example, given a data class:

```<code>public class Person {
  private Name name;
  private PhoneNumber phoneNumber;
  private Address address;
}
</code>```

a purported unit test then attempts to validate correct parsing:

```<code>@Test
public void shouldParsePerson() {
    String json = "{ the json would be here }";
    Person person = new Gson().fromJson(json, Person.class);

    assertThat(person.getName().getFirst()).isEqualTo("Jim");
    // more assertions based on what the JSON was would be here
}
</code>```

What is this really testing? For me, it appears to be testing that Gson works. The test is tightly coupled to both the structure of the JSON and the class in Java that it maps to. Is the test really worth writing? Is it worth maintaining? Is it useful? Wouldn't an integration test somewhere else that relies on the parsing code catch this anyways?

There is another question here that is related to my question, but it is actually different because it is asking how to unit test consumers of an API that wraps third parts classes, while I'm asking what constitutes a valid unit test that involves a third party class. My question is more philosophical in nature, while the other is more practical. My question could also be extended to things like testing configuration code which isn't necessarily involving third party classes.

答:
In general, unit testing should test your code, not the code of some library.  Presumably the library already contains its own unit tests.

Certainly, one or two unit tests would help you get the feel of the library and how it works.  But detailed testing of this kind generally falls under the purview of integration testing.

Title: Unit test JSON parsing code?


问:
Coordinating between developers on common resources
In our organization some of the resources (such as QA machines etc) are shared. Different folks get done at different times and some tests have to be run (during dev and QA) on these machines. Right now, we just skype a message to the team stating "I am going to run some destructive tests on such and such machines - let me know if anyone has an issue". This approach obviously has many issues (what happens if someone missed the message etc.)  Apart from maintaining a shared google doc that needs to be constantly updated - is there an easier way that folks use for such coordination?</p>

答:
A central scheduler is the heavy weight way to go but has several advantages.

If you set up a number of machines (or virtual machines) that tests can be run on (or machines can be spun up when a test is required) then you can have a central queue that people can submit jobs to and it can figure out what machines are free and what resources can be made available for them.

Advantages:

That way you know tests can be run one at once (if they need to be e.g. are destructive).

You can see what is in the queue.

You can schedule regular tests to have an appropriate priority to your new requests for tests.

You can also kill off tests when you know you need to clear the queue for an important test run.

The other big option that I would normally recommend you consider is continuous delivery / deployment but from your question I'm guessing that isn't an option at the moment.