问:
Understanding how layers are separated in an MVC application
I am using Visual Studio 2013 MVC 5 application using Razor.

I want to understand in which order layers sit and interact with each other.

In my solution I have:

UI Layer (Main Project) - comprising of Model, View and Controller

Data Access Layer (Class Library) - which contains generic Stored Procedure methods and Connection Class

Repository (Class Library) - which contains data access code (Create/Update/Delete)

Business Layer (Class Library) - which contains business validations

Separate Layer for REST

I am preparing architecture diagram and want to understand how layers talk to each other.

I assume the order is like this:

```<code>**Data Access Layer -> Model -> Repository -> Business Layer -> Controller -> View**
</code>```

Where does REST sits?

答:
I assume by REST you mean a Web Api of some sort?

this should be an alternative UI layer ie

DAL -> Repo -> Model/Services

-> MVC app

OR

-> Web.API

OR

-> Windows app

OR

--> Mobile App

etc

Alternatively you can expose the repository as an API layer (although you'll have to consider security)

DAL -> Repo -> RepoService API -> RepoClient -> Models/BLL(ie on a mobile app with web data)

AND/OR you if your Business logic is comprised of services you can expose these

the idea is to rewrite as little code as possible when you change the user interface


问:
Software License Web Application
We are in the process of building a web application for a client and they have inquired about owning the code for the site. We would like to issue a license agreement to the client for use of the code if we for any reason we are no longer working on the project.   We would like to have ownership of the code but allow them use wherever they see fit, the only limitation we would like to have is the sale of the code. The are a company with several employees and will only be using the application within their company.

What would such a license agreement look like?

答: You're going to need a custom license. Free licenses don't cover your situation, and commercial licenses can't be reused. You'll need your own. So talk to a lawyer.</p>

ContentLicense: CC BY-SA 2.5

Title: Software License Web Application


问:
Is there any point in preventing developers from having a local copy of the database in their machine?
Is there any point to having a dedicated development database server(s) that all developers can use, i.e. they don't have a local copy of the db in their machines. Quite clearly, this will slow down development but I'm curious whether anyone actually does this in the enterprise level. I know I should trust the devs we hire and I'm guessing this will mostly be the kind of answers that I will be getting but if anyone actually does this I would want to know if it's even worth doing.

UPDATE:

Great answers. My question arises from this question from quora regarding source code protection: http://www.quora.com/How-does-Facebook-protect-their-source-code

Here's the pertinent answer that got me thinking:

Facebook (and Google and probably many others) don't have employees check out code on their laptops. Code is checked out on developer servers or workstations and employees connect to these to work. These are only accessible on the corporate network, and connecting  from outside the network requires VPN, which itself requires multi-factor authentication.

Now that I think about this, if developer have terminal access to the development servers then they must have access to mostly whatever is in there which most likely includes the db.

答:
Sometimes you have a corporate environment where development is client-side only, and databases are the realm of the DBAs. In these cases, devs will still have a common development instance to work on even if they cannot make changes to it, they can still fill it with crap data for testing. If your DB is a mainframe or minicomputer, then chances are the API to access it wil be via stored procedures rather than plain SQL, in which case hiding the underlying schema is ok as the devs don't need to know it - they do need to know the sprocs however.

Incidentally, even if you do have devs with local DBs they use, its still worth having a centralised DB server that hosts the 'last release' or even just an integration DB, so devs can test their code against a known state DB with good (or reasonable) data in it.

The 2nd aspect is code security. I used to work for a company in the financial services sector that took security very seriously, our offshore devs would only work on code by RDPing onto computers that were hosted in the local office. My laptop was locked down to prevent use of filesharing and email websites and things like the USB ports were disabled. I think this is required for PCI security accreditation.

ContentLicense: CC BY-SA 3.0


问:
Uploading text data to server from SQLite is faster or text files?
My application receives a lot of data every milliseconds(name,id,value,.. of a signal from a simulator device). and I should upload this data to MySQL server. First I need to save them in a database and upload them to the server via GSM network. The reason that I save data into the mobile device is that the connection is so slow and the app receives a quite large number of data at a time and cannot upload them at once, also it may encounter disconnection problem. In fact, I just need a temporary storage and I don't want to do any data manipulation in the SQLite. Currently I am writing the data to the simple text file(CSV) and then upload every 20 lines to the server using name/value pairs in Android HttpPost, but what about SQLite? Is it faster to insert data to SQLite and then upload it? Which approach is preferable?

Here is the sample data that I receive from the simulator device:

```
time,id,name,value
143125738713,id1,name1,8.000077
143125738714,id1,name1,8.000004
143125738714,id1,name1,8.000008
143125738715,id2,name2,0.0
143125738716,id2,name2,0.0
```

答:
For a definitive answer, one would have to measure, and I am sure it will be possible to create a badly implemented CSV writer which is slower than a well written SQLite writer.

However, when it comes to writing sequential data records to a file, there is not much out there which can beat using to a simple file stream in speed. Each additional layer of abstraction upon that will probably slow your program down. Thus I would not expect writing to a text file to be slower than writing to any kind of database, even it is as lightweight as SQLlite, as long as there is not any "performance bug" in the program.

If speed is your main concern, and the network connection is your bottleneck, you may consider to apply some kind of data compression before sending the files over the line, and decompress it on the server before inserting it.


问:
Is physical Agile board "always" better than electronic tool?
Whenever the question comes up on which Agile tool to use use there always some people that answer "don't use an electronic tool because you will lose the big-visible-board advantage which better generate team conversation".

Is this always the case or are there any contexts where an electronic tool is a better choice?  What are some of the pros and cons of each approach?

答:
80% of my team is remote, so our normal communication is remote.

For this situation I find that an electronic board always seems better than a physical board for us.  In fact I don't now how we would effectively do a physical board (I have done plenty of physical boards in the past when most people are also physically present).  One camera that all of us watch I guess - though if we're watching on a screen, its already not really a physical board for us...


问:
Defects Review and Management
The doubt or question i have is something every developer might be facing time to time.  it is related to testing and development team and their perspective.

I have observed that most of the Defects which are getting logged are purely based on judgement rather than requirement. apart from that there is attitude that bugs which are getting logged has to be resolved which is causing lot of trouble and rework.

What we as developer should do? How to tackle these scenarios?

Approach which i have adopted so far is to reject the issues which are not as per the requirement.

答:
This sounds to me like a break-down of communication at a couple of levels. Since you've also not stated what your position in the project is, I'll assume that you're a regular dev who's working under an architect.

Breakdown of Workflow

Firstly it sounds like there's not a properly defined way to handle bugs as they're entered into the tracking system. Someone has to rank them according to importance and then assign them to be fixed within budget and time-line constraints.

Even basic bug-tracking systems have the ability to classify, rank and document various aspects of the issue. If you feel like these features could be used better, have a discussion with your architect or manager.

Breakdown of Trust

More importantly, it seems like there's a little bit of defensiveness and mistrust of whoever your testers are.

Understand that their role is to act as the user, so it might be better if they're not too bogged down with the details of the requirements specification. If they're raising bugs for you, don't immediately assume that they haven't understood the requirements well enough; try and drill down into what exactly they were trying to do and why they landed at that use-case.

Also if it's something that keeps coming up then there might be something that wasn't properly defined in the requirements.

Summary

All in all, just understand that you and the testers are on the same team and that you'll are both just trying to make a better product for the user. After all, customers aren't going to get your requirements document; either the thing works or it doesn't.

Title: Defects Review and Management


答:
First MVC has 3 layers. Model, View, and Controller. Trying to Make BLL or n-Teir Layers fit is not going to work very well.

M - Model, this is where you "access and store" your data.

V - View, This is where you render, or represent your data.

C - Controller, This is the glue that lets views tell your models how/what to render via views.

In a modern web application, there are actually several applications at work.

Your DAL could probably be an MVC application, Models being tables, Views being the output of the stored procedures and Controllers being the stored procedures themselves.

"Repository" could be a MVC application where the model is the class objects that store data after retrieval from the DAL app. The controller would be what ever logic you have to select what needs pulling from the DAL. And the view would be, for example an exposed webservice.

And so on...

Basically, It would look like your project (or your understanding) is not using MVC properly. MVC is not always the best tool. Sometimes good old n-teir is "better".

A good example of an multi-MVC application:

A Web service that feeds a Mobile App and a Javascript/HTML app.

The web service would have it's own MVC, Models consisting of database/storage access. Views being the rendered web service json/xml. Controllers being authentication logic, and server side validations.

The Mobile app would be a MVC app, the Models being the classes that retrieve data from the web service. The controllers being classes that help translate the web service data to the views. And the views being the XML (android) or nib (iOS) files that get rendered.

The JS/HTML app would be the same structure as the mobile app. The Models being the part that gets/and holds data from the web services. The Controllers being the classes that "parse" that data, and the views being what ever is rendering the HTML.

The main problem with trying to get n-teir to fit in  MVC terms are that they are not comparable, exactly.  Your Business logic should be in two places. Either controller (if controlling things) or models if validating things. DAO fits in controllers (select * where x=1) and models (CRUD).  Views and UI are pretty much the same. But UI/BLL/DAO is not the same as MVC. You should try to pick one methodology and use that instead of trying to blend the two.

Also, just to make sure were talking the same thing UI can't be a whole project. I assume you have a UI project which could be an MVC app with the models pulling from the DAO project.

Title: Understanding how layers are separated in an MVC application

Body:
I am using Visual Studio 2013 MVC 5 application using Razor.

I want to understand in which order layers sit and interact with each other.

In my solution I have:

UI Layer (Main Project) - comprising of Model, View and Controller

Data Access Layer (Class Library) - which contains generic Stored Procedure methods and Connection Class

Repository (Class Library) - which contains data access code (Create/Update/Delete)

Business Layer (Class Library) - which contains business validations

Separate Layer for REST

I am preparing architecture diagram and want to understand how layers talk to each other.

I assume the order is like this:

```<code>**Data Access Layer -> Model -> Repository -> Business Layer -> Controller -> View**
</code>```

Where does REST sits?


问:
Functional vs object-oriented style in C#
I'm learning functional programming and face the following confusion when applying it to my C# projects:

I begin by writing pure, static functions and use function composition.

After the code reaches a certain size, I realize some of these functions tend to "cluster" about some types. For example, there exist >5 functions having the same type as parameter.

Next step, my object-oriented background takes over and I move these functions to this type (class) as methods. As a result, their signatures simplify and they often become more cohesive. However, I lose the benefits of functional style.

I've grown very fond of functional approach, but I cannot convince myself that my initial code was better above.
Which approach would you prefer in this situation (in C# or another mixed language)?

Related: Design in "mixed" languages: object oriented design or functional programming?

```<code>class MyType { }

class Functions
{
    public static void X(MyType t) { }
    public static void Y(MyType t) { }
    public static void Z(MyType t) { }
    public static void T(MyType t) { }
    public static void U(MyType t) { }
}

class Class1
{
    public MyType T { get; private set; }
    public Class1(MyType t) { T = t; }
    public void X() { }
    public void Y() { }
    public void Z() { }
    public void T() { }
    public void U() { }
}
</code>```

答:
However, I lose the benefits of functional style.

If you always lose the benefits of functional style code when converting bundles of functions to objects, you're doing it wrong (or have an usual idea of what the benefits of functional style are).

After all, instance functions are the same thing as static functions but simply have an additional implicit parameter. If you're making these functions impure, that's your problem, not a problem inherent to OO code. If you make your classes mutable, then yes, you're going to lose functional style benefits.

But if you keep your classes immutable (except for collections/DTOs), I find that you can maintain many of the benefits of functional style coding while getting some OO goodness as well.


答:
I don't think that simply using static methods makes it Functional

I don't think simply moving your previously static methods to a class makes it OO

If you are doing OO, then your classes should have properties and the methods should change those properties. This makes the 'data object' mutable and functional programming goes out the window

While Static does stop you using properties from the same class, you can still reference other static data or databases etc. Functional programming relies on your methods returning the same result for the same parameters every time.

Going from your Example code:

ive followed your pattern but added a real method

```<code>public class MyType
{
    public int ANumber { get; set; }
}

public class StaticFunctions
{
    public static int AddOne(MyType x)
    {
        return x.ANumber + 1;
    }
}
</code>```

so you convert your static method to OO via this kind of pattern:

```<code>public class MyOOClass
{
    public MyType data { get; private set; }
    public MyOOClass(MyType data)
    { this.data = data; }

    public int AddOne()
    {
        return this.data.ANumber + 1;
    }
}
</code>```

But really this is nothing more than a namespace for your static functions. it arguably makes them harder to use as you have to initiate an extra MyOOClass for every MyType.

If you wanted to make it OO I would change it to something like this:

```<code>public class OOClass
{
    public int ANumber { get; private set; }
    public OOClass(int n)
    {
        this.ANumber = n;
    }

    public void AddOne()
    {
        this.ANumber= this.ANumber+1;
    }
}
</code>```

if you wanted to make it functional i would change it to something like this:

```<code>public Func<int, int> AddOne = (x) => x + 1;
</code>```

My Personal fave though would be ADM

```<code>public class AdditionService()
{
    public MyType AddOne(MyType a)
    {
        return new MyType() {ANumber=a.ANumber+1};
    }
}
</code>```

Title: Functional vs object-oriented style in C#

Body:
I'm learning functional programming and face the following confusion when applying it to my C# projects:

I begin by writing pure, static functions and use function composition.

After the code reaches a certain size, I realize some of these functions tend to "cluster" about some types. For example, there exist >5 functions having the same type as parameter.

Next step, my object-oriented background takes over and I move these functions to this type (class) as methods. As a result, their signatures simplify and they often become more cohesive. However, I lose the benefits of functional style.

I've grown very fond of functional approach, but I cannot convince myself that my initial code was better above.
Which approach would you prefer in this situation (in C# or another mixed language)?

Related: Design in "mixed" languages: object oriented design or functional programming?

```<code>class MyType { }

class Functions
{
    public static void X(MyType t) { }
    public static void Y(MyType t) { }
    public static void Z(MyType t) { }
    public static void T(MyType t) { }
    public static void U(MyType t) { }
}

class Class1
{
    public MyType T { get; private set; }
    public Class1(MyType t) { T = t; }
    public void X() { }
    public void Y() { }
    public void Z() { }
    public void T() { }
    public void U() { }
}
</code>```

Body:
I don't think that simply using static methods makes it Functional

I don't think simply moving your previously static methods to a class makes it OO

If you are doing OO, then your classes should have properties and the methods should change those properties. This makes the 'data object' mutable and functional programming goes out the window

While Static does stop you using properties from the same class, you can still reference other static data or databases etc. Functional programming relies on your methods returning the same result for the same parameters every time.

Going from your Example code:

ive followed your pattern but added a real method

public class MyType
{
    public int ANumber { get; set; }
}

public class StaticFunctions
{
    public static int AddOne(MyType x)
    {
        return x.ANumber + 1;
    }
}

so you convert your static method to OO via this kind of pattern:

public class MyOOClass
{
    public MyType data { get; private set; }
    public MyOOClass(MyType data)
    { this.data = data; }

    public int AddOne()
    {
        return this.data.ANumber + 1;
    }
}

But really this is nothing more than a namespace for your static functions. it arguably makes them harder to use as you have to initiate an extra MyOOClass for every MyType.

If you wanted to make it OO I would change it to something like this:

public class OOClass
{
    public int ANumber { get; private set; }
    public OOClass(int n)
    {
        this.ANumber = n;
    }

    public void AddOne()
    {
        this.ANumber= this.ANumber+1;
    }
}

if you wanted to make it functional i would change it to something like this:

public Func<int, int> AddOne = (x) => x + 1;

My Personal fave though would be ADM

public class AdditionService()
{
    public MyType AddOne(MyType a)
    {
        return new MyType() {ANumber=a.ANumber+1};
    }
}


答:
You can write functions even when using classes.

You said you created static functions, so there is no "state". When you move those methods to their respective classes, of course they can't continue to be static, they need to be regular instance methods.

But if you don't modify any of the parameters, even the receiver of the message (which is the same as the container of the method), it continues to be functional style. Just don't modify any of the parameters.

The real advantage of the functional style is that the functional style can be functionally executed in a way that is really simple: replace the called code with the body of the ode being called. You can repeat this many times. And therefore you can be sure it produces the desired output.


答:
I am very familiar with this problem!

Also, controversially, I believe it is caused by AGILE DEVELOPMENT!

Think about it. Agile tries to drive devs faster by getting them to concentrate on completing what is asked for and move on to the next task. This is great, but it puts a huge pressure on the person writing the spec. If they miss something out it wont get done.

Usually the person writing the spec or tasks is a project manager who a: is not technical and b: hasn't been given anything more than 'I want a Webernet page! you have 3 months!'

They get around the problem of 'no spec' by hiring testers and telling them 'Just raise anything you don't like as a bug'

Again this is fine, because Agile is supposed to be iterative. Those bugs can go back in the queue as requirements and you just spin the dev wheel until everyone is happy.

BUT! that dosnt happen. What happens is the task is not accepted as done because bugs, the project is delayed indefinitely and the devs are blamed for either being slow or writing buggy code.

My personal fix for this (as a dev) is to ask for the test cases to be written first.

If you know what the tests are, you can test your code before you release it to test and it should pass 100% of the time. Happy Testers, happy Devs

If the test list seems short, the PM can see it right there and say 'Oh surely it should also do this?' Happy PM

Title: Defects Review and Management

Body:
The doubt or question i have is something every developer might be facing time to time.  it is related to testing and development team and their perspective.

I have observed that most of the Defects which are getting logged are purely based on judgement rather than requirement. apart from that there is attitude that bugs which are getting logged has to be resolved which is causing lot of trouble and rework.

What we as developer should do? How to tackle these scenarios?

Approach which i have adopted so far is to reject the issues which are not as per the requirement.


答:
SQLite is awesome but it is "not optimised" for insert speed (but note that you can run it in significantly faster 'async' mode which will not protect your data if something crashes - this may be acceptable for your use-case if you don't mind losing some of those data points)

You'll be better off appending to a filestream.

Title: Uploading text data to server from SQLite is faster or text files?

Body:
My application receives a lot of data every milliseconds(name,id,value,.. of a signal from a simulator device). and I should upload this data to MySQL server. First I need to save them in a database and upload them to the server via GSM network. The reason that I save data into the mobile device is that the connection is so slow and the app receives a quite large number of data at a time and cannot upload them at once, also it may encounter disconnection problem. In fact, I just need a temporary storage and I don't want to do any data manipulation in the SQLite. Currently I am writing the data to the simple text file(CSV) and then upload every 20 lines to the server using name/value pairs in Android HttpPost, but what about SQLite? Is it faster to insert data to SQLite and then upload it? Which approach is preferable?

Here is the sample data that I receive from the simulator device:

```
time,id,name,value
143125738713,id1,name1,8.000077
143125738714,id1,name1,8.000004
143125738714,id1,name1,8.000008
143125738715,id2,name2,0.0
143125738716,id2,name2,0.0
```


问:
Git Workflow for BDD?
Recently I was working with Behavior Driven Development approach in Rails using RSpec and Capybara. Everything looks okay and it even can speed up whole planning-development bridge in my work (by defining closely behavior of app than usual specification documentation). Anyway, here is my though: is BDD so cool why there is no version control workflow for it? Here is my thought:

Rationale

BDD usually contains two things of each feature:

described test

implementation

That means there are two entities of each feature - dependent to build full-feature, but separated physically. Moreover, the standard procedure (also known as cycle) of building each feature contains:

Write behavioral tests

Write implementation

Although there is no implementation of this proccess in version control, I question the Internet why and there wasn't any response.

Proposition

Assume that there are three types of branches:

master (or some kind of dev branch)

wish

implementation (those two will be described later)

Wish

BDD covers planning process by adding some tests of particular feature before writing code and let them fail. Why just separate this process in branch and tell that is wish how software should work. For example, there is a wish_A branch with particular (based on the RSpec) feature test. This branch is just for developing the test scenario for feature at once.

Implementation

It is natural that each wish should become working code eventually. So this is the way of implementing behavior - by branching wish_A and implementing there a working code. By the last word of lifecycle, the implementation branch is merged into dev or master or any opther version/codename branch.

Issues

Dependency issues

Each wish branch can be depends on many other wishes. Assume that:

A_wish and B_wish are basic, independent features

AB_wish requires A_wish and B_wish fuctionallity

I can't figure what problems might occur after branching from one of A or B and merging another. Implementation of those wishes should be similar - with some conflicts or other problems of code's tech nature.

Question

I can't find why this is not implemented by some software-development approach or why it won't work with BDD. Are there particular reasons for not doing some kind of generic approach?

答:
Honestly, this doesn't sound like something your VCS should care about. Your VCS should only care about the storage of, revisions to and merging of changes to your source code. The idea of a wishlist of features doesn't fit with any of those things.

A wishlist of features is the domain of a product backlog (or something similar). Stakeholders can file new items for the wishlist, which are in turn fleshed out by the product owner. Part of that fleshing out might be the writing (and negotiation with devs) of the text for the BDD spec.

When a wishlist item is ready to be worked on, developers can take whatever workflow they like to implement it. When there is code to be stored and revisioned, then your VCS comes in to play.

Title: Git Workflow for BDD?


问:
Why is Inversion of Control named that way?
The words invert or control are not used at all to define Inversion of Control in the definitions that I've seen.

Definitions

Wikipedia

inversion of control (IoC) is a programming technique, expressed here
  in terms of object-oriented programming, in which object coupling is
  bound at run time by an assembler object and is typically not known at
  compile time using static analysis.  ~http://en.wikipedia.org/wiki/Inversion_of_control

Martin Fowler

Inversion of Control is a common pattern in the Java community that helps wire lightweight containers or assemble
  components from different projects into a cohesive application. ~ based on  http://www.martinfowler.com/articles/injection.html (reworded)

So why is Inversion of Control named Inversion of Control? What control is being inverted and by what? Is there a way to define Inversion of Control using the terminology: invert and control?

答:
Here's a simple overview:

Control refers to what the program does next

On the top level, there are typically two things that control the control: the application itself and the user

In the olden days, control was owned by the application first and the user second. If the application needed something from the user, it would stop and ask and then move on to its next task. The user's interaction provided mostly data rather than controlling what the application did next. This is a little foreign to us nowadays since we don't see this type of behavior very often.

If we switch that around and give the user primary control, then we have inverted the control. This means that instead of the user waiting around for the application to give it something to do, the application sits around waiting for user to give it something to do. GUI's are a great example of this and pretty much anything with an event loop has inverted control.

Note that my example is on the top level and that this concept of inversion of control can be abstracted to different layers of control within the application (i.e. dependency injection). This may be why it is so hard to get a straight answer.


问:
How do you face decoding issues?
For what I understand, given a sequence of bytes without any further information, it's not generally possible to understand which encoding we are talking about. Of course we can guess (e.g. perl's Encode::Guess and similar tools), but sometimes this is just not feasible.

In my case, I've got a byte array which is \xe2\x80\xa1, and I can guess from the context (as a human) that it should correspond either to a à character (\xc3\xa0 in UTF-8) or to a á (\xc3\xa1 in UTF-8). It comes from an xml which declares iso8859-1 in the header, and is produced by a third party tool, which is clearly broken, but I have to deal with it. As you can guess the decoding fails, and no luck with Encode::Guess.

How would you face this kind of problem? I know there's no silver bullet, but is there a tool which outstands the others?

答:
XML encoding can be tricky, because some XML generators might hard-code a generic content type such as ISO-8859-1 even if the document contains e.g. UTF-8. Part of the reason is most text is ASCII, and valid (7-bit) ASCII is also valid as most other encodings. Developers might not understand character encoding or might not care (works with my test data!).

One general approach is to attempt to decode the XML using the provided content-type. As with HTML, this is located near the top of the document and no non-ASCII characters should be between the start of the document and this encoding (except for byte order marks which implicitly provide a content-type).

If this encoding fails, then try with one or more predefined content-types. Good candidates are UTF-8, UTF-16, and ISO-8859-1. Plain old (7-bit) ASCII also decodes fine as UTF-8 and ISO-8859-1 so that is implied here as well.

Please note that depending on the language and XML implementation you may be able to "plow through" errors or not: it is best to have it fail fast on errors so you know to try another encoding.

See Also

Correcting the XML encoding

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

Title: How do you face decoding issues?


问:
What uses are there today for manually writing Makefiles?
I remember the general gist of writing Makefiles, but, due to CMake, autotools and other such Makefile generators, I've forgotten so many details that, if you were to ask me to write a makefile from scratch for a complex project, well, it would take me a couple of hours at least.

There must be many opinions out there, I'm looking for the most informative answer. Considering ninja (Makefiles not intended to be hand-written) and all the automatic generators, does it make any sense to arbitrarily brush up on Makefile syntax, aside from legacy code maintenance?

答:
As a software developer, you should be familiar with the toolchain used by whatever project you are on. You need not be an expert in everything because your team should have one developer to own that process and be intimately familiar with all of the details, but you should be able to look at any build script and understand what it does.

With Makefiles specifically, you are more likely to be using a tool such as Automake to generate them anyway. So there is not much use in manually writing Makefiles, but you should be able to read them in case something does not work right.

Even if you did manually change a Makefile, next time you generate it your changes will go poof so why bother? Focus your efforts on updating the upstream configurations used to generate the Makefile to begin with.


问:
Is specifying copyright necessary in a closed source project?
I am working on a back-end, closed-source system for my company, the code for which is never likely to be open-sourced. Is there any reason for including a copyright notice and year at the top of each code file as you find in many open-source projects, or is this unnecessary from a legal standpoint?</p>

答:
Always, always, always include copyright notices in your code regardless of anyone's intent to distribute or not to distribute the source code.

Reasons:

Policy may change in the future. Who wants to manually add a few hundred copyright notices or try to come up with a regex or other process to do it correctly? Just make it part of your "new file" template and be done with it.

While the software might be an internal system, never underestimate the desire of management to sell anything they can to generate more revenue. C-levels network and talk. Once one of them figures out "we have an internal system for X" and "company Y will pay us millions of dollars for a system to do X" then guess what? Time to market and sell/license the system!

Rogue employee may steal source code. Sure they could remove the notices, but the fact that your copy has it intact is usable evidence against said rogue employee.

Copyright notices and source control metadata (added on date X) can provide valuable evidence to prove ownership.

Inadvertent disclosure. Perhaps a customer is on-site and sees some code or accidentally gains access. The copyright notice and lack of a license makes it abundantly clear that the customer is not allowed to take or use the code.

In the U.S., copyright is implicitly assigned the instant it is created:

When is my work protected?

Your work is under copyright protection the moment it is created and
fixed in a tangible form that it is perceptible either directly or
with the aid of a machine or device.

Source: U.S. Copyright Office

There is no legal requirement to have a copyright notice in the case described in the question. However, unless the copyright is registered (unlikely in this situation), arguments about ownership could devolve into an argument where two entity's words are pitted against each other at face value. By affixing copyright notices to a work you make it known both to potential copyright infringers as well as a court of law that you (or your employer in the case of a work for hire) assert ownership over the work.

Owning a copyright is different from proving ownership of a copyright. Given the low likelihood of registering a copyright in the scenario presented in this question, it is even more important to assert ownership any way possible.


答:
Generally speaking, a software project is a collection of code, data and tests. Typically these should all live in the same repository. Using BDD or TDD means simply to check in (or at least develop) your tests before developing your code. It doesn't have to be any more complicated than that.

So, the reason why no specialized workflow has been created is because no specialized workflow is required. You create a branch for the new feature, you create some tests and check them in to that branch, then you write the code and check it in to the same branch.

Title: Git Workflow for BDD?

Body:
Recently I was working with Behavior Driven Development approach in Rails using RSpec and Capybara. Everything looks okay and it even can speed up whole planning-development bridge in my work (by defining closely behavior of app than usual specification documentation). Anyway, here is my though: is BDD so cool why there is no version control workflow for it? Here is my thought:

Rationale

BDD usually contains two things of each feature:

described test

implementation

That means there are two entities of each feature - dependent to build full-feature, but separated physically. Moreover, the standard procedure (also known as cycle) of building each feature contains:

Write behavioral tests

Write implementation

Although there is no implementation of this proccess in version control, I question the Internet why and there wasn't any response.

Proposition

Assume that there are three types of branches:

master (or some kind of dev branch)

wish

implementation (those two will be described later)

Wish

BDD covers planning process by adding some tests of particular feature before writing code and let them fail. Why just separate this process in branch and tell that is wish how software should work. For example, there is a wish_A branch with particular (based on the RSpec) feature test. This branch is just for developing the test scenario for feature at once.

Implementation

It is natural that each wish should become working code eventually. So this is the way of implementing behavior - by branching wish_A and implementing there a working code. By the last word of lifecycle, the implementation branch is merged into dev or master or any opther version/codename branch.

Issues

Dependency issues

Each wish branch can be depends on many other wishes. Assume that:

A_wish and B_wish are basic, independent features

AB_wish requires A_wish and B_wish fuctionallity

I can't figure what problems might occur after branching from one of A or B and merging another. Implementation of those wishes should be similar - with some conflicts or other problems of code's tech nature.

Question

I can't find why this is not implemented by some software-development approach or why it won't work with BDD. Are there particular reasons for not doing some kind of generic approach?


问:
Skillset improvement in coming new year
Here is a little background information.

I have been working for Java 10 years.

The product I am working on went to live about 3 years ago. Now, the product is getting stable.

After all the post-product drama, I gained a lot of knowledge about Oracle & SQL.
People(mainly management) were desperated enough to give me deep oracle-related task over DBAs. I admit I considered becoming DBA but eventually decided to remain as a programmer.

DBAs & Management are demanding all the DB & Query related task back to DBA, which makes me a bit sad.

In short, I anticipate a lot of time next year.
What would you do to improve your skillset??

I am thinking to upgrade my Java version(Not from experience though, we are using JDK1.5) to 1.6 getting certificate.

Any good idea from fellow developers??

-----------Edit ---------------------

How about data modeling for application? Do you guys think it is developer role??

答:
To me, "improving your skillset" has absolutely nothing to do with specific languages or technologies.  Instead, it is improving your ability to write in general.

For a metaphor:
If this field were like music (and it is), "improving your skillset" by getting JDK 1.6 instead of 1.5 is like learning the harmonic minor scale in the key of a.  However, if you dedicate your time to pattern recognition, fore-sight, and design, you just learn to spot a harmonic minor scale in ANY key.

Great musicians, like great software developers, aren't restricted to a set a tools.

Title: Skillset improvement in coming new year


问:
Python - best way to have interdependent variable in a class
Newbie Python questions: I want to model something that can have a several inter-connected instance variables and if I set one, I want to recalculate the others. Any can be set.

E.g. a circle - each instance has an area, circumference and radius (let's ignore the diameter). If I set the area, I want the circumference & radius re-calculated and vice-versa. Should I :

```<code>class circle:

   def area(self):
       return cmath.pi*self.radius*self.radius

   def circumference(self):
      return 2 * cmath.pi * self.radius

   def radius(self):
      return self.circumference/(2*cmath.pi)

circle1 = circle()
circle1.radius = 5
print "Circle1's area is {0} and its circumference is {1}".format(circle1.area, circle1.circumference)
</code>```

Now there's nothing in the code sample to calculate the area once the radius has been set, so do I need @property with setters and getters for the radius, area and circumference to calculate the other attributes when this one is set or am I barking up completely the wrong tree?

答:
Instead of keeping 3 member fields and synchronizing them, you only need to store one actual value in memory - the radius is a good choice in this example - and always use it:

```<code>import cmath

class Circle(object):
    def __init__(self, radius=0.0):
        self._radius = radius

    @property
    def radius(self):
       return self._radius

    @radius.setter
    def radius(self, radius):
        self._radius = float(radius)

    @property
    def area(self):
       return cmath.pi * self._radius * self._radius

    @area.setter
    def area(self, area):
        self._radius = (area / cmath.pi) ** 0.5

    @property
    def circumference(self):
        return 2 * cmath.pi * self._radius

    @circumference.setter
    def circumference(self, circumference):
        self._radius = circumference / cmath.pi / 2

circle1 = Circle()
circle1.radius = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)

circle1.area = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)

circle1.circumference = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)
</code>```

This solution seems too obvious though - is there a specific reason you want to have separate member fields? You can usually find a smaller number of values you can calculate the rest from...

ContentLicense: CC BY-SA 4.0

Body:
Instead of keeping 3 member fields and synchronizing them, you only need to store one actual value in memory - the radius is a good choice in this example - and always use it:

import cmath

class Circle(object):
    def __init__(self, radius=0.0):
        self._radius = radius

    @property
    def radius(self):
       return self._radius

    @radius.setter
    def radius(self, radius):
        self._radius = float(radius)

    @property
    def area(self):
       return cmath.pi * self._radius * self._radius

    @area.setter
    def area(self, area):
        self._radius = (area / cmath.pi) ** 0.5

    @property
    def circumference(self):
        return 2 * cmath.pi * self._radius

    @circumference.setter
    def circumference(self, circumference):
        self._radius = circumference / cmath.pi / 2

circle1 = Circle()
circle1.radius = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)

circle1.area = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)

circle1.circumference = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)

This solution seems too obvious though - is there a specific reason you want to have separate member fields? You can usually find a smaller number of values you can calculate the rest from...


问:
When and why should a destructor be declared as virtual?
As in

```<code>class TestA
{
     TestA();
     virtual ~TestA();
}
</code>```

So why and when should the destructor for TestA be virtual??

答: The destructor should be declared virtual if inheritance is involved and the derived class needs to be destroyed in a specific way that differs from the base class.</p>


问:
Abstract classes in package structure
I have an abstract class that will have many implementors. There are, of course, many places to put abstract classes in a Java package structure. Should the abstract class be in the same package as the implementors, or should it be in an "abstract package" package, or somewhere else? Please explain why you would place it there - I'm looking for design discussion, not just what I should do in this particular case.</p>

答:
I would put it (like any other class) in the package it belongs most from it's content. That mostly - but not everytime - means, that you put it in the same package as implementing classes. Sometimes you put an abstract class in the same package as some other class using this abstract class - it's part of the API of the other class. Implementing classes could be somewhere else in that case. I never use extra packages for abstract classes or other stuff like exception-classes or so.

Why so? I prefer to use package-structure as building a system for categorizing the content of the software, instead as using it for implementation details. The abstract-class may become later a valid non-abstract-class without breaking the API. But if I have to move it's package it would break again old code. Unnessecary I think.

Title: Abstract classes in package structure


问:
Structuring Procedural vs OO code
I have spent the vast majority of my programming career using Java and very OO based C++. I am really interested in learning to think more procedurally, so I have been starting to do some practice using a more restricted subset of C++ (basically C) and trying to keep my code very procedural.

My question lies in the area of how to structure a program. In Java, I am constantly thinking of objects... so when I create a class I am thinking of:

What is this object representing?

What can this object do?

What do others need to be able to do to it?

What do I expose, what do I hide?

Etc

In the case of procedural code, how does this sort of thing work? Lets say wanted a struct to represent a Car. I would create a header to define it in... but where do functions go that should operate on a car type? Would you also define all Car related functions in the same file line you would a Java class? Am I totally thinking about this the wrong way, in that there should not be any Car related functions since the emphasis should not be on the Car object but on the functions themselves? IS the idea of a member function totally thrown out the window?

The bottom line is my brain has been wired to think about Objects, Encapsulation, Polymorphism, etc.. and I cant seem to wrap my head around anything else. How can I practice?

Any advice is appreciated!

答: I'd recommend reading some of the structured programming "classics": books by Ed Yourdon, Larry Constantine, especially a lot of Dave Parnas' stuff. They talk a lot about top-down design, using structure charts and data-flow diagrams, breaking code into modules and how to handle coupling and cohesion. It's interesting reading, and some of the tools (e.g., data flow diagrams) can still be used today. I sometimes feel that a structured approach is a better fit to some problems (those involving parsing or state machines, usually), but that's not a popular opinion.</p>

Title: Structuring Procedural vs OO code


答:
Any class that has any virtual methods should have a virtual destructor.  Otherwise, the superclass's destructor will not be called if the object is deleted through a pointer to the child class.

In other words, if the keyword virtual exists in the class declaration, you must at least have this:

```<code>virtual ~Class() {};
</code>```

In theory, you don't need to do this if you never delete a child object through a pointer to a base class, but in practice, it is far safer to do this at the outset regardless of how the class is used, as not doing so has no real benefit.

Title: When and why should a destructor be declared as virtual?

Body:
As in

```<code>class TestA
{
     TestA();
     virtual ~TestA();
}
</code>```

So why and when should the destructor for TestA be virtual??

Body:
Any class that has any virtual methods should have a virtual destructor.  Otherwise, the superclass's destructor will not be called if the object is deleted through a pointer to the child class.

In other words, if the keyword virtual exists in the class declaration, you must at least have this:

virtual ~Class() {};

In theory, you don't need to do this if you never delete a child object through a pointer to a base class, but in practice, it is far safer to do this at the outset regardless of how the class is used, as not doing so has no real benefit.


问:
Why is iterating through List<T> more expensive than iterating through Array in .NET?
According to the answers in this post, List<T> is backed by an Array. According to this article, list iteration is considerably slower than array iteration.

If Lists are arrays 'under the hood', why do they take longer to iterate over, especially with foreach?

Note: This is assuming Lists are implemented with Arrays. I might have just interpreted the information wrong.

答:
Iterating through a List is (slightly) slower than a plain array due to a few factors:

Bounds checks: This is likely to be the biggest factor; every single indexer access to the List is going to do a bounds check. Bounds checking on a raw array can often be trivially optimized out of a loop by the JIT.

Method call costs: The indexer on a List is a method call. This might get inlined, but it also might not.

An extra indirection: In order to get to the array inside the List, you need to dereference the List reference. With an array, you have a reference directly to the necessary data.

Potentially an extra copy of the element: When you use the List indexer, you get a copy of the element back. With an array, you can access the element directly in memory. Depending on what the rest of your code looks like, you can avoid making a copy of that data.

When using the Enumerator to iterate, your costs are mostly dominated by the aforementioned bounds check as well as the "version" check to make sure you haven't modified the list while iterating over it.


答: DexterW made some good points, but if you still want to focus on expanding options for using  your current skill set, with mobile development needs (corporate as well as general public) being so hot, why don't you consider learning some Android development?  Java is the core language used for that.</p>

Title: Skillset improvement in coming new year

Body:
Here is a little background information.

I have been working for Java 10 years.

The product I am working on went to live about 3 years ago. Now, the product is getting stable.

After all the post-product drama, I gained a lot of knowledge about Oracle & SQL.
People(mainly management) were desperated enough to give me deep oracle-related task over DBAs. I admit I considered becoming DBA but eventually decided to remain as a programmer.

DBAs & Management are demanding all the DB & Query related task back to DBA, which makes me a bit sad.

In short, I anticipate a lot of time next year.
What would you do to improve your skillset??

I am thinking to upgrade my Java version(Not from experience though, we are using JDK1.5) to 1.6 getting certificate.

Any good idea from fellow developers??

-----------Edit ---------------------

How about data modeling for application? Do you guys think it is developer role??


问:
Sense user-agent to determine HTML - Keep HTML and Logic separate?
I am of-the-understanding that you should try to keep HTML out of your logic, and keep logic out of your HTML.  E.G.: You don't write HTML in (C# strings or Javascript Services) and pass them into the View or DOM.  Likewise, you don't write classic ASP anymore (and I personally limit/nill Razor).  HTML is for HTML, Services are for Logic.  My question is based on this best-practice.  Of course there are small rare one-off's.  Counter E.G.: Razor fans use the HTML Extensions class.  But Razor is its own beast.

With that "best-practice" in mind, is it bad to sense the User-Agent in the headers and send keys or HTML to the View for that specific media?  E.G.: I sense an iPad user-agent, so I either send iPad specific

答:
Your absolutely correct with your thinking, yes you absolutely need to keep them separate.

However, it doesn't need to be as hard as you might think it is, in order to get your layout working correctly across multiple devices.

Realistically, you have 3 approaches that are considered modern practice in this arena.

1) Create a satellite site for each platform you wish to support, then in a single simple index controller, sniff the user agent and redirect to the appropriate satellite site.

