答:
Is this how long they usually are, or do they depend on the size of the development team?

No. In my experience, they're either <10 minutes for a manageable team or like 30 minutes because the team is too large or there's nobody (good) in charge. Once you get over 10 minutes, people get antsy and stop listening.

Must every team member speak in these?

Yes. If they didn't do anything worth speaking about, they shouldn't be in the scrum - either because they belong on another team (stop wasting their time), or because they need to be fired (stop wasting your time).


问:
How-To: a browser based, real time, shared memory inspection/debugger application

Background:

I have a C application running under Linux utilizing shared memory. I also have a debugger written in Python that can link to said shared memory and access individual variable values of global scope.

Question:

How can I develop a local browser-based application/page that, via my Python process, I can connect with in order to display near real-time variable values in a prettified form?

Usage:

I should be able to launch my background applications, then launch this server/client application in a browser, then be given an option to load a page with list of variables names (2-way communication), after which it simply should start displaying all the names with their values.

What I need:

Technical, process-flow solution, that utilizes solely Python if possible (understanding html/css/js/etc are necessary), and provides the ability to update the browser page's list of values automatically at >= 20Hz.

Additional details:

It needs to update the page between 20-60Hz, preferably in order (e.g. 'time' may be a value and want to update as 1.3 -> 1.4 -> 1.5...

Only needs to work with Firefox

Linux-only development, don't care about Windows or Mac

I don't want to use a real GUI app like QT/WX/GTK

答:
The concept of a local web app is a good and appropriate one. I have built several of these, and they work well. They have very fast update times, and let me work with Web tools rather than the declining breed of GUI toolkits.

I recommend a WebSocket-based connection between your Python code and your web page/client/app. This will give you near-real-time update speed and the ability to communicate bi-directionally between Python and a JavaScript-based front-end/app. You can use whatever JavaScript frameworks or widgets you like. There are some quite good graphing, plotting, and visualization frameworks for web apps these days--some better than what you typically see in GUIs, even.

There are an increasing number of ways to integrate WebSockets and Python. I prefer the Flask web app framework for its combination of simplicity and generality. You can run it natively (it has a built-in web server), atop Tornado, behind a real web server, etc. For a local app, you may want to review this simple demo which requires no extra middleware.

ContentLicense: CC BY-SA 3.0


问:
instance methods, stack or heap
Do methods (and their variables) that belong to an object instance go on the stack or the heap?

Ex

```<code>Main()
{
Myclass Myobj = new Myclass();
Myobj.Doit();
}

class Myclass
{
 Void Doit()
 {
 Int myint = 5;
 }
}
</code>```

I use c# primarily, but I assume the answer is language agnostic.

答:
In C# memory management is an implementation detail. There is no guarantee whatsoever where your objects will go.

There isn't even the guarantee that a 'stack' even exists in the operating system running it.

Don't base any logic on it.

The article where I have my knowledge from:

Link

Title: instance methods, stack or heap

ContentLicense: CC BY-SA 4.0


问:
I'm graduating with a Computer Science degree but I don't feel like I know how to program
I'm graduating with a Computer Science degree but I see websites like Stack Overflow and search engines like Google and don't know where I'd even begin to write something like that. During one summer I did have the opportunity to work as a iPhone developer, but I felt like I was mostly gluing together libraries that other people had written with little understanding of the mechanics happening beneath the hood.

I'm trying to improve my knowledge by studying algorithms, but it is a long and painful process. I find algorithms difficult and at the rate I am learning a decade will have passed before I will master the material in the book. Given my current situation, I've spent a month looking for work but my skills (C, Python, Objective-C) are relatively shallow and are not so desirable in the local market, where C#, Java, and web development are much higher in demand. That is not to say that C and Python opportunities do not exist but they tend to demand 3+ years of experience I do not have. My GPA is OK (3.0) but it's not high enough to apply to the large companies like IBM or return for graduate studies.

Basically I'm graduating with a Computer Science degree but I don't feel like I've learned how to program. I thought that joining a company and programming full-time would give me a chance to develop my skills and learn from those more experienced than myself, but I'm struggling to find work and am starting to get really frustrated.

I am going to cast my net wider and look beyond the city I've grown up in, but what have other people in similar situation tried to do? I've worked hard but don't have the confidence to go out on my own and write my own app. (That is, become an indie developer in the iPhone app market.) If nothing turns up I will need to consider upgrading and learning more popular skills or try something marginally related like IT, but given all the effort I've put in that feels like copping out.

答:
Nobody graduates as an expert and that's true for anything, not just programming. You study to know the basics but by working is how you gain real competence. You might become an expert programmer if you do it from 3 to 10 years. In few months you can expect to be able to do something useful. There's no rush and it's a slow process for anyone, so don't worry about it.

In my opinion you really can't demand newbies to spend all their time learning at home. Of course it can speed things up, increase your value and make you more confident, but only if you want to. Otherwise I'd be happy to learn at work.

ContentLicense: CC BY-SA 2.5


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
From my Java-centric perspective:

Non-standard coding style.

Non-private variables.

Missing final on fields.

Pointless or overuse of inheritance.

Huge classes or blocks of code.

Too many comments (they're probably just wishful thinking anyway).

Unstructured logging.

Getters and setters (interfaces should be about behaviour).

Duplicated data.

Strange dependencies.

Statics, including thread-globals.

For multi-threaded code, parts of the same class that are expected to be run in different threads (notably GUI code).

Dead code.

String manipulation mixed in with other code.

Generally mixing layers (higher level stuff, combined with iterating over an array of primitives or thread-handling, say).

Any use of reflection.

catch blocks without useful code (bad: comments, printf, logging or just empty).


答:
In general, program code exists in an area outside of what you mean when you say "stack" and "heap." While you mentioned C#, there are no language tags so I will describe how a typical modern desktop OS handles this at a low level.

When your program loads, there are two main areas of memory: code and data. The OS allocates enough memory to load the program, which contains the executable code, static data (e.g. constants), and whatever bootstrap code the compiler includes (something has to call main).

In this sense the code is on a heap, simply because everything is heap allocated from the perspective of the OS. However, from the vantage point of your program, it is outside your program's stack and heap. You cannot allocate memory in either location and put code in it, generally (exception: next paragraph).

Some languages allow eval or exec calls where a variable is executed as code, which could include a function and a call to that function. In that sense the code could exist in the stack or heap, although the details are abstracted away most of the time in languages that allow that (e.g. Perl or PHP). It is difficult to impossible to know for sure where the code resides in this case.

This separation of code away from the data segment (and therefor the heap and stack) is only becoming stronger as newer CPUs have hardware-level support for forbidding execution of code from the data segment. The idea is to help neutralize viruses which depend on that to modify running code and therefor spread and evade detection. If a program is subject to the execute flag protection, code cannot be run from the data (stack and heap) part of memory.

Title: instance methods, stack or heap

Body:
Do methods (and their variables) that belong to an object instance go on the stack or the heap?

Ex

```<code>Main()
{
Myclass Myobj = new Myclass();
Myobj.Doit();
}

class Myclass
{
 Void Doit()
 {
 Int myint = 5;
 }
}
</code>```

I use c# primarily, but I assume the answer is language agnostic.


问:
Efficient database access for related data
As an example for this question, consider a content management system that has a content database table which contains things like the page title and location as well as the content itself which could be quite a large amount of text. There is a second database table with details of resources (such as images and files) that are associated with a content item. Each page in the content management system may have one or many content items, each with it's own resources.

At present I am retrieving a list of content items and then for each content item doing a second query to retrieve the list of related resources. On a page with 10 content items, this means 11 queries.

I could do a join and retrieve all content and related resources in one query, but it concerns me that where there are multiple resources for a content item, the content item will be duplicated and, because the content item might be large, this might be very inefficient with so much duplicate data.

Another option is to have a stored procedure that returns two recordsets. The first recordset contains the content, and the second recordset contains the related resources for all of the content items in the first recordset, which is separated out by the receiving server.

So the question is what is generally the most efficient way to retrieve data in this situation?

I know that performance testing is often the answer but for this question I was looking for best practise type advice or alternatives that I may not have thought of.

答: For related sets of information like this a single "jumbo" call to the DB server is preferable.  Although the total data returned is the same as for 11 individual calls, all those network packets, connection set up and lock management add up over time.</p>


答:
The CLR standard does not require a stack or a heap, so lets get that out of the way first. But C# implemented on paper isn't very useful. I describe here the implementations we can run code with "in practice", like the Microsoft C# or Mono C#. Regardless, the method and local variables have a conceptual relationship with classes and object instances that you have to understand, because it isn't specific to C#, it is the same for computer languages in general.

Instance methods are stored in the same way that static methods are.

Methods are part of the code (in CLR, bytecode), they are compiled instructions, low level CLR opcodes that make up the assembly. So in the C# model they aren't part of a heap, the heap is for data. (See caveat footnote at bottom). In languages that aren't object oriented, there are plain functions. In those languages, the functions are just code that receives arguments. In CLR a plain function is a static method (or class method). The only difference in a function and a method is that syntactic sugar makes the function appear to be owned, but its object is really just the first "implicit" argument (this), and in most languages it comes before the method call, ie. obj.Foo(). The first argument to the function must still be loaded by an instruction; in CLR MSIL, this is loaded by ldarg.0 except in the case of a static method. So obj.Foo(arg) is equivalent to Foo(obj,arg).

When you compile a class, the compiler emits a set of instructions that represent the method and packs it into a code segment.

The relationship of the method to the object is actually similar to the relationship of class to object. The method is part of the class (ie part of the type, not part of the object. The method is akin to static data, but the "method data" happens to be code. Like static fields, the methods exist prior to and without any existence of an object instance and are just part of the object's type. I might have 1,000,000 instances of a string, but there is a single copy of string::Concat(string) somewhere.

As far as a method's local variables, they do not exist until the method is called. At the beginning of a CLR method, the call frame assures space for all local variables in that method. They are known ahead of time, but are simply formal notation until the method runs, then they become real data addresses. An instruction tells the CLR how much space to allocate. Local variable values are conceptually and practically on the stack, yet mapped to registers. The variables are "local" to the scope of the method, and go away when the method returns (though the objects they refer may not). There are instructions for dealing with them in CLR. Lets look at a rough sample of MSIL (IL assembly for CLR) for your DoIt() method.

```<code>.method void MyClass::Doit()
{
    .locals init([0]int myint)   // declares the locals for the method
    ldc.i4.5
    stloc 'myint'                // initialize myint to 0
    ret
}
</code>```

Locals are aggressively mapped to real CPU registers by the JIT compiler so they mostly exist on a stack when CLR is interpreting or verifying bytecode. In practice, locals exist in registers, but spill over to a stack on the low level hardware.

Finally, for any computer language, there are 3 primary groups of syntax.

Type declarations and definitions (formal ideas, compiler enforced, and metadata)

Algorithmic (code, methods, statements, expressions)

Data and variables (data)

Caveat: Runtime systems are commonly implemented in C or C++. A CLR assembly and its methods are loaded into the runtime heap of the host language used to write the CLR. But conceptually that is a different heap than the "heap" you are accessing within the CLR.

Title: instance methods, stack or heap

Body:
The CLR standard does not require a stack or a heap, so lets get that out of the way first. But C# implemented on paper isn't very useful. I describe here the implementations we can run code with "in practice", like the Microsoft C# or Mono C#. Regardless, the method and local variables have a conceptual relationship with classes and object instances that you have to understand, because it isn't specific to C#, it is the same for computer languages in general.

Instance methods are stored in the same way that static methods are.

Methods are part of the code (in CLR, bytecode), they are compiled instructions, low level CLR opcodes that make up the assembly. So in the C# model they aren't part of a heap, the heap is for data. (See caveat footnote at bottom). In languages that aren't object oriented, there are plain functions. In those languages, the functions are just code that receives arguments. In CLR a plain function is a static method (or class method). The only difference in a function and a method is that syntactic sugar makes the function appear to be owned, but its object is really just the first "implicit" argument (this), and in most languages it comes before the method call, ie. obj.Foo(). The first argument to the function must still be loaded by an instruction; in CLR MSIL, this is loaded by ldarg.0 except in the case of a static method. So obj.Foo(arg) is equivalent to Foo(obj,arg).

When you compile a class, the compiler emits a set of instructions that represent the method and packs it into a code segment.

The relationship of the method to the object is actually similar to the relationship of class to object. The method is part of the class (ie part of the type, not part of the object. The method is akin to static data, but the "method data" happens to be code. Like static fields, the methods exist prior to and without any existence of an object instance and are just part of the object's type. I might have 1,000,000 instances of a string, but there is a single copy of string::Concat(string) somewhere.

As far as a method's local variables, they do not exist until the method is called. At the beginning of a CLR method, the call frame assures space for all local variables in that method. They are known ahead of time, but are simply formal notation until the method runs, then they become real data addresses. An instruction tells the CLR how much space to allocate. Local variable values are conceptually and practically on the stack, yet mapped to registers. The variables are "local" to the scope of the method, and go away when the method returns (though the objects they refer may not). There are instructions for dealing with them in CLR. Lets look at a rough sample of MSIL (IL assembly for CLR) for your DoIt() method.

.method void MyClass::Doit()
{
    .locals init([0]int myint)   // declares the locals for the method
    ldc.i4.5
    stloc 'myint'                // initialize myint to 0
    ret
}

Locals are aggressively mapped to real CPU registers by the JIT compiler so they mostly exist on a stack when CLR is interpreting or verifying bytecode. In practice, locals exist in registers, but spill over to a stack on the low level hardware.

Finally, for any computer language, there are 3 primary groups of syntax.

Type declarations and definitions (formal ideas, compiler enforced, and metadata)

Algorithmic (code, methods, statements, expressions)

Data and variables (data)

Caveat: Runtime systems are commonly implemented in C or C++. A CLR assembly and its methods are loaded into the runtime heap of the host language used to write the CLR. But conceptually that is a different heap than the "heap" you are accessing within the CLR.


问:
Why are floating point numbers used often in Science/Engineering?
While investigating the accuracy of floating point numbers, I've seen in a few places a statement similar to

"float and double are (designed for/used often in) engineering and scientific calculation"

From my understanding, the strength of floats and doubles are the amount of memory they use for their (good, but not perfect) precision.

I feel like I'm almost getting an understanding from this answer

"floating point numbers let you model continuous quantities"

I still am not convinced I understand. Engineering and Science both sound like fields where you would want precise results from your calculations, which, from my understanding, floating points do not give. I'm also not sure I follow what a "continuous quantity" is, exactly.

Can somebody expand on this explanation and perhaps give an example?

答:
What alternative do you propose?

Continuous quantities are represented using real numbers in mathematics.  There is no data type that can encode every possible real number (because reals are uncountable), so that means we can only pick a subset of those real numbers that we're most interested in.

You can pick all computable reals, which is similar to what computer algebra systems (CAS) do.  The problem is that it becomes rapidly unfeasible as your expression tree grows larger and larger.  It's also very slow: try solving a huge system of differential equations in Mathematica symbolically and compare against some other floating-point based implementation and you'll see a dramatic difference in speed.  Additionally, as Jörg W Mittag and kasperd have pointed out: you don't even have decidable equality/comparison operations.

You could use exact rational numbers, but that doesn't really work for many applications because you need to calculate square roots or cosines or logarithms etc.  Furthermore, there is also a tendency for rationals to become increasingly complex and thus requiring more space to store and time to process as you perform more and more calculations on them.

You could also use arbitrary-precision decimals, but then even something as simple as division won't work because you get infinitely repeating digits.  You can also run into the issue of increasing complexity as you perform more similar to rational numbers, though to a lesser extent.

So you'd be forced to use approximations at some point, in which case that's exactly where floating-point numbers do best.  Floating-point numbers are also of fixed width (unlike all the other 3 data types mentioned earlier), which prevents the complexity increase as you perform more and more calculations on them.


答:
You might use an HTTP server library like libonion (or perhaps Wt), perhaps even in your C application, and use AJAX techniques (perhaps with Jquery) -and perhaps WebSocket- to periodically update the dynamic web page. FWIW, my MELT monitor is doing this.

Notice that web technology cannot guarantee any update frequency, in particular in the event of long latency (imagine the browser being in Australia, and your C application running in the middle of the USA with a bad internet connection between them). But if both the HTTP server program (e.g. your C application using libonion) and the browser are near (on the same LAN) you probably would be able to get 20Hz updates.

In my view, you might not need any Python or PHP code (by adding HTTP server ability in your C application with libonion). However, you need to become familiar with web technologies (HTML5, Javascript, DOM) and HTTP. For that w3schools -and other websites- is not perfect but has a lot of useful information.

If for whatever reason you still need to have a separate Python process, I'm sure you would be able to find Python HTTP server libraries.

Title: How-To: a browser based, real time, shared memory inspection/debugger application

Body:
Background:

I have a C application running under Linux utilizing shared memory. I also have a debugger written in Python that can link to said shared memory and access individual variable values of global scope.

Question:

How can I develop a local browser-based application/page that, via my Python process, I can connect with in order to display near real-time variable values in a prettified form?

Usage:

I should be able to launch my background applications, then launch this server/client application in a browser, then be given an option to load a page with list of variables names (2-way communication), after which it simply should start displaying all the names with their values.

What I need:

Technical, process-flow solution, that utilizes solely Python if possible (understanding html/css/js/etc are necessary), and provides the ability to update the browser page's list of values automatically at >= 20Hz.

Additional details:

It needs to update the page between 20-60Hz, preferably in order (e.g. 'time' may be a value and want to update as 1.3 -> 1.4 -> 1.5...

Only needs to work with Firefox

Linux-only development, don't care about Windows or Mac

I don't want to use a real GUI app like QT/WX/GTK


问:
Using streams as method parameters and/or return types
So let's say I have a 'Transformer' interface that can transform one file-type to another. Let's say I also wish to use streams to provide the data to the Transformer. Which is the approach that is considered 'best practise';

```<code>public InputStream transform(InputStream data);
</code>```

OR

```<code>public void transform(InputStream originalData, OutputStream newData);
</code>```

Although the first method seems to be slightly more concise to me (ie, you get an inputstream that you can consume immediately) it seems to violate the whole 'creator of a stream should be the one who closes it' principle.

The second method, whilst needing a bit more work on the part of the client to handle the outputstream, seems like it might be more useful in some cases (ie, passing a ServletOutputStream as the 'newData' argument) and the client code will handle all opening/closing of streams.

I am leaning towards the second method but I have seen both used in various APIs I have come across and am wondering if there are situations where one would be preferred over the other?

答:
Generally speaking, using output parameters is considered bad practice. After all, the return value is meant to be the result of the computation that the function performs. The parameters are supposed to be the inputs for that computation and exporting the result through a parameter is just semantically wrong.

I found a more detailed answer on StackOverflow. The question there is about c# but the answer applies to other programming languages too.

If you want an answer more specific to your problem, please post the body of your methods.


问:
A "Composite API" layer
We are giving services a complete overhaul at work: Swapping soap for rest, resculpting the domains to give better separation of concerns, etc.

These new services will be publicly available. During one of our on-going conversations to refine our architectural vision, the idea of a "Composite API" was introduced. I am hoping to get some community feedback regarding the validity of this approach. I will list the pros and cons as I understand them. Disclaimer: I am no SOA expert

Pros

Clients will received fully hydrated objects instead of having to make multiple service calls to compose something useful

A&A is isolated to one place and does not need to muddy service behavior

Cons (again, this is purely my understanding).

Composed resources obscure the security of individual resources

Requesting an individual child resource might return a 403, but requesting a parent resource returns a 200 with content and is missing parts of the data. While this may be acceptable client-side, I feel it's a bit or a risk server-side. Developers will have to maintain the security of the individual resources in one way, and the security of composed resources in another.

After reading Martin Fowler's article on microservices, I do think the domain service should govern the actual write, but this doesn't necessarily contradict the API gateway.

Complicated reads/writes based on user role

Basically, we may serve some info on a dto that some users should not see. Serving the id is not an issue, but serving the object that the id represents is. Of course, the composite api could simply not serve the object, but that's when the real problem comes. The back-end service no longer cares who the user is, only that the dto contains all necessary information to complete a write successfully. If we naively send null for a field because the client didn't have it, we'd blow away valid data. This means the composite layer must somehow fetch the existing object and merge with the pending request to make sure the appropriate writes happen. If we control what fields are updated within the respective service, it's as simple as not changing the field before writing to the database. If not, it seems like a lot more work.

Positing the API gateway leaves 2 options:

Let the composite api construct the aggregated response

Allow each domain service to construct a fully hydrated response, but only accept trimmed requests.

Option 1 does seem to be the least amount of code.

Consolidated A&A, not quite

For better or worse, we still have audit fields on a lot of tables. This means we need to include the username on an UpdatedBy field. Because the payload may have many entities on it and because we don't care about the audit fields client-side, we left them off the service DTOs. Instead, we are now passing custom headers into each service that contains the userId, username, and potentially the user roles. When the request hits the client, we convert those headers into something that will be available in the code block where we are creating/updating the domain models. I feel like there are plenty of plugins for various frameworks and platforms do this for us if we change our services to rely on an auth protocol, namely OAuth. Internally users/apps, and external users/apps should hit a common auth provider, get a token, and consume services as allowed. This makes each service responsible for controlling how a write should happen, which I kinda think is best place for that logic.

While passing the header works when there is a header, it doesn't work so well when there isn't. Say we have a backend service that needs to call a domain service. We could leverage the same authentication protocol a user would have, which isn't bad. Now say that backend service is doing work on a user's behalf. How would we distinguish the service acting on its own from the service acting on a behalf of a user? Perhaps it's best to keep the domain services behind the API gateway for external use and allow backend services to use custom headers to simulate who the user was.

Payload size

The client will have to fetch all of the data either way, but does it really need to write it all back? Why can't we just send ids?

It can send back the ids. The domain service will expect that, and the API gateway will act as a reverse proxy in that sense.

Domain ambiguity

If a client receives a composed object within one request, they get the impression they can put the resource back with modifications anywhere, even if some of those parts came from some other domain. Responding with ids only removes this ambiguity.

Concurrency

We'd have to expose data versions on the DTOs, and potentially versions on parts of the DTOs, hope for a good write, relay a failure back to the client, and determine which part of the transaction failed. Granted, this is true with any transactional write where "last in wins" is unacceptable. I think it just exacerbates the problem.

Service versioning requires more coupling

For mobile clients, service versioning is a big deal, so we'll already have service versioning. With a composite api, we now need to support versioning in a third place. Not the worst thing ever, but still, I'd rather not.

Strongly-typed clients may require more work to adapt

Consider the relationship between a lookup object and a hydrated dto that is composed with that lookup object. When the lookup object changes server-side, it will have to change in two places client-side, once on the lookup, and once on the hydrated object. If we choose not to compose them, the client only needs to send back ids to the server.

Why not just introduce an ESB

If we really need this, why not use an existing product instead of writing another service that is coupled to all the other services?

It looks like the API gateway is between the client and domain services, whereas an ESB might not be. In a lot of ways they are very similar. I'm still comparing the two.

I poured it on a little at the end, but I think these are all valid concerns. Anyway, I'd like to get a lot of feedback on this.

I finally found some documenation:

Microservices.io: API Gateway Pattern

Optimizing the Netflix API

答:
As for this part:

Clients will received fully hydrated objects instead of having to make
  multiple service calls to compose something useful

Take a look at this nice article: Best Practices for Designing a Pragmatic RESTful API. It contains some nice pieces of wisdom, one of them is the suggestion to give API clients the ability to decide how much information is returned in each call, by using an embed parameter in the query string that contains a comma separated list of the dependend entities that should be returned. For example: GET customers/1234?embed=invoices,messages.

This way you let the client to decide whether it wants to performs many small queries to your API or just a single big one.

Title: A "Composite API" layer


问:
Model relationships with DDD (or with sense)?
Here is a simplified requirement:

User creates a Question with multiple Answers. Question must have at least one Answer.

Clarification: think Question and Answer as in a test: there is one question, but several answers, where few may be correct. User is the actor who is preparing this test, hence he creates question and answers.

I am trying to model this simple example so to 1) match the real life model 2) to be expressive with the code, so to minimize potential misuse and errors, and to give hints to developers how to use the model.

Question is an entity, while answer is value object. Question holds answers. So far, I have these possible solutions.

[A] Factory inside Question

Instead of creating Answer manually, we can call:

```<code>Answer answer = question.createAnswer()
answer.setText("");
...
</code>```

That will create an answer and add it to the question. Then we can manipulate answer by setting it's properties. This way, only questions can crete an answer. Also, we prevent to have an answer without a question. Yet, we do not have control over creating answers, as that is hardcoded in the Question.

There is also one problem with the 'language' of above code. User is the one who creates answers, not the question. Personally, I don't like we create value object and depending on developer to fill it with values - how he can be sure what is required to add?

[B] Factory inside Question, take #2

Some says we should have this kind of method in Question:

```<code>question.addAnswer(String answer, boolean correct, int level....);
</code>```

Similar to above solution, this method takes mandatory data for the answer and creates one that will be also added to the question.

Problem here is that we duplicate the constructor of the Answer for no good reason. Also, does question really creates an answer?

[C] Constructor dependencies

Let's be free to create both objects by our selves. Let's also express the dependency right in constructor:

```<code>Question q = new Question(...);
Answer a = new Answer(q, ...);   // answer can't exist without a question
</code>```

This gives hints to developer, as answer can't be created without a question. However, we do not see the 'language' that says that answer is 'added' to the question. On the other hand, do we really need to see it?

[D] Constructor dependency, take #2

We can do the opposite:

```<code>Answer a1 = new Answer("",...);
Answer a2 = new Answer("",...);
Question q = new Question("", a1, a2);
</code>```

This is opposite situation of above. Here answers can exist without a question (which does not make sense), but question can not exist without answer (which make sense). Also, the 'language' here is more clear on that question will have the answers.

[E] Common way

This is what I call the common way, the first thing that ppl usually do:

```<code>Question q = new Question("",...);
Answer a = new Answer("",...);
q.addAnswer(a);
</code>```

which is 'loose' version of above two answers, since both answer and question may exist without each other. There is no special hint that you have to bind them together.

[F] Combined

Or should I combine C, D, E - to cover all the ways how relationship can be made, so to help developers to use whatever is best for them.

Question

I know people may choose one of the answers above based on the 'hunch'. But I wonder if any of above variant is better then the other with a good reason for that. Also, please don't think inside the above question, I would like to squeeze here some best practices that could be applied on most cases - and if you agree, most use cases of creation some entities are similar. Also, lets be technology agnostic here, eg. I do not want to think if ORM is going to be used or not. Just want good, expressive mode.

Any wisdom on this?

EDIT

Please ignore other properties of Question and Answer, they are not relevant for the question. I edited above text and changed the most of the constructors (where needed): now they accept any of necessary property values needed. That may be just a question string, or map of strings in different languages, statuses etc. - whatever properties are passed, they are not a focus for this ;) So just assume we are above passing necessary parameters, unless said different. Thanx!

答:
I would go either [C] or [E].

First, why not A and B? I don't want my Question be responsible for creating any related value. Imagine if Question has many other value objects - would you put create method for every one? Or if there are some complex aggregates, the same case.

Why not [D]? Because it is opposite to what we have in nature. We first do create a Question. You can imagine a web page where you create all this - user would first create a question, right? Therefore, not D.

[E] is KISS, like @Euphoric said. But I also start to like [C] recently. This is not so confusing as it seems. Moreover, imagine if Question depends on more things - then developer must to know what he needs to put inside the Question to have it properly initialized. Although you are right - there is no 'visual' language explaining that answer is actually added to the question.

Additional reading

Questions like this makes me wonder if our computer languages are too generic for modeling. (I understand they have to be generic to answer on all programming requirements). Recently I am trying to find a better way to express the business language using fluent interfaces. Something like this (in sudo language):

```<code>use(question).addAnswer(answer).storeToRepo();
</code>```

i.e. trying to move away from any big *Services and *Repository classes to smaller chunks of business logic. Just an idea.

Body:
I would go either [C] or [E].

First, why not A and B? I don't want my Question be responsible for creating any related value. Imagine if Question has many other value objects - would you put create method for every one? Or if there are some complex aggregates, the same case.

Why not [D]? Because it is opposite to what we have in nature. We first do create a Question. You can imagine a web page where you create all this - user would first create a question, right? Therefore, not D.

[E] is KISS, like @Euphoric said. But I also start to like [C] recently. This is not so confusing as it seems. Moreover, imagine if Question depends on more things - then developer must to know what he needs to put inside the Question to have it properly initialized. Although you are right - there is no 'visual' language explaining that answer is actually added to the question.

Additional reading

Questions like this makes me wonder if our computer languages are too generic for modeling. (I understand they have to be generic to answer on all programming requirements). Recently I am trying to find a better way to express the business language using fluent interfaces. Something like this (in sudo language):

use(question).addAnswer(answer).storeToRepo();

i.e. trying to move away from any big *Services and *Repository classes to smaller chunks of business logic. Just an idea.


问:
What was used to consume api's before webservices?
Most of the companies that offer public api these days do it through a web service. What was used before web services were popular? For example, if a company wanted to release a c# public api would it have release the dll files implementing a remote database connection? Or did they do something different from my assumption?</p>

答: Even today, the overwhelming majority of APIs are not webservices. The MS Word API, for example looked pretty much exactly like it does today both before and after webservices became popular.


答:
Because

1) The authors make the assumptions that "engineering and scientific calculation" measure real-world physical quantities

2) Physical quantities are continuous, and exactly as you state "floating point numbers let you model continuous quantities"

