答:
At @amon's suggestion, here's an answer that's more monadic. It's a very boiled down version, where you have to accept a few assumptions:

the "unit" or "return" function is the class constructor

the "bind" operation happens at compile time, so it's hidden from the invocation

the "action" functions are also bound to the class at compile time

although the class is generic and wraps any arbitrary class E, I think that's actually overkill in this case. But I left it that way as an example of what you could do.

With those considerations, the monad translates into a fluent wrapper class (although you're giving up a lot of the flexibility that you'd get in a purely functional language):

```<code>public class RepositoryLookup<E> {
    private String source;
    private E answer;
    private Exception exception;

    public RepositoryLookup<E>(String source) {
        this.source = source;
    }

    public RepositoryLookup<E> fetchElement() {
        if (answer != null) return this;
        if (! exception instanceOf NotFoundException) return this;

        try {
            answer = lookup(source);
        }
        catch (Exception e) {
            exception = e;
        }

        return this;
    }

    public RepositoryLookup<E> orFetchSimilarElement() {
        if (answer != null) return this;
        if (! exception instanceOf NotFoundException) return this;

        try {
            answer = lookupVariation(source);
        }
        catch (Exception e) {
            exception = e;
        }

        return this;
    }

    public RepositoryLookup<E> orFetchParentElement() {
        if (answer != null) return this;
        if (! exception instanceOf NotFoundException) return this;

        try {
            answer = lookupParent(source);
        }
        catch (Exception e) {
            exception = e;
        }

        return this;
    }

    public boolean failed() {
        return exception != null;
    }

    public Exception getException() {
        return exception;
    }

    public E getAnswer() {
        // better to check failed() explicitly ;)
        if (this.exception != null) {
            throw new IllegalArgumentException(exception);
        }
        // TODO: add a null check here?
        return answer;
    }
}
</code>```