2) Use media queries.  Media Query support is now (and has been for some time) good enough and well supported enough to use in full production sites.

3) Use a UI toolkit such as KnockoutJS or Angular and modify class names and attributes on your layouts in real time, responding to user agent changes.

In more detail

If you decide to go with option 1, then the first thing you need to be aware of is the extra work.

Essentially, you'll be maintaining two sites.

Your back-end however should likely still stay the same.  If you use a classic nTier design with a SOLID Composition Root, then your business layer, data layer etc can all be shared, so maintaining separate sub sites does become much easier.

Option 2 on the other hand, means that you still only maintain one site, but the disadvantage you have here is one of complexity.

To use media queries successfully, you need to design your site for one platform, usually desktop, then you need to decide what rules you wish to override and for which screen widths.

While this is not strictly modifying your site based on user agent, you are still adapting your layout to a given screen width, which means that on narrower screens (such as a mobile device) you are still maintaining a readable output, while only having to change the minimum amount needed to maintain that readability.

This tends to be the route that many of the CMS's take, especially wordpress designs, because it requires very little code, and everything can be changed directly in the CSS.

You are however limited to changing only what can be changed using CSS, and since there is still a fair bit of instability in the CSS3 spec, you may find that you still need to limit some of the changes you'd like to make.

This brings me to Option 3 (This is my preferred option) and the way I work for most of what I do.