.. and the rest of my answer is summed up nicely by Rufflewind, so I'm not going to repeat that here.

Title: Why are floating point numbers used often in Science/Engineering?

Body:
While investigating the accuracy of floating point numbers, I've seen in a few places a statement similar to

"float and double are (designed for/used often in) engineering and scientific calculation"

From my understanding, the strength of floats and doubles are the amount of memory they use for their (good, but not perfect) precision.

I feel like I'm almost getting an understanding from this answer

"floating point numbers let you model continuous quantities"

I still am not convinced I understand. Engineering and Science both sound like fields where you would want precise results from your calculations, which, from my understanding, floating points do not give. I'm also not sure I follow what a "continuous quantity" is, exactly.

Can somebody expand on this explanation and perhaps give an example?


答:
There are a variety of ways that it could be done. First, don't blindly assume web services are a recent idea. The idea of putting a service for other computers to consume on a web server seems to have been invented multiple times, some quite early in the history of the web.

Other alternatives included defining a  protocol that could be used via a socket (my company did this for a service that one of our clients was considering launching in 1999), or publishing a dll (or, quite frequently, an ocx library) that implemented the api.

One alternative that became common in the world of stock quote provision is to provide an executable program that supplies data via the Windows DDE system. You can still get such systems today (e.g. from ADVFN).