(this won't compile... certain details are left unfinished to keep the sample small)

And the invocation would look like this:

```<code>Repository<String> repository = new Repository<String>(x);
repository.fetchElement().orFetchParentElement().orFetchSimilarElement();

if (repository.failed()) {
    throw new IllegalArgumentException(repository.getException());
}

System.err.println("Got " + repository.getAnswer());
</code>```

Note that you have the flexibility to compose the "fetch" operations as you like. It will stop when it gets an answer or an exception other than not found.

I did this really fast; it's not quite right, but hopefully conveys the idea

Body:
At @amon's suggestion, here's an answer that's more monadic. It's a very boiled down version, where you have to accept a few assumptions:

the "unit" or "return" function is the class constructor

the "bind" operation happens at compile time, so it's hidden from the invocation

the "action" functions are also bound to the class at compile time

although the class is generic and wraps any arbitrary class E, I think that's actually overkill in this case. But I left it that way as an example of what you could do.

With those considerations, the monad translates into a fluent wrapper class (although you're giving up a lot of the flexibility that you'd get in a purely functional language):

public class RepositoryLookup<E> {
    private String source;
    private E answer;
    private Exception exception;

    public RepositoryLookup<E>(String source) {
        this.source = source;
    }

    public RepositoryLookup<E> fetchElement() {
        if (answer != null) return this;
        if (! exception instanceOf NotFoundException) return this;

        try {
            answer = lookup(source);
        }
        catch (Exception e) {
            exception = e;
        }

        return this;
    }

    public RepositoryLookup<E> orFetchSimilarElement() {
        if (answer != null) return this;
        if (! exception instanceOf NotFoundException) return this;

        try {
            answer = lookupVariation(source);
        }
        catch (Exception e) {
            exception = e;
        }

        return this;
    }

    public RepositoryLookup<E> orFetchParentElement() {
        if (answer != null) return this;
        if (! exception instanceOf NotFoundException) return this;

        try {
            answer = lookupParent(source);
        }
        catch (Exception e) {
            exception = e;
        }

        return this;
    }

    public boolean failed() {
        return exception != null;
    }

    public Exception getException() {
        return exception;
    }

    public E getAnswer() {
        // better to check failed() explicitly ;)
        if (this.exception != null) {
            throw new IllegalArgumentException(exception);
        }
        // TODO: add a null check here?
        return answer;
    }
}

(this won't compile... certain details are left unfinished to keep the sample small)

And the invocation would look like this:

Repository<String> repository = new Repository<String>(x);
repository.fetchElement().orFetchParentElement().orFetchSimilarElement();

if (repository.failed()) {
    throw new IllegalArgumentException(repository.getException());
}

System.err.println("Got " + repository.getAnswer());

Note that you have the flexibility to compose the "fetch" operations as you like. It will stop when it gets an answer or an exception other than not found.

I did this really fast; it's not quite right, but hopefully conveys the idea


问:
Design review: how well does my object oriented design fit the SOLID principles?
This thread will be long, but I will try to make it as short as I can. Thank you.

I have recently implemented a relatively simple program. What this program does is generate a simple piece of music and play it.

I will describe the object oriented design of the program and would like to hear your review of the design. Especially how well it fits the SOLID principles, where it doesn't, and how I can improve my design to be more SOLID in the future.

(If there's something in the description that isn't clear enough, please tell me.)

I have divided my design into two parts.

1- The "behind the scenes" system that generates the content - a series of notes and chords (as will be explained later) - and is responsible for playing it.

2- The system that provides a UI to control the "behind the scenes" system. This system tells the other system when to create new music and when to play it.

I will describe each system separately.

System 1 - responsible for the generating and playing music.

The way music is created is by first generating a chord progression (a series of chords to be played one after the other), and then generating a melody based on that progression. I will describe how this is designed 'from the bottom up'.

Generating a chord progression.

Class Note: the most basic class. Responsible for playing sound files, and is set in instantiation to play a specific sound (C, D, etc.). It has an interface to play() and to stop() the playback. It also has a method getName() to identify it (the name is fed to the Note through the constructor).

Class Chord: this class is instantiated with an array of three Note objects and a name. For example, a Chord named cMajor will be instantiated with the Notes c, e, and g and the string "CMajor". Chord has an interface to play() and stop() the notes it's composed with, has a method getName() and a method getNotes() that returns the array of Notes.

Class Progression: this class is instantiated with an array of Chord objects, and has logic to play and stop them one after the other in a particular tempo (speed, in BPM - beats per minute). It has a method play(int bpm) and a method getChords() that returns the array of Chords.

Class ProgressionGenerator: implements an algorithm to create a particular series of Chord objects, and instantiate a Progression with these chords.

To summarize: a Progression is composed of Chords, which are composed of Notes. The ProgressionGenerator instantiates a Progression with a particular series of Chords.

Generating a melody.

Class MelodyNote: composed with a single Note. It has an attribute double duration which specifies for how long this note is to be played relative to a measure/bar of music (e.g. 'half note' is specified as 0.5, 'quarter' as 0.25). It has a method getDuration() and an interface to play() and stop() it's inner Note (basically delegates to the Note).

Class Melody: composed with a series of MelodyNotes. Has logic to play the series of notes in a particular speed. It uses each MelodyNote's duration to know when to stop a note and play the next one.

Class MelodyGenerator: implements an algorithm to generate a series of MelodyNotes and instantiate a Melody with it. It does this based on a Progression. The method signature is Melody generate(Progression prog).

So to summarize:

Progression --> composed with Chords --> composed with Notes

Melody --> composed with MelodyNote

Each object controls it's inner objects and exposes them. For example Chord has logic to play it's inner Notes, and has a method getNotes() that returns them to whoever needs to know. For example, MelodyGenerator uses progression.getChords() in order to build a melody according a particular series of chords. It also uses chord.getNotes() when choosing what notes to place over a chord.

One last thing: the generators use the singleton class NotesAndChordsSupplier to get the Note and Chord instances they need. It hands them existing instances.

System 2 - responsible for providing a UI to control the creation and playback of music.

This system is designed using the MVC pattern. The Model encapsulates the creation and playing of music. The View is the UI that provides buttons to tell the Model to play and make new music. The Controller is notified by the View when buttons are pressed and invokes the proper actions on the Model.

The Model

The Model contains a Progression, a ProgressionGenerator, a Melody and a MelodyGenerator. When it's told to generate new music, it simply delegates the task to the generators. When it's told to play music, it delegates the task to the melody and progression. Simplified code:

```<code>public void makeNewMusic(){
    progression = progGenerator.generate();
    melody = melodyGenerator.generate(progression);
}

public void playMusic(){ // this actually starts two separate threads, but irrelevant.
    progression.play();
    melody.play();
}
</code>```

The Model is connected (in a loosely-coupled manner) to two objects: it's Melody and the View - both via the Observer pattern.

The Model implements two interfaces: Observer and Observable. It's registered as an observer to the Melody, and the View is registered as an Observer to the Model.

When the Melody finishes it's playback, it notifies it's observer - the Model. When the Model is notified, it notifies it's own observer - the View.

This way, the View gets notifies when playback is finished, so it can re-enable it's UI buttons that were disabled during playback.

The View

The View is the UI and it has two buttons: Play and New Tune. They invoke playButtonPressed() and newTuneButtonPressed() on the Controller, respectively.

The View also features enableButtons() and disableButtons() methods.

As I said, the View is registered as an Observer to the Model. It is notified when playback of the music is finished, so it can re-enable it's buttons that were disabled by the Controller when playback started.

The Controller

When the View calls newTuneButtonPressed() on the Controller, it simply delegates to the Model: model.makeNewMusic().

When the View invokes playButtonPreesed() on the Controller, two things happen. 1- The Controller calls disableButtons() on the View. 2- The Controller calls playMusic() on the Model.

All buttons on the View are disabled by the Controller when music playback starts.

The Controller registers the View as an observer to the Model, and the Model as an observer to it's member Melody.

UML class diagram to illustrate the architecture

(Please note: in this post I ommited a class Scale, which isn't important. Ignore it in the diagram).

Thank you for reading all of this. I will appreciate any kind of criticism of the object oriented design of the program.

Especially, how well are SOLID and OO principles integrated in my design, and how can I design more in the spirit of SOLID on the future.

答:
I'm not sure I can give you a thorough review via internet, but some notes as I read through:

There is more than one note with the same name. Low C, middle C, high C, etc. And even there, "high"/"low" is relative to the instrument playing them, so those probably aren't sufficient names.

I don't particularly like Note knowing how to play itself. The same note can be played by different instruments, for different durations, with different techniques (trill, staccato, etc.).

I don't particularly like having a play and stop. This adds temporal coupling (you can only stop after play. Play with a duration may be better.

I don't particularly like Note being constructable. There is a well defined set of notes. Making them static and immutable makes them more easily comparable, better in concurrent scenarios, easier to reason about...

You don't mention the language, but getBlah methods are smelly to me.

Progression has a beats per minute, but that assumes each chord gets equal time. It also assumes that there's no transition between chords/notes (slurs, percussion effects).

There's no reason to have a singleton. Even if you don't want the notes and stuff to be static & immutable, having more than one flyweight isn't going to end the world. If you only want one, only make one.

As a matter of practicality, you will likely need to test playing the notes in sequence (if that is what you plan to do) since program (and sound card) latency may make it sound bad.

I am not sure your generators are sufficiently generic enough to include directly in the model. You should consider having interfaces for those dependencies.

Your Observer and Observable interfaces are weird. Even in a language without delegates/events, you'd still give these things concrete names or some message to pass in the function call. These make it seem as though there's only ever one (implied) event signaled between two objects.

...and that's about it. Hope that helps.

ContentLicense: CC BY-SA 3.0


问:
What are the benefits of Android way of "saving memory" - explicitly passing Context objects everywhere?
Turned out, this question is not easy to formulate for me, but let's try.

In Android, pretty much any UI object depends on a Context, and has defined lifetime. Android can also destroy and recreate UI objects and even whole application process at any time, and so on. This makes coding asynchronous operations correctly not straightforward. (and sometimes very cumbersome) But I never have seen a real explanation, why it's done that way? There are other OSes, including mobile OSes (iOS, for example), that don't do such things. So, what are the wins of Android way (volatile UI objects and Contexts)? Does that allow Android applications to use much less RAM, or maybe there are other benefits?

答:
You are right about using "less" memory but it's not just less, but a fixed upper bound to each process's heap size. That means normal Java garbage collection can operate inside every instance of the Java runtime, without coordination with other processes. It also means processes can be the sandbox boundary for Android apps.

This has proven to be more successful than implementations of multi-tasking VMs, and other approaches for sharing a single VM among multiple applications.

Android's multi-process approach is made possible by Zygote. Zygote enables fast startup of an Android runtime by having most of the base classes loaded. You don't even copy the heap since Android runs in copy-on-write mode. It's pretty cool that processes, multiple runtime instance (LOTS of runtime instances compare to any other Java environment), and limited heap size all work together so well.


问:
MongoDB: Replicate data in documents vs. “join”
Disclaimer: This is a question derived from this one.

What do you think about the following example of use case?

I have a table containing orders.

These orders has a lot of related information needed by my current queries (think about the products; the buyer information; the region, country and state of the sale point; and so on)

In order to think with a de-normalized approach, I don't have to put identifiers of these related items in my main orders collection. Instead, I have to repeat all the information for each order (ie: I will repeat the buyer's name, surname, etc. for each of its orders).

Assuming the previous premise, I'm committing to maintain all the data related to an order without a lot of updates (because if I modify the buyer's name, I'll have to iterate through all orders updating the ones made by the same buyer, and as MongoDB blocks at a document level on updates, I would be blocking the entire order at the update moment).

This raises the following questions:

Do I have to replicate all the products' related data? (ie: category, maker and optional attributes like color, size…)

What if a new feature is requested and I've to make a lot of queries with the products "as the entry point of the query"? (ie: reports showing the products' sales performance grouping by region, country, or whatever)

Is it fair enough to apply the $unwind operation to my orders original collection? (What about the performance?)

I should have to do another collection with these queries in mind and replicate again all the products' information (and their orders)?

Wouldn't be better to store a product_id in the original orders collection in order to be more tolerable to requirements change? (What about emulating JOINs?)

The optimal approach would be a mixed solution with a RDBMS system like MySQL in order to retrieve the complete data?

I mean: store products, users, and location identifiers in the orders collection and have  queries in MySQL like getAllUsersDataByIds in which I would perform a SELECT * FROM users WHERE user_id IN ( :identifiers_retrieved_from_the_mongodb_query )

答:
In order to get join-like information from your model, (like the statistics on products), you can also do one of these two things:

createa a separate products_statistic collection which is updated with the needed info each time an order is saved/updated in the db

create a map-reduce operation that calculates the needed info for products (takes in orders, for each product in each order counts statistics x,y,z for that product). Mongo's integration with Hadoop can greatly increase performance in this case (check it out here)


问:
RFC syntax definition
I would like to bring our specifications to a better level of fine-grained definition of syntaxes, semantics and the like. I read my fair share of RFCs and just love the way they define things like "how an email adress looks like" or "what a correct URL is".

But, I haven't yet found a definition of the syntax of those definitions. Like, e.g. how do you define optional parts? How do you define repetition? How to correctly define alternatives (/ vs |)

Is there an RFC that defines the syntax all those other RFCs use to define their actual domain-specific definitions that I could adapt to our specifications?

答:
The grammar formalism used in many modern RFCs is called Augmented Backus-Naur-Form, and is specified in RFC 5234 – Augmented BNF for Syntax Specifications: ABNF:

Internet technical specifications often need to define a formal syntax.  Over the years, a modified version of Backus-Naur Form (BNF), called Augmented BNF (ABNF), has been popular among many Internet specifications.  The current specification documents ABNF. It balances compactness and simplicity with reasonable representational power.  The differences between standard BNF and ABNF involve naming rules, repetition, alternatives, order-independence, and value ranges.  This specification also supplies additional rule definitions and encoding for a core lexical analyzer of the type common to several Internet specifications.

Title: RFC syntax definition


问:
What's the most used programming language in high performance computing? And why?
I believe a lot of Fortran is used in HPC, but not sure if that's only for legacy reasons.

Features of modern programming languages like garbage collection or run-time polymorphism are not suitable for HPC since speed matters so not sure where C# or Java or C++ come in.

Any thoughts?

答:
I think for real pedal to the metal, the only real choice is Fortran. The reasoning is that  the most important thing for the exploitation of low level ILP (Instruction Level Parallism)
is memory address disambiguation. The defacto rules in Fortran allow the compiler to determine
that two address are unique (and hence the order of loads and store, or even stores and  stores can be interchanged without risk of generating incorrect code). C leaves too much scope
 for overlapping pointers for the compiler to extract as much low level parallelism from the code.

Also, array alignment, w.r.t cache lines, and SSE/AVX boundaries is important to the generation and execution of efficient loops. If arrays are passed via common blocks, the compiler/loader
can assure that all arrays start on the same address alignment boundaries, and more efficient
SSE/AVX loads and stores can be utilized. The newer hardware can handle unaligned memory accesses, but because the memory access isn't aligned properly partial use of cache lines results in lower performance. Even
if a C programmer properly aligns all his arrays, is there a mechanism to communicate
this to the compiler?

To summarize, the two most important issues, are the independence of memory addresses, and the recognition by the compiler that the accessed data structures have the same "natural" alignment that the hardware wants. So far Fortran does the best job on those two tasks.

ContentLicense: CC BY-SA 2.5


问:
alternatives to nested try-catches for fallbacks
I have a situation where I am trying to retrieve an object. If the lookup fails I have several fallbacks in place, each of which may fail.  So the code looks like:

```<code>try {
    return repository.getElement(x);
} catch (NotFoundException e) {
    try {
        return repository.getSimilarElement(x);
    } catch (NotFoundException e1) {
        try {
            return repository.getParentElement(x);
        } catch (NotFoundException e2) {
            //can't recover
            throw new IllegalArgumentException(e);
        }
    }
}
</code>```

This looks awfully ugly.  I hate to return null, but is that better in this situation?

```<code>Element e = return repository.getElement(x);
if (e == null) {
    e = repository.getSimilarElement(x);
}
if (e == null) {
    e = repository.getParentElement(x);
}
if (e == null) {
    throw new IllegalArgumentException();
}
return e;
</code>```

Are there other alternatives?

Is using nested try-catch blocks an anti-pattern? is related, but the answers there are along the lines of "sometimes, but it's usually avoidable", without saying when or how to avoid it.

答:
If you're anticipating that a lot of those repository calls are going to throw NotFoundException, you could use a wrapper around the repository to streamline the code. I wouldn't recommend this for normal operations, mind you:

```<code>public class TolerantRepository implements SomeKindOfRepositoryInterfaceHopefully {

    private Repository repo;

    public TolerantRepository( Repository r ) {
        this.repo = r;
    }

    public SomeType getElement( SomeType x ) {
        try {
            return this.repo.getElement(x);
        }
        catch (NotFoundException e) {
            /* For example */
            return null;
        }
    }

    // and the same for other methods...

}
</code>```

Body:
If you're anticipating that a lot of those repository calls are going to throw NotFoundException, you could use a wrapper around the repository to streamline the code. I wouldn't recommend this for normal operations, mind you:

public class TolerantRepository implements SomeKindOfRepositoryInterfaceHopefully {

    private Repository repo;

    public TolerantRepository( Repository r ) {
        this.repo = r;
    }

    public SomeType getElement( SomeType x ) {
        try {
            return this.repo.getElement(x);
        }
        catch (NotFoundException e) {
            /* For example */
            return null;
        }
    }

    // and the same for other methods...

}


问:
How to handle long method names in sequence diagram?
I have a C# application that is developed with VS 2010 pro. The ultimate version would have a sequence diagram feature.

Since I will "create" my sequence diagram manually, how do I deal with quite long method names?

```<code>object.createPathForCustomerIDblablablabla_click()
</code>```

Do I just use the method names as they are already given? Use a shorter name in the sequence diagram?

I would like it to fit on a A4 page.

答:
Since you already have code and you are reverse engineering it into a UML model, I would highly recommend keeping the method and attribute names as they are in the code. This will make it easier for someone to go between the code and the model. However, using exact function names aren't required in a sequence diagram. Typically, I've seen this earlier on in the design process when activity, sequence, and communication diagrams are being used to describe a use case. The breakdown of the classes and functions may change, but the general approach is described using names that may or may not become the names of the methods.

Stylistically, though, long method names may be considered a code smell (see this C2 Wiki article on code smells, this C2 Wiki article on using good naming, and this Stack Overflow question about long variable and function names). You may not want to refactor it now, but perhaps make a note of it somehow to revisit the next time you're working with that code. As you can tell, long method names can make documentation difficult to create and read in the future, so that's another good argument for choosing good names in the future or refactoring existing code.


问:
Organizing uncommented, dirty code?
I would like to ask you some questions about dirty code. There are some beginners who coded on a medium project. The code is a very huge ball of mud. They are not advanced programmers. They just know how to use keyboard an a little about java. They just wrote code with 12 000 lines in their main class, though, 6 000 lines belongs to NetBeans itself.

My job is to analyze the code and suggest a good way to maintain the code. My idea is to scrap the project and start a new one with OOP methodology. Recently I collected some notes and ideas about the problem, from this site and some others.

Now, I have the followings questions:

Should we repair the code, and change it to a OOP? We are now debugging it.

The code has no comments, no documentation, no particular style of programming, and so forth. Changing it is really expensive and time consuming. What do we can do about this?

How can I teach them to follow all the rules (commenting, OOP, good code quality, etc.)?

The code is erroneous and error prone. What can we do? Testing? We almost write two or three A4 papers for correction, but it seems endless.

I should have to say that I am new with them. I think I have broken the rules about adding people too late to the project, as well. Do you think I have to leave them?

答:
Should we repair the code, and change it to a OOP? We are now
  debugging it. [... contains errors, no documention ...]

I've been there, you have my sympathies. I even wrote an article about this which might help you get some perspective. But in short:

If the code contains lots of duplication, you should rewrite. If there is no discernible structure (no clear interfaces, spaghetti), refactoring will fail and you should probably rewrite.

How can I teach them to follow all the rules?

Begin with explaining why they might want to do that by showing them what they can gain from it personally. When they agree with this and are willing to learn, start teaching them using shuhari.

Title: Organizing uncommented, dirty code?


问:
Should I use an Exception in a case like this?
I have a Windows service with a fluent interface like this:

```<code>aRequest = Repository.getRequest()
                     .createProcess()
                     .validate();
</code>```

Sometimes getRequest() could return a null value and this would cause an error in createProcess(). I could banally split getRequest() from createProcess(), but if I wouldn't do that what way should I follow, what way is better:

Check if request (this) is null and in the case return null:

```<code>if(this is null)
  return null
</code>```

I could do this check in every method next to getRequest(). At the end aRequest will be null.

Throw an exception if createProcess() method receive a null value:

```<code>if(this is null)
   throw new NullRequestException();
</code>```

PRO of the second way: Only second method need a check, independently of the number of method in the chain.

CON of the first way: Every method in the chain needs a check

Now the question: Is second way a bad use of exception concept, since could be normal the absence of request sometimes?

答:
Is it possible to not return null from getRequest(), or at least have a separate version of it doing so? If it threw an exception instead, and other parts of the chain would do the same,  you'd have a nice consistent error handling.

What a pity that both Java and C# lack the Maybe and Either idioms; Optional has seen some adoption, though. Returning null is a bad idea: it hides the source of your problem. It is infuriating during troubleshooting. In general, fail fast, right where the problem occurs. I'd use exceptions.


答:
I think it is fine that getRequest returns null, so long as the reader knows that it can.

The problem of your example, the way it's written, it reads as it should 100% of the time it will create a process.

If the expectation is that getRequest should never return null, then that method should be the one throwing the exception.  If it's expected that getRequest returns null instead, you should modify your usage of it to handle that case.

```<code>private Request createProcessIfRequestFound() {
    var request = Repository.getRequest();

    if (request != null) {
        request.createProcess().validate();
    }

    return request;
}
</code>```

My personal preference is to avoid fluent interfaces, in my opinion, ironically, I find they are less fluent than writing code non-"fluently"

Title: Should I use an Exception in a case like this?

Body:
I have a Windows service with a fluent interface like this:

```<code>aRequest = Repository.getRequest()
                     .createProcess()
                     .validate();
</code>```

Sometimes getRequest() could return a null value and this would cause an error in createProcess(). I could banally split getRequest() from createProcess(), but if I wouldn't do that what way should I follow, what way is better:

Check if request (this) is null and in the case return null:

```<code>if(this is null)
  return null
</code>```

I could do this check in every method next to getRequest(). At the end aRequest will be null.

Throw an exception if createProcess() method receive a null value:

```<code>if(this is null)
   throw new NullRequestException();
</code>```

PRO of the second way: Only second method need a check, independently of the number of method in the chain.

CON of the first way: Every method in the chain needs a check

Now the question: Is second way a bad use of exception concept, since could be normal the absence of request sometimes?

Body:
I think it is fine that getRequest returns null, so long as the reader knows that it can.

The problem of your example, the way it's written, it reads as it should 100% of the time it will create a process.

If the expectation is that getRequest should never return null, then that method should be the one throwing the exception.  If it's expected that getRequest returns null instead, you should modify your usage of it to handle that case.

private Request createProcessIfRequestFound() {
    var request = Repository.getRequest();

    if (request != null) {
        request.createProcess().validate();
    }

    return request;
}

My personal preference is to avoid fluent interfaces, in my opinion, ironically, I find they are less fluent than writing code non-"fluently"


答:
If you want to maintain the fluent syntax, getRequest() must never return null! The fluent interface must return this at every step, and this can't be null. ;)

If the internal call inside getRequest returns a null, then you need to change the state of Repository so that validate() can pick up that condition and throw an exception or handle it appropriately. You could have a member variable "String answer;" and set & check that for null, or else have a "boolean nullAnswer;" member.

Also, take a look at Guava's "Optional" class, because it's a great way of handling values that might not be present. Even then, make sure your fluent methods always returns this (or the variant return new Respository(...)).


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答: Fallthrough by default in C and C++ switch statements.</p>


答:
Aside:

Contrary to popular belief, long names are not always a bad thing.
Used in moderation,
they can be helpful.
For example,
if a method returns a boolean value that indicates that the application startup should be aborted if the execution fails while the application is starting up then one of these is more clear than the other:

getTerminateDuringStartup

getHaltApplicationStartupIfExecutionFailsDuringStartupFlag

On to the Question:

If the names are too long to conveniently fit in a diagram, consider creating short names in the diagram only and map them to the full method name.

For example: Use createPFCIDbbbbc in the diagram and include a page that maps the short name to the long name.  Consider flagging the short names; one way is to add an asterisk to the front of shortened names.  In that case, *createPFCIDbbbbc would indicate that it is a shortened name and createBlammyQ would indicate that it is not a shortened names.

On the map page, start with a statement like "Some method names are too long to conveniently fit in the diagrams that follow.  In these cases the method name will start with an asterisk to indicate that it is a shortened name.  The list below maps between the shortened names and the actual method name in code".  Then have a simple table like this:

```<code>Shortened Name         Actual Method Name
createPFCIDbbbbc       createPathForCustomerIDblablablabla_click
</code>```

Title: How to handle long method names in sequence diagram?

Body:
I have a C# application that is developed with VS 2010 pro. The ultimate version would have a sequence diagram feature.

Since I will "create" my sequence diagram manually, how do I deal with quite long method names?

```<code>object.createPathForCustomerIDblablablabla_click()
</code>```

Do I just use the method names as they are already given? Use a shorter name in the sequence diagram?

I would like it to fit on a A4 page.

Body:
Aside:

Contrary to popular belief, long names are not always a bad thing.
Used in moderation,
they can be helpful.
For example,
if a method returns a boolean value that indicates that the application startup should be aborted if the execution fails while the application is starting up then one of these is more clear than the other:

getTerminateDuringStartup

getHaltApplicationStartupIfExecutionFailsDuringStartupFlag

On to the Question:

If the names are too long to conveniently fit in a diagram, consider creating short names in the diagram only and map them to the full method name.

For example: Use createPFCIDbbbbc in the diagram and include a page that maps the short name to the long name.  Consider flagging the short names; one way is to add an asterisk to the front of shortened names.  In that case, *createPFCIDbbbbc would indicate that it is a shortened name and createBlammyQ would indicate that it is not a shortened names.

On the map page, start with a statement like "Some method names are too long to conveniently fit in the diagrams that follow.  In these cases the method name will start with an asterisk to indicate that it is a shortened name.  The list below maps between the shortened names and the actual method name in code".  Then have a simple table like this:

Shortened Name         Actual Method Name
createPFCIDbbbbc       createPathForCustomerIDblablablabla_click


问:
Git: Branch or Fork?
I have a game project that will have two versions:

A simple version of the game, the core.

An advanced version of the game.

I have the 1st version in my public repository, and only I will be working on it. As for the 2nd version, two friends of mine and I will work on it. The crucial part is that I want the two versions to stay in my repository.

I thought I might use branches for this, but considering this question and its answer, it's not good practice to do so in terms of versioning. As far as I've found out, forking your own repository is not possible.

What are my options here? How can I keep both versions in my repository?

答:
The answer to the question "should I clone or fork" is exactly the same as the answer to this question "do I want my own personal version of this project?"  yes = fork, no = clone the repository.

In git, branch is a light weight thing that is often temporary and may be deleted.  A fork (on github) is a new project that is based on a previous project.  You clone a repository to do work on it as a team member.

Many public projects have you fork the project to keep the working changes out of the main project.

For phase 2, fork the project then clone it to your working computer and have your friends do the same.

Title: Git: Branch or Fork?


问:
Why is studying a Lisp interpreter in lisp so important?
I have seen many CS curriculums and learning suggestions for new programmers that call for the aspiring programmer to study a Lisp interpreter that is specifically written in Lisp.  All these sites say things similar to, "its an intellectual revelation", "it is an enlightenment experience every serious programmer should have," or "it shows you hardware/software relationships," and other vague statements, particularly from this article taken from this reputable how-to.

The general sentiment of my question is, how does Lisp achieve the above goals and why Lisp?  Why not some other language?

I am asking this because I just finished writing a scheme interpreter in scheme (taken from SICP http://mitpress.mit.edu/sicp/ ) and now I am writing a python interpreter in scheme and I am struggling to have this legendary epiphany that is supposed to come specifically from the former.  I am looking for specific technical details between the two languages that I can exploit in their scheme interpreters to gain understanding about how programs work.

More specifically:

Why is the study of an interpreter that is written in the language it interprets so emphasized - is it merely a great mental exercise to keep the original language and built language straight or are there specific problems whose solutions can only be found in the nature of the original language?

How do Lisp interpreters demonstrate good architecture concepts for one's future software design?

What would I miss if I did this exercise in a different language like C++ or Java?

What is the most used takeaway or "mental tool" from this exercise? **

** I selected the answer I did because I have noticed that I have gained from this exercise more skill in designing parsing tools in my head than any other single tool and I would like to find different methods of parsing that may work better for the scheme interpreter than the python interpreter.

答:
LISP is itself structured in a way which makes it extremely easy to parse. If you try to write a compiler, you will notice that it's a lot easier if everything in your language is an expression and has a low level of ambiguity. LISP forces parentheses everywhere to eliminate ambiguity and has no statements, only expressions.

The very fact that LISP is very easy to parse encourages users to parse their own source code and do magic tricks with it. The line between data and code becomes blurred and you can easily do things which normally require quite some effort, like reflection, dynamic code rewrite, plugins and serialization.

That's the gist of it. The exercise is probably meant to give you some insight into what is possible when the code is easily parseable from itself.

ContentLicense: CC BY-SA 4.0


答:
The simple answer to your question is to try Lisp, preferably in conjunction with SICP.  Then you will be enlightened.

That said...

Code is Data

Most languages make a sharp distinction between code and data; Lisp does not.  This makes it possible to, for example, trivially write a Lisp parser in Lisp, and to manipulate Lisp code within Lisp.  The best description of this enlightenment that I have found is The Nature of Lisp.

This is true in part because the syntax for the language is so simple.  It makes possible things in Lisp (like metaprogramming) which are impractical in other languages because the syntax gets in the way.

Further Reading

Beating the Averages

Title: Why is studying a Lisp interpreter in lisp so important?

Body:
I have seen many CS curriculums and learning suggestions for new programmers that call for the aspiring programmer to study a Lisp interpreter that is specifically written in Lisp.  All these sites say things similar to, "its an intellectual revelation", "it is an enlightenment experience every serious programmer should have," or "it shows you hardware/software relationships," and other vague statements, particularly from this article taken from this reputable how-to.

The general sentiment of my question is, how does Lisp achieve the above goals and why Lisp?  Why not some other language?

I am asking this because I just finished writing a scheme interpreter in scheme (taken from SICP http://mitpress.mit.edu/sicp/ ) and now I am writing a python interpreter in scheme and I am struggling to have this legendary epiphany that is supposed to come specifically from the former.  I am looking for specific technical details between the two languages that I can exploit in their scheme interpreters to gain understanding about how programs work.

More specifically:

Why is the study of an interpreter that is written in the language it interprets so emphasized - is it merely a great mental exercise to keep the original language and built language straight or are there specific problems whose solutions can only be found in the nature of the original language?

How do Lisp interpreters demonstrate good architecture concepts for one's future software design?

What would I miss if I did this exercise in a different language like C++ or Java?

What is the most used takeaway or "mental tool" from this exercise? **

** I selected the answer I did because I have noticed that I have gained from this exercise more skill in designing parsing tools in my head than any other single tool and I would like to find different methods of parsing that may work better for the scheme interpreter than the python interpreter.


答:
Why is the study of an interpreter that is written in the language it
  interprets so emphasized?

In general, studying an interpreter gives you insight into its language and features.
In general, studying code in a programming language is like practicing a spoken language by listening and reading: it familiarizes you with what that language can do, how it's used, and common "idioms".
More specifically, Lisp is a homoiconic language, meaning its syntax for expressions is the same as its syntax for data. Writing code in Lisp looks awfully like you're writing out a list, and vice-versa. Thus, interpreting Lisp code with Lisp code is as simple as running through lists with car and cdr.

How should I capitalize on this exercise to get the most out of it
  conceptually?

Think about how the interpreter would interpret itself - in many meta-circular interpreter implementations (where a homoiconic language interprets itself) can just "pass through" the function. For example, To implement car, simply take the car of the argument. This takes the emphasis away from data storage mechanisms and focuses on functionality.

How do lisp interpreters demonstrate good architecture concepts for
  one's future software design?

Interpreters can be very complicated, which encourages good architecture in designing them. With that in mind, this one is more dependent on the individual interpreter.

What would I miss if I did this exercise in a different language like
  C++ or Java?

These languages aren't homoiconic, so they don't benefit from the grace and simplicity of a meta-circular Lisp interpreter. This makes the exercise harder, and perhaps less common, but I wouldn't say it's really any less beneficial.

What is the most used takeaway or "mental tool" from this exercise?

I'm not sure I have a good answer for this one; simply that it helps to see how the interpreter works and, maybe more importantly, tinker around with it to see how minor changes to the language can be easily implemented.


答:
To me it seems that you need two Repositories not two Branches. A branch is a mechanism to handle the changes within a single repository in order to eventually merge them with the rest of code.

If you really want to keep both versions of a Similar code-base in the same repository, then your only option is to go for a Branch, however as mentioned earlier, the main purpose of a branch is to separate some specific commits in a way that they don't conflict with the rest of code during the development period, and merge them when they are ready to go.

There are situations that a repository has two slightly different branches -- e.g. 32-bit and 64-bit versions of the same source-code, however I'd still recommend you to go for separated repositories, if that's an option.

Title: Git: Branch or Fork?

Body:
I have a game project that will have two versions:

A simple version of the game, the core.

An advanced version of the game.

I have the 1st version in my public repository, and only I will be working on it. As for the 2nd version, two friends of mine and I will work on it. The crucial part is that I want the two versions to stay in my repository.

I thought I might use branches for this, but considering this question and its answer, it's not good practice to do so in terms of versioning. As far as I've found out, forking your own repository is not possible.

What are my options here? How can I keep both versions in my repository?


问:
Exception when logging exception: is it correct to ignore them?
My question is specific to php, but i think it can be useful in other languages.

I log into a table all the exception a code can throw:

```<code>try{
 //Some code
 } catch (Exception $e) {
      $log = new Log(basename($_SERVER['PHP_SELF']), $_SESSION['id'], LogType::EXCEPTION, $e);
      try {
           $log ->addLog();
       } catch (Exception $e2) {
                //
       }
 }
</code>```

The function addLog insert the exception informations into a database.
But (by example if the connection with the database is lost) this function can throw an exception. I can't see what i have to do with this exception except ignoring it.

I know ignoring exception is a bad practice, but what can i do in this particular case?

If there is no problem to ignore it, is there a better way to indicate that this exception should not be taken into account?

答:
I had a function as fallback for logging to file as @CodeART and @Andy sugested

```<code>function log(Exception $e) {
    $file = fopen('log/error.log', 'a+');
    if ($file !== false) {
        fwrite($file, $e->getMessage() . "\r\n" . $e->getTraceAsString());
        fclose($file);
    }
}
</code>```

You could call it within the second catch. To use it you should configure your environment and make sure the script was write permission on your log directory

Body:
I had a function as fallback for logging to file as @CodeART and @Andy sugested

function log(Exception $e) {
    $file = fopen('log/error.log', 'a+');
    if ($file !== false) {
        fwrite($file, $e->getMessage() . "\r\n" . $e->getTraceAsString());
        fclose($file);
    }
}

You could call it within the second catch. To use it you should configure your environment and make sure the script was write permission on your log directory


问:
Why are more programmers not freelance these days?
Leaving the whole pie to only a few of them, amplifying the huge differences between the two status. Pay is a (huge) one, not having to do overtime is another.

I leave the question open to hopefully get many great answers on all the different subjects that affects that feeling and decision not to go.

While this question is really global, I'll be interested in any studies, facts, articles, opinions regarding local markets such as US, India and even Australia in which I'm in love with.

答:
I would probably never consider going freelance, for all the reasons others have already given...

On the other hand, I would indeed consider starting a software company (be it for the web, mobile or desktop).  This is a completely different venture!  It is very difficult to be succesfull, and you still need a lot of work that's not programming.  But at least, if it really works, you're not limited into getting rewards proportional to your quantity of work as is the case with freelancing: you can get exponential returns!


问:
What happened to VM based deployments?
Watched some MountainWest RubyConf 2014 talks and noticed an interesting theme. Many dynamic programming environments back in the old days used to be self-contained VM images, e.g. SmallTalk, GemStone/S.

One could checkpoint, modify, and ship these images wholesale and have it up and running with very little effort. Fast forward to now and I'm still using Make files to configure and install binaries. What happened?

答:
It turns out that providing a VM which modulates all communication to the OS is darn hard. In the best case, you end up with a knee-capped interface that improves as people complain about not being able to do certain things.

Remember that quite a lot of these dynamica languages evolved as glue, no one ever thought that Perl would need to run on windows when Larry Wall first created it. It was a lot more important for it to just be able to seemlessly interact with unix since that's what everyone wanted to do with it.

Things in smalltalk VM land aren't all hunkydory either, it's near impossible to do the sort of things your acustomed to being 5 lines of perl since smalltalk plays terribly with the outside world.

At best nowadays if you want crossplatform VM's you should invest some time in Groovy or JRuby which run on a VM which has painfully evolved to be a useful crossplatform interface.

Title: What happened to VM based deployments?


问:
Dependency Inversion Principle: Understanding how both low level components and high level components depend on abstractions
I'm learning about the Dependency Inversion Principle. It states that:

High level modules should not depend upon low-level modules. Both
  should depend upon abstractions.

For a while I tried to understand what it means that both the high level components and the low level components, rely on the abstractions and are dependent on them.

I'm assuming both should depend on the same abstraction in some way. Please correct me if this is wrong.

I have come to some conclusion about what this means. Please confirm if this is accurate.

"The high level components are dependent on the abstraction" - Meaning:

The high level components talk to an interface to communicate with the low level components, instead of communicating with concrete low level components directly. The low level components implement this interface.

"The low level components are dependent on the abstraction" - Meaning:

The low level components are defined and designed in the terms of the interface. They are designed to fit the interface. They are dependent on the interface, in the way that the interface defines how they are designed. (Often low level classes implement that interface).

This way, both the high level components and the low level ones are 'dependent on the abstraction', but in different ways.

Is this a good understanding?

答:
Your understanding of the concept is very accurate.

Pointing out exceptions, special cases or philosophical minutiae right now would be diverting you from your present clarity of concept.

I would suggest, though, you use UML symbols:

Open arrow : uses

Closed arrow: inherits or implements

<< name in brackets >> : interface or abstract class


答:
At the risk of giving a "me too" answer, if you try it you'll see...

If you study computer languages, you're likely to get the impression that it's at least half about parsing.
If you learn Lisp, you'll realize parsing the surface syntax is nothing more than a convenience for people (like most of us) who don't like Lots of Irritating Single Parentheses.

Then you could realize that a big price was paid for that convenience.
In Lisp it is trivial for a program to build another program and execute it.
In other languages it is an advanced technique, like doing multiplication in roman numerals.

Of course, nearly everybody would ask "who needs to do that?"
Well, you could very well see that it opens up a whole vista of things you never even realized you couldn't do before.
You can do it in other languages, but not nearly so easily.

INSERTED to answer Izkata comment:

The SHRDLU natural-language-understanding program worked by translating an English statement or question into a program in a Lisp dialect called MICRO-PLANNER and executing it.

Programs that manipulate programs, for example to simplify them or prove them correct are naturally written in Lisp.

I used program generation in a program to comprehend visual scenes, where it had to deal with all the symmetries capable in 3-dimensional objects, without multiplying the code.

Anything having to do with logic and theorem-proving deals in manipulating logical expressions, which are a form of program.

Symbolic math, such as symbolic integral or differential calculus, involves manipulating math expressions, which are like miniature programs.

Any problem involving code generation, or the more highbrow term "partial evaluation", is natural in Lisp. I did this for a database bridge program a long time ago. I did it in C, which was not as easy as Lisp, but I got the idea from Lisp. That was regarded as a technique that almost nobody could do at that time (especially the COBOL-heads). Maybe more now, I hope.

... that's just a few ...

Then you realize some things that are considered "modern" today have been old-hat in Lisp for 40-some years.
Like functional programming.
Like garbage collection.
Like closures.

That's not to say modern languages don't have new good ideas, like OOP, etc.
But if you learn Lisp it will broaden your perspective.


答:
Yes, many people think of software construction as in building construction. The DB is the "foundation" the DAL sits on top of it, the Business Layer Sits on the DAL, the UI sits on the Business Layer...

Instead think of it as a hanging mobile. Where the "layers" hang from a common anchor. UI and Business Layer both hang from the Business Interface, Business Layer and DAL both hang from the DAL interface, DAL and Database connect through the DB Interface.

Title: Dependency Inversion Principle: Understanding how both low level components and high level components depend on abstractions

Body:
I'm learning about the Dependency Inversion Principle. It states that:

High level modules should not depend upon low-level modules. Both
  should depend upon abstractions.

For a while I tried to understand what it means that both the high level components and the low level components, rely on the abstractions and are dependent on them.

I'm assuming both should depend on the same abstraction in some way. Please correct me if this is wrong.

I have come to some conclusion about what this means. Please confirm if this is accurate.

"The high level components are dependent on the abstraction" - Meaning:

The high level components talk to an interface to communicate with the low level components, instead of communicating with concrete low level components directly. The low level components implement this interface.

"The low level components are dependent on the abstraction" - Meaning:

The low level components are defined and designed in the terms of the interface. They are designed to fit the interface. They are dependent on the interface, in the way that the interface defines how they are designed. (Often low level classes implement that interface).

This way, both the high level components and the low level ones are 'dependent on the abstraction', but in different ways.

Is this a good understanding?


问:
Which Computer Vision / Image Processing technique would solve light imbalance in images?
Given a colour image whose light intensity is dim at the edges and bright in the middle, such as [dim    bright    dim], which computer vision technique would be recommended to correct this imbalance?

While I believe Histogram Equalisation could help, I've read that it also introduces an unrealistic look to an image by exaggerating the blue channel.

I consider implementing an image processor for this task.

答:
One classic approach is using top hat filtering for leveling uneven illumination. You should perform morphological opening with a large structuring element, then remove the result from the original image.

If you have dark objects on light background you should do bottom hat filtering (dual of top hat filtering): subtract the closing with a large structuring element from the original image.


问:
Practical programming according to the Dependency Inversion Principle
What the Dependency Inversion Priciple implies in practice is that in a system, high level components should depend on abstractions of the low level components (instead of on the low level components directly), and the low level components should be defined in terms of these abstractions.

The key point for my question is that the low level components are defined in terms of the abstractions, which is defined in terms of the high level components. Meaning: the high level components 'define the abstraction' in terms of what would be convenient for them, and the low level components have to be defined according to that abstraction (usually an interface).

So if the high level component is a Car, and the low level component is the Engine, and an interface IEngine is defined - it will be defined according to the needs of the Car, and Engine will have to fit these needs. So if it's convenient for the Car to be able to simply start the engine, IEngine would feature a method start() and Engine would have to implement it.

My question is:

When starting programming on a project designed according to the Dependency Inversion Principle - are the high level components usually implemented before the low level ones, ie. "top to bottom" development?

Since the principle implies that the low level components are designed according to what is convenient for the high level components, it makes sense to first start programming the high level components, and only then define the ILowLevelComponent interface, based on what we learned the high level components need when we programmed them.

For example we're implementing a system that simulates a car. Car is the high level component, while Engine and SteeringWheel are the low level components. Engine and SteeringWheel take care of the concrete work of moving the car around, while Car takes care of coordinating everything and creating a functioning system.

If we were designing the system according to DIP, that means that Engine and SteeringWheel are defined in terms of an abstraction, that is defined in terms of what is convenient for Car.

So it would make sense to first implement Car, understand exactly how it's going to work in high level terms and what it needs to work, and only then define the IEngine and ISteeringWheel interfaces, according to what the Car needs. And then ofcourse implement the concrete classes that implement the interfaces.

So what I'm asking is: when working on a project that is designed in the spirit of DIP, is the "top to bottom development" approach common? Is this how work is usually done on project following the Dependency Inversion Principle?

答:
It's usually not written in stone:

Sometimes it can be done so. Higher level component needs something, then interface is designed, then a mockup object implementes it so developing of a higher level component doesn't have to wait.

Sometimes developing can be done both ways and meet in the middle.

Interfaces are not always defined by what the higher component "needs", for example a LightSource interface will not have a getPriceInDollars method even when the higher level component seems to need it. Maybe another interface will have that getprice method and some implementor will implement both interfaces.

Sometimes existing components and interfaces are reused in a new project.

Sometimes existing classes, from previous projects, can me made to implement new interfaces to be compliant with the new architecture without changing behavior or breaking previous contracts, maybe with the use of structural design patterns (Adapter, Composite, Decorator, etc.)

Sometimes  the higher level component simply adapts to whatever interface (abstract class or interface ) the lower level component has, like when when you use 3rd party library. The designer of the library ( say a library for creating charts ) thought of a very generic consumer. And that doesn't make such a library less usefull. NOTE: It's still DIP because you are programming to abstractions even though a 3rd party designed said abstractions.

In OOD and OOP, higher level components are not always written first and low level components are not always written last. DIP has the added advantage of you not having to develop strictlly in a top-down or bottom-up fashion.

Lower level components tend to amalgatate into APIs or libraries which are transversal to projects.


问:
Are random number generators security holes?
If I retrieve a random number from a database (e.g. RAND() in SQL Server) or using a programming language and send this in some form back to a client machine, is there an economic chance I will be sending an indicator of what's in my server's memory that might form a security problem (like revealing my schema, etc)?</p>

答:
The only part of memory used is a designated buffer which is used only for the number generation.

The real risk of RNG is predictability, for key generation you need random data, if it isn't random an attacker can guess the key and break your encrypted data.


问:
What, in reference to DDD, is a bounded context?
When working through the book "Implementing Domain Driven Design" by Vaughn Vernon, I have been unable to gain a good grasp on what a bounded context actually is.

The book defines a bounded context as "a conceptual boundary where a domain model is applicable. It provides Ubiquitous Language that is spoken by the team and expressed in its carefully designed software model" (the "Guide to this Book" prefacing section). This definition would make it sound as though a bounded context is the model and language of a subdomain, where that subdomain may happen to be the core domain (which seems like it ought to be referred to as a "core subdomain", but that is another discussion...). This still leaves some ambiguity as to what a bounded context provides. Is it a grouping of one or more subdomains? If only one subdomain corresponds to a bounded context, what is the bounded context actually telling us?

Chapter 3 of the same book, however, refers to the integration techniques between bounded contexts. This, however, would seem to imply that the bounded contexts are actually software systems or artefacts of some variety.

Martin Fowler briefly discusses the idea of a bounded context (http://martinfowler.com/bliki/BoundedContext.html), but does not really clarify the issue.

At the end of the day, what is a bounded context? Is it a grouping of subdomains? The model and language for a subdomain? The implementation of a subdomain? Without these answers, it seems rather difficult to understand how to decompose a real-life problem space into bounded contexts.

答:
Domain Driven Design techniques are used to help us make models of the world that we live in. These models exist as ideas in the minds of the people involved in a project.

Because telepathy is still in its infancy, these ideas are communicated between people using words and phrases.

Words and phrases can be ambiguous at the best of times. To help us reduce ambiguity, we use 'context' to clarify their meaning.

When people get deeply immersed in a software project that spans years, they seem to forget the context from which came the ideas that turned into the words which turned into the variable names that were baked into the code.

Newbies arrive to the project and start using and consuming its language. Perhaps they are users, perhaps they are developers. If there is no context provided to them, they will come up with their own context (and, therefore, meaning) from their own life experience.

This newly applied context will guide how new developers refactor or develop the code. If they applied the wrong context, they will refactor and develop the code in, perhaps ever-so-slightly, the wrong direction. Wrong directions, however slight, can cause much bigger problems down the line.

As I see it, a 'bounded context' is merely a 'clarified context' that is handed to project newbies so they don't apply their own arbitrary context to taint our, beautifully honed, model.

It is some explicit acknowledgement, by the team, that this phrase, in this part of the project means exactly this thing (and not, as you might well think, that thing).

Just as it is a good idea to mark the boundaries between your garden and your neighbour's garden. You specify the boundary explicitly so that you don't get angry when they start digging a flower bed on your perfectly manicured lawn.

That is it. It is a very simple idea which is so important that lots has been written about it.

So yes. A bounded context is quite literally a boundary, a 'fence', that distinguishes between the context of one subdomain from the context of another subdomain in a project.

The model and language of a subdomain are isolated from other model and languages to avoid ambiguities in meaning.

But, yes. The world is not so simple.

You and the team have to be rigorous in adhering to the defined context. It is really easy to be lazy and re-imagine the context to cut corners during software construction.

Also, things interact with other things and bounded contexts need to interact with each other too.  So, there are various patterns to describe how those interactions occur. See Eric Evan's book Domain Driven Design Chapter 14 for these various patterns: Shared Kernel,   Customer Supplier,   Conformist,   Anticorruption Layer,  Separate Ways,   Open Host Service,   Published Language.


答: No, the specific thing that you are concerned about (inspired by Heartbleed?) will not happen. A random number generator does not simply pull bytes from memory (that's not very random). You can assume that the random number generator will not leak private information to clients.</p>

Title: Are random number generators security holes?

Body: If I retrieve a random number from a database (e.g. RAND() in SQL Server) or using a programming language and send this in some form back to a client machine, is there an economic chance I will be sending an indicator of what's in my server's memory that might form a security problem (like revealing my schema, etc)?</p>


问:
Persist AJAX values
I have a simulator that pulls data from a DB - calculates and return JSON result to an ajax call that renders a table for the results.

The calculation procedure are as follow:

grab X number of data that are group together and have weights to
them.

use historical data and run a weight distribution algorithm on the
group.

return as a JSON the metrics of each data, the old value, and the
calculated new value

2 Questions:

1) Is Javascript calculation better or worse (or equal) to PHP calculation in order to yield the results.

2) IF Javascript calculation is faster or on par to PHP then I would assume the trip to call ajax is a small bottleneck. So one possibility would be to pre-load data and have it calculated on the fly. Now how would you persist that pre-loading efficiently? Would that just simply load everything in a simple var via ajax?

Thus far it takes approx 55 seconds for the result to return 2000 entries on 14 days worth of data.

答:
You are correct you need to optimize your code somehow.

However, the first rule of code optimization is to

Measure, don't guess.

There very likely are performance differences between Javascript on a desktop and PHP on a server, but those differences aren't big enough to solve your problem.

If you are using Chrome as your browser, press F12 and pay attention to the Network section.  It also helps to heavily use  debugger;, console.time('foo'); and console.timeEnd('foo'); in your javascript code.

Your first question should be to determine if the server is slow in getting the data to the client or if the client is slow in displaying the data.

You can't optimize code until you know for sure which code needs optimizing.

Title: Persist AJAX values


问:
Interface method signature not restrictive enough
I wrote a piece of code at my job sometime ago. While writting the code I wrote few interfaces who would allow me to add more flexibility and at that time I was also trying to understand OOP concept more deeper. So in the interface I wrote I have a method signature similar to this :

```<code>void Add(ImyBase objToAdd)
</code>```

And then I have few class implementing this interface. But what is bothering me is that I find myself doing this kind of thing pretty often in this Add method

```<code>public void Add(ImyBase objToAdd)
{
    if(!(objToAdd is ImyBaseDeviation))
        throw new ArgumentException("blablabla");

    //do stuff
}
</code>```

At the time it was a smell to me but I didn't really bothered with it simply because I'm solo on this projet and this piece of code is only used within my compagny and there only 2 IT guys in there (me + some one else) and this is not near to change. Anyway I recently came back to that piece of code and from my previous reading (actually more than that but this one is pretty similar) it now actually really look bad to me and I'm trying to figure out the best way to improve this piece of code.

I don't like the code as it stand now because the interface allow more than the concrete type generally allow so basically the concret implementation doesn't respect the contract given by the interface.

I tough of a few solutions

First simply delete the Add method from the interface since anyway calling Add have a high chance to throw an exception. So to call Add you need the concret type anyway. So here the object would still have a Add method but with the accepted type as a parameter.

Secondly add a method who would look something like this in the interface

```<code>bool IsValidToAdd(ImyBase objToTest)
</code>```

But that doesn't satisfy me.

So I'm seeking advise from more advance people like you to help me to figure out what would be the best way to implement this so it stay the cleanest possible.

Sorry I'm not a native anglophone so if my question need editing or grammar fixing please go ahead. Thank you

答:
It's not an easy question to answer without some examples, but I see three ways you can go, depending on the actual in-use scenarios.

Get rid of ImyBase.  You might replace specific (or all) uses with ImyBaseDeviation, and strip it out of anywhere it wasn't used.
Do this if: there's nothing that uses ImyBase which doesn't also require something in ImyBaseDeviation (like a second, different implementation of ImyBase, such as IAnimal -> ICat and IDog).

Pull things from ImyBaseDeviation back into ImyBase.  You'll want to pull enough functionality up that everything clearly should require one or the other.  Remember, you can use the less-specific interface anywhere you're expecting the more-specific one.
Do this if: the two interfaces actually mean different things (such as IAnimal -> IHerbivore).

Do #2, but "shadow" the base interface's methods in the specific one.  This happens a lot with generics.  There might be a IFoo interface:

```<code>interface IFoo
{
  object GetValue();
}

interface IFoo<T> : IFoo
{
  new T GetValue();
}
</code>```

This is how IEnumerable<T> handles it, for example.

Do this if: the two are very closely related, but one uses a more specific type than the other.

Hopefully this points you in the right direction, at least.

Body:
It's not an easy question to answer without some examples, but I see three ways you can go, depending on the actual in-use scenarios.

Get rid of ImyBase.  You might replace specific (or all) uses with ImyBaseDeviation, and strip it out of anywhere it wasn't used.
Do this if: there's nothing that uses ImyBase which doesn't also require something in ImyBaseDeviation (like a second, different implementation of ImyBase, such as IAnimal -> ICat and IDog).

Pull things from ImyBaseDeviation back into ImyBase.  You'll want to pull enough functionality up that everything clearly should require one or the other.  Remember, you can use the less-specific interface anywhere you're expecting the more-specific one.
Do this if: the two interfaces actually mean different things (such as IAnimal -> IHerbivore).

Do #2, but "shadow" the base interface's methods in the specific one.  This happens a lot with generics.  There might be a IFoo interface:

interface IFoo
{
  object GetValue();
}

interface IFoo<T> : IFoo
{
  new T GetValue();
}

This is how IEnumerable<T> handles it, for example.

Do this if: the two are very closely related, but one uses a more specific type than the other.

Hopefully this points you in the right direction, at least.


问:
To Repository Or Not To Repository
When I first learnt about Domain Driven Design, I was also introduced to the repository and unit of work patterns that once seemed to be top notch for the cool kids that threw SQL queries like cavemans against databases. The deeper I got into that topic, the more I learnt that they don't seem to be necessary anymore because of ORMs like EF and NHibernate that implement both unit of work and repositories into one API, called session or context.

Now I'm unsure what to do. To repository or not to repository. I really understand the argument that such leaky abstractions only over-complicate things while adding absolutely nothing that may simplify data access, however, it doesn't feel right to couple every possible aspect of my application to e.g. Entity Framework. Usually, I follow a few simple guidelines:

The domain layer is the heart of the system, containing entities, services, repositories...

The infrastructure layer provides implementations of domain interfaces of a infrastructural concern, e.g. file, database, protocols..

The application layer hosts a composition root that wire things up and orchestrates everything.

My solutions usually look like this:

```<code>Domain.Module1
Domain.Module2
    IModule2Repo
    IModule2Service
    Module2
Infrastructure.Persistence
    Repositories
        EntityFrameworkRepositoryBase
MyApp
    Boostrapper
        -> inject EntityFrameworkRepositoryBase into IRepository etc.
</code>```

I keep my domain layer clean by using a IRepository<'T> which is also a domain concern not depending on anything else that tells me how to access data. When I now would make a concrete implementation of IModule2Service that requires data access, I would have to inject DbContext and by this, coupling it directly to the infrastructure layer.
(Coming to Visual Studio project, this can end up really tricky because of circular dependencies!)

Additionally What can be an alternative to depositories and fucktons of works? CQRS? How does one abstract a pure infrastructural framework?

答:
Engineering is all about compromises. And so is software development. Right now, I believe only other option, that would be simpler, is to work directly with ORM. But like you said, that might lock you into specific persistence framework.

So you have to ask yourself "Is the additional complexity worth the decoupling of your code from persistence". Every time I hear people say they want to decouple their code from persistence I ask "How many times in your career did you change your persistence framework?"

The problems I see with repositories is that they make common changes harder. Eg. adding new way to query an aggregate. And they make uncommon changes (supposedly) easier. Eg. changing implementation of repositories.

Then there is also the unit-testing argument, to which I say "If persistence framework doesn't allow you to mock a database, either in memory or locally, then it is not worth using the framework at all."

Title: To Repository Or Not To Repository


问:
Should we use any JS framework which makes HTML as scripting language
After studying HTML 5, I learnt that HTML is purely for defining semantics of data. And it has provided various tag for each purpose. Although we can create our own tags, can provide styling and it will work still we use standard tags because they are known at global level. And all search engines can understand them.

JS frameworks like AngularJS provide the way of creating own directive/tags. Which are non-standard tags.

Moreover, I believe that programming logic should be kept apart from HTML :ng-if, ng-repeat etc. It makes HTML page very difficult to understand by a pure UI designer. I would say these frameworks make a HTML page developer friendly not designer friendly.

If we put all the logic on a HTML page, there would not be any difference between a server side page & a HTML page.

I believe there should not be any non-standard tag and no programming logic (like conditional or looping statements) presents on HTML page. Instead JS should handle/control HTML from outside.

Please tell me if I am incorrect somewhere. Or give me some positives views So I can think about using such frameworks.

答:
Logic is often present in HTML templates on the client side because it makes sense to have it there. The logic contained within is not business logic, but simple conditionals and loops for controlling the output HTML, usually based on the data in question. There are couple of benefits to this.

First, including this logic in the view groups the structure of (part of) the page with logic which may augment it, creating a single point of change for the creation of the HTML output.

Secondly, including logic in the view makes the template generation easier to comprehend, as the generation logic is shown inline with the structure it is inserting elements in to. Take the following for example of structure and logic combined and compare it with the subsequent separated version. I think most developers would find the former much easier to comprehend.

In reference to the OPs point about the templates becoming difficult to understand for a "pure UI designer", I think the syntax of the average templating system is sufficiently English-like and readable that the average designer will be comfortable in at least reading the code and understanding it, if not modifying it. It's certainly more friendly for a designer than having separate code in a turing complete language they would need to maintain to update the templates.

Inline

```<code><div id="myPagePart">
    <table>
        <thead>
            <tr><td>Header</td></tr>
        </thead>
        <tbody>
            {{ foreach item in collection }}
                <tr><td>{{item.name}}</td></tr>
            {{ endforeach}}
        </tbody>
</div>
</code>```

Separated

```<code><div id="myPagePart">
    <table>
        <thead>
            <tr><td>Header</td></tr>
        </thead>
        <tbody id="tablePart></tbody>
    </table>
</div>

var tableBody = document.getElementById("tablePart");
for(var i = 0; i <= data.length-1; i++){
    var item = data[i];
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    td.innerText = item.name;
    tr.appendChild(td);
    tableBody.appendChild(tr);
}
</code>```

Body:
Logic is often present in HTML templates on the client side because it makes sense to have it there. The logic contained within is not business logic, but simple conditionals and loops for controlling the output HTML, usually based on the data in question. There are couple of benefits to this.

First, including this logic in the view groups the structure of (part of) the page with logic which may augment it, creating a single point of change for the creation of the HTML output.

Secondly, including logic in the view makes the template generation easier to comprehend, as the generation logic is shown inline with the structure it is inserting elements in to. Take the following for example of structure and logic combined and compare it with the subsequent separated version. I think most developers would find the former much easier to comprehend.

In reference to the OPs point about the templates becoming difficult to understand for a "pure UI designer", I think the syntax of the average templating system is sufficiently English-like and readable that the average designer will be comfortable in at least reading the code and understanding it, if not modifying it. It's certainly more friendly for a designer than having separate code in a turing complete language they would need to maintain to update the templates.

Inline

<div id="myPagePart">
    <table>
        <thead>
            <tr><td>Header</td></tr>
        </thead>
        <tbody>
            {{ foreach item in collection }}
                <tr><td>{{item.name}}</td></tr>
            {{ endforeach}}
        </tbody>
</div>

Separated

<div id="myPagePart">
    <table>
        <thead>
            <tr><td>Header</td></tr>
        </thead>
        <tbody id="tablePart></tbody>
    </table>
</div>

var tableBody = document.getElementById("tablePart");
for(var i = 0; i <= data.length-1; i++){
    var item = data[i];
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    td.innerText = item.name;
    tr.appendChild(td);
    tableBody.appendChild(tr);
}


问:
Model Driven Architecture Approach in programming / modelling
I know the basics of the model driven architecture: it is all about model the system which I want to create and create the core code afterwards. I used CORBA a while ago. First thing that I needed to do was to create an abstract interface (some kind of model of the system I want to build) and generate core code later.

But I have a different question: is model driven architecture a broad approach or not? I mean, let's say, that I have the language (modelling language) in which I want to model EXISTING system (opposite to the system I want to CREATE), and then analyze the model of the created system and different facts about that modeled abstraction.

In this case, can the process I described above be considered the model driven architecture approach? I mean, I have the model, but this is the model of the existing system, not the system to be created.

答:
My own limited experiences of attempting to use modeling on existing code have not been very satisfying. I pointed one "reverse engineering" tool at a fairly trivial Android program written in Java and the result was an incomprehensible mess of UML class boxes and relationships.

My guess is that MDA might be helpful if you were assigned to rework some legacy code...say taking some sort of monolithic UNIX app and restructuring it so that some portions ran in the cloud, some on iOS, and some on Android. You could model the pieces (at a fairly high level!) model the interactions between the pieces, and create wrappers for chunks of legacy code that you would put inside some of the wrappers..(?) Other pieces (iOS for example) might need to be totally re-implemented.

However, whether this approach would actually work well in practice or not would depend heavily on the specifics of the task at hand.


问:
How do I find average bits per symbol using huffman code?
I'm trying to write a program in c for Huffman coding, but I am stuck. For input I have:

```<code>Sample input:
4      // here I scan how many letters I have
A 00   // and for everyone I scan how they are coded in string down
B 10
C 01
D 11
001010010101001011010101010110011000 //this is a suboptimal huffman code
</code>```

So first I have to decode this string, and to find out how many times every letter         appear. And I already do that. But now I have to find out how many bits have every letter using huffman tree, and in the output I have to print the average bit per symbol.

The output for this example here have to be:

```<code>Sample output
1.722
</code>```

So now, how to find out how many bits have every letter with huffman coding?

答:
To solve this you need to create the huffman tree and compute the bits needed to represent every symbol. Then you can compute total bits needed for original string in huffman encoding and divide by number of characters.

First you map your input string based on the original character encoding :

```<code>00 A
10 B
10 B
01 C
01 C
01 C
00 A
10 B
11 D
01 C
01 C
01 C
01 C
01 C
10 B
01 C
10 B
00 A
</code>```

Next you count number of occurrence of each character:

```<code>3 00,A
9 01,C
5 10,B
1 11,D
</code>```

Now we make a min priority queue using the occurrence as key, this looks like :

```<code>[(1,D), (3,A), (5, B), (9,C)]
</code>```

Keep applying the huffman process ( http://en.wikipedia.org/wiki/Huffman_coding ). So first you combine D and A to make a new node 'DA' which key = 1+3 = 4. Put this back in the priority queue:

```<code>[(4, DA), (5, B), (9,C)]
</code>```

Now DA and B combine to give DAB:

```<code>[(9, DAB), (9,C)]
</code>```

Now DAB and C combine to give root node : 'DABC'

```<code>[(18, DABC)]
</code>```

Now the process stops and we give each character a new encoding based on how far it is away from the root node. 'C' was combined the last so that get's only one bit. Let's say I always use '0' for the second element ( of the two that got picked from priority queue). The implicit bits are represented in parenthesis:

```<code>C =      0, DAB =      1
B = (1)  0, DA  = (1)  1
A = (11) 0, D   = (11) 1
</code>```

So you get the encoding:

```<code>C = 0
B = 10
A = 110
D = 111
</code>```

Encoding original message:

```<code>Total bits needed = 9 * 1 + 5 * 2 + 3 * 3 + 3 * 1
= 9 + 10 + 9 + 3
= 31

Number of Characters = 18

Average bits = 31 / 18 = 1.722222
</code>```

Body:
To solve this you need to create the huffman tree and compute the bits needed to represent every symbol. Then you can compute total bits needed for original string in huffman encoding and divide by number of characters.

First you map your input string based on the original character encoding :

00 A
10 B
10 B
01 C
01 C
01 C
00 A
10 B
11 D
01 C
01 C
01 C
01 C
01 C
10 B
01 C
10 B
00 A

Next you count number of occurrence of each character:

3 00,A
9 01,C
5 10,B
1 11,D

Now we make a min priority queue using the occurrence as key, this looks like :

[(1,D), (3,A), (5, B), (9,C)]

Keep applying the huffman process ( http://en.wikipedia.org/wiki/Huffman_coding ). So first you combine D and A to make a new node 'DA' which key = 1+3 = 4. Put this back in the priority queue:

[(4, DA), (5, B), (9,C)]

Now DA and B combine to give DAB:

[(9, DAB), (9,C)]

Now DAB and C combine to give root node : 'DABC'

[(18, DABC)]

Now the process stops and we give each character a new encoding based on how far it is away from the root node. 'C' was combined the last so that get's only one bit. Let's say I always use '0' for the second element ( of the two that got picked from priority queue). The implicit bits are represented in parenthesis:

C =      0, DAB =      1
B = (1)  0, DA  = (1)  1
A = (11) 0, D   = (11) 1

So you get the encoding:

C = 0
B = 10
A = 110
D = 111

Encoding original message:

Total bits needed = 9 * 1 + 5 * 2 + 3 * 3 + 3 * 1
= 9 + 10 + 9 + 3
= 31

Number of Characters = 18

Average bits = 31 / 18 = 1.722222


问:
What does the author of Code Complete mean when talking about hiding global data?
In section 6.4 of Code Complete 2nd Edition there is a paragraph about hiding global data. What I am particularly interested in, is that McConnell (the author of the book) gives examples of the benefits of hiding global data. There is one example that I cannot understand. I don't have the English version of the book, so I'll try to translate the text.

Hiding global data. (...) You can change the structure of the data without modifying the program.

What does McConnell mean by that? Is he talking about changing global data? If so, why wouldn't you have to modify your program when you are using methods to retreive that data? Or maybe he is referring to something else here?

I would greatly appreciate if someone could clear up my confusion. If you could also provide an example, it would be great (examples are awesome, you know).

答:
The author is talking about the structure of the global data, and how changing that structure would impact the code that uses it.

If the global data is accessible directly, then changing the data structure implies potentially having to change all the code that uses it.

If the global data is only accessible via an interface (e.g. a set of functions), then changing the structure implies only changing these accessors. The rest of the code doesn't have to change.

As simple example would be code that starts out with an array of integers (a static int[] in some Java class for instance). If that array is globally accessible, then people will start using it with array syntax (i.e. Global.cool_stuff[x] = 1;). If for some reason you want to change that array to a collection type (vector, list, whatever), then you have to change all the code that uses this piece of global data since it has become, at least syntactically, invalid.

If that data had only been accessible via a set of accessor/mutator functions ("hidden behind" an interface), then you would only need to change that small set of functions. The code that actually uses the data can remain unchanged.


问:
Difference between "String" and "string" in .NET and which is best?
In the .NET Framework, at least in the C# language, we have two "versions" of the string type:

"string"

"String"

It appears that they are interchangeable, but are they really?  If they are not interchangeable, is it generally better to use one instead of the other, and under what circumstances?

答:
String is used with namespace System.String, string is used C# compiler specification, moreover System.String is reference type value. You are preferred to deal with System objects, string for literals purposes only. System and system both working is same.

```<code>string TC = new System.String('/', 5);
</code>```

String is used for comparing, equal and other purposes as well.

Body:
String is used with namespace System.String, string is used C# compiler specification, moreover System.String is reference type value. You are preferred to deal with System objects, string for literals purposes only. System and system both working is same.

string TC = new System.String('/', 5);

String is used for comparing, equal and other purposes as well.


问:
Naming test methods in Java
Over at codereview a comment hinted that using snake_case to name test methods is a good idea.

This contradicted my views and I did some research and there seem to be a lot of examples that actually use snake_case for this.

Myself, I use classic camelCase names like testXyz for unit tests or a BDD approach givenXyzWhenXyzThenXyz for integration tests.

There also is a third option that combines both ways, e.g. useCase_WhenSomething_ThenAssertion.

My question is: What are good arguments for either using snake_case or camelCase to name test methods?

I'd like to start this with a few arguments from my experience and work:

In Favor of camelCase

It follows the general Java coding conventions of using camelCase.

It is consistent with production code.

I personally find camelCase no harder to read than snake_case – I'm used to descriptive names from production code anyway.

IDE support suffers when using snake_case (at least Eclipse).

In Favor of snake_case

Some frameworks can generate reports from tests and using snake_case allows such frameworks to create correct sentences from the test names.

In Favor of a combination of both

?

What are other arguments? How does maybe the pattern in which the test methods are named affect the arguments?

Little disclaimer: Of course, ultimatively it comes down to team conventions. However, it might be worth discussing pros and cons for certain conventions.

答:
I'll drop a few cents since it's my comment being referred to.

I, also, got this naming approach from Roy Osherove and I particularly like it. Following a methodname that is built in this manner we can have something like this:

```<code>createUser_WithNonExistingEmail_ShouldThrowArgumentException
</code>```

In standard camelCasing this becomes

```<code>createUserWithNonExistingEmailShouldThrowArgumentException
</code>```

It's not unreadable, but it is a lot harder to read. The reason these explicit underscores are added is because the method names are per definition a lot longer if you make them as descriptive as suggested by Osherove.

A unit test's methodname has to combine several aspects. It should contain

The unit under test

The scenario that's being tested

The expected return value

A non-unit test's methodname has to contain

The main action performed by that method

This summary alone should indicate that this is a special kind of method. I feel like we can divert from the path of the conventions because the intention behind method names in this scenario is different from traditional methods (which were kept in mind when the conventions were made).

Unit tests are different from traditional methods in a few other ways as well: they will never get called by you explicitly and so they should just be as readable and descriptive as possible for your test results.

Title: Naming test methods in Java

Body:
I'll drop a few cents since it's my comment being referred to.

I, also, got this naming approach from Roy Osherove and I particularly like it. Following a methodname that is built in this manner we can have something like this:

createUser_WithNonExistingEmail_ShouldThrowArgumentException

In standard camelCasing this becomes

createUserWithNonExistingEmailShouldThrowArgumentException

It's not unreadable, but it is a lot harder to read. The reason these explicit underscores are added is because the method names are per definition a lot longer if you make them as descriptive as suggested by Osherove.

A unit test's methodname has to combine several aspects. It should contain

The unit under test

The scenario that's being tested

The expected return value

A non-unit test's methodname has to contain

The main action performed by that method

This summary alone should indicate that this is a special kind of method. I feel like we can divert from the path of the conventions because the intention behind method names in this scenario is different from traditional methods (which were kept in mind when the conventions were made).

Unit tests are different from traditional methods in a few other ways as well: they will never get called by you explicitly and so they should just be as readable and descriptive as possible for your test results.