问:
Tracing and Logging per item instead of per application
I'm building a service in .NET that process "things" in the background and I'd like to trace the execution of these things per item, not per application.

Most logging frameworks (I'm familiar with System.Diagnostics.TraceSource and NLog) work in a way that you generate messages for everything and decide in a configuration file what and where to store using filters.

But in this case, I may be processing tens of thousands of items at any given time, and I just need to log information for one of them. The amount of log information I generate per item is huge, and it is not just a string with some parameters, so I'd rather avoid unnecessary processing and IO.

I'm already using NLog for application exceptions and things like that, so for this specific use I don't require log levels (info, errors, warnings, exceptions). All entries are "information entries" like what data is being generated or which decision was taken by the steps, so we can analyze what is going on for specific items in production.

One last note is that this information will not be stored on a file, but will be buffered in memory and sent via web sockets to a listening service. If the connection is not up, we just throw away the data.

I already have some flags per item I process in a context object, like:

```<code>interface IItemContext {
    Guid ItemID { get; }
    bool StepXLoggingEnabled { get; }
    bool StepYLoggingEnabled { get; }
    bool StepZLoggingEnabled { get; }
}
</code>```

My current take on this is to have a bunch of extension methods on the Context object that decide if logging should happen and extract the information needed and delegate to another service.

```<code>internal static class ItemContextLogExtensions {
    public static void LogStepX(this IItemContext context, string data1, Foo data2) {
        if (context.StepXLoggingEnabled) {

            // do some work to extract/generate information relevant to my logging
            var entry = new LogEntry {
                Message = "StepX ...",
                Details = ""
            };

            SomeLogService.Current.Log(entry);
        }
    }
}
</code>```

This way I can control when the log needs to be generated and can delegate to NLog during development if needed.

I keep thinking about just using NLog or TraceSource directly in the IItemContext, but while I don't want to reinvent the wheel, I wonder if there is any sense in trying to use them for this at all. It seems to me that in this case, these frameworks it will end up being just a glorified concurrent queue with a lot of methods I don't have use for.

What do you think? Is my take a good solution? Am I missing something? What could be other options to achieve this?

And am I missing some feature from NLog or some other .NET logging library that is specifically geared toward this kind of logging that can be enabled per item instead of per application?

答: This screams out for a Log4Net custom appender.  You could write your own, have it check the active item to determine whether to log or not, and log to a per-item memory buffer.</p>


问:
Handle server-side/client-side when for showing missing information as placeholders
I have a database table which stores Incident details. Each Incident can have an image saved for it. There are some Incidents which will not have an image for it.

I have an API which pulls the image for a given Incident. I have an issue with handling the API in case an Incident doesn't have the image.

What is the best approach to handle this (and why :) )?:

Telling the client in advance which Incident has the image, and which don't. So the client calling the API should only call it when there is an image for the Incident.

Sending a predefined error message as the result.

Sending a generic placeholder like image to the client when an image is not available for the Incident.

答:
I would prefer option 1.

This would involve expanding your current definition of an Incident to contain a hasImage flag so that the client can decide for which Incidents to call the image fetching API (eg, getIncidentImage(...))

Thos covers modelling and API design.

As other people have mentioned, from a UX perspective, you might want to include a placeholder image in the UI when an Incident lack one.  If it were up to me, fetching this placeholder image would be done by invoking a getPlaceholderImage() method in your image API and not the getIncidentImage(...) method.  This is because, in my opinion, the decision to use a placeholder image when an Incident image is missing is a UI concern and, therefore, your image API shouldn't be aware of it.

Also, as I mentioned in my earlier comment, if it's perfectly normal for an Incident to not have an associated image then I recommend not returning an error when calling your getIncidentImage(...) message.  An empty result should be sufficient and is less confusing to the API users.

ContentLicense: CC BY-SA 3.0


问:
PHP package management with/without Composer
I noticed that many (large) PHP applications use Composer for managing the dependencies. I'm currently trying to figure out if I should switch to Composer (at the moment I'm simply keeping my dependencies in a folder called vendor/ - without being able to automatically update them).

I prefer this way because:

I don't rely on 3rd party websites/repositories to get the source code (I find this as being a security concern as well); and, also, what happens if one of the repositories goes down for any reason? I will no longer be able to update/install my application?

I don't need Composer installed (on the local machine/production machine); this is just a minor issue;

It's faster; obviously, the updates can be pushed faster to production if they come from a single source - it's enough to just update my bundle (that contains all vendor packages) and then simply push/pull the changes to/from production;

I'm using many components that are not aware of Composer (standalone libraries, GitHub repositories that are lacking the composer.json file, many JS/CSS assets, even isolated single PHP classes that I prefer to think as 3rd party libraries etc); if I were to use Composer I would have to use a tool like Satis to manage these (and things get more complicated without a real benefit);

I have my application deployed to several domains (around 25) and it's easier to maintain it this way (a single bundle where all changes get [automatically] pushed and later on the bundle itself can be pushed to production);

There are many changes and updates (a few commits each day to the main application package) and I find it easier to simply push these commits to production rather than setting up tags for each commit so that Composer can see the difference and update to the new version;

On the other hand, there are some problems with my approach:

First of all, I'm including all the vendor packages in my codebase/build; I know this is not a good practice and I understand the arguments behind this (I'd prefer to avoid this);

It may be a good thing that I'm able to trace all source code changes to my application in a single repository (I use git). Obviously, all vendor changes will be reflected in the bundle repository. But on the other hand there's some redundancy - I'm also working myself on some of the dependent vendor packages so it doesn't make much sense to COMMIT the changes there and add the relevant message to the COMMIT and then the same changes to be commited on the bundle package, as well;

More bundles: I have a few applications that are extensions of the main application - they provide their own business logic, additional controllers etc; For these I need to create separate bundles that will again contain all the vendor packages - so, whenever a vendor package gets updates I need to propagate these changes to the additional bundles, too;

It's not that straightforward to work in a team: how should the process go? Each member should update the core application package then update the bundle itself? Then the other members will download both the bundle and the core application? Again, I find it somehow redundant;

My approach worked so far, but I think that I might be missing something in this whole developing/deployment process. I'm trying to stay focused on developing rather than managing dependencies/deploying so I'd prefer that the deployment process is as smooth and transparent as possible. Also, with this approach the update on each server takes about 30 seconds, with composer it would take a lot more (as the update in Composer needs to connect to all 3rd party repositories).

So, as a summary:

I think there's a redundancy in my current way of working;

I'd like to know if there are better ways to handle this (simple deployment process to all my 25 domains - about 20 of them are sharing the same codebase; no source code redundancy; team work friendly);

There are many updates to the source code each day so the update/deployment process should not be a hassle;

I really like the modular approach for developing: having an application that *requires* other modules; if I need the same application just slightly modified I add an additional module that changes some of the existing logic and that's it. I'd like to keep it this way without having to build bundles made up of modules and then install the bundle.

Any ideas for improvement?

Edit:
I found two articles related to this topic that are quite interesting: http://www.redotheweb.com/2013/09/12/should-you-commit-dependencies.html and http://addyosmani.com/blog/checking-in-front-end-dependencies/. I believe that what they are mainly saying is that "it depends". So, I assume that, at least for me it would be better to checkin my dependencies.

答:
Most of your issues with Composer can be mitigated:

Host a copy of the dependencies yourself. You can even keep them updated automatically via a scheduled git pull. For a large project and/or a corporate environment this is a good step.

Use a build system or continuous integration server which creates a production ready bundle you can upload in one fell swoop. This can be as simple as a single shell script. If you're using a proper deploy system (as opposed to manual FTP uploads), this should be trivial to hook up.

These two things should alleviate most of your concerns. You didn't indicate whether you're already using a deployment system; if not this may actually be your biggest problem. In an automated deployment your build step can be as complex as necessary, if it can all be scripted it doesn't really matter.

Regarding:

I'm using many components that are not aware of Composer; if I were to use Composer I would have to use a tool like Satis to manage these.

You are aware that you can simply write an inline definition of the missing composer.json file inside your own composer.json? For most situations this allows you to retrofit Composer support without problems.

There are many changes and updates and I find it easier to simply push these commits to production rather than setting up tags for each commit so that Composer can see the difference and update to the new version

It is not necessary to create individual tags. You can use git commit numbers just as well.

Composer is helpful just for the dependency resolution alone. More and more packages are becoming more and more complex, tracking down dependencies manually can be quite a chore. Not to mention the occasional version conflict, which is hard to catch manually and usually only manifests as obscure bugs at runtime if you don't use a dependency manager.

Getting a proper development, dependency management, build, test, deploy workflow set up is one of those things that may take a while upfront, but saves you countless hours in the long run on sufficiently complex projects.


答:
I would use option

Change the API so every request for an image returns the image + a status information. If there is no image, you return a 0 byte stream for the image and a status like "no image available".

So the user of the API needs only one roundtrip to retrieve the full information, the operation is atomic, you don't return an error for a valid operation, and you don't waste bandwidth by sending the same image placeholders over the line over and over again.

If the user of the API wants to display a (fixed) placeholder, he is free to do this, but that should be decoupled from the API itself.

Title: Handle server-side/client-side when for showing missing information as placeholders

Body:
I have a database table which stores Incident details. Each Incident can have an image saved for it. There are some Incidents which will not have an image for it.

I have an API which pulls the image for a given Incident. I have an issue with handling the API in case an Incident doesn't have the image.

What is the best approach to handle this (and why :) )?:

Telling the client in advance which Incident has the image, and which don't. So the client calling the API should only call it when there is an image for the Incident.

Sending a predefined error message as the result.

Sending a generic placeholder like image to the client when an image is not available for the Incident.


问:
Interface inherits from interface without specifying new member
Is it some kind of bad design to have something like this:

```<code>public interface IFooStream
{
    long Length { get; }
    long Position {get; set;}
    //...
}

public interface IReadableFooStream<T> : IFooStream
{
    int Read(T[] buffer, int offset, int count);
}

public interface IByteStream : IReadableFooStream<byte>
{
}

public interface IFloatStream : IReadableFooStream<float>
{
}
</code>```