Title: What was used to consume api's before webservices?

Body: Most of the companies that offer public api these days do it through a web service. What was used before web services were popular? For example, if a company wanted to release a c# public api would it have release the dll files implementing a remote database connection? Or did they do something different from my assumption?</p>


问:
Peer review for tests just like code reviews
Does anyone practice the "code review" process for functional tests? Do you find it useful? The way that my current employer practices SCRUM we include functional testing as part of our "must have done" stuff in any given sprint.</p>

答: It makes perfect sense to me.  Any code you write should be looked at by someone else, even if the code is only used internally and will never be run by the customer.</p>


答:
TL;DR We do not know how to compute most functions with perfect precision, there is therefore no point representing numbers with perfect precision.

All of the answers so far miss the most important point: we cannot compute exact values of most numbers. As an important special case, we cannot compute exact values of the exponential function — to cite only the most important irrational function.

Naive answer to the naive question

It seems your question is rather “there is exact arithmetic libraries, why don't we use them in place of floating point arithmetic?”  The answer is that exact arithmetic works on rational numbers and that:

Archimede's number — the pedantic name of π — is not rational.

Many other important constants are not rational.

Many other important constants are not even known to be rational or not.

For any non-zero rational number x the number exp(x) is irrational.

Similar statements hold for radicals, logarithms, and a wealth of functions important to scientists (Gauss's distribution, its CDF, Bessel functions, Euler functions, …).

The rational number is a lucky accident. Most numbers are not rational (see Baire's theorem) so computing on numbers will always bring us out of the rational world.

What is computing and representing a number?

We may react by saying “OK, the problem is that rational numbers were not such a great choice to represent real numbers.” Then we roll up our sleaves fork Debian and devise a new representation system for real numbers.

If we want to compute numbers we have to pick a representation system for real numbers and describe important operations on them — i.e. define what computing means. Since we are interested in scientific computing, we want to represent accurately all decimal numbers (our measures), their quotients (rational numbers), values of the exponential functions and some funny constants, like Archimede's number.

The problem is that the only way to perfectly represent numbers in such a system is to use symbolic form, that is, not to compute anything at all and work with algebraic expressions.  This is a rather crippled representation of real numbers, because we cannot reliably compare two numbers (which one is greater)? We cannot even easily answer the question “Is the given number equal to 0?”.

If you look for more precise mathematical definitions and problems, look for rational numbers, transcendental numbers, best approximations, and Baire's theorem, for instance.


答:
Updated. Clarifications taken into account.

Looks like this is a multiple choice domain, which usually has the following requirements

a question must have at least two choices so that you could choose among

there must be at least one correct choice

there should not be a choice without a question

Based on the above

[A] can't ensure the invariant from point 1, you may end up with a question without any choice

[B] has the same disadvantage as [A]

[C] has the same disadvantage as [A] and [B]

[D] is a valid approach, but it's better to pass the choices as a list rather than passing them individually

[E] has the same disadvantage as [A], [B] and [C]

Hence, I would go for [D] because it allows to ensure domain rules from points 1, 2 and 3 are followed. Even if you say that it's very unlikely for a question to remain without any choice for a long period of time, it's always a good idea to convey domain requirements through the code.

I would also rename the Answer to Choice as it makes more sense to me in this domain.

```<code>public class Choice implements ValueObject {

    private Question q;
    private final String txt;
    private final boolean isCorrect;
    private boolean isSelected = false;

    public Choice(String txt, boolean isCorrect) {
        // validate and assign
    }

    public void assignToQuestion(Question q) {
        this.q = q;
    }

    public void select() {
        isSelected = true;
    }

    public void unselect() {
        isSelected = false;
    }

    public boolean isSelected() {
        return isSelected;
    }
}

public class Question implements Entity {

    private final String txt;
    private final List<Choice> choices;

    public Question(String txt, List<Choice> choices) {
        // ensure requirements are met
        // 1. make sure there are more than 2 choices
        // 2. make sure at least 1 of the choices is correct
        // 3. assign each choice to this question
    }
}

Choice ch1 = new Choice("The sky", false);
Choice ch2 = new Choice("Ceiling", true);
List<Choice> choices = Arrays.asList(ch1, ch2);
Question q = new Question("What's up?", choices);
</code>```

A note. If you make the Question entity an aggregate root and the Choice value object a part of the same aggregate, there's no chances one can store a Choice without it being assigned to a Question (even though you don't pass a direct reference to the Question as an argument to the Choice's constructor), because the repositories work with roots only and once you build your Question you have all your choices assigned to it in the constructor.

Hope this helps.

UPDATE

If it really bothers you how the choices are created ahead of their question, there are few tricks you might find useful

1) Rearrange the code so that it looks like they are created after the question or at least at the same time

```<code>Question q = new Question(
    "What's up?",
    Arrays.asList(
        new Choice("The sky", false),
        new Choice("Ceiling", true)
    )
);
</code>```

2) Hide constructors and use a static factory method