Simply design your layout as a universal kind of layout, one which while not pretty, works generically on most devices.

Then, wire in your favorite UI toolkit.  (For me this is KnockoutJS mixed with Twitter Bootstrap).

Use your UI toolkit to fill in the dynamic parts of your layout, based on a rest endpoint sniffing the UA from the request.

For example. in my CSS I might have:

```<code>.rule_for_desktop
{
  color: blah;
  width: blah;
}

.rule_for_iphone
{
  color: blah;
  width: blah;
}

.rule_for_android
{
  color: blah;
  width: blah;
}
</code>```

and in my view model for knockout i might have:

```<code>var cssRule = ko.observable("rule_for_desktop");
// More code for the rest of the VM here
</code>```

and in my HTML (This is based on knockout) I might have

```<code><div id="myElement" data-bind="css: cssRule">... some content</div>
</code>```

What then happens is my layout defaults to a desktop layout (or whatever I set as the default in my viewmodel.

If I then fire off an AJAX request, or perform some UA sniffing in the JS code, beacuse my 'cssRule' property is an observable the css rule used in my mark up instantly changes, and takes effect.

Body:
Your absolutely correct with your thinking, yes you absolutely need to keep them separate.

However, it doesn't need to be as hard as you might think it is, in order to get your layout working correctly across multiple devices.

Realistically, you have 3 approaches that are considered modern practice in this arena.

1) Create a satellite site for each platform you wish to support, then in a single simple index controller, sniff the user agent and redirect to the appropriate satellite site.