How would you solve something like this? I definitely must have the IByteStream and the IFloatStream interface.

答:
The IFooStream just connects both types since both got a length and a
  position,... But actually the IByteStream and the IFloatStream already
  exist as an essential part of the audio lib.

It sounds like the only other types in the lib that depend on IFooStream and IReadableFooStream<T> are IByteStream and IFloatStream. Those last two sound like the interesting ones that the rest of the lib use. If no other types actually depend on IReadableFooStream<T>, and it is there for the sake of inheritance, I agree that it smells.

I really need them to know whether an implementation provides raw data
  or provides samples.

So then, why not prefer composition over inheritance and call them what they are?

```<code>public interface IProvideRawStream
{
    IFooStream Stream { get; }
    int Read(byte[] buffer, int offset, int count);
}

public interface IProvideSampleStream
{
    IFooStream Stream { get; }
    int Read(float[] buffer, int offset, int count);
}
</code>```

... or, if composition doesn't make sense in the API, what is wrong with having inheritance go only 1 level deep?

```<code>public interface IFooStream
{
    long Length { get; }
    long Position {get; set;}
    //...
}

public interface IProvideRawStream : IFooStream
{
    int Read(byte[] buffer, int offset, int count);
}

public interface IProvideSampleStream : IFooStream
{
    int Read(float[] buffer, int offset, int count);
}
</code>```

Body:
The IFooStream just connects both types since both got a length and a
  position,... But actually the IByteStream and the IFloatStream already
  exist as an essential part of the audio lib.

It sounds like the only other types in the lib that depend on IFooStream and IReadableFooStream<T> are IByteStream and IFloatStream. Those last two sound like the interesting ones that the rest of the lib use. If no other types actually depend on IReadableFooStream<T>, and it is there for the sake of inheritance, I agree that it smells.

I really need them to know whether an implementation provides raw data
  or provides samples.

So then, why not prefer composition over inheritance and call them what they are?

public interface IProvideRawStream
{
    IFooStream Stream { get; }
    int Read(byte[] buffer, int offset, int count);
}

public interface IProvideSampleStream
{
    IFooStream Stream { get; }
    int Read(float[] buffer, int offset, int count);
}

... or, if composition doesn't make sense in the API, what is wrong with having inheritance go only 1 level deep?

public interface IFooStream
{
    long Length { get; }
    long Position {get; set;}
    //...
}

public interface IProvideRawStream : IFooStream
{
    int Read(byte[] buffer, int offset, int count);
}

public interface IProvideSampleStream : IFooStream
{
    int Read(float[] buffer, int offset, int count);
}


问:
Query on hiding implementation details in java
With the below piece of thread related code, I see that author of Thread class is hiding the details about the working of start() method. What a user of Thread class need to know is, class Thread would expect a piece of his own code which will be an instance of Runnable's anonymous concrete sub-class that gets passed.

```<code>/* TestThread.java */
public class TestThread{

    public static void main(String[] args){
    Thread threadObject = new Thread(new Runnable(){
        public void run(){
           /* your own code that has to run*/
           System.out.println("a new thread");
        }
    });
    threadObject.start();
    System.out.println("Main thread");
    }
}
</code>```

But in this below program, It looks like we partially hide the implementation details of listFiles(filter) method. Because if author has to change the logic of listFiles(filter) in future without affecting the users, he should make sure that method signature boolean accept(File dir, String name); should not get affected.

```<code>/* ListDirectoryWithFilter.java */

import java.io.File;
import java.io.FilenameFilter;

public class ListDirectoryWithFilter{
    public static void main(String[] args){
        String path = System.getProperty("user.home") + File.separator + "workspace" +
                                            File.separator + "JavaCode" + File.separator + "src";
        File dir = new File(path);

        if(dir.isDirectory()){
            File[] files = dir.listFiles(new FilenameFilter(){
                public boolean accept(File dir, String file){
                    return file.endsWith(".java");
                }
            });
            for(File file : files){
                System.out.println(file.getName());
            }
        }
    }
}
</code>```

Do you think, it would have been better that listFiles(filter) method just expect a regular expression(*.java) from the user and rest is the result that user expects?

It looked a bit unnecessary approach for me, to implement a two argument accept(,) method and then pass it to listFiles() method.

So, Are such implementations a good practice? If yes, when do we think of such implementations?

答:
Yes, it is good practice. It looks a bit boilerplate and weird, because Java 7 and below does not support functional programming very well.

The difference to just a regular expression is, that a regular expression limits you in your options to filter for files. E.g. lets say you want to filter files not by their name only but [just/additionally] by their content or other metadata (in the future). Then, regular expressions are insufficient to do this. Also, they can be quite slow - and a malicious regex might even break the program if you don't use techniques to prevent it from taking a lot of time to execute the regex.

To explain it more general: what is what you want to do? You want to filter files of a directory. That's it. Not more, not less. I can't read anything of regular expressions in this explaination, so they should not be used. A general filter approach should be used which includes to be able to use regex but does not limit it to regex.


答:
This API is less about hiding implementation details and more about deferring to the programmer for the interesting parts of the action.

listFiles() knows how to iterate over the files in a directory and return a subset of the them. Thread knows how to run code in parallel to the code that is currently running. However, from the application's perspective, those are the boring parts. The interesting parts are the decision of if a file should be include and the actual code that is run in parallel. By taking a functional interface (a concept formalized in Java 8), these implementations do exactly what they need to and no more. The programmer calling these methods know exactly how to implement the interesting parts. This style of API gives the programmer the flexibility to do what they want, even if it might be more complex than the most common cases.

Title: Query on hiding implementation details in java

Body:
With the below piece of thread related code, I see that author of Thread class is hiding the details about the working of start() method. What a user of Thread class need to know is, class Thread would expect a piece of his own code which will be an instance of Runnable's anonymous concrete sub-class that gets passed.

```<code>/* TestThread.java */
public class TestThread{

    public static void main(String[] args){
    Thread threadObject = new Thread(new Runnable(){
        public void run(){
           /* your own code that has to run*/
           System.out.println("a new thread");
        }
    });
    threadObject.start();
    System.out.println("Main thread");
    }
}
</code>```

But in this below program, It looks like we partially hide the implementation details of listFiles(filter) method. Because if author has to change the logic of listFiles(filter) in future without affecting the users, he should make sure that method signature boolean accept(File dir, String name); should not get affected.

```<code>/* ListDirectoryWithFilter.java */

import java.io.File;
import java.io.FilenameFilter;

public class ListDirectoryWithFilter{
    public static void main(String[] args){
        String path = System.getProperty("user.home") + File.separator + "workspace" +
                                            File.separator + "JavaCode" + File.separator + "src";
        File dir = new File(path);

        if(dir.isDirectory()){
            File[] files = dir.listFiles(new FilenameFilter(){
                public boolean accept(File dir, String file){
                    return file.endsWith(".java");
                }
            });
            for(File file : files){
                System.out.println(file.getName());
            }
        }
    }
}
</code>```

Do you think, it would have been better that listFiles(filter) method just expect a regular expression(*.java) from the user and rest is the result that user expects?

It looked a bit unnecessary approach for me, to implement a two argument accept(,) method and then pass it to listFiles() method.

So, Are such implementations a good practice? If yes, when do we think of such implementations?


问:
What design pattern for changing interface?
Sorry guys, I should have clarified the fact that the modified method is abstract in Father. Then if the method signature changes, all its implementations in SonX shall also change(at least the signature, though the implementation may stay still).

Now the question should be asked like following:
Say I have the abstract class Father, and three(or more) of his children class Son1, Son2 and Son3. Now I have to change one method, in other words, add an argument to one abstract method of Father. However, I will have to change all the implemented methods(the modified abstract method in Father) in SonX, which costs too much. The change to the signature of the method in SonX is essential cause the clients are interacting with SonX and the clients shall invoke the new version of the method.

So my question is: is there any design pattern suitable for such a situation in which the interfaces will change?

Thanks.

答:
I feel many people implement inheritance too quickly. Using it as a tool to reduce code. This is not the purpose for inheritance. Used like this, you will always have these problems because inheritance is not implemented properly.

On the basics, inheritances spells out a relationship between 2 classes. The relationship is called an "IS A" relationship. In your case, SonX as you describe, is not conforming to this relationship. It is not a Father. Let me explain...

The basic SOLID principles of which in particular I draw your attention to the L part (LSP for Liskov substitution principle). States that any child class should be able to directly replace its parent. If it cannot do this, then it does not conform to proper inheritance.

You find yourself breaking this rule whenever you directly override parent methods in child classes. Parent methods should be overloaded using polymorphism by adding another method of the same name with different parameters, not directly overridden. For example...

Father class has a method Foo. Therefore, by inheriting this class to Son, you are saying that Son IS A Father. Therefore Son should also have method Foo.

If you declare method Foo as virtual in father, so it can be directly overridden in Son, and then override it, then Son no longer conforms to the IS A relationship. As the Foo method in Son does something different than it was originally defined in father.

However, if you overload Foo in the Son class and give it a different signature to allow it to do its job. Then technically, Son can still do all the things Father can do along with a few extras of its own in the overloaded Foo. This is because the original Foo inherited from the Father, is still intact and fully working.

If you really must have a design pattern to decouple abstractions (which is also a good practice in general), there is a design pattern called the bridge pattern and the Visitor Pattern among others (as recommended in the comments by Christopher and Jordao). But I do highly encourage a full working (meaning you have done a few examples of each in actual code so its not a theoretical) understanding of all the SOLID principles first.

I'd also recommend a simpler pattern too. Introduce Parameter Object. It generally applies if you have methods with a lot of parameters (personally I feel more than 3 or 4), where you make a class and pass that around instead.

Don't forget also that you can inherit and extend interfaces and abstract classes and then inherit from those child classes or interfaces. But the bridge pattern is probably better choice due to the decoupling it offers.

Hope this helps.

OwnerDisplayName: qingjinlyc

OwnerDisplayName: FranAsm


问:
How to do "image shifting" faster?
I have a grayscale matrix (implemented as a simple array) to be shown on a display:

```<code>line 1: | a | b | c |
line 2: | d | e | f |
</code>```

a-f are grayscale values. This pattern has to be shifted by a variable percentage to the left or to the right.

What I currently do is an easy approach:

For example, shift 20% to left, so:

```<code>a_new = a * (1 - 0.2) + b * 0.2
b_new = b * (1 - 0.2) + c * 0.2
c_new = c * (1 - 0.2) + 0
</code>```

and so on. That is, I have a loop over all elements.

With only six elements I don't care, but in fact the matrix is much bigger.

Of course, the factor (1 - 0.2) can be reused, but I wonder if there is a smarter way of calculating the resulting (shifted) matrix?

答:
The basic approach would be; for each row:

Load the entire row into "SIMD register 1" (MMX, SSE, AVX, Neon, whatever)

Copy it into "SIMD register 2"

Multiply "SIMD register 2" by 0.2 (pity it's not 25%...)

Subtract "SIMD register 2" from "SIMD register 1"

Shift "SIMD register 2" right by 1 element

Add "SIMD register 2" to "SIMD register 1"

Store "SIMD register 1" in the destination

The basic approach is "basic". In practice you're probably going to have to handle the case where the entire row doesn't fit in a SIMD register. This mostly means that the "shift right" is going to have to involve storing the lowest element (that would've been shifted out) and shifting it in during the next shift as a new highest element.

In any case, it shouldn't be that hard to end up limited by RAM bandwidth for large arrays/matrices (assuming you're also doing sane pre-fetch, and possibly non-temporal stores).

Title: How to do "image shifting" faster?


问:
Why is close() implemented in InputStream/OutputStream?
It make sense to see close() as non-core functionality of stream objects. This is the reason this method is placed in interface Closeable. One evidence is that class ByteArrayInputStream does not require the close() operation.

```<code>public abstract class InputStream implements Closeable {}

public abstract class OutputStream implements Closeable, Flushable {}
</code>```

Based on the above definitions my observation is that interface Closeable should not be implemented by abstract class InputStream/OutputStream; it has to be left to concrete sub-classes (like class FileInputStream) to implement it.

Do you think my understanding is correct?

答:
Just my two cents. The goal of this answer is to give some thoughts and attract more answers, not trying to sound like definitive or even informative.

Why are streams abstract base classes instead of interfaces?

It is possible to define a strictly minimal interface.

Typically this consists of: read, write, seek, tell (returns current file position), get length, truncate (reduce file size), close.

However, to make the stream implementation convenient to use, a lot of helper methods on the class would be needed.

Without these helper methods, it would make the programming language impractical, because it would then be too troublesome to use streams as a fundamental feature of the standard library.

These helper methods make use of the minimal interface.

Typically, default (standard) implementations can be provided for these helper methods, that would completely satisfy the needs most of the time.

Therefore, abstract base classes are used to provide these default helper method implementations to improve the usability of the standard library.

Is the close() method fundamental to the operation of streams?

Contrary to your point of view, I would argue that streams that do not require closing is the minority, rather than majority.

File system handles

Operating-system owned resources, such as:

Sockets

Pipes

Operating-system managed shared memory (as opposed to JVM-managed memory)

Database connections

To put it bluntly,

It appears that array-backed streams are the only kind of streams that do not require explicit closing.

Does the cost-benefit analysis favor the inclusion of the close() method into the stream interface?

It seems so. For streams that do not require explicit closing, it is harmless to require it to provide a trivial close() method that does nothing.

Similar observation can be found in the C# language, where it is common to see interfaces that subtype from  IDisposable.

Would the failure to include the close() method in the stream interface cause extraordinary harm to implementations that require it?

Yes. Not having it on the interface, or splitting it out to a second Closeable interface would cause extraordinary harm.

In the first code snippet below, suppose InputStream does not contain the close() method. Here is what the code would look like:

```<code>public void parseAndCloseStream(InputStream strm) throws IOException
{
    if (strm == null) { /* ... to avoid NPE inside finally */ }
    try
    {
        // read from stream
    }
    finally
    {
        if (strm instanceof Closeable)
        {
            Closeable c = (Closeable)strm;
            c.close();
        }
    }
}
</code>```

In other words, because the omission implies that "not every InputStream is a Closeable", any consumer of any InputStream instance now has the additional responsibility to check whether the instance is indeed Closeable.

The try-with pattern would then also require more code, because you cannot use an InputStream there unless you can cast it into a Closeable.

Is it a violation of Interface Segregation Principle?

No.

If a method is fundamental to the operation for the majority of implementation, it makes sense to require it.

Likewise, if a method is cohesive with the rest of the methods in that interface (i.e. common-sense for its inclusion), it is not a violation.

Specifically, Interface Segregation Principle does not require:

Does not require an interface to be minimal; even though there are benefits for keeping an interface small and simple.

Does not require one to separate out all orthogonal facets of an interface, if doing so will cause more harm than good (great inconvenience).

Body:
Just my two cents. The goal of this answer is to give some thoughts and attract more answers, not trying to sound like definitive or even informative.

Why are streams abstract base classes instead of interfaces?

It is possible to define a strictly minimal interface.

Typically this consists of: read, write, seek, tell (returns current file position), get length, truncate (reduce file size), close.

However, to make the stream implementation convenient to use, a lot of helper methods on the class would be needed.

Without these helper methods, it would make the programming language impractical, because it would then be too troublesome to use streams as a fundamental feature of the standard library.

These helper methods make use of the minimal interface.

Typically, default (standard) implementations can be provided for these helper methods, that would completely satisfy the needs most of the time.

Therefore, abstract base classes are used to provide these default helper method implementations to improve the usability of the standard library.

Is the close() method fundamental to the operation of streams?

Contrary to your point of view, I would argue that streams that do not require closing is the minority, rather than majority.

File system handles

Operating-system owned resources, such as:

Sockets

Pipes

Operating-system managed shared memory (as opposed to JVM-managed memory)

Database connections

To put it bluntly,

It appears that array-backed streams are the only kind of streams that do not require explicit closing.

Does the cost-benefit analysis favor the inclusion of the close() method into the stream interface?

It seems so. For streams that do not require explicit closing, it is harmless to require it to provide a trivial close() method that does nothing.

Similar observation can be found in the C# language, where it is common to see interfaces that subtype from  IDisposable.

Would the failure to include the close() method in the stream interface cause extraordinary harm to implementations that require it?

Yes. Not having it on the interface, or splitting it out to a second Closeable interface would cause extraordinary harm.

In the first code snippet below, suppose InputStream does not contain the close() method. Here is what the code would look like:

public void parseAndCloseStream(InputStream strm) throws IOException
{
    if (strm == null) { /* ... to avoid NPE inside finally */ }
    try
    {
        // read from stream
    }
    finally
    {
        if (strm instanceof Closeable)
        {
            Closeable c = (Closeable)strm;
            c.close();
        }
    }
}

In other words, because the omission implies that "not every InputStream is a Closeable", any consumer of any InputStream instance now has the additional responsibility to check whether the instance is indeed Closeable.

The try-with pattern would then also require more code, because you cannot use an InputStream there unless you can cast it into a Closeable.

Is it a violation of Interface Segregation Principle?

No.

If a method is fundamental to the operation for the majority of implementation, it makes sense to require it.

Likewise, if a method is cohesive with the rest of the methods in that interface (i.e. common-sense for its inclusion), it is not a violation.

Specifically, Interface Segregation Principle does not require:

Does not require an interface to be minimal; even though there are benefits for keeping an interface small and simple.

Does not require one to separate out all orthogonal facets of an interface, if doing so will cause more harm than good (great inconvenience).


问:
Need help identifying a league scheduling algorithm
I am trying to create a sports league scheduler.  I am having trouble identifying an algorithm to help me efficiently fill in each slot.

Sample data to build the schedule would be:

10 teams

Each team plays each other 1 time (45 total games
required)

Each team plays no more than 1 time per day

In my testing I am using 9 days with 5 slots per day.

Combo Table (contains 45 combos)

ID

Team1ID

Team2ID

bitAssigned

Schedule Table (contains 45 time slots)

scheduleID

homeTeamID

awayTeamID

GameDate

GameTime

Right now my existing procedures fill about 90% of the slots leaving 10% of my slots empty to a scheduling conflict based off the rules above.

I loop over my schedule table in ascending date/time order.

My first slot could be Saturday at 8am.

I query a list of teams that haven't been scheduled yet.  I then make an array of possible combinations of those teams.  I then use that array to pull 1 random record from my combinations table from of combinations that haven't been scheduled yet and I place those teams on the schedule.  I then set that combination as used.

I repeat the loop over and over again and each time my list of available teams gets smaller and my array as a result is smaller too.

I'm finding that some days go fine, and on other days my final last 2 remaining teams have already played in a previous week so they are not added to the schedule again.

The only thing I havent tried yet is to "reset" the conflict days and try them over again to see if I get better placements.

Does anyone have any suggestions?

答:
I generated the 10 team single round robin schedule below. It took me about 3 minutes.

Schedule info:

10 teams - 1 round robin (only the first 6 weeks are displayed)

Season start date 1/6/15 - end date 3/5/15

2 games each Tuesday, 3 games each Thursday, 5 games each week
no skip dates

All teams are distributed to play in the 5 time slots equally.

All play 9 games.

All play each other once.

All are distributed evenly as home & visitor (either 5 / 4, or 4 / 5).
Note: at the end of round robin 2 all teams play 18 games (9 as home & 9 as visitor) and
all teams have 2 Byes.

All are distributed to play evenly in the 5 time slots each week.

We used an outdated Honeywell main frame computer and just under 3 years to put this whole thing together. Once our scheduling software was debugged, it took the main frame computer many hours searching millions of permutations & combinations to calculate and create the balanced patterns for 4 to 22 teams that we were looking for.

```<code>10 Team Division Schedule   DATE 12/20/14

DATE   DAY TIME    LOCATION  GM  HOME vs VISITOR

Jan  6 Tue 6:00pm  Field #1   1  # 1 vs #10
Jan  6 Tue 6:00pm  Field #2   1  # 2 vs # 9
Jan  8 Thu 6:30pm  Field #3   1  # 3 vs # 8
Jan  8 Thu 6:30pm  Field #4   1  # 4 vs # 7
Jan  8 Thu 6:30pm  Field #5   1  # 5 vs # 6

Jan 13 Tue 6:00pm  Field #1   2  # 6 vs # 3
Jan 13 Tue 6:00pm  Field #2   2  #10 vs # 8
Jan 15 Thu 6:30pm  Field #3   2  # 7 vs # 2
Jan 15 Thu 6:30pm  Field #4   2  # 9 vs # 1
Jan 15 Thu 6:30pm  Field #5   2  # 4 vs # 5

Jan 20 Tue 6:00pm  Field #1   3  # 7 vs # 9
Jan 20 Tue 6:00pm  Field #2   3  # 5 vs # 2
Jan 22 Thu 6:30pm  Field #3   3  # 6 vs #10
Jan 22 Thu 6:30pm  Field #4   3  # 3 vs # 4
Jan 22 Thu 6:30pm  Field #5   3  # 8 vs # 1

Jan 27 Tue 6:00pm  Field #1   4  # 9 vs # 5
Jan 27 Tue 6:00pm  Field #2   4  # 1 vs # 7
Jan 29 Thu 6:30pm  Field #3   4  # 2 vs # 3
Jan 29 Thu 6:30pm  Field #4   4  # 8 vs # 6
Jan 29 Thu 6:30pm  Field #5   4  #10 vs # 4

Feb  3 Tue 6:00pm  Field #1   5  # 4 vs # 8
Feb  3 Tue 6:00pm  Field #2   5  # 7 vs # 5
Feb  5 Thu 6:30pm  Field #3   5  # 1 vs # 6
Feb  5 Thu 6:30pm  Field #4   5  #10 vs # 2
Feb  5 Thu 6:30pm  Field #5   5  # 3 vs # 9

Feb 10 Tue 6:00pm  Field #1   6  # 3 vs # 7
Feb 10 Tue 6:00pm  Field #2   6  # 6 vs # 4
Feb 12 Thu 6:30pm  Field #3   6  # 5 vs # 1
Feb 12 Thu 6:30pm  Field #4   6  # 9 vs #10
Feb 12 Thu 6:30pm  Field #5   6  # 8 vs # 2
</code>```

There is no algorithm that solves the overall scheduling problems associated with the hundreds or thousands of different types of leagues, sports, and potential situations.
What we did to solve this problem was to take a different approach to calculate schedules.  It starts with the very complex math to determine proper round robin team pairings (match-ups), but that was just the beginning. Other pieces are needed to create a useful balanced schedule that can be published and distributed.  Players, coaches, parents, etc., all need to know not only who they are playing; but where they are playing; what time they are playing; if they are home or visitor; and for many leagues, a game number.

I hope this helps you and others understand what took us 3 years to figure out.

Body:
I generated the 10 team single round robin schedule below. It took me about 3 minutes.

Schedule info:

10 teams - 1 round robin (only the first 6 weeks are displayed)

Season start date 1/6/15 - end date 3/5/15

2 games each Tuesday, 3 games each Thursday, 5 games each week
no skip dates

All teams are distributed to play in the 5 time slots equally.

All play 9 games.

All play each other once.

All are distributed evenly as home & visitor (either 5 / 4, or 4 / 5).
Note: at the end of round robin 2 all teams play 18 games (9 as home & 9 as visitor) and
all teams have 2 Byes.

All are distributed to play evenly in the 5 time slots each week.

We used an outdated Honeywell main frame computer and just under 3 years to put this whole thing together. Once our scheduling software was debugged, it took the main frame computer many hours searching millions of permutations & combinations to calculate and create the balanced patterns for 4 to 22 teams that we were looking for.

10 Team Division Schedule   DATE 12/20/14

DATE   DAY TIME    LOCATION  GM  HOME vs VISITOR

Jan  6 Tue 6:00pm  Field #1   1  # 1 vs #10
Jan  6 Tue 6:00pm  Field #2   1  # 2 vs # 9
Jan  8 Thu 6:30pm  Field #3   1  # 3 vs # 8
Jan  8 Thu 6:30pm  Field #4   1  # 4 vs # 7
Jan  8 Thu 6:30pm  Field #5   1  # 5 vs # 6

Jan 13 Tue 6:00pm  Field #1   2  # 6 vs # 3
Jan 13 Tue 6:00pm  Field #2   2  #10 vs # 8
Jan 15 Thu 6:30pm  Field #3   2  # 7 vs # 2
Jan 15 Thu 6:30pm  Field #4   2  # 9 vs # 1
Jan 15 Thu 6:30pm  Field #5   2  # 4 vs # 5

Jan 20 Tue 6:00pm  Field #1   3  # 7 vs # 9
Jan 20 Tue 6:00pm  Field #2   3  # 5 vs # 2
Jan 22 Thu 6:30pm  Field #3   3  # 6 vs #10
Jan 22 Thu 6:30pm  Field #4   3  # 3 vs # 4
Jan 22 Thu 6:30pm  Field #5   3  # 8 vs # 1

Jan 27 Tue 6:00pm  Field #1   4  # 9 vs # 5
Jan 27 Tue 6:00pm  Field #2   4  # 1 vs # 7
Jan 29 Thu 6:30pm  Field #3   4  # 2 vs # 3
Jan 29 Thu 6:30pm  Field #4   4  # 8 vs # 6
Jan 29 Thu 6:30pm  Field #5   4  #10 vs # 4

Feb  3 Tue 6:00pm  Field #1   5  # 4 vs # 8
Feb  3 Tue 6:00pm  Field #2   5  # 7 vs # 5
Feb  5 Thu 6:30pm  Field #3   5  # 1 vs # 6
Feb  5 Thu 6:30pm  Field #4   5  #10 vs # 2
Feb  5 Thu 6:30pm  Field #5   5  # 3 vs # 9

Feb 10 Tue 6:00pm  Field #1   6  # 3 vs # 7
Feb 10 Tue 6:00pm  Field #2   6  # 6 vs # 4
Feb 12 Thu 6:30pm  Field #3   6  # 5 vs # 1
Feb 12 Thu 6:30pm  Field #4   6  # 9 vs #10
Feb 12 Thu 6:30pm  Field #5   6  # 8 vs # 2

There is no algorithm that solves the overall scheduling problems associated with the hundreds or thousands of different types of leagues, sports, and potential situations.
What we did to solve this problem was to take a different approach to calculate schedules.  It starts with the very complex math to determine proper round robin team pairings (match-ups), but that was just the beginning. Other pieces are needed to create a useful balanced schedule that can be published and distributed.  Players, coaches, parents, etc., all need to know not only who they are playing; but where they are playing; what time they are playing; if they are home or visitor; and for many leagues, a game number.

I hope this helps you and others understand what took us 3 years to figure out.


问:
The Better Parts and Delegation: Is Crockford Too Extreme?
Douglas Crockford has recently been giving a talk called The Better Parts. The gist of the talk is that JavaScript developers should actually avoid a superset of the The Bad Parts, which now includes new, Object.create, any from of delegation or inheritence, including ES6 classes, and this.

Specifically, Crockford recommends defining new object types by using a constructor function that creates and returns a new object, and that uses closure to create private variables and so on. The obvious issue with this is that every instance has each of its methods bound directly to the instance; there's no delegation, and that's memory hungry. Crockford claims that this is a non-issue, because memory is so cheap. I found that pretty unconvincing.

In a case where some type needed a bunch of methods and a very large number of instances might exist at once, surely any decent JavaScript developer will put those methods in an object, and have every instance delegate to it. It then seems reasonable to just use that kind of one step delegation by default. This goes against the recommendations in The Better Parts, and as soon as somebody says "why not make that delegation recursive", we're back to where we began.

Obviously, if you are creating a very large number of instances of anything, you'd use delegation as an obvious optimisation, but we're normally talking about relatively small numbers, so for that case, can we just forget the costs?

What are the runtime costs of following Crockford's advice, specifically regarding avoiding delegation? On the kinds of consumer devices that typically run web browsers, are the costs generally minor?

答:
This reminds me of a recent question on https://cs.stackexchange.com/questions/35385/for-small-values-of-n-on-can-be-treated-as-if-its-o1.  And the answer is really the same -- yes, for small values.

What is small and will you be dealing with small?  That sorta floats, based upon experience and your domain. But you go to experts for their expertise, absence either a definite performance problem or your own expertise saying that your domain is atypical, I'd trust them on a performance issue like this.

Remember, he is talking to the audience, not you individually.  If you want to know if he is right in your case, then measure...


问:
How to code a one-sided virtual economy
I'm attempting to make an online game with a mini-economy in it. The challenge is that the only person selling anything will be the website itself, and hence the supply and demand curve doesn't apply (as it costs the website nothing to produce the items being sold).

Products sold will have several factors that contribute to its value.  Each of these factors can be represented by a number, but it is difficult to know if product X is better than product Y if X has a better A and Y has a better B.  The monetary value of each factor (and thus, each product) is hard for me to calculate, which is why I would like an economy to do that for me.

Some products are upper-end products, and should be inaccessible to players who don't have the money.

There will be several types of products on the market, each serving completely different purposes in the game.

I'm guessing that there will be a larger number of lower-level players.

I have three ideas on how to develop it:

Generate an initial price on each product.  Each time a person buys a product A, the price of A goes up a fixed amount, X, and the price of every other product goes down X/(# of products).

Generate an initial price on each product.  Each time a person buys a product A, the price goes up X.  Each minute, the price of A goes down Y.

Produce each product at a fixed rate, with lower amounts of high-end products.  Upon production, add the product to an auction, where each player can cast a bid on the amount he will pay.  The initial bid will be generated.

I believe that method #1 and #2 will overvalue low end products, and undervalue high end products, so #3 is my favorite.  #3 also only has 1 value for me to generate, while #1 and #2 have multiple.  However, #3 may have problems if the initial bid is too high for the products, or it produces products at a lower rate than it should, causing a shortage.

Is auctioning off products the best way to determine the product's price?  Is there a better way to do this?

答:
Without knowing much about the intended game; I'd give each attribute a weighting factor such that the price is the sum of each "attribute * weighting factor".

For example, let's say (for weapons) you have the 4 attributes durability, slice damage, bash damage and speed. You might decide to assign weights like this:

3 coins per point of durability

10 coins per point of slice damage

8 coins per point of bash damage

5 coins per point of speed

Now imagine there's a sword with 120 durability that does 20 slice damage per hit, and can hit 1 time per second. It's price would be 120*3+20*10+5*1 = 565 coins. The price of a mace with 160 durability and 19 bash damage that can hit 0.8 times per second would be 3*160+19*8+5*0.8 = 636 coins.

The nice things about a system like this is that you can fine-tune the weights (and effect whole groups of items at once); and that it's easy to dynamically generate random items that are priced appropriately.

Note: One of the things I dislike about a lot of games is that there's a specific set of equipment to achieve the best result; and you can find out all the stats for all the pieces of equipment on a web site. E.g. a typical "min/max" player might
decide their equipment (from the item list on a fan's web site) then grind a specific quest or dungeon until they get that piece of equipment. The random/dynamically generated equipment solves that (forces players to play the game continually hoping they'll get a lucky drop).

Title: How to code a one-sided virtual economy


答:
Virtual economies can be very hard to get right. Fortunately, by not having players selling items they've crafted/looted themselves you've simplified the problem somewhat: you can control supply, which will allow you to prevent the massive deflation in item values that can occur when they're produced in much higher volumes than they're consumed.

A couple of other problems to watch out for:

Can players transfer items between themselves? If so, this will reduce demand for low level items substantially, as players trade away items they no longer need.

(assuming you're talking about selling items for game currency, not real money) what prevents high level players from accumulating extremely large amounts of cash, which might cause runaway inflation?

Assuming you have good answers to these (item decay, where items quality is reduced with use, is one possible answer to both problems, but a lot of players don't like it), auctions are a good bet. You can generate the initial bids as a percentage of recent selling prices for similar items, which should solve that problem. And then keep an eye out for products which often don't sell, or which always attract a lot of bids, as these could be warnings that you've got the resupply rate wrong.

Here are a few must-read articles on online game economies:

http://psychochild.org/?p=1179
http://www.raphkoster.com/2006/09/07/agc-mmo-economies/
http://www.raphkoster.com/2012/03/20/do-auction-houses-suck/

Title: How to code a one-sided virtual economy

Body:
I'm attempting to make an online game with a mini-economy in it. The challenge is that the only person selling anything will be the website itself, and hence the supply and demand curve doesn't apply (as it costs the website nothing to produce the items being sold).

Products sold will have several factors that contribute to its value.  Each of these factors can be represented by a number, but it is difficult to know if product X is better than product Y if X has a better A and Y has a better B.  The monetary value of each factor (and thus, each product) is hard for me to calculate, which is why I would like an economy to do that for me.

Some products are upper-end products, and should be inaccessible to players who don't have the money.

There will be several types of products on the market, each serving completely different purposes in the game.

I'm guessing that there will be a larger number of lower-level players.

I have three ideas on how to develop it:

Generate an initial price on each product.  Each time a person buys a product A, the price of A goes up a fixed amount, X, and the price of every other product goes down X/(# of products).

Generate an initial price on each product.  Each time a person buys a product A, the price goes up X.  Each minute, the price of A goes down Y.

Produce each product at a fixed rate, with lower amounts of high-end products.  Upon production, add the product to an auction, where each player can cast a bid on the amount he will pay.  The initial bid will be generated.

I believe that method #1 and #2 will overvalue low end products, and undervalue high end products, so #3 is my favorite.  #3 also only has 1 value for me to generate, while #1 and #2 have multiple.  However, #3 may have problems if the initial bid is too high for the products, or it produces products at a lower rate than it should, causing a shortage.

Is auctioning off products the best way to determine the product's price?  Is there a better way to do this?


问:
Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?
The coding standards for the code hosted in drupal.org suggest to use two spaces to indent the code; other sites suggest to use tabs to indent the code.

What is the proper indentation character for everything, and in every situation? Please explain the answer you give.

答:
Use tabs to indent the start of the line, one tab per indent level, and let everyone pick how wide they want that to be.

Use spaces if you're lining up characters within a line, so they always line up regardless of tab size.

And find and punch all the early software authors who let this stupid thing become an issue in the first place.

(Seriously, why is this even something that's discussed? Next you'll be telling me you also want to use multiple characters for line breaks!)

ContentLicense: CC BY-SA 2.5


问:
Compose nested EventEmitters elegantly
I am developing a server-side JavaScript tool, and trying to do so in a modular way.

I have a Parser class that is an EventEmitter - you call parse and it will eventually emit data and end events. It is generally invoked like so:

```<code>var parser = new Parser(options);

parser
  .on('data', handleData)
  .on('end', handleEnd)
  .parse();
</code>```

Now I want to extend this Parser in a way that imposes some sort of state - rather than simply emitting data for every parse result, it tracks how the results change between parses. I have built another class called Stateful that accepts a Parser instance and is built around it (composition-style). It is an EventEmitter itself and emits insert, update, delete, and end. You use it like so:

```<code>var parser = new Stateful(new Parser(options));

parser
  .on(/* handle events */)
  .parse();
</code>```

Now I want to extend this functionality further. In addition to tracking state, I want to track the order of these parse results according to some pre-defined sorting algorithm, as each parse result is emitted. This does have a performance hit over the Stateful parser, and there would be reason to use Stateful with tracking sort order, so I want to keep it separate. It will emit the same events as Stateful, but they will have some additional objects passed to their handlers.

So what is the best way to do this?

I could further nest composition, like so:

```<code>var parser = new Ordered(new Stateful(new Parser(options)));
</code>```

But that seems smelly to me. Ordered relies upon being passed a Stateful and would break if it was just passed a Parser.

Alternatively, I could say that Ordered inherits from Stateful, but remember that Stateful communicates with events, which do not like to behave polymorphically. Take this example below. I used ES6 class pseudo-syntax for terseness, let me know if it is unclear at all. I am actually writing this in ES5.

```<code>class Stateful extends EventEmitter {
  constructor(parser) {
    this.parser = parser;

    parser
      .on('data', this.handleData.bind(this))
      .on('end', this.handleEnd.bind(this));
  }

  handleData(data) {
    if (isNew(data)) {
      this.emit('insert', data);
    } else {
      this.emit('update', data);
    }
  }

  handleEnd() {
    for (data in dataNotYetHandled()) {
      this.emit('delete', data);
    }
    this.emit('end');
  }
}

class Ordered extends Stateful {
  /* ??? */
}
</code>```

The handleData and handleEnd methods emit events directly, so I cannot make use of them directly in the superclass implementation. I could separate the logic from the emit calls, but that would break encapsulation, requiring my subclass to make use of calls outside of its superclass's public interface.

What pattern would be best here? I am in control of all 3 classes and could make changes to the interfaces of any of them. Please let me know if I could provide any more info. Thanks.

答: I have decided to re-implement the solution using Node Streams, rather than simple events, allowing me to use pipe().

Title: Compose nested EventEmitters elegantly


答:
The fact that you need to make a change to the interface of a superclass but do not also have a similar need to change its subclasses suggests to me that you have a design error of some kind. Your subclasses would appear, at least in some cases, not to be substitutable for their base class, otherwise they would need to change too.

It may be that your inheritance structure is wrong in that there is an as yet unidentified base class that all of Father and SonX should inherit instead of being direct descendants. Then Father alone could implement the method that needs to change. If there is behavior in common it might belong in the base class, or it may be better if SonX have a Father object they can delegate to.

Title: What design pattern for changing interface?

Body:
Sorry guys, I should have clarified the fact that the modified method is abstract in Father. Then if the method signature changes, all its implementations in SonX shall also change(at least the signature, though the implementation may stay still).

Now the question should be asked like following:
Say I have the abstract class Father, and three(or more) of his children class Son1, Son2 and Son3. Now I have to change one method, in other words, add an argument to one abstract method of Father. However, I will have to change all the implemented methods(the modified abstract method in Father) in SonX, which costs too much. The change to the signature of the method in SonX is essential cause the clients are interacting with SonX and the clients shall invoke the new version of the method.

So my question is: is there any design pattern suitable for such a situation in which the interfaces will change?

Thanks.


问:
How to test android apps that depend on telecom provider connection?
I am planning to write an app that needs phone number and contact list. Is there any way that I can test my app without buying a telecom provider connection for my android phone. Without a sim the phone doesn't have a phone number and I am wondering if mock phone number is only way to get pass this.</p>

答: There is one way that you can use default emulator in android and you can send a call to your emulator from DDMS. You can check some functionality using this method.</p>


问:
Why does Git's stash commit need two parents?
Why does Git's stash commit need two parents?

In the Hacker's Guide to Git, I see this mental model for stashes:

The guide tells me that stash@{0} needs both A and B as parents.  Why? Why doesn't the stash just point to B, getting rid of the need for C?  I think I am missing something in my Git comprehension.

答: Because two things are stashed: the indexed content and the worktree content.  Both are derived from the checked-out commit.  When popping the stash, both can be restored.</p>


问:
Model of simple traffic simulation
I want to write a simple traffic simulation with one road intersection. First I thought of a cellular automata in the model but it should not be limited by an underlying discrete grid system so the streets could be more independent to location or levels. Currently I can think of three approaches and I would like to get your thoughts on it.

Street as Entity
An agent is part of this entity when it's driving on it.

Intersection (or Endpoint) as Entity
An agent drives from endpoint A to B.

Intersection and Street as Entity
Merged Point 1 and 2 in one system.

This reminds me somehow about the benefit of a Moore vs Mealy machine (States vs. Transition). What do you think would be the best representation to go with. As mentioned, the entire system should be not just limited by discrete values because I would like to animate the transition of the agent from street A to B. Any ideas appreciated.

答:
Just some thoughts.

(Mandatory disclaimer: use of the information for purposes other than strictly personal use or entertainment, or use for purposes that may harm safety or cause loss of assets or life, is strictly forbidden.)

Since I'm not certain about what you mean by "entity", I will just list the properties (model and behavior) a person (who can code) would naturally expect from these road structures and vehicles.

Streets, a bundle of lanes

Streets can be one-line, multi-lane, single-direction or bi-direction.

For simplicity, let's discount lane-changing behaviors and all sources of obstructions:

Entering of vehicle from a lot into a lane.

Exiting of a vehicle from a lane into a lot.

Lane-changing in general.

Multiple vehicles are allowed to enter one street in one direction, being initially assigned a lane number from 1 to N.

Upon exiting from the other end of the street, these vehicles can be found to have magically switched lane assignments.

For simplicity, the simulation will not look into how that happened.

Lane-passing.

Parking on the curb, and the occasional slight traffic obstruction it causes.

Jaywalking pedestrians

Lane, a one-dimensional position on a curve.

Mathematically speaking, the (traversal) position of a vehicle on a lane is a real number between 0 and x, where x is the physical arc-length of the lane (one stretch of a street).

While a vehicle is on a lane, it will have an instantaneous velocity, and also an acceleration/deceleration (rate of change of velocity).

For simplicity, let's discount rotational mechanics, torque, turning radius, or rollover (accident).

The simulation will treat all lane traversals as strictly linear motion as far as the physics is concerned.

Intersection, a complicated Venn diagram of exclusive zones

Even with the most simplistic simulation, we must agree that we can't let north-south and east-west traffic flowing at the same time. If it is so, it would not be an at-grade intersection; it would be an overpass or underpass.

Below we make the typical assumption of a four-way intersection, i.e. having four ingress (incoming) and four egress (leaving) directions.

4 x 4 makes 16 possible vehicle trajectories. (This includes U-turns.)

By using pen-and-paper, one can work out the exclusion rules that allow different combinations of these trajectories to be used at different traffic signals.

A vehicle entering the intersection will have a velocity

Each trajectory takes a certain amount of time to traverse given a velocity. Work backwards and one can get a fake "length" value.

It is common knowledge that a vehicle must slow down upon entering an intersection and return to normal speed upon exiting, but for sake of simplicity it will be omitted from simulation.

How do I run a simulation, with many agents, with time, and with many different lengths and velocities?

Two ideas come to my mind.

Finite, fixed time-steps. Say, by the second.

At the current timestamp, calculate where each vehicle will be (position, velocity and acceleration/deceleration), and what the vehicle's steering and gas pedal behaviors will be (based on each agent's received stimuli)

Event-based time simulation.

For each agent, one would forecast the next future timestamp at which one has to re-examine the agent's whereabouts and responses. Store this future timestamp ("event") in a priority queue.

After forecasting future events from all agents, the agent with the nearest timestamp will be processed. The vehicles surrounding the agent will also have their status updated. If all calculations work out to be correct (no conflicts), the global simulation timestamp is updated, and the next future timestamp will be picked from the queue and processed.

Title: Model of simple traffic simulation


问:
readability vs shorter code in returning from function
In something as simple as

```<code>int sq(int x) { int y = x*x; return y; }
</code>```

versus

```<code>int sq(int x) { return (x*x); }
</code>```

the former function requires an extra IL step.

EDIT: IL code from the first example, using the current C# compiler from VS 2013 Update 4 (.NET Framework 4.5.1), code from the optimized release version:

```<code>  IL_0000:  ldarg.0
  IL_0001:  ldarg.0
  IL_0002:  mul
  IL_0003:  stloc.0   // These two instructions
  IL_0004:  ldloc.0   // seem to be unneccessary
  IL_0005:  ret
</code>```

and from the second example:

```<code>  IL_0000:  ldarg.0
  IL_0001:  ldarg.0
  IL_0002:  mul
  IL_0003:  ret
</code>```

Is that IL extra step indicative of data being copied in memory? Is this difference still present when using something seemingly better optimized? (C?)

If yes to first or both: can I use the latter, especially when the returned data takes a lot of space, and presumably a lot of time to be moved in memory? Or should I favor the former, because it is more readable? LINQ makes it easy to have whole functions inside a long return() line, but my example faces the same choice were it C. Speed or readability?

In general, would you put the last bit of maths between the parentheses in the return line?

答:
Any self respecting compiler will compile both examples to the same IL. Further, the first isn't any more readable, since you have a garbage variable with no information. It's just noise which decreases readability. If that temporary actually had a good name that provided some useful information to the reader, then the first way would (usually) be better.

But in general, favor readability over speed (which is only barely correlated to length of code).


问:
Is there a useful correlation between choice of web-browser/search engine and good quality programmers?
After a round of interviews earlier this year, which included some practical questions with access to a computer, I noticed that, at least for the applicants we were seeing, there was a high inverse correlation between quality of applicant and the explicit choice of Bing/IE as the stack for search/browsing the web. That is, a large number of applicants specifically searched for IE to use as a browser when browsing the web, and specifically used Bing as the search engine (even typing in Bing in the Google search box, before starting a search)

Is this just an outlier, a fluke, or is there some sort of information I can obtain from this observation? So far, my best candidates are:

Yes, there is a high correlation between good programmers and choice of web browser/search engine

There is some training program, or community, which advises using IE/Bing during interviews, and I just happened to run into a poor selection from that group

Something else is going on, that I don't know about, but someone here might know.

So, to repeat, the question is: is there more than coincidence at work here, and, if there is, what's going on?

答:
It is a strange, but a very interesting question indeed.

I believe there should be a correlation.

Good programmers strive for efficiency and quality. IE/Bing cannot provide those compared to Firefox/Google. If people don't care about those very basic things, tools in their work, chances are they won't care about their work or anything at all. And it is a known quality of a good programmer that he cares and has an own opinion of the things.

It is also possible that those programmers weren't web programmers. But even so, there should have seen "the Internet" in their practice since it's become a primary source of the information and knowledge. And then, they couldn't have missed Google and Firefox, Opera, Safari and Chrome.


问:
Where did the three tenets of OOP originate
It is easy to find the origin of the term OOP coined by Alan Kay when he created Smalltalk, but I can't find if when creating the language he also created the 3 tenets of OOP (Encapsulation, Inheritance, Polymorphism). Especially since he is much more focused on the message passing aspect of the language.

So where did the 3 pillars originate from? Was it Smalltalk and Alan Kay or someplace else?

答:
Both Encapsulation and Polymorphism are consequences of Message Passing. (If all you can do is send a message and wait for a response, then you cannot possibly know what the receiver does to generate the response (Encapsulation) and different receiver may respond differently to the same message (Polymorphism).)

Alan Kay liked Inheritance, but didn't consider it fundamental. In fact, he designed the first version of Smalltalk without inheritance, because he couldn't figure out how to do inheritance without classes, and he disliked classes even more than he liked inheritance. It was only when Dan Ingalls came up with the design of metaclasses that Dr. Kay found classes at least somewhat acceptable. In any case, he considered inheritance simply a method of code reuse, not something inherent to OO.


答:
First of all, micro-optimizations like this rarely make sense. You should focus on readability and worry about these kinds of optimizations only when you've identified the code that you actually need to optimize by profiling.

Now, if you're still interested about performance, looking at IL doesn't make much sense, because it's not IL that's executed.

Instead, what you should do is to measure.

Another option would be do look at the generated machine code (usually x86). But the problem with that is that CPUs are very complicated and it can be very difficult to figure out which version of the code is going to be faster.

Note: looking at the machine code is not as simple as opening the Disassembly window. You need to run in the Release mode, and make sure the CLR actually does optimize the code (either by unchecking "Supress JIT optimization on module load" or by starting without the debugger attached: Ctrl+F5, and attaching it later e.g. using Debugger.Break() and selecting to debug the code).

If you do that, you will most likely notice that both versions of the method are going to be inlined, which makes it hard to see which instructions belong to your method (but both versions generate the same machine code for me).

If you want to compare the two versions of the method in isolation, you can use [MethodImpl(MethodImplOptions.NoInlining)]. With that, the code I'm getting for both versions of the method is the same:

```<code>push        ebp
mov         ebp,esp
mov         eax,edx
imul        eax,edx
pop         ebp
ret
</code>```

Title: readability vs shorter code in returning from function

Body:
In something as simple as

```<code>int sq(int x) { int y = x*x; return y; }
</code>```

versus

```<code>int sq(int x) { return (x*x); }
</code>```

the former function requires an extra IL step.

EDIT: IL code from the first example, using the current C# compiler from VS 2013 Update 4 (.NET Framework 4.5.1), code from the optimized release version:

```<code>  IL_0000:  ldarg.0
  IL_0001:  ldarg.0
  IL_0002:  mul
  IL_0003:  stloc.0   // These two instructions
  IL_0004:  ldloc.0   // seem to be unneccessary
  IL_0005:  ret
</code>```

and from the second example:

```<code>  IL_0000:  ldarg.0
  IL_0001:  ldarg.0
  IL_0002:  mul
  IL_0003:  ret
</code>```

Is that IL extra step indicative of data being copied in memory? Is this difference still present when using something seemingly better optimized? (C?)

If yes to first or both: can I use the latter, especially when the returned data takes a lot of space, and presumably a lot of time to be moved in memory? Or should I favor the former, because it is more readable? LINQ makes it easy to have whole functions inside a long return() line, but my example faces the same choice were it C. Speed or readability?

In general, would you put the last bit of maths between the parentheses in the return line?

Body:
First of all, micro-optimizations like this rarely make sense. You should focus on readability and worry about these kinds of optimizations only when you've identified the code that you actually need to optimize by profiling.

Now, if you're still interested about performance, looking at IL doesn't make much sense, because it's not IL that's executed.

Instead, what you should do is to measure.

Another option would be do look at the generated machine code (usually x86). But the problem with that is that CPUs are very complicated and it can be very difficult to figure out which version of the code is going to be faster.

Note: looking at the machine code is not as simple as opening the Disassembly window. You need to run in the Release mode, and make sure the CLR actually does optimize the code (either by unchecking "Supress JIT optimization on module load" or by starting without the debugger attached: Ctrl+F5, and attaching it later e.g. using Debugger.Break() and selecting to debug the code).

If you do that, you will most likely notice that both versions of the method are going to be inlined, which makes it hard to see which instructions belong to your method (but both versions generate the same machine code for me).

If you want to compare the two versions of the method in isolation, you can use [MethodImpl(MethodImplOptions.NoInlining)]. With that, the code I'm getting for both versions of the method is the same:

push        ebp
mov         ebp,esp
mov         eax,edx
imul        eax,edx
pop         ebp
ret


答:
Alan Kay may have created the term, but object-oriented programming didn't originate with Smalltalk; it originated with Simula, an ALGOL variant with classes and many of the concepts we consider to be core OOP principles today, including inheritance and virtual methods (polymorphism).

Encapsulation (private, protected, public) was not in the original Simula, but it was added to the TOPS-10 version, and was later integrated into Simula 87.  From there, these core concepts have spread to the rest of the object-oriented world.

For all Alan Kay's talk of inventing OOP, it's Simula's style that has been successful.  Smalltalk-style OOP has largely failed in the marketplace of ideas everywhere and every time it's been introduced, with one notable exception.  Objective-C uses Smalltalk-style OOP, and it's found a good deal of success in iOS, because Apple built their whole API around it and thus shoved it down their developers' throats.  Outside of the Apple ecosystem, though, Objective-C is as little used as any other implementation of OOP-by-message-passing.

Title: Where did the three tenets of OOP originate

Body:
It is easy to find the origin of the term OOP coined by Alan Kay when he created Smalltalk, but I can't find if when creating the language he also created the 3 tenets of OOP (Encapsulation, Inheritance, Polymorphism). Especially since he is much more focused on the message passing aspect of the language.

So where did the 3 pillars originate from? Was it Smalltalk and Alan Kay or someplace else?


答:
Shortage is not an issue. Economy works the way it is exactly because there is shortage. Without shortage, you cannot have an economy. If there is shortage of a highly desired item because its production rate is too low, people will bid up, raising the price, making the highly desirable item inaccessible to less wealthy players. At that point, you can increase or reduce production rate to increase your profit/revenue; at one point, the price will decrease to the point where increasing production rate further will no longer increase your profit/revenue. Congratulations, you've reached the market equilibrium. That's the right price that people are willing to pay for that item. Note that as you don't actually have production costs, profit is the same as revenue.

Optionally, you can model the production cost to shape the market the way you wanted it to be. Your shops can have a total production capacity that is shared among all items so that increasing the production rate of one item reduces the production rate of all other items. A higher level item should have a higher production cost and the production cost of a single type of item should increase as production rate of that item type increases. If people keeps bidding a highly desirable item price up, that would increase its production rate up to the point where increasing the production rate of that item any further actually reduces the shop's total "profit". The goal of the algorithm that controls production rate should be to maximize profit given a certain production capacity.

These would be your controls over the market:

Total production capacity (controls global item price)

Production multipliers of each item (controls the price of that item type)

The market capacity formulas would be something like:

```<code>Constraint:
SUM[(Production Rate of I * Production Multiplier of I) for I in (All Items)] <= Total capacity
Sales Rate of I < Production Rate of I
</code>```

And you have to solve:

```<code>Goal: Maximize(Sum[(Sales Rate of I * Selling Price of I) for I in (All Items)] by varying Production Rate
</code>```

As more people bids on a highly desirable item, the price of that item will go up making it unaffordable for most people and the majority would settle for the more affordable items. The shops, in its pursuit of maximizing profit, will make more of the affordable items to match their demands.

By setting the goal of shops as maximizing profit, the market also acts as a dynamic money sink. If there's a lot of rich players, the price of the most desired items would be driven way, way up, in effect the bids increases the money sink rate and self-regulating inflation.

Title: How to code a one-sided virtual economy

Body:
Shortage is not an issue. Economy works the way it is exactly because there is shortage. Without shortage, you cannot have an economy. If there is shortage of a highly desired item because its production rate is too low, people will bid up, raising the price, making the highly desirable item inaccessible to less wealthy players. At that point, you can increase or reduce production rate to increase your profit/revenue; at one point, the price will decrease to the point where increasing production rate further will no longer increase your profit/revenue. Congratulations, you've reached the market equilibrium. That's the right price that people are willing to pay for that item. Note that as you don't actually have production costs, profit is the same as revenue.

Optionally, you can model the production cost to shape the market the way you wanted it to be. Your shops can have a total production capacity that is shared among all items so that increasing the production rate of one item reduces the production rate of all other items. A higher level item should have a higher production cost and the production cost of a single type of item should increase as production rate of that item type increases. If people keeps bidding a highly desirable item price up, that would increase its production rate up to the point where increasing the production rate of that item any further actually reduces the shop's total "profit". The goal of the algorithm that controls production rate should be to maximize profit given a certain production capacity.

These would be your controls over the market:

Total production capacity (controls global item price)

Production multipliers of each item (controls the price of that item type)

The market capacity formulas would be something like:

Constraint:
SUM[(Production Rate of I * Production Multiplier of I) for I in (All Items)] <= Total capacity
Sales Rate of I < Production Rate of I

And you have to solve:

Goal: Maximize(Sum[(Sales Rate of I * Selling Price of I) for I in (All Items)] by varying Production Rate

As more people bids on a highly desirable item, the price of that item will go up making it unaffordable for most people and the majority would settle for the more affordable items. The shops, in its pursuit of maximizing profit, will make more of the affordable items to match their demands.

By setting the goal of shops as maximizing profit, the market also acts as a dynamic money sink. If there's a lot of rich players, the price of the most desired items would be driven way, way up, in effect the bids increases the money sink rate and self-regulating inflation.


答:
The IL that you're looking at isn't necessarily indicative of the native code that the JIT compiler will generate at runtime (or that ngen will generate if you pre-compile your native binaries).

The IL in this case is obviously remaining somewhat representative of the original code.

EDIT: The comments posted after the OP posted the IL and disassembly have noted that the assembly is a debug build, so optimizations are turned off, and the JIT will likely optimize this away if you compile a release build.

EDIT: And I definitely agree with the comments that debugging the "assign to variable, return the variable" variant is easier, for the simple fact that you can inspect the result of the assignment before the method returns.

However, every compiler (C#, VB.NET, FORTRAN, COBOL, F#, etc.) is a different beast, transforming those languages into common IL, which is then transformed by the JIT into native code for the CPU the CLR finds itself running on.

IL is an acronym for "Intermediate Language," after all, not for "Fully Optimized Native Machine Language."  I'd imagine the return on investment from creating fully optimized IL when the JIT itself is already an optimizing compiler may not be worth it in most cases.

Also, it might be interesting if you would post the actual IL from each example.

I guess I wouldn't really worry about it.

It's probably a rare occurrence that you're going to outwit the optimizations built into the compiler. Those optimizations are what those guys (and/or gals) are focusing on all the time.

I'd worry more about correct, human-readable code that's easy to debug, and the 80/20 rule. 80% of the performance issues are going to be in 20% of the code. Actually, it's probably more like 95/5.

Profile your code. Run tests and time them, then optimize the parts that are actually problematic. I'd bet you lunch that the problem bits are often in places you don't expect, and a lot of code you thought was going to be a performance issue just won't be, because it runs rarely or isn't in a super-critical path. And I'll bet the JIT optimizes away whatever you're worried about with this example, anyway. ;-)


问:
Whats the difference between byte and Byte?
Alright so of course, I know the differences.
byte is a primitive and Byte is an object. Byte offers more functions but there is one thing I dont understand. Why would anyone create a variable using Byte? It takes a lot longer. As an example:

```<code>byte primitive:
byte mikeHawk = 5;

Byte object:
byte blackHawk = Byte.valueOf((byte)5);
</code>```

I've been reading a Java book and its teaching me about the object primitives.
I mean, its a lot easier to add and subtract with primitives too.
Maybe I am missing something. Thanks

答:
The Java language has a lot of historical baggage. In Java, everything is an object – with the exception of primitive types such as int or byte that represent C-like value types. While these primitives are generally more efficient, they have some serious restrictions:

You can't call methods on non-objects. There is a compiler technique called “autoboxing” that transparently wraps primitives in a full object in order to allow methods to be called on them. In Java, autoboxing is performed whenever a primitive is assigned or cast to the corresponding object type, e.g. when assigned to a variable or used as a method parameter.

Type parameters for generics must be objects due to historical Java limitations. You can't have an ArrayList<byte> but must use an ArrayList<Byte>: The type parameters exist only during compile time for the purpose of static type checking, while they are treated as an Object during run time. Other languages such as C++ or C# did not use this design and can parameterize over primitive types as well.

So, while byte is the efficient representation of a byte, the Byte wrapper class contains all the overhead necessary for methods to be called and for the value to be used as a regular object.


问:
Template pattern with varying input type in overridden method
I am trying to use template pattern to define a generic algorithm in java.
But the method that needs to be overridden, takes an object as input.
This object will vary depending on the concrete implementation.

So I decided to use inheritance in input parameter.
I am passing parent object in the overridden method of the abstract class.
In the overriding method of concrete class I downcast it to the child and get the required details.
It is said that downcasting is a code smell.
How can I achieve this without downcasting.
Or is there any other better solution.

Example code that shows the issue:

```<code>abstract class GenericAlgorithm {
    void someMethod(GeneralParameter gp);
}

class ConcreteAlgorithm extends GenericAlgorithm {
    @Override
    void someMethod(GeneralParameter gp) {
        // I can't take a SpecificParameter as argument,
        // so I would need to downcast the parameter
        SpecificParameter sp = (SpecificParameter) gp;
        ...
    }
}
</code>```

答:
Use generics to specify the parameter type. The parent class would restrict this parameter to be a subclass of GeneralParameter:

```<code>abstract class GenericAlgorithm<Param extends GeneralParameter> {
    void someMethod(Param p);
}
</code>```

Then, the subclass would extend the parent class but provide the used parameter type as a type argument:

```<code>class ConcreteAlgorithm extends GenericAlgorithm<SpecificParameter> {
    @Override
    void someMethod(SpecificParameter p) {
        ...
    }
}
</code>```

Note that this may require you to also use generics for other parts of your program if you want to avoid casting. Here's a full (albeit contrived) example that creates Sandwiches.

```<code>abstract class SandwichMaker<S extends Spread> {
    public void make(S spread) {
        toastBread();
        addSpread(spread);
        enjoy();
    }

    protected void toastBread() {
        System.out.println("...toasting bread");
    }

    protected abstract void addSpread(S spread);

    protected void enjoy() {
        System.out.println("this is yummy!");
    }
}

class CheeseSandwichMaker extends SandwichMaker<Cheese> {
    @Override
    protected void addSpread(Cheese cheese) {
        System.out.println("... adding " + cheese.name + " cheese from " + cheese.origin);
    }
}

interface Spread {}
class Cheese implements Spread {
    public final String name;
    public final String origin;

    public Cheese(String name, String origin) {
        this.name = name;
        this.origin = origin;
    }
}

...

SandwichMaker<Cheese> sandwich = new CheeseSandwichMaker();
sandwich.make(new Cheese("Camembert", "Normandy, France"));
sandwich.make(new Cheese("Cheddar", "Somerset, England"));
</code>```

See it live on ideone.

Body:
Use generics to specify the parameter type. The parent class would restrict this parameter to be a subclass of GeneralParameter:

abstract class GenericAlgorithm<Param extends GeneralParameter> {
    void someMethod(Param p);
}

Then, the subclass would extend the parent class but provide the used parameter type as a type argument:

class ConcreteAlgorithm extends GenericAlgorithm<SpecificParameter> {
    @Override
    void someMethod(SpecificParameter p) {
        ...
    }
}

Note that this may require you to also use generics for other parts of your program if you want to avoid casting. Here's a full (albeit contrived) example that creates Sandwiches.

abstract class SandwichMaker<S extends Spread> {
    public void make(S spread) {
        toastBread();
        addSpread(spread);
        enjoy();
    }

    protected void toastBread() {
        System.out.println("...toasting bread");
    }

    protected abstract void addSpread(S spread);

    protected void enjoy() {
        System.out.println("this is yummy!");
    }
}

class CheeseSandwichMaker extends SandwichMaker<Cheese> {
    @Override
    protected void addSpread(Cheese cheese) {
        System.out.println("... adding " + cheese.name + " cheese from " + cheese.origin);
    }
}

interface Spread {}
class Cheese implements Spread {
    public final String name;
    public final String origin;

    public Cheese(String name, String origin) {
        this.name = name;
        this.origin = origin;
    }
}

...

SandwichMaker<Cheese> sandwich = new CheeseSandwichMaker();
sandwich.make(new Cheese("Camembert", "Normandy, France"));
sandwich.make(new Cheese("Cheddar", "Somerset, England"));

See it live on ideone.


问:
Why define struct in variable?
Consider the following program:

Many people when they want to use a struct, they create a new variable as:

```<code>struct structureName variableName
</code>```

While it works when you just define it as:

```<code> structureName variableName
</code>```

My teacher always uses the first method. My question is how do they differ? Do I ever need to specify struct before defining my variableName. Here is an example to explain my question:

```<code>struct example {
    int n;
    char c;
};

int main() {
    example o;
    o.c = 'c';
    o.n = 5;
    printf("%c", o.c);
    printf("%d\n", o.n); //this works

    struct example ex; // this versus "example o" without using struct keyword
    ex.c = 'e';
    ex.n = 7;
    printf("%c", ex.c);
    printf("%d", ex.n); //this works

    return 0;
}
</code>```

答:
This is one of the differences between C and C++.

In C, structure names are completely separate from other names and you must use the struct keyword to tell the compiler to look for the name of a structure.

Another way to put it is that the struct keyword is actually part of the name of the structure.

When designing C++, this was changed and the use of the struct (or class) keyword was made optional when referring to a structure or class.

Title: Why define struct in variable?


问:
Query on java I/O BufferedOutputStream write() method
Below is the code that is written using byte stream non-buffer class FileInputStream and FileOutputStream with the usage of explicit user buffers.

```<code>public class FileCopyUserBuffer{
    public static void main(String[] args){

        String inFileStr = "C:\\practice_in.jpg";
        String outFileStr = "C:\\practice_out.jpg";

        FileInputStream in = null;
        FileOutputStream out = null;

        try{
            in = new FileInputStream(inFileStr);
            out = new FileOutputStream(outFileStr);

            startTime = System.nanoTime();
            byte[] byteBuf = new byte[4096];
            int numBytesRead;

            while((numBytesRead = in.read(byteBuf)) != -1){
                out.write(byteBuf, 0, numBytesRead);
            }

        }catch(IOException ex){
            ex.printStackTrace();
        }
    }
}
</code>```

Below is the program written using byte based buffer I/O stream class BufferedOutputStream & BufferedInputStream.

```<code>public class FileCopyBufferedStream{
    public void main(String[] args){

        String inFileStr = "C:\\practice_in.jpg";
        String outFileStr = "C:\\practice_out.jpg";

        BufferedInputStream in = null;
        BufferedOutputStream out = null;

        File fileIn = new File(inFileStr);
        System.out.println("File size is: " + fileIn.length() + " bytes");

        try{
            in = new BufferedInputStream(new FileInputStream(inFileStr));
            out = new BufferedOutputStream(new FileOutputStream(outFileStr));

            startTime = System.nanoTime();
            int byteRead;
            while((byteRead = in.read()) != -1){
                out.write(byteRead);
            }

        }catch(IOException ex){
            ex.printStackTrace();
        }
    }
}
</code>```

Above two programs perform the same functionality but am not clear about the functionality of write(#bytes) method of class BufferedOutputStream.

Based on the observation, below two classes have their own buffers.

```<code>public class BufferedInputStream extends FilterInputStream {
    .........
    protected volatile byte buf[];
    ..........
}

public  class BufferedOutputStream extends FilterOutputStream {
    ........
    protected byte buf[];
    .......
}
</code>```

In second program, How does out object of class BufferedOutputStream is able to write the buffer that is part of class BufferedInputStream? Because we are not passing buffer as argument of out.write(#bytes) method[which looks non-intuitive] unlike the first program which passes user  buffer out.write(byteBuf,,)? In second program, out object should at-least have access to object reference in to access the buffer populated using in.read().

答:
Because we are not passing buffer as argument of out.write(#bytes) method[which looks non-intuitive] unlike the first program which passes user buffer out.write(byteBuf,,)?

No, you are not passing buffer as argument,
you are passing the single byte that you have read.
You have that single byte in the byteRead variable,
returned by BufferedInputStream,
and you are passing that single byte into BufferedOutputStream.

In second program, out object should at-least have access to object reference in to access the buffer populated using in.read().

No, BufferedOutputStream doesn't have access to BufferedInputStream's buffer.

It seems you simply misunderstood what .read() without arguments really does.
There's nothing magical going on here.


问:
User Story vs Requirement
User Story captures what the user wants to do with the system at a high level. I understand that the user story would further drive a number low level requirements. Is user story same as high level requirement for the system?</p>

答:
Stumbled upon this during a google search and thought I would throw my opinion in.

There is really no difference between a requirement and a user story. Both are stating the desired outcome or goal from a user perspective.

The only difference is the way this goal or outcome is captured by a business analyst. In this case it is in the wording.

Example:

As a team lead I want to view which of my team are working on mortgage cases so that I can monitor their performance.

The solution shall display team members working on mortgage cases.

Both of the above could be interpreted in the same way but both also have a lot of ambiguity. The main point here is a difference in style. I think the issue we mostly see is how far into defining the solution do we go before we have moved out of the world of requirement and into the world of functional design. Is it down to the business analyst to state "list logged in users by first and second name on the main application menu" or is that too much information? When we are sat talking to our stakeholders and we all know the solution and can interpret what it will look like, even the likely code language it will be built on and the way it will deployed do we really need to play the pureist game of "let's define objectives and not solutions". This is where I feel the confusion really is.

Requirements often make the assumption we know nothing about the solution just desired outcomes. Yes this makes everything solution agnostic but does that really help us in the development cycle? If we can accurately define something early then why not do it?

All in all though I would not worry about user stories and requirements differences. Ultimately you want to define enough information for.someone to develop a solution. A user story that is too high level will simply be knocked back and requested to be broken down into smaller user stories. The same as a " the system shall" style.requirement will probably be knocked back as being too ambiguous if it does not have enough detail.

In the end go with what your developers and stakeholders like to see and work from that.

Title: User Story vs Requirement


问:
Which 'InputStream' subtype is used by 'Socket' type object here?
In the below server socket program, byte stream object is used to read data from client, as mentioned -  InputStream in = socket.getInputStream();

```<code>public class SingleThreadTCPServer{
    ServerSocket serverSocket;
    int serverPort = 3333;

    public SingleThreadTCPServer(){
        try{
            serverSocket = new ServerSocket(serverPort);
            System.out.println("ServerSocket: " + serverSocket);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private void listen(){
        try{
            while(true){  //run until you terminate the program
                //Wait for connection. Block until a connection is made.
                Socket socket = serverSocket.accept();
                System.out.println("Socket: " + socket);
                InputStream in = socket.getInputStream();
                int byteRead;
                //Block until the client closes the connection (i.e., read() returns -1)
                while((byteRead = in.read()) != -1){
                    System.out.println((char)byteRead);
                }
            }
        }catch(IOException ex){
            ex.printStackTrace();
        }

    }

    public static void main(String[] args){
        new SingleThreadTCPServer().listen();
    }
}
</code>```

I had been through the implementation of getInputStream() method but could not understand the actual subtype of InputStream object that is actually returned from getInputStream()

Among the below subtypes,

Which is the actual stream type that is being used by server to read data from client?

答: There's no inherent reason to believe that those are the only subtypes of InputStream. They are merely the only ones described by the Java language beforehand. The implementation of the socket can use any subtype. It is an implementation detail that is not specified.</p>