```<code>public class Question implements Entity {
    ...

    private Question(String txt) { ... }

    public static Question newInstance(String txt, List<Choice> choices) {
        Question q = new Question(txt);
        for (Choice ch : choices) {
            q.assignChoice(ch);
        }
    }

    public void assignChoice(Choice ch) { ... }
    ...
}
</code>```

3) Use the builder pattern

```<code>Question q = new Question.Builder("What's up?")
    .assignChoice(new Choice("The sky", false))
    .assignChoice(new Choice("Ceiling", true))
    .build();
</code>```

However, everything depends on your domain. Most of the times the order of objects creation is not important from the problem domain perspective. What is more important is that as soon as you get an instance of your class it is logically complete and ready to use.

Outdated. Everything below is irrelevant to the question after clarifications.

First of all, according to DDD domain model should make sense in the real world. Hence, few points

a question may have no answers

there should not be an answer without a question

an answer should correspond to exactly one question

an "empty" answer doesn't answer a question

Based on the above

[A] may contradict point 4 because it's easy to misuse and forget to set the text.

[B] is a valid approach but requires parameters that are optional

[C] may contradict point 4 because it allows an answer with no text

[D] contradicts point 1 and may contradict points 2 and 3

[E] may contradict points 2, 3 and 4

Secondly, we can make use of OOP features to enforce domain logic. Namely we can use constructors for the required parameters and setters for the optional ones.