2) Use media queries.  Media Query support is now (and has been for some time) good enough and well supported enough to use in full production sites.

3) Use a UI toolkit such as KnockoutJS or Angular and modify class names and attributes on your layouts in real time, responding to user agent changes.

In more detail

If you decide to go with option 1, then the first thing you need to be aware of is the extra work.

Essentially, you'll be maintaining two sites.

Your back-end however should likely still stay the same.  If you use a classic nTier design with a SOLID Composition Root, then your business layer, data layer etc can all be shared, so maintaining separate sub sites does become much easier.

Option 2 on the other hand, means that you still only maintain one site, but the disadvantage you have here is one of complexity.

To use media queries successfully, you need to design your site for one platform, usually desktop, then you need to decide what rules you wish to override and for which screen widths.

While this is not strictly modifying your site based on user agent, you are still adapting your layout to a given screen width, which means that on narrower screens (such as a mobile device) you are still maintaining a readable output, while only having to change the minimum amount needed to maintain that readability.

This tends to be the route that many of the CMS's take, especially wordpress designs, because it requires very little code, and everything can be changed directly in the CSS.

You are however limited to changing only what can be changed using CSS, and since there is still a fair bit of instability in the CSS3 spec, you may find that you still need to limit some of the changes you'd like to make.

This brings me to Option 3 (This is my preferred option) and the way I work for most of what I do.