Thirdly, I would use the ubiquitous language which is supposed to be more natural for the domain.

And finally, we can design it all using DDD patterns like aggregate roots, entities and value objects. We can make the Question a root of its aggregate and the Answer a part of it. This is a logical decision because an answer has no meaning outside of a question's context.

So, all the above boil down to the following design

```<code>class Answer implements ValueObject {

    private final Question q;
    private String txt;
    private boolean isCorrect = false;

    Answer(Question q, String txt) {
        // validate and assign
    }

    public void markAsCorrect() {
        isCorrect = true;
    }

    public boolean isCorrect() {
        return isCorrect;
    }
}

public class Question implements Entity {

    private String txt;
    private final List<Answer> answers = new ArrayList<>();

    public Question(String txt) {
        // validate and assign
    }

    // Ubiquitous Language: answer() instead of addAnswer()
    public void answer(String txt) {
        answers.add(new Answer(this, txt));
    }
}

Question q = new Question("What's up?");
q.answer("The sky");
</code>```

P.S. Answering to your question I made few assumptions about your domain which might not be correct, so feel free to adjust the above with your specifics.

Title: Model relationships with DDD (or with sense)?

Body:
Here is a simplified requirement:

User creates a Question with multiple Answers. Question must have at least one Answer.

Clarification: think Question and Answer as in a test: there is one question, but several answers, where few may be correct. User is the actor who is preparing this test, hence he creates question and answers.

I am trying to model this simple example so to 1) match the real life model 2) to be expressive with the code, so to minimize potential misuse and errors, and to give hints to developers how to use the model.

Question is an entity, while answer is value object. Question holds answers. So far, I have these possible solutions.

[A] Factory inside Question

Instead of creating Answer manually, we can call:

```<code>Answer answer = question.createAnswer()
answer.setText("");
...
</code>```

That will create an answer and add it to the question. Then we can manipulate answer by setting it's properties. This way, only questions can crete an answer. Also, we prevent to have an answer without a question. Yet, we do not have control over creating answers, as that is hardcoded in the Question.

There is also one problem with the 'language' of above code. User is the one who creates answers, not the question. Personally, I don't like we create value object and depending on developer to fill it with values - how he can be sure what is required to add?

[B] Factory inside Question, take #2

Some says we should have this kind of method in Question:

```<code>question.addAnswer(String answer, boolean correct, int level....);
</code>```

Similar to above solution, this method takes mandatory data for the answer and creates one that will be also added to the question.

Problem here is that we duplicate the constructor of the Answer for no good reason. Also, does question really creates an answer?

[C] Constructor dependencies

Let's be free to create both objects by our selves. Let's also express the dependency right in constructor:

```<code>Question q = new Question(...);
Answer a = new Answer(q, ...);   // answer can't exist without a question
</code>```

This gives hints to developer, as answer can't be created without a question. However, we do not see the 'language' that says that answer is 'added' to the question. On the other hand, do we really need to see it?

[D] Constructor dependency, take #2

We can do the opposite:

```<code>Answer a1 = new Answer("",...);
Answer a2 = new Answer("",...);
Question q = new Question("", a1, a2);
</code>```

This is opposite situation of above. Here answers can exist without a question (which does not make sense), but question can not exist without answer (which make sense). Also, the 'language' here is more clear on that question will have the answers.

[E] Common way

This is what I call the common way, the first thing that ppl usually do:

```<code>Question q = new Question("",...);
Answer a = new Answer("",...);
q.addAnswer(a);
</code>```

which is 'loose' version of above two answers, since both answer and question may exist without each other. There is no special hint that you have to bind them together.

[F] Combined

Or should I combine C, D, E - to cover all the ways how relationship can be made, so to help developers to use whatever is best for them.

Question

I know people may choose one of the answers above based on the 'hunch'. But I wonder if any of above variant is better then the other with a good reason for that. Also, please don't think inside the above question, I would like to squeeze here some best practices that could be applied on most cases - and if you agree, most use cases of creation some entities are similar. Also, lets be technology agnostic here, eg. I do not want to think if ORM is going to be used or not. Just want good, expressive mode.

Any wisdom on this?

EDIT

Please ignore other properties of Question and Answer, they are not relevant for the question. I edited above text and changed the most of the constructors (where needed): now they accept any of necessary property values needed. That may be just a question string, or map of strings in different languages, statuses etc. - whatever properties are passed, they are not a focus for this ;) So just assume we are above passing necessary parameters, unless said different. Thanx!

Body:
Updated. Clarifications taken into account.

Looks like this is a multiple choice domain, which usually has the following requirements

a question must have at least two choices so that you could choose among

there must be at least one correct choice

there should not be a choice without a question

Based on the above

[A] can't ensure the invariant from point 1, you may end up with a question without any choice

[B] has the same disadvantage as [A]

[C] has the same disadvantage as [A] and [B]

[D] is a valid approach, but it's better to pass the choices as a list rather than passing them individually

[E] has the same disadvantage as [A], [B] and [C]

Hence, I would go for [D] because it allows to ensure domain rules from points 1, 2 and 3 are followed. Even if you say that it's very unlikely for a question to remain without any choice for a long period of time, it's always a good idea to convey domain requirements through the code.

I would also rename the Answer to Choice as it makes more sense to me in this domain.

public class Choice implements ValueObject {

    private Question q;
    private final String txt;
    private final boolean isCorrect;
    private boolean isSelected = false;

    public Choice(String txt, boolean isCorrect) {
        // validate and assign
    }

    public void assignToQuestion(Question q) {
        this.q = q;
    }

    public void select() {
        isSelected = true;
    }

    public void unselect() {
        isSelected = false;
    }

    public boolean isSelected() {
        return isSelected;
    }
}

public class Question implements Entity {

    private final String txt;
    private final List<Choice> choices;

    public Question(String txt, List<Choice> choices) {
        // ensure requirements are met
        // 1. make sure there are more than 2 choices
        // 2. make sure at least 1 of the choices is correct
        // 3. assign each choice to this question
    }
}

Choice ch1 = new Choice("The sky", false);
Choice ch2 = new Choice("Ceiling", true);
List<Choice> choices = Arrays.asList(ch1, ch2);
Question q = new Question("What's up?", choices);

A note. If you make the Question entity an aggregate root and the Choice value object a part of the same aggregate, there's no chances one can store a Choice without it being assigned to a Question (even though you don't pass a direct reference to the Question as an argument to the Choice's constructor), because the repositories work with roots only and once you build your Question you have all your choices assigned to it in the constructor.

Hope this helps.

UPDATE

If it really bothers you how the choices are created ahead of their question, there are few tricks you might find useful

1) Rearrange the code so that it looks like they are created after the question or at least at the same time

Question q = new Question(
    "What's up?",
    Arrays.asList(
        new Choice("The sky", false),
        new Choice("Ceiling", true)
    )
);

2) Hide constructors and use a static factory method

public class Question implements Entity {
    ...

    private Question(String txt) { ... }

    public static Question newInstance(String txt, List<Choice> choices) {
        Question q = new Question(txt);
        for (Choice ch : choices) {
            q.assignChoice(ch);
        }
    }

    public void assignChoice(Choice ch) { ... }
    ...
}

3) Use the builder pattern

Question q = new Question.Builder("What's up?")
    .assignChoice(new Choice("The sky", false))
    .assignChoice(new Choice("Ceiling", true))
    .build();

However, everything depends on your domain. Most of the times the order of objects creation is not important from the problem domain perspective. What is more important is that as soon as you get an instance of your class it is logically complete and ready to use.

Outdated. Everything below is irrelevant to the question after clarifications.

First of all, according to DDD domain model should make sense in the real world. Hence, few points

a question may have no answers

there should not be an answer without a question

an answer should correspond to exactly one question

an "empty" answer doesn't answer a question

Based on the above

[A] may contradict point 4 because it's easy to misuse and forget to set the text.

[B] is a valid approach but requires parameters that are optional

[C] may contradict point 4 because it allows an answer with no text

[D] contradicts point 1 and may contradict points 2 and 3

[E] may contradict points 2, 3 and 4

Secondly, we can make use of OOP features to enforce domain logic. Namely we can use constructors for the required parameters and setters for the optional ones.

Thirdly, I would use the ubiquitous language which is supposed to be more natural for the domain.

And finally, we can design it all using DDD patterns like aggregate roots, entities and value objects. We can make the Question a root of its aggregate and the Answer a part of it. This is a logical decision because an answer has no meaning outside of a question's context.

So, all the above boil down to the following design

class Answer implements ValueObject {

    private final Question q;
    private String txt;
    private boolean isCorrect = false;

    Answer(Question q, String txt) {
        // validate and assign
    }

    public void markAsCorrect() {
        isCorrect = true;
    }

    public boolean isCorrect() {
        return isCorrect;
    }
}

public class Question implements Entity {

    private String txt;
    private final List<Answer> answers = new ArrayList<>();

    public Question(String txt) {
        // validate and assign
    }

    // Ubiquitous Language: answer() instead of addAnswer()
    public void answer(String txt) {
        answers.add(new Answer(this, txt));
    }
}

Question q = new Question("What's up?");
q.answer("The sky");

P.S. Answering to your question I made few assumptions about your domain which might not be correct, so feel free to adjust the above with your specifics.


问:
Stored procedure in asp.net webforms
Previously while working on database in asp.net I was using stored procedure with no tier architecture. So I was including connection string, crud query etc in every button click event.

Then I was told to use three tier architecture. I googled some way and found not so convincing answers. Help me find a proper one, the standard one.

答:
Whoever told you to use a three tier architecture clearly has some misunderstanding about the term and passed that misunderstanding to you. Tiers describe a physical separation between the parts of a system, layers describe a logical separation. What you're after is a layered architecture, you're already using a two tier one.

A typical three tier application is made up of a presentation tier (web, mobile or desktop applications), a business logic tier and a database/storage tier (SQL Server, MySQL, NOSQL). This is valid for applications that expose their logic to multiple clients through the means of a public API. The StackExchange network can be seen as a multitier architecture.

A multilayer application will be structured, conceptually, the same way as a multitier one, with the important difference that some of the layers (presentation, business logic, data access) can reside within the same physical boundary (tier), such as an assembly or an ASP.NET WebForms application.

The main problem you have in your application is that you don't have a clear separation between the data access layer, the business logic layer (which can be omitted if you're merely presenting some data from a database) and the presentation layer, hence the suggestion you received. Your presentation layer should be oblivious to the persistence layer. You are supposed to abstract the data access part of the code behind a class or an interface. This would give you the logical separation between presentation (the webpage) and data access (the class/interface).

Another problem that you may have is that inside the stored procedure you may be performing some business rules which would normally reside within the business logic layer. The opinions on this are divided and the decision on where to place these rules depends on multiple factors.

Title: Stored procedure in asp.net webforms


问:
Sorting list and changing same values to nearly the same
I have a list of doubles that need to be sorted and changed so that there are no two numbers that are the same (difference smaller then 0.05) and I need to do it fast. I don't care about preserving order for values that are the same.

What I'm doing right now is:

```<code>List<double> values;

bool sortfunction(double a, double b)
{
   return a < b;
}

.....
qSort(values.start, values.end, sortfunction);

for(int i = 0; i < values.count() - 1; i++)
{
   if(values[i] == values[i+1])
   {
      values[i+1] += 0.1;
   }
}
</code>```

But the problem is with lists like  { 0. ,0. ,0. ,5. ,6.3 }. The result being { 0. ,0.1 ,0. ,5. ,6.3 }. Can you think of something that does not require multiple passes of sorting?

答:
Clearly this is just a sketch:

```<code>#include <algorithm>
#include <iostream>
#include <vector>

std::vector<double> values = {0.0, 0.0, 0.0, 0.0, 0.1, 0.3, 0.4, 5.0, 6.3, 6.3};

int main()
{
  std::sort(values.begin(), values.end());

  for (int i(0), sup(values.size()); i < sup; ++i)
    for (int j(i + 1); j < sup && std::abs(values[i] - values[j]) < 0.05; ++j)
      values[j] += 0.1;

  for (auto v : values)
    std::cout << v << '\n';
}
</code>```

With minor adjustments it'll work also for lists:

```<code>std::list<double> values = { ... };

values.sort();

for (auto a(values.begin()), end(values.end()); a != end; ++a)
  for (auto b(std::next(a)); b != end && std::abs(*a - *b) < 0.05; ++b)
    *b += 0.1;
</code>```

Body:
Clearly this is just a sketch:

#include <algorithm>
#include <iostream>
#include <vector>

std::vector<double> values = {0.0, 0.0, 0.0, 0.0, 0.1, 0.3, 0.4, 5.0, 6.3, 6.3};

int main()
{
  std::sort(values.begin(), values.end());

  for (int i(0), sup(values.size()); i < sup; ++i)
    for (int j(i + 1); j < sup && std::abs(values[i] - values[j]) < 0.05; ++j)
      values[j] += 0.1;

  for (auto v : values)
    std::cout << v << '\n';
}

With minor adjustments it'll work also for lists:

std::list<double> values = { ... };

values.sort();

for (auto a(values.begin()), end(values.end()); a != end; ++a)
  for (auto b(std::next(a)); b != end && std::abs(*a - *b) < 0.05; ++b)
    *b += 0.1;


问:
file quantity limit in a directory on a linux file server and why?
What is a good limit to use on the quantity of files in a directory, and why?

EDIT:
Why shouldn't someone create a system that puts hundreds of thousands of files in the same directory?

Why I ask:

Someone set up a system that dumps files in a folder with a human readable date-time.

My task it to create a system that gets the files for a select time period.

Normally this wouldn't be a problem but the folder has 500,000 files in it and is growing and my system is expected to get them in real time.

Parsing 500,000 files takes too long, so I think it is the responsibility of the person who built the system that inputs the files on the FTP server to create a directory structure such as having a sub folder for each day.

答:
Stock answer: "It depends".

Trying to do anything of any size or complexity using the file system as a "database" is going to be tricky and trying to do it "in real time" is going to be downright difficult.

The problem is that you tend to have lots of files, which means that you have to operate on "a" file many, many times.  Doing "something" once takes an amount of time; doing that "something" many times takes many times longer; it doesn't scale well.

That said, you can offset this overhead this by organising your data sensibly.
You say you're working with date ranges, so arrange your files into a directory structure that supports this, an obvious choice might be this:

```<code>root/
  2014/
    01/
      01/
        2014-01-01-00-00-00.dat
        2014-01-01-00-00-01.dat
      02/
        2014-01-02-00-00-00.dat
        2014-01-02-00-00-01.dat
</code>```

Now, retrieving a days'-worth of files is relatively straight-forward (and, therefore, quick).

Of course, depending on what you're doing, loading the whole thing into a database might be a better solution ...   YMMV

Body:
Stock answer: "It depends".

Trying to do anything of any size or complexity using the file system as a "database" is going to be tricky and trying to do it "in real time" is going to be downright difficult.

The problem is that you tend to have lots of files, which means that you have to operate on "a" file many, many times.  Doing "something" once takes an amount of time; doing that "something" many times takes many times longer; it doesn't scale well.

That said, you can offset this overhead this by organising your data sensibly.
You say you're working with date ranges, so arrange your files into a directory structure that supports this, an obvious choice might be this:

root/
  2014/
    01/
      01/
        2014-01-01-00-00-00.dat
        2014-01-01-00-00-01.dat
      02/
        2014-01-02-00-00-00.dat
        2014-01-02-00-00-01.dat

Now, retrieving a days'-worth of files is relatively straight-forward (and, therefore, quick).

Of course, depending on what you're doing, loading the whole thing into a database might be a better solution ...   YMMV


问:
Why use services (REST/SOAP) instead of a library?
Let's say you're looking at breaking up your applications into services.  Are there any good reasons to adopt a SOA approach vs. just creating a library API that can be loaded by the applications that need it.</p>

答:
There are several good answers but I would like to add more things to the given answers:

The API library method is very useful when you want to interact with things with as little overhead as possible. The consequence is that there is a higher coupling between API and the applications using it. Sometimes, this is okay for application and even necessary, however if you have a very distributed system or you think interoperability is a huge issue, you might need to go one step up the abstraction latter and use other ways of communicating. Especially, if you want to have a distributed system, SOAP is kind of the next step in SOA, but you will still be left with the dependence between the units, since they have to know each others procedures. REST takes it to a new level, by allowing a machine to learn something about the content on the other services in a unified way.

In your case, if your application is not distributed I don't see any reason to transform you application into SOA.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: When you have to distribute an application or put a website into production outside the confines of your company, everything that you thought didn't matter, does.</p>


问:
Do I have to make source code open, if I use GPLv2 licensed software to derive data
I'm working on a calendar project, on my own. In this project I've to use Swiss Ephemeris. It is licensed under GPLv2 and commercial. With commercial version of license, developers entitled to distribute the software, as his/her wish. But as this is my personal project, I've to use the GPLv2 license.

By using the library and data file, I'm generating data for calendars. In future I shall publish these calendars in a website, freely. In this process obviously I've to modify the library, write some of my own code and other chores. Will I've to make my final source code open.

I don't have any problem to make this public. But I'm asking, if I've to.

Edit: From the detailed answer from @apsillers & others, it is clear to me that, I'll not have to make my software GPL or even give source code to the visitors to the website. Though I've to make my displayed data GPL by the clause, as the Swiss Ephemeris data, licensed under GPLv2 or later and commercial:

More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.

答:
The GPLv2 only requires you to provide source code (and unencumbered redistribution rights) to those whom you give the software.  If the software is only on your computer, you don't need to distribute code, because you're not distributing binaries. (As an aside, the Affero GPL (AGPL) has more strict requirements than the plain GPL: with AGPL-licensed software, you must also share the source code with anyone who interacts with your software through a network.)

Regardless of the GPL version you use, however, any data file you create with the software is NOT part of the same work, and so does not typically need to be licensed under the GPL.

In addition, be aware that simple lists are in many cases not even eligible for copyright protection.  If you were to want to claim a copyright on your calendar data, I'd recommend consulting with an attorney.


答:
Since you're making a derivative work of GPL-licensed software, your combined work would need to be licensed under the GPL as a whole. However, if you don't want to distribute your work, you are in no way compelled to shared your changes.

The GPL FAQ has this to say on keeping your modifications private:

Does the GPL require that source code of modified versions be posted to the public?

The GPL does not require you to release your modified version, or any part of it. You are free to make modifications and use them privately, without ever releasing them...

But if you release the modified version to the public in some way, the GPL requires you to make the modified source code available to the program's users, under the GPL.

Thus, the GPL gives permission to release the modified program in certain ways, and not in other ways; but the decision of whether to release it is up to you.

Thus, you are not required to make your modified program public, but you if you do, you must share it under the GPL.

Perhaps you're also worried that sharing your output calendars will compel you to share your modified code. The FAQ explains that output data produced by a GPL-licensed work is not covered by the GPL, unless the output actually contains GPL-licensed material (e.g., if part of the GPL-licensed program itself is included in the program's output):

Is there some way that I can GPL the output people get from use of my program? For example, if my program is used to develop hardware designs, can I require that these designs must be free?

In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert his own data, the copyright on the output belongs to him, not you. More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.

So the only way you have a say in the use of the output is if substantial parts of the output are copied (more or less) from text in your program. For instance, part of the output of Bison (see above) would be covered by the GNU GPL, if we had not made an exception in this specific case.

In what cases is the output of a GPL program covered by the GPL too?

Only when the program copies part of itself into the output.

So, your output is probably not GPL-licensed. Note that even in some unusual case where the output is somehow GPL-licensed (like a Bison grammar), the output is a separate work from the program that created it. You'd need to obey GPL restrictions on the output, but sharing GPL-licensed output does not mean you must share changes on the GPL-licnesed program that created that output. The GPL on the program only comes into effect when the program itself is distributed, not when its output is distributed.

Title: Do I have to make source code open, if I use GPLv2 licensed software to derive data

Body:
I'm working on a calendar project, on my own. In this project I've to use Swiss Ephemeris. It is licensed under GPLv2 and commercial. With commercial version of license, developers entitled to distribute the software, as his/her wish. But as this is my personal project, I've to use the GPLv2 license.

By using the library and data file, I'm generating data for calendars. In future I shall publish these calendars in a website, freely. In this process obviously I've to modify the library, write some of my own code and other chores. Will I've to make my final source code open.

I don't have any problem to make this public. But I'm asking, if I've to.

Edit: From the detailed answer from @apsillers & others, it is clear to me that, I'll not have to make my software GPL or even give source code to the visitors to the website. Though I've to make my displayed data GPL by the clause, as the Swiss Ephemeris data, licensed under GPLv2 or later and commercial:

More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.


问:
Implementing a Username Class
I am attempting to encapsulate several features about a user in a single class. Although the main use for this class would be to initialize it once and never have to call set any variables again, I would like this class to be scalable to be called many times. Although by putting this into a class I feel like I am either over-complicating it or breaking OOP standards.

At the moment I am currently using these current sorts of calls throughout VBA code:

```<code>username = GetUsername()
</code>```

OR

```<code>IF userHasSecurity(GetUsername(), "WhatUserHasAccessTo") = true THEN
</code>```

What I am hoping to do it replace it (respectively) with:

```<code>  Set UserID = New Username
  UserID.GetUserName
</code>```

OR

```<code>IF UserID.HasModuleAccess("WhatUserHasAccessTo") = true THEN
</code>```

In addition to this change, I have a function that returns Active Directory information and also verify if usernames input exist in Active Directory

The Class Diagram is as such

```<code>Private UserName As String
Private FirstName As String
Private MiddleInitial As String
Private LastName As String

Private Sub class_Initialize()
Private Function findCurrentUsername() As String
Private Function doesUsernameExist(usernameToCheck As String) As Boolean
Public Property Get GetUserName() As String
Public Property Let setUsername(newUsername As String)
Public Property Get getFirstName() As String
Private Property Let setFirstName(newFirstName As String)
Public Property Get getLastName() As String
Private Property Let setLastName(newLastName As String)
Public Property Get getMiddleInitial() As String
Private Property Let setMiddleInitial(newMiddleInitial As String)
Private Function findNameDetails()
Public Property Get getFullName() As String
Public Function HasModuleAccess(moduleName As String, Optional appName As String) As Boolean
Public Function getUserActiveDirectoryGroups() As DAO.Recordset
</code>```

Is this more an opinion based execution(standalone functions vs. class) thing or is there something to gain? Does this break OOP standards and am I using classes incorrectly?

答:
*before sitting down to writing code etc. - search, research available resources, functions - basically don't reinvent the wheel...

There is an Environ() function in VBA that pretty much does what you are describing and trying to imitate by using your own wrapper class.. ask yourself is it worth it? do you really need it that much?

Rule of thumb

Stick with good encapsulation

you said:

Although the main use for this class would be to initialize it once and never have to call set any variables again,

Don't assume things that may break good encapsulation - don't assume you will never have to do X and Y with your class - there are different techniques to protect objects state through properties.

As already pointed out in the comment section - it's important that your class is rather named User and not Username.

It's a user. If it's meant to be reusable meaning you can reuse it in many different projects - not have many instances of it then it shouldn't be depended on any other, unrelated, piece of your application - specially the active directory etc. If VBA supported parametarised constructors that could have been a different story based on some crucial circumstances but it does not so no argument is needed.

read this: Properties vs public variables in class modules

Hope you get the idea because as far as your User class goes you don't really need some of the properties you currently declared as properties...

I mean, look - you are not storing User's age -- you don't really need a Let property to check whether the age passed is not negative or not greater than some huge number... You are only storing some strings like firstName, lastName, middleInitial etc.. if you don't need to protect the access to change those then they should ideally be just public variables - acting sort of like read/write properties - without the ability to verify the data being assigned to them - but does it matter? They're Strings...

One good candidate for a property could be an Enumerable property UserAccessLevel...

First you would probably want to define a public Enum like

```<code>Public Enum UserAccessLevel
    ualReadOnly
    ualWriteOnly
    ualReadWrite
End Enum
</code>```

then you could have a property like

```<code>private currentUserAccessLevel as UserAccessLevel

' cool stuff

Public Property Get ModuleAccess() as UserAccessLevel
    ModuleAccess = currentUserAccessLevel
End Property

Public Property Let ModuleAccess(value as UserAccessLevel)
    currentUserAccessLevel = value
End Property
</code>```

That would be cool with all the intelli-sense tips for your enums etc...

Now, I have noticed this:

```<code>Public Function getUserActiveDirectoryGroups() As DAO.Recordset
</code>```

And I have mixed feelings because

VBA doesn't support class polymorphism - so you can't derive a CustomUser from User - I know, that sucks... but you can create a new class and expose a User as a property of the class etc. Too broad to discuss here though...