Simply design your layout as a universal kind of layout, one which while not pretty, works generically on most devices.

Then, wire in your favorite UI toolkit.  (For me this is KnockoutJS mixed with Twitter Bootstrap).

Use your UI toolkit to fill in the dynamic parts of your layout, based on a rest endpoint sniffing the UA from the request.

For example. in my CSS I might have:

.rule_for_desktop
{
  color: blah;
  width: blah;
}

.rule_for_iphone
{
  color: blah;
  width: blah;
}

.rule_for_android
{
  color: blah;
  width: blah;
}

and in my view model for knockout i might have:

var cssRule = ko.observable("rule_for_desktop");
// More code for the rest of the VM here

and in my HTML (This is based on knockout) I might have

<div id="myElement" data-bind="css: cssRule">... some content</div>

What then happens is my layout defaults to a desktop layout (or whatever I set as the default in my viewmodel.

If I then fire off an AJAX request, or perform some UA sniffing in the JS code, beacuse my 'cssRule' property is an observable the css rule used in my mark up instantly changes, and takes effect.


问:
What does it mean to "define a profile" in the context of an Internet RFC?
I've seen the phrase defines a profile of XYZ on a couple of IETF RFCs. For example, RFC 3339 reads:

This section discusses desirable qualities of date and time formats
     and defines a profile of ISO 8601 for use in Internet protocols.

What exactly does it mean to define a profile of some other standard? My guess is that it means to create a standard based on a restricted subset of the parent standard, but I haven't found any documentation to confirm this.

答:
Welcome to the wonderful world of ad-hoc definitions made at a time before anyone really understood what the internet was, or indeed was going to be all about.

While there's no official definition of the usage of "profile" as meaning a restricted subset of another standard, over the years it has become common use to body's like the ietf to mean just that.

The problem you have here is not so much one of standards, but one of government and academia based red-tape from an age gone by, where groups like the ietf are still run by the old guard who still insist on using the original terminology used back at the beginning.

I don't claim to be an expert in how any of these groups think, but I've been working in I.T long enough to have seen a fair few of these RFC's when they where brand new and first released, and a lot of the terminology exists for no other reason than "Beacuse they can"

Back then when much of this "Internet stuff" was still quite new, and large chunks of it where run by various university and government bodies, many of the departments that started the projects off, had to have ways of making themselves stand out from each other.

Understand that this was all in the days before any of the glitzy marketing and SEO practices we have today, and one way of making your department stand out was to get folks using a common terminology which inherently linked back to your vocabulary, and as a result your projects, ultimately putting you at the front of what that group was trying to achieve.

As time marched on, much of this terminology became set in stone within the various organisations, to the point where there are even standards for how the standards body's are allowed to describe standards to those who use them.

These days, were left with quite a surplus of definitions that don't make a lot of sense to a newer generation, and which in some places could actually be deemed as harmful and confusing.

Think for a moment how much the HTML4 spec was tidied up to accommodate HTML5.  A lot of the work involved here was nothing to do with what should or should not make it into the specification, a vast amount of it was simply due to the mammoth task surrounding the existing specifications and re-wording things so that some kind of sense could be made of them.

Your guess as to the intended definition is probably as close as your going to get, and from what I can remember it's certainly accurate, I wouldn't however be surprised if there where definitions that did in fact actually conflict with that.

To be perfectly honest, I wouldn't be at all surprised if there was an RFC available somewhere that actually defined what the various definitions should be defined as in definition documents :-)

Unfortunately my days of remembering what each number on each RFC is/was and what it referred to are long behind me, I just use the various search tools on "rfc-editor.org" these days.


答:
There's a lot of use in being able to "Manually Build" a project these days.

Whether that's through the use of a makefile, a shell script or a good old fashioned MsDos based batch file, it really doesn't matter.

There's not just legacy code maintenance as you point out, what about emergency patches and bug fixes to get systems back up and running.

Over the years, I've done a lot of work as a field engineer, and I've lost count of the amount of times I've been stuck in a data center with nothing more than an SSH terminal on the Laptop I have plugged in to some wacky & wonderful custom server system.

You don't always have the luxury of your usual tools, especially when your working on custom projects that are currently undergoing integration testing.

For that reason and that reason alone, it's always a good idea to be able to work using the barest of development environments, and if that means a copy of GCC, Make and Vim running off an 8gb bootable key chain containing a very basic *nix distro then it's worthwhile keeping the practice up.

Title: What uses are there today for manually writing Makefiles?

Body:
I remember the general gist of writing Makefiles, but, due to CMake, autotools and other such Makefile generators, I've forgotten so many details that, if you were to ask me to write a makefile from scratch for a complex project, well, it would take me a couple of hours at least.

There must be many opinions out there, I'm looking for the most informative answer. Considering ninja (Makefiles not intended to be hand-written) and all the automatic generators, does it make any sense to arbitrarily brush up on Makefile syntax, aside from legacy code maintenance?


问:
GPLing an implementation of a patented algorithm
TL;DR: Can you publicly release your own implementation of a patented algorithm as a free research tool for others, under the GPL, when you do not hold the patent (but will happily give clear and thorough attribution to the owners of the patent)? see below for clarification.

First off, apologies if this question has already been answered.  After ~30 minutes of googling and stack-exchanging, I haven't found anything that quite answers what I'm facing.

I work in an academic group and part of our work has been implementing a CT reconstruction algorithm similar to what is done clinically by a major manufacturer.  This manufacturer has a patent that definitely covers what we have implemented.  (I did the implementation from a paper published almost 10 years earlier, only to find that they had also patented the algorithm a little over a year ago. Damn.)

They have a patent on the method of reconstruction and several of the equations utilized, but no source code or anything of the sort.  The code implementation is 100% unique to our group. We're talking patents, not copyright.

We are planning to write a "technical note" about our implementation (gpu-based, more detail on how we implemented the published algorithms (i.e. much more detail than what's patented), etc. all stuff which is not described in the patent) for publication in a major journal ** AND ** this would include releasing our source code.  I would like to release it under GPLv2.0 to provide folks with a research tool.

The GPL would prevent us and anyone down the road from using our code in proprietary software, and if anyone were to use it to make money, they would have to pay rights to the patent owner (and release any code derived from ours). I would like to somehow make clear that we are not claiming any rights to the algorithm, and the only the implementation would be covered by the GPL, however I recognize this distinction may not be possible under the current US legal setup (blegh).

Even if we could somehow make that distinction clear when/if we release, are we violating any of their rights with the patent?  I'm thinking they would have to somehow show that our release damaged their business covered by the patent.

Any thoughts from more experienced folks are much appreciated!  I think this may be kind of a gray area (or not! I'm not a lawyer! haha).

We do NOT wish to infringe upon the patent and don't pretend to have any claim to.  We have a good relationship with the vendor, so we'll most likely end up figuring it out with them, but if they said no, I was curious if it's just because of their feels or if thay have a legitimate claim against our group.

答:
The short answer

In order to license something to others, you have to hold the rights to it.  So your ability to license your code covered by the patent may depend on what you can work out with the patent holder.

The long answer

There are a number of ways this can go.  You can get a release from the patent holder.  You can release your code and hope the patent holder doesn't care; they might not.  You can come up with an algorithm that is unencumbered by the patent.  You can pay a negotiated patent royalty.

Whether anyone makes money from the GPL'd code may not matter, if public dissemination of the code hinders their ability to profit from the invention. The choice of license may not matter either; it's still a patent issue whether the source code is "copyleft" or not (though your vendor might have a preference as to which license you actually use).

The actual answer

This is one of those times where it might be useful to consult an attorney that specializes in patent and licensing law.  They can not only advise you how far you can go with your source code without invoking the patent, but also how an agreement can be correctly crafted between you and the vendor.


问:
Memory Limit of a Single Program and mmap
If one has a 32 bit machine, a single program cannot address more than 2^32 bytes, or 4 GB. Would making use of mmap() allow one to exceed the 4 GB limit?</p>

答:
No, you can never exceed 4GiB of simultaneously addressable memory for a 32-bit binary. Usually, the kernel takes half and you are left with 2GiB user. Some kernels support a compromise split of 1GiB/3GiB.

However, you can ask the OS to map different portions of a file into memory at different times, essentially performing time multiplexing of the available address space. IMHO, at that point you might as well not memory map anything and just read() from the file into buffers.


问:
What algorithm should I use for a lot of if else(s)?
I have to implement a lot of if else statements and I'm thinking of using Decision Tree but I'm not sure if it's going to be the right algorithm.

I don't want to insert a piece of html code based on these conditions.

directly after an iframe embed (same 300 character rule as columns 4 and 5)
directly after a heading tag (same 300 character rule as columns 4 and 5)
directly after a facebook embed
directly after a twitter embed
directly after a vine embed
directly after an instagram embed
directly after any Oembed
directly after an image
directly after a video
directly after a gallery
directly after a protected iframe

So I will scan the whole content of my HTML and try not to add an Ad based on those conditions. The rules will grow as well that's why I don't want to use if else(s).

If I'm missing anything please let me know I will provide more context.

Thanks.

答:
As it looks like these are primarily a list of exclusion filters, something like this might get you where you want to be (example in Java, includes calls to functions that probably don't exist as parts of the test):</p>

```<code>private static List<Predicate<Node>> AD_FILTERS = Arrays.asList(
  (node) -> node.getPreviousSibling().isIFrame(),
  (node) -> node.getPreviousSibling().isHeading(),
   ...
  (node) -> node.getPreviousSibling().isIFrame() && node.getPreviousSibling().isProtected()
);

...
if (AD_FILTERS.stream().map(filter -> filter.test(node)).allMatch(x -> x == false)) {
  // insert the add
}
</code>```

Body:
As it looks like these are primarily a list of exclusion filters, something like this might get you where you want to be (example in Java, includes calls to functions that probably don't exist as parts of the test):

private static List<Predicate<Node>> AD_FILTERS = Arrays.asList(
  (node) -> node.getPreviousSibling().isIFrame(),
  (node) -> node.getPreviousSibling().isHeading(),
   ...
  (node) -> node.getPreviousSibling().isIFrame() && node.getPreviousSibling().isProtected()
);

...
if (AD_FILTERS.stream().map(filter -> filter.test(node)).allMatch(x -> x == false)) {
  // insert the add
}


答:
I haven't found an authoritative definition from IETF, but in the following context from RFC 3339, the definition (at least for that RFC) appears to be conformant subset.

The following section defines a profile of ISO 8601 for use on the
     Internet.  It is a conformant subset of the ISO 8601 extended format.

Title: What does it mean to "define a profile" in the context of an Internet RFC?

Body:
I've seen the phrase defines a profile of XYZ on a couple of IETF RFCs. For example, RFC 3339 reads:

This section discusses desirable qualities of date and time formats
     and defines a profile of ISO 8601 for use in Internet protocols.

What exactly does it mean to define a profile of some other standard? My guess is that it means to create a standard based on a restricted subset of the parent standard, but I haven't found any documentation to confirm this.


问:
How to protect controller endpoint from abuse?
I am building a web app that will first validate a promotion code via AJAX call and then if it is valid, allow the user to fill out the rest of the form, I use KnockoutJS to reveal and hide the elements.

My issue is, what is stopping a sneaky user from building a code generator and pumping the codes into my ajax endpoint until he gets a valid code? What is the recommended way of stopping this abuse?

PS: In the final step of the form I also validate the promotion code server-side just in case.

答:
I'm not sure if this is the best idea, but it's a decent start to prevent brute forcing your validator.

Include a random hash with the original form that has to be passed to the endpoint. Keep a counter in non-persistent storage referencing that hash which expires after some reasonably short timeframe.

Then start returning 503 errors after some threshold is met. Finding the sweet spot is hard, but you want to make it easy for a human, but frustrating for a bad user.


问:
Setting up an [AWS] environment locally
Currently, our infrastructure sits on AWS (EC2, ElasticBeanstalk, RDS) and consists of a few different services that work together to create our production environment, these consist of a:

MySQL server

PHP/Apache server

few NodeJS servers

Currently for development, it is a real pain to setup a local environment that mimics what we have setup for production. We are using MAMP to setup mysql + apache, but to setup the node servers and configure things locally is quite time consuming.

I'd like to ditch MAMP for a solution that is more similar to the ec2 boxes that each service will run on. I've been looking into setting up docker containers on vagrant, as I think that's the way forward.

My question is: What is the best way to setup a micro-service style architecture for local development using Vagrant + docker (or whatever tool is better) so that the local environment closely matches production?

答:
Vagrant has several provisioning options, including Chef or simply Shell scripts. If you are using one of these techniques to provision your EC2 instances, you should be able to use the same technique to provision your Vagrant started instances.

If, on the other hand, you're setting up your EC2 instances by hand, then you're outta luck.

Note, this assumes you haven't tightly integrated with other AWS services like DynamoDB. If you rely on proprietary AWS services, you may not be able to suitably simulate your production environment.

As to whether you should use one Vagrant instance per microservice or one Vagrant instance for all services, that depends on whether or not your microservices can co-exist. If they can, I'd put them on as few Vagrant instances as possible just to make managing the number of Vagrant instances easier. If, however, they have conflicting requirements (say in Linux versions) I'd go with 1 Vagrant instance per microservice.

Title: Setting up an [AWS] environment locally


问:
Is it necessary anymore to extract logic from API controllers?
I've been working in MVC web frameworks since its they started getting popular with RoR and ASP.NET MVC. I have always been careful to never put "business logic" on my controllers since that couples the framework with the logic. These days, like many of you, I'm not really using the MVC part of my framework, since I'm not returning "views" and framework artifacts. Instead, I'm just using routes to controller actions to build API's that return xml or json.

In the past couple years, I've been trying to move closer to CQRS, so my business logic ends up being packaged in commands and handlers with a dispatcher to connect the two. The "real" business logic is actually in my entities, but my command handlers drive the operations. I have also started allowing multiple services to expose different bounded contexts (micro-services). Then I started thinking "outside the box" (outside for me, at least).

Why do I bother with dispatcher, commands, and command handlers? Now that my framework is only a networking layer over my bounded context, why not let my controllers be my command handlers? Why not let my dispatcher be the routing system in my framework? Why not let the content of the HTTP request be my command?

答:
Well.. main idea of CQRS to separate read and write operations. You might use of this pattern for one main reason,

The change that CQRS introduces is to split that conceptual model into
  separate models for update and display - Martin Fowler

So if you have two of these models to maintain, it would be very hard not to use commands, command handlers and so on.

But since you think you can get rid of those and move the logic to controllers (of course not the domain logic), then probably you are not actually using CQRS, and probably you should not use it if you don't need to.


问:
How to plan your software project if you are work depend on required deliverable with unexpected delivery date
I have worked for many software projects where I am developing software solution to the customer where I need to integrate with the customer back-end using web service provided by the customer in order to retrieve information, etc...

The problem is the customer might not deliver the required web service on time. Or might deliver web service in a different sequence than the plan.

My question is how to plan the project so that my coding and implementation will start according to the delivered required web services? Should I consider using agile? an how to use it in that case?

And how to deal with the risk of the delaying from customer?

The solution can be divided into phases and might be delivered based on the readiness of the web service.

Suppose I require 16 web service. If the customer deliver three now  I can implement part of the project and go live with it. After if customer develop another two web service I can be ready to implement another part of the project. and so on
How to put that in the plan structure ?

答:
Well... this happens all the time, and going agile is not going to fix the issue, rather you could get the web service definitions / contracts finalized. At this point you could actually start to build your system with mocking of the client web service using some tool like SOAPUI.

Once the customer service is up and running, you can actually test it. Of course this is not the ideal solution but, if you do not have any other things that can be done during this period, this may actually save some time.


答: You could block the user IP address after few attempts within certain period of time (say if certain IP address sends 10 requests over 1 minutes, then block the IP for 10 minutes.</p>

Title: How to protect controller endpoint from abuse?

Body:
I am building a web app that will first validate a promotion code via AJAX call and then if it is valid, allow the user to fill out the rest of the form, I use KnockoutJS to reveal and hide the elements.

My issue is, what is stopping a sneaky user from building a code generator and pumping the codes into my ajax endpoint until he gets a valid code? What is the recommended way of stopping this abuse?

PS: In the final step of the form I also validate the promotion code server-side just in case.


答:
You could use something like this,

Define a rule class where the regex expression to detect the tag is specified, and loop through expressions and insert html where necessary.

```<code>class Rule
{
    string tagRegEx;
    string htmlToInsert;
}

public string Process(string html,List<Rule> rules)
{
    //for each rule, check for regex matches and insert the htmlToInsert after
    return html;
}
</code>```

Another approach is to use a HTML parser, and use the it's inbuilt function to find nodes and insert your html after them.

Title: What algorithm should I use for a lot of if else(s)?

Body:
I have to implement a lot of if else statements and I'm thinking of using Decision Tree but I'm not sure if it's going to be the right algorithm.

I don't want to insert a piece of html code based on these conditions.

directly after an iframe embed (same 300 character rule as columns 4 and 5)
directly after a heading tag (same 300 character rule as columns 4 and 5)
directly after a facebook embed
directly after a twitter embed
directly after a vine embed
directly after an instagram embed
directly after any Oembed
directly after an image
directly after a video
directly after a gallery
directly after a protected iframe

So I will scan the whole content of my HTML and try not to add an Ad based on those conditions. The rules will grow as well that's why I don't want to use if else(s).

If I'm missing anything please let me know I will provide more context.

Thanks.

Body:
You could use something like this,

Define a rule class where the regex expression to detect the tag is specified, and loop through expressions and insert html where necessary.

class Rule
{
    string tagRegEx;
    string htmlToInsert;
}

public string Process(string html,List<Rule> rules)
{
    //for each rule, check for regex matches and insert the htmlToInsert after
    return html;
}

Another approach is to use a HTML parser, and use the it's inbuilt function to find nodes and insert your html after them.


问:
What do you call an iterator that returns the current, previous and next siblings of each node of a list?
What do you call an iterator that given a list [a, b, c], returns an object of the form { prev, curr, next } for each iteration?

e.g, (? === undefined)

```<code>{ prev: ?, curr: a, next: b }
{ prev: a, curr: b, next: c }
{ prev: b, curr: c, next: ? }
</code>```

I thought tuples, but I am used to think that a tuple is usually a 2-item list so I am undecided.

EDIT: Triples could work, but I was also wondering if there is any mention of this type of structures in the literature. I am familiar with linked lists, but this is different.

EDIT 2: Here is the generator implementation in JavaScript.

```<code>  /**
    @syntax
    Parsec.prototype.tuples([a, b, c])
      { prev: ?, curr: a, next: b }
      { prev: a, curr: b, next: c }
      { prev: b, curr: c, next: ? }
    @param {Array|String} list List to iterate.
    @param {Object} [last] Define to use as the last value.
    @param {Object} [prev] Define to use as the first prev value.
    @param {Object} [curr] Define to use as the first curr value.
  */
  function* tuples(list, last, prev, curr) {
    for (let next of list) {
      if (curr !== undefined) yield { prev, curr, next /* add last here? */}
      prev = curr
      curr = next
    }
    yield { prev, curr, last }
  }
</code>```

答:
Well this seems like a theory question on algorithms and datastructures.

As for the datastructure, if you want to return the three results at once, of course you need to put them into one datastructure, and of course that would make it a triple.
Without a given syntax it's hard to give an answer and the question seems not properly stated, I feel the question is also how to calculate previous and next, and for this I would say something like:

```<code>curry = this;
prev = this;
next = this;
prev —-;
next++;

if(pre <0) prev = undefined;
if (next >= length) next = undefined;
</code>```

As for the name of this kind of itertor, well as you already did I would call it triple or triplet, as it needs to store 3 values.

Body:
Well this seems like a theory question on algorithms and datastructures.

As for the datastructure, if you want to return the three results at once, of course you need to put them into one datastructure, and of course that would make it a triple.
Without a given syntax it's hard to give an answer and the question seems not properly stated, I feel the question is also how to calculate previous and next, and for this I would say something like:

curry = this;
prev = this;
next = this;
prev —-;
next++;

if(pre <0) prev = undefined;
if (next >= length) next = undefined;

As for the name of this kind of itertor, well as you already did I would call it triple or triplet, as it needs to store 3 values.


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
An example (IMHO) of a valid use:

```<code>printf("Success in %d %s\n", nr_of_tries, (nr_of_tries == 1 ? "try" : "tries"));
</code>```

This results in more readable code than having 2 distinct print statements.
Nested examples depend: (understandable ? yes : no)

Title: Ternary operator considered harmful?

Body:
An example (IMHO) of a valid use:

printf("Success in %d %s\n", nr_of_tries, (nr_of_tries == 1 ? "try" : "tries"));

This results in more readable code than having 2 distinct print statements.
Nested examples depend: (understandable ? yes : no)


答:
Apart from triple (which only means "we have three values") and node (which has been suggested by manlio), I can suggest the following alternatives:

Sliding window

It looks like you always have a window of three consecutives elements in the list. This is the most appropriate name IMHO according to your situation.

That structure does not allow to easily navigate the list in terms of prev, next pointers, however (maybe it is intentional).
If you want to navigate the data-structure, you might want to call it a node (like in doubly-linked lists, as manlio said) or a cursor, which is a slightly better name that conveys the iterative capabilities of the object.

Cursor

Iterators in Ada are built upon a so-called Cursor type, which encapsulates the position of an iterator inside a structure, along with Next and Previous operations.

See for example Gem #127 or the Rationale for Ada 2005.

Zipper

You question originally reminded me of Zippers which are construct  usually found with purely functional data-structures. They allow to iterate over a structure while keeping enough context to navigate it.

For example, a list zipper would contain the reversed list of previous elements (Prefix), Current element and the usual Tail list:

```<code>(Prefix,Current,Tail)
</code>```

It is easy to build a zipper for the next element in constant time:

```<code>(cons(Current,Prefix),head(Tail),tail(Tail))
</code>```

Or, a zipper for the previous element in constant time:

```<code>(tail(Prefix),head(Prefix),cons(Current,Tail))
</code>```

Of course, the cost of this approach is that you are manipulating two lists instead of one (during the lifetime of the iterator/zipper). Contrary to doubly-linked lists, you don't have to mutate your data-structures.

Your structure is clearly not a zipper, but it shared enough similarities with them that I thought it would be interesting to write about them.

Title: What do you call an iterator that returns the current, previous and next siblings of each node of a list?

Body:
What do you call an iterator that given a list [a, b, c], returns an object of the form { prev, curr, next } for each iteration?

e.g, (? === undefined)

```<code>{ prev: ?, curr: a, next: b }
{ prev: a, curr: b, next: c }
{ prev: b, curr: c, next: ? }
</code>```

I thought tuples, but I am used to think that a tuple is usually a 2-item list so I am undecided.

EDIT: Triples could work, but I was also wondering if there is any mention of this type of structures in the literature. I am familiar with linked lists, but this is different.

EDIT 2: Here is the generator implementation in JavaScript.

```<code>  /**
    @syntax
    Parsec.prototype.tuples([a, b, c])
      { prev: ?, curr: a, next: b }
      { prev: a, curr: b, next: c }
      { prev: b, curr: c, next: ? }
    @param {Array|String} list List to iterate.
    @param {Object} [last] Define to use as the last value.
    @param {Object} [prev] Define to use as the first prev value.
    @param {Object} [curr] Define to use as the first curr value.
  */
  function* tuples(list, last, prev, curr) {
    for (let next of list) {
      if (curr !== undefined) yield { prev, curr, next /* add last here? */}
      prev = curr
      curr = next
    }
    yield { prev, curr, last }
  }
</code>```

Body:
Apart from triple (which only means "we have three values") and node (which has been suggested by manlio), I can suggest the following alternatives:

Sliding window

It looks like you always have a window of three consecutives elements in the list. This is the most appropriate name IMHO according to your situation.

That structure does not allow to easily navigate the list in terms of prev, next pointers, however (maybe it is intentional).
If you want to navigate the data-structure, you might want to call it a node (like in doubly-linked lists, as manlio said) or a cursor, which is a slightly better name that conveys the iterative capabilities of the object.

Cursor

Iterators in Ada are built upon a so-called Cursor type, which encapsulates the position of an iterator inside a structure, along with Next and Previous operations.

See for example Gem #127 or the Rationale for Ada 2005.

Zipper

You question originally reminded me of Zippers which are construct  usually found with purely functional data-structures. They allow to iterate over a structure while keeping enough context to navigate it.

For example, a list zipper would contain the reversed list of previous elements (Prefix), Current element and the usual Tail list:

(Prefix,Current,Tail)

It is easy to build a zipper for the next element in constant time:

(cons(Current,Prefix),head(Tail),tail(Tail))

Or, a zipper for the previous element in constant time:

(tail(Prefix),head(Prefix),cons(Current,Tail))

Of course, the cost of this approach is that you are manipulating two lists instead of one (during the lifetime of the iterator/zipper). Contrary to doubly-linked lists, you don't have to mutate your data-structures.

Your structure is clearly not a zipper, but it shared enough similarities with them that I thought it would be interesting to write about them.


答:
A tuple is a finite sequence (ordered list) of elements. It's true in mathematics, relational databases and many languages (e.g. C++, Prolog, Python...).

So tuple could be a good name.

node is an alternative since an object of the form {prev, curr, next} remembers of a node of a doubly linked list.


答:
In Scala, this is called a sliding window:

```<code>Seq(1, 2, 3, 4, 5).sliding(2).foreach(println)
// List(1, 2)
// List(2, 3)
// List(3, 4)
// List(4, 5)
</code>```

As opposed to grouped when the elements don't overlap:

```<code>Seq(1, 2, 3, 4, 5).grouped(2).foreach(println)
// List(1, 2)
// List(3, 4)
// List(5)
</code>```

In Ruby, it is called cons:

```<code>[1, 2, 3, 4, 5].each_cons(2).to_a
# => [[1, 2], [2, 3], [3, 4], [4, 5]]
</code>```

and the other one is called slice:

```<code>[1, 2, 3, 4, 5].each_slice(2).to_a
# => [[1, 2], [3, 4], [5]]
</code>```

Note: in your case, the window starts before the first element and ends after the last, whereas in Ruby and Scala it starts at the first element and ends at the last, but that's just an arbitrary API design choice, and probably shouldn't affect the name.

I think "cons" (for "consecutive") is an unfortunate choice of name, because it clashes with the well-established term "cons" for "construct", as in Lisp and other functional languages. I like "sliding window" or "sliding view" much better.

Body:
In Scala, this is called a sliding window:

Seq(1, 2, 3, 4, 5).sliding(2).foreach(println)
// List(1, 2)
// List(2, 3)
// List(3, 4)
// List(4, 5)

As opposed to grouped when the elements don't overlap:

Seq(1, 2, 3, 4, 5).grouped(2).foreach(println)
// List(1, 2)
// List(3, 4)
// List(5)

In Ruby, it is called cons:

[1, 2, 3, 4, 5].each_cons(2).to_a
# => [[1, 2], [2, 3], [3, 4], [4, 5]]

and the other one is called slice:

[1, 2, 3, 4, 5].each_slice(2).to_a
# => [[1, 2], [3, 4], [5]]

Note: in your case, the window starts before the first element and ends after the last, whereas in Ruby and Scala it starts at the first element and ends at the last, but that's just an arbitrary API design choice, and probably shouldn't affect the name.

I think "cons" (for "consecutive") is an unfortunate choice of name, because it clashes with the well-established term "cons" for "construct", as in Lisp and other functional languages. I like "sliding window" or "sliding view" much better.


问:
Testing binary stream
I am building a binary file importer using Python. The specific file structure is defined in a specification. This looks like:

File

Map Block

String, Short Integer, Long Integer, String, Short Integer, Long Integer...

Block1

String, String, Long Integer, String, Short Integer, String, Long Integer, Long Integer....

Block2

Block3

etc

I have proved the concept of collecting and decoding the binary data and I can access each block of data individually by collecting the Map Block first.

However I can't figure out the best way to Test it.
The current tests I have are:
test_get_string
test_get_short
test_get_long

Can you suggest what suite of tests I might build next?
Would I be best testing with an actual file or create long binary strings to test with?

答:
The purpose of your implementation is to get comething decoded. It's not to move data from disk to memory, that is just an incidental auxiliary function. Therefore, your code should be decoupled so that the importer works with a stream, and in practice it should be coupled to a standard file-reading implementation (preferably from the standard library).

Similarly, your unit test should test the decoding logic, not the file I/O - I should hope that that has been tested with the standard library, and anyway it's not your concern. Therefore, testing with handcrafted input data, without touching the file system, is both faster and better according to sound software engineering principles.

Title: Testing binary stream


答:
If you work with a stream to import (as suggested by Killian) then you can test each of the functions to get individual values by mocking that stream. Mocking the stream means that you setup the next few bytes before calling the to be tested function and let the test fail when it requests more than the needed number of bytes. After the function all those bytes should have been read.

Part of the correctness assertion would be that it doesn't read more or less than the amount of bytes it needs to decode and the correctness of the value.

You can also test getting each block individually again with ensuring it only reads exactly as many bytes it needs and correctness of the read in values.

For testing the map block decoding you can construct one and then query the offsets of some blocks using that map block.

Title: Testing binary stream

Body:
I am building a binary file importer using Python. The specific file structure is defined in a specification. This looks like:

File

Map Block

String, Short Integer, Long Integer, String, Short Integer, Long Integer...

Block1

String, String, Long Integer, String, Short Integer, String, Long Integer, Long Integer....

Block2

Block3

etc

I have proved the concept of collecting and decoding the binary data and I can access each block of data individually by collecting the Map Block first.

However I can't figure out the best way to Test it.
The current tests I have are:
test_get_string
test_get_short
test_get_long

Can you suggest what suite of tests I might build next?
Would I be best testing with an actual file or create long binary strings to test with?


问:
Design method to return List of objects
I need to create a method which will return a List of IRule objects.

This is what I have written, am I correct in the approach? Or should I follow any patterns/principles?

```<code>public IList<IRule> GetRules()
{
    return new List<IRule> {
         new Rule1(),
         new Rule2(),
         ...etc
     }
}
</code>```

答:
Why not use yield?

```<code> public System.Collections.Generic.IEnumerable<IRule> GetRules()
 {

      yield return new Rule1(new Writer1());
      yield return new Rule2(new Writer2());
      //...etc

 }
</code>```

The user of the function will decide if they want all the rules at once or to get them lazily.

Update

The other solutions have mentioned caching - if you need/want caching, this solution won't work.

Title: Design method to return List of objects

Body:
Why not use yield?

 public System.Collections.Generic.IEnumerable<IRule> GetRules()
 {

      yield return new Rule1(new Writer1());
      yield return new Rule2(new Writer2());
      //...etc

 }

The user of the function will decide if they want all the rules at once or to get them lazily.

Update

The other solutions have mentioned caching - if you need/want caching, this solution won't work.