getUserActiveDirectoryGroups() may not necessarily be something that any other project may want to use. I mean it's cool to have it there as long as it's not dependant on any other external and unrelated to the current User class members.

Say that the getUserActiveDirectoryGroups() needs to know things that current User class doesn't have access / doesn't know than it would probably be a better idea not to include that with the user class.

I could talk about this for another hour or two but I really hope at this point you feel a little bit more enlightened :)

Stick with good encapsulation.

from here

Understand the object-oriented principle of Encapsulation.

Learn the available modifiers for type members.

Protect object state through properties.

Control access to methods.

Title: Implementing a Username Class

Body:
*before sitting down to writing code etc. - search, research available resources, functions - basically don't reinvent the wheel...

There is an Environ() function in VBA that pretty much does what you are describing and trying to imitate by using your own wrapper class.. ask yourself is it worth it? do you really need it that much?

Rule of thumb

Stick with good encapsulation

you said:

Although the main use for this class would be to initialize it once and never have to call set any variables again,

Don't assume things that may break good encapsulation - don't assume you will never have to do X and Y with your class - there are different techniques to protect objects state through properties.

As already pointed out in the comment section - it's important that your class is rather named User and not Username.

It's a user. If it's meant to be reusable meaning you can reuse it in many different projects - not have many instances of it then it shouldn't be depended on any other, unrelated, piece of your application - specially the active directory etc. If VBA supported parametarised constructors that could have been a different story based on some crucial circumstances but it does not so no argument is needed.

read this: Properties vs public variables in class modules

Hope you get the idea because as far as your User class goes you don't really need some of the properties you currently declared as properties...

I mean, look - you are not storing User's age -- you don't really need a Let property to check whether the age passed is not negative or not greater than some huge number... You are only storing some strings like firstName, lastName, middleInitial etc.. if you don't need to protect the access to change those then they should ideally be just public variables - acting sort of like read/write properties - without the ability to verify the data being assigned to them - but does it matter? They're Strings...

One good candidate for a property could be an Enumerable property UserAccessLevel...

First you would probably want to define a public Enum like

Public Enum UserAccessLevel
    ualReadOnly
    ualWriteOnly
    ualReadWrite
End Enum

then you could have a property like

private currentUserAccessLevel as UserAccessLevel

' cool stuff

Public Property Get ModuleAccess() as UserAccessLevel
    ModuleAccess = currentUserAccessLevel
End Property

Public Property Let ModuleAccess(value as UserAccessLevel)
    currentUserAccessLevel = value
End Property

That would be cool with all the intelli-sense tips for your enums etc...

Now, I have noticed this:

Public Function getUserActiveDirectoryGroups() As DAO.Recordset

And I have mixed feelings because

VBA doesn't support class polymorphism - so you can't derive a CustomUser from User - I know, that sucks... but you can create a new class and expose a User as a property of the class etc. Too broad to discuss here though...

getUserActiveDirectoryGroups() may not necessarily be something that any other project may want to use. I mean it's cool to have it there as long as it's not dependant on any other external and unrelated to the current User class members.

Say that the getUserActiveDirectoryGroups() needs to know things that current User class doesn't have access / doesn't know than it would probably be a better idea not to include that with the user class.

I could talk about this for another hour or two but I really hope at this point you feel a little bit more enlightened :)

Stick with good encapsulation.

from here

Understand the object-oriented principle of Encapsulation.

Learn the available modifiers for type members.

Protect object state through properties.

Control access to methods.


问:
Practices for organizing JavaScript AMD imports
Our company has been using newer versions of the Dojo framework, which have progressed to an AMD-based loader format. I'm currently trying to find logical ways to separate layer files, taking a module and all its dependencies, and wrapping them all into single minified files. My goals are generally as follows:

Minimize the number of separate requests made per-page

When possible, make use of cache so that large modules that have already been used are re-retrieved.

Our app consists of many hundreds of pages and dialogs, much of which have their own custom logic and related scripts.

I'm starting to run into more and more complex issues in terms of finding the right way to construct layer files for the best performance. Just recently, I ran into the following type of scenario:

A depends on B, depends on C, depends on D ...etc... depends on Z.

A1 depends on D (which depends on ... Z)

A2 depends on L (which depends on ... Z)

The scenario is mostly just an example - I don't have 24 dependencies in a straight tree. But under our previous method of simply declaring all objects globally under a namespace, this would be a simple matter of minifying everything to one layer file that's included on relevant pages. As it stands now, I'm not sure what I'd gain by making D its own layer, or A, or L. Just to avoid loading the same code twice, we'd be separating it into about 3 or 4 requests. One troublesome fact is the way that the page's script will always immediately put out new script requests for anything in its "require()" block that it hasn't cached just yet. Moreover, it's become very complicated just to comprehend and discuss.

I wanted to know how other people tend to approach this problem, hopefully in a simpler way; the previous version of our product had some significant javascript loading-time issues, so this certainly isn't premature optimization (it could be "past-mature"). We are starting to switch our pages to using asynchronously-loaded script tags now that most of our scripts support it, in case that's any help.

答:
(Self-answer)
One thing I've been trying lately, and with moderate success, is making separate boot layers. Since we can at least be certain that any particular block of JavaScript will either all execute, or not execute at all, and it needs to be available for any define/requires to work, it's a pretty good place to put all of the main "library modules" for any particular user type.

From there, I've been making minified layers for every "page script", excluding any modules already written in one of the user type boot scripts. There's still a lot of manual work, and in fact some restructuring. For performance, I need to have the login page for each user type request their "layer" before they get to their homepage (each script totals over a megabyte - not a small app). It seems to be fitting my needs so far, but hasn't gone through any actual performance test.


问:
How to describe styles and approaches of C++ programming?
How can I say more than just "C++" on my resume, reports or other writings, to convey clearly what kind of C++ programming I've been doing?

Are there well-defined styles of C++? ("Styles" might not be quite the right word.)  Examples:  using C++ as an "improved C" taking advantage of stronger typechecking, syntactic niceties, but little or lightweight use of classes;  using heavy OO techniques where almost everything is made into a class (and there could be different styles of that) - but staying away from templates and advanced techniques;  and heavy use of metaprogramming and every cutting edge advanced C++ feature.    I've seen code where there's such heavy use of computer science terminology and advanced features only a CS PhD would be able to understand it,  and code so clean and straightforward that EEs and physicists with modest programming skills can understand it.

This isn't about literally coding styles - fussy details about brackets, indentation, commenting and all that - but one's philosophy of what good code is, the approach to organizing it all, and degree of fanaticism or reluctance to use various major techniques, procedural vs OO vs functional and so forth.

Can such variations be categorized in a meaningful way?   How to name these for someone not expert at software development, with an amount of knowledge to be expected of a good executive or recruiter (never mind the PHBs)?

Ideally, there'd be a way anyone can say on their resume "C++ in blah-blah style" or "mumbleific C++" and land jobs or freelance projects in that category/style of C++.  An improved-C++ coder could avoid projects full of heavy template-bloated code.

(To some extent this question may be more general than C++, but C++ being around for years and being multi-paradigm, leads to the most confusion.)

答: The purpose of a resume is to get you an interview.  That means it has to have all the right buzzwords to get you past the HR, and just enough substance to get the technical manager interested in talking to you.  The technical interview is where you should discuss your coding style and design philosophy.</p>


问:
Updating ip address for custom domain
I'm looking to transfer the ipaddress for my site from one ip address to another. Reading through the Register.com documentation it says that it may take awhile for the DNS changes to replicate/propogate.

Since this transition includes a different sql database, how do I force the update so I don't lose any data that may be add/updated during the transition period?

答:
Welcome to the web hosting shell game.

First, you can drop your dns TTL to something absurdly low -- we use 60 seconds when we are about to move things. That said, not everything honors your TTL value.

A lot depends on specifics but there are a few ways to do this. Probably the most effective would be to push the front end out to a proxy, have that proxy back-haul to your current site then, when ready, repoint the proxy at the new host. I would suggest using a service such as cloudflare as the proxy rather than handling it yourself.

Another approach would be to use a second, temporary domain name while things propigate. To do so setup your new app to listen on new.example.com as well as www.example.com; then when ready setup the old server to redirect all requests to new.example.com. Give it a day or so then setup the new server to redirect new.example.com to www.example.com so you keep a cannonical domain name.

Title: Updating ip address for custom domain


答:
We also practice SCRUM. And the same as you, we also include functional testing as part of our definition as done.

From my experience, I find it incredibly useful. We have significantly reduced the number of bugs in our code by simply forcing the functional testing.

A second nice thing about the code review, is it gives you another view over the actual functionality, and to make 100% sure that it is in line with what the customer/client wanted. There has been a few times when someone was going over code and functionality where the person went ... "Hang on, this is not right..." and it turned out that the person implementing the code just misunderstood something.

Title: Peer review for tests just like code reviews

Body: Does anyone practice the "code review" process for functional tests? Do you find it useful? The way that my current employer practices SCRUM we include functional testing as part of our "must have done" stuff in any given sprint.</p>