问:
When is an object passed to a function?
Trying to clearly state the semantics of a function call.

In calling a function, are the arguments passed to the function the ones the calling code initially gives or the ones the function receives?

With code like below, the calling code in bar() calls foo() twice.  This first time with int 2, then ...

1) Function foo() is called with a double 3.1, x has the converted value of int 3,

or

2) The value double 3.1 is converted to int 3 and function foo() is called,

or

3) Something else.

IOWs, is the conversion of double 3.1 to int 3 part of the call of a function (the conversion would not happen without the function call) or is it a preceding activity (consider to be part of the calling code) before the function call?

```<code>void foo(int x);

void bar() {
  foo(2);
  foo(3.1);
}
</code>```

This query is primarily C, yet language agnostic thoughts appreciated.  A quick answer is not needed.

[Edit]

Note: This is not an question of how platforms create the binary/executable to implement the program code - just about the code/language.

[Edit 2]
@ Erik Eidt useful comment provided better words to use (at least for C) for this question.

Perhaps a more succinct question would be, from the language perspective: "Are functions called with "actual arguments" or "formal parameters"?

C11 3.3 actual arguments and 3.16 1 formal parameter.

答:
Consider a language L0 that does no implicit conversions like double to int, "default argument promotions", array conversions to "address of first object", etc.  Code like foo(int); double x; foo(x); is then a compile time error.

```<code>double x;
foo(x); // Bad L0 code
</code>```

L0 is not relevant to this question other than it shows if L0 code wanted to call foo(int) with a double, it would explicitly perform the conversion.

```<code>double x;
foo(double_to_int(x));  // L0: Explicit conversion before calling `foo()`.
</code>```

Consider a language L1 that does all the above implicit conversions.  When code has a call to function foo(int) and a double parameter is passed, a function is created that that accepts the double, converts it to an int and then performs the code of foo(int).  The L1 compiler has at least 4 choices: make 2 independent functions, 2 functions where one calls the other, makes one function with multiple entry points: one for int arguments and another for double, or one function with type information added in the passed argument.

```<code>double x;
foo(x); // Good L1 code, no conversion done in the calling code.
</code>```

C is certainly not LO with C's implicit conversions.  C could be L1 as there is little in the C spec that defines how to organize its passing of arguments - its ABI.  As @Erik Eidt provided with useful comments to some key definitions, a language like C (and L1), which has a potential difference between actual arguments and formal parameters.

This muddies the boundary between calling code and the called function.

In the end, with C, it is the formal parameter definition which says "acquires a value on entry to the function" implying the function is not called yet until this point.

Ref

C11 3.3

actual argument

expression in the comma-separated list bounded by the parentheses in a function call expression, or a sequence of preprocessing tokens in the comma-separated list bounded by the parentheses in a function-like macro invocation

C11 3.16

formal parameter

object declared as part of a function declaration or definition that acquires a value on entry to the function, or an identifier from the comma-separated list bounded by the parentheses immediately following the macro name in a function-like macro definition

Title: When is an object passed to a function?

Body:
Consider a language L0 that does no implicit conversions like double to int, "default argument promotions", array conversions to "address of first object", etc.  Code like foo(int); double x; foo(x); is then a compile time error.

double x;
foo(x); // Bad L0 code

L0 is not relevant to this question other than it shows if L0 code wanted to call foo(int) with a double, it would explicitly perform the conversion.

double x;
foo(double_to_int(x));  // L0: Explicit conversion before calling `foo()`.

Consider a language L1 that does all the above implicit conversions.  When code has a call to function foo(int) and a double parameter is passed, a function is created that that accepts the double, converts it to an int and then performs the code of foo(int).  The L1 compiler has at least 4 choices: make 2 independent functions, 2 functions where one calls the other, makes one function with multiple entry points: one for int arguments and another for double, or one function with type information added in the passed argument.

double x;
foo(x); // Good L1 code, no conversion done in the calling code.

C is certainly not LO with C's implicit conversions.  C could be L1 as there is little in the C spec that defines how to organize its passing of arguments - its ABI.  As @Erik Eidt provided with useful comments to some key definitions, a language like C (and L1), which has a potential difference between actual arguments and formal parameters.

This muddies the boundary between calling code and the called function.

In the end, with C, it is the formal parameter definition which says "acquires a value on entry to the function" implying the function is not called yet until this point.

Ref

C11 3.3

actual argument

expression in the comma-separated list bounded by the parentheses in a function call expression, or a sequence of preprocessing tokens in the comma-separated list bounded by the parentheses in a function-like macro invocation

C11 3.16

formal parameter

object declared as part of a function declaration or definition that acquires a value on entry to the function, or an identifier from the comma-separated list bounded by the parentheses immediately following the macro name in a function-like macro definition


问:
User Inputs: Bounding Box, best practice?
I am creating a function in matlab that takes in two lat/long coordinates (opposite corners of a rectangle) and returns information about data in the region.

How do I group my inputs?

e.g. [lat1,long1] and [lat2,long2]; or [lat1,lat2], [long1,long2].

To make it easy on the user I currently have the lats and longs grouped together like the latter example, but am thinking the former is a bit more appropriate for science/math.

答:
It depends, of course, on the semantics that the user of your function would expect, based on the domain. With lat1, long1, lat2, long2 you’re essentially taking two points: lat1, long1 and lat2, long2.

```<code>  *-(lat1, long1)     --+
  |                     |

  |                     |
  +--                  -* (lat2, long2)
</code>```

Whereas with lat1, lat2, long1, long2, you’re taking 4 axis bounds: the top, bottom, left, and right. I’ve never seen this before, but I can imagine it might be common in some domains, or for example when using interval arithmetic.

```<code>  |                     |
 -+---------lat1--------+-
  |                     |
  |                     |
long1                 long2
  |                     |
  |                     |
 -+---------lat2--------+-
  |                     |
</code>```

I don’t know how Matlab deals with types, but in a conventional imperative language I would expect functions to take arguments of more descriptive types, for example:

```<code>Info rect_info(Point top_left, Point bottom_right)
Info area_info(Range vertical, Range horizontal)
</code>```

It’s also worth considering terminology. Two arbitrary numbers are not necessarily a Point, but you can represent a Point with them—if your API takes numbers when it wants points, then you’re exposing implementation details to the user. You could go a step further—two arbitrary Points are not necessarily a Rectangle, and two arbitrary Ranges are not necessarily an Area.

ContentLicense: CC BY-SA 3.0

Body:
It depends, of course, on the semantics that the user of your function would expect, based on the domain. With lat1, long1, lat2, long2 you’re essentially taking two points: lat1, long1 and lat2, long2.

  *-(lat1, long1)     --+
  |                     |

  |                     |
  +--                  -* (lat2, long2)

Whereas with lat1, lat2, long1, long2, you’re taking 4 axis bounds: the top, bottom, left, and right. I’ve never seen this before, but I can imagine it might be common in some domains, or for example when using interval arithmetic.

  |                     |
 -+---------lat1--------+-
  |                     |
  |                     |
long1                 long2
  |                     |
  |                     |
 -+---------lat2--------+-
  |                     |

I don’t know how Matlab deals with types, but in a conventional imperative language I would expect functions to take arguments of more descriptive types, for example:

Info rect_info(Point top_left, Point bottom_right)
Info area_info(Range vertical, Range horizontal)

It’s also worth considering terminology. Two arbitrary numbers are not necessarily a Point, but you can represent a Point with them—if your API takes numbers when it wants points, then you’re exposing implementation details to the user. You could go a step further—two arbitrary Points are not necessarily a Rectangle, and two arbitrary Ranges are not necessarily an Area.


问:
Strategy to avoid running out of memory in memory intensive application
My C# .NET application has to read lots of files with electrical readings. There are several calculation to be done and output files need to be generated.
Due to the nature of the input it would be very inefficient to output after each input line or even after one file, so it would be better to do so after a chunk of files.

The reason for this is, that each file contains a list of readings/electrical units for one time stamp, but the output needs to be files for each unit.

So for instance the input would be 100 files each containing e.g. volt, ampere, watt, status code for one timestamp (2015_08_31_00_00_00.txt, 2015_08_31_00_00_05.txt ...).
 The output should be per electrical unit and e.g. one file per day
(c://ampere/2015_08_31.txt, c://volt/2015_08_31.txt ...).

Note that this is a simplified picture of the application. In reality there are several different input and output formats, directory structures etc.

What I want to do is, keep the calculated and ready for output values in memory and output them according to different strategies. This could be e.g. until all input files are processed.

As some strategies like this one can result in too much data in memory, I would like to monitor the memory usage and decide if I need to output sooner.

I do know how to get the used memory of my program, but how do I safely get an estimation on the available memory?

As far as I understand this is not a simple task due to memory fragmentation, paging, trashing and so on. I do know in this case that I got the 32-Bit induced memory limit with the current build settings, but I would like to get a general answer which could also be applied to a 64-Bit program.

How do I estimate when enough memory is still available to write to disk, but use a good amount of RAM to optimize I/O?

Update

I have not yet implemented this feature so I cannot tell if memory problems would occur under usual circumstances. Thanks to all your comments and answers I see it isn't easily accomplishable.

My current idea is to use a fixed input limit based on the size of the input files. This still would not protect against problems if other programs creates heavy load.
Each file is always just a few KB.

I will keep the SQLite idea in mind but I will have to check if I get an OK

答:
Unfortunately, there's really no good way to answer the question "how much RAM is my program using?" or "how close am I to hitting the OutOfMemoryException wall?", for a number of reasons. It's a lot more complicated than it looks like it should be.

One thing you might want to do, though, is make sure that you're not holding on to the input data unnecessarily.  For example, depending on how you're processing the data, it could be feasible to read the file, and perform the relevant calculations, one line at a time, or one small batch of lines at a time.  If you hold on to aggregate results, but don't keep the input data around, that should keep the memory usage down.

If that doesn't help, because your results just keep piling up, the best way to handle that is to offload them out of memory.  Put them in a relational database, for example, as fast as they come in, and then they end up on disc instead.  And then at the end of the day, perform a query that will pull in the day's results (HINT: this is a lot easier if you have a timestamp field that gets set when you insert the records) and save them out to their final version in your output files.


问:
Fix a leaky abstraction (type checking)
I have a method that accepts an interface and does type checking on the parameter, and depending upon the type a decision is made to either send an email or an alert

```<code>    public void Bar(ISomeInterface someClass)
    {
        if (someClass is SomeClassToo)
        {
            Emailer.Send(someClass.Something());
        }
        else
        {
            Alerter.Alert(someClass.Something());
        }
    }
</code>```

I know this is bad for obvious reasons, but I would like to know what other options I have to resolve this, as one of the solutions I have is to put an abstraction on each of the classes that implements ISomeInterface for the emailer/alerter using an ICommunicator (see below) but I am not sure that is right as it feels like somewhere in my code there will have to be something that checks the type or knows about each type even if it is just in an IOC container configuration.

```<code>public class SomeClass : ISomeInterface
{
    private ICommunicator _communicator;

    public SomeClass(ICommunicator communicator)
    {
        _communicator = communicator;
    }

    public void Something()
    {
        if (_communicator != null)
        {
            _communicator.Send("yee ha");
        }
    }
</code>```

答:
Without the full context it's hard to know the right thing to do.

It seems to me though that the ISomeInterface implementers need to do something differently, depending on the implementation.  That leads me to believe that your second approach is correct.

The thing is, each ISomeInterface implementation can have its own list of dependencies.  One could take an Alerter while another could take an Emailer.  So long as a "third party" class could call ISomeInterface.Something() without needing to know anything about whether Something() is calling an Emailer or an Alerter or a SkynetActivatoryou're set.  When SomeClass is constructed, something will need to know which dependencies to provide to it, but that's ok, because it's a concrete class.

Concrete classes are allowed to have dependencies.  Interfaces should not be dependent on implementation.

Title: Fix a leaky abstraction (type checking)


问:
Defining and testing detailed user interface requirements
I am in the process of designing and building a small web app. While implementing a first prototype I discovered that I make many unwritten assumptions about the behaviour of the interface. For example:

When the user selects a product in the product browser, the product inspector quickly slides out the left side displaying the product data. If the inspector is already opened, the data is only updated. The header background color changes with a radial animation.

Right now it's just me on the project, so I define these implicit requirements on the fly. But after every change that could break something I have to recall all of them in order to test them. I obviously should write them down somewhere.  I know unit testing, I know scenarios and personas, use-case diagrams; this seems to be something different and I don't know how to do it properly.

So, what is the usual way of defining, documenting, and also guaranteeing such requirements? Where do I put them? How do I structure them? How do I test them effectively? Should I ship them with the source code or put them in the project Wiki?

Also, these requirements are likely to change frequently, especially since I am using a rapid prototyping approach. I do not want to spend a lot of time drawing diagrams, etc. But simply dumping them into a text file without any structure seems to be a time waster as well, as soon as I have to test a specific part of the application.

答:
Selenium IDE allows you to walk through a scenario and add assertions to check it works as expected. which you can then save as a file you can play back later. It does have a few limitations.

the extension only works in firefox.

checking for visual changes may be difficult. ( it looks like you can check css properties )


问:
How to implement a branch-and-bound in a functional programming language?
I am trying to write a branch and bound search on the set of all functions f: D -> R, where the domain size is small (|D| ~ 20) and the range is much bigger (|R| ~ 2^20). Initially, I came up with the following solution.

```<code>(builder (domain range condlist partial-map)
            (let ((passed? (check condlist partial-map)))
              (cond
               ((not passed?) nil)
               (domain (recur-on-first domain range condlist partial-map '()))
               (t partial-map))))
(recur-on-first (domain range condlist partial-map ignored)
                   (cond
                    ((null range) nil)
                    (t (let ((first-to-first
                              (builder (cdr domain)
                                       (append ignored (cdr range))
                                       condlist
                                       (cons (cons (car domain) (car range)) partial-map))))
                         (or first-to-first
                             (recur-on-first domain
                                             (cdr range)
                                             condlist
                                             partial-map
                                             (cons (car range) ignored))))))))
</code>```

Here the parameter condlist to the function builder is a list of conditions that should be satisfied by a solution. The function check returns nil iff any element in the list of conditions is violated by the partial-map. The function recur-on-first assigns the first element in the domain to the first element in the range and tries to build a solution from there. Failing this recur-on-first invokes itself to try and construct a solution that assigns the first element in the domain to some element other than the first one in the range. However, it has to maintain a list ignored that stores these discarded elements (like the first element in the range) as they could be images of some other elements in the domain.

There are two problems that I can see with this solution. The first one is that the lists ignored and range in the function recur-on-first are quite large and appending them is an expensive operation. The second problem is that the recursion depth of the solution depends on the size of the range.

So I came up with the following solution that uses doubly linked lists to store the elements in the range. The functions start, next and end provide facilities to iterate over the doubly linked list.

```<code>(builder (domain range condlist &optional (partial-map nil))
            (block builder
                   (let ((passed? (check condlist partial-map)))
                     (cond
                       ((not passed?) nil)
                       (domain (let* ((cur (start range))
                                      (prev (dbl-node-prev cur)))
                                 (loop
                                   (if (not (end cur))
                                     (progn
                                       (splice-out range cur)
                                       (let ((sol (builder (cdr domain)
                                                           range
                                                           condlist
                                                           (cons (cons (car domain) (data cur)) partial-map))))
                                         (splice-in range prev cur)
                                         (if sol (return-from builder sol)))
                                       (setq prev cur)
                                       (setq cur (next cur)))
                                     (return-from builder nil)))))
                       (t partial-map))))))
</code>```

The runtime of the second solution is much better than the runtime of the first solution. The append operation in the first solution is replaced by splicing elements in and out of a doubly linked list (these operations are constant time) and the recursion depth only depends on the size of the domain. But my problem with this solution is that it uses C style code. So my question is this.

Is there a solution that is as efficient as the second solution but does not use setfs and mutable data structures? In other words, is there an efficient functional programming solution to this problem?

答: First idea that comes to mind: use the same general approach, but replace the loop with a tail-recursive call whose parameter is the spliced list for the next stage of the computation?  You never have to modify the spliced list, just generate a new list at each stage.  This admittedly is not constant-time, but you need to walk the list to find where to splice anyway.  It might even be able to re-use most of the nodes, especially if you can use a singly-linked list.</p>


答:
If you know the maximum amount of space you will need for your output, and it fits into your address space, you can use a function such as VirtualAlloc() to reserve a range of memory addresses, with or without committing pages.  This won’t allocate any physical pages until you actually try to write to them.  Therefore, you won’t get any out-of-memory errors just for reserving the memory region.  You can also open the input files as memory-mapped files, so that the OS will only copy the physical pages from disk when you read them.

At that point, you won’t need to make any additional calls to allocate your memory: when you run out of physical memory, the OS should just page out the pages you aren’t using to virtual memory, or you can VirtualFree() the pages after they’re written.

Title: Strategy to avoid running out of memory in memory intensive application

Body:
My C# .NET application has to read lots of files with electrical readings. There are several calculation to be done and output files need to be generated.
Due to the nature of the input it would be very inefficient to output after each input line or even after one file, so it would be better to do so after a chunk of files.

The reason for this is, that each file contains a list of readings/electrical units for one time stamp, but the output needs to be files for each unit.

So for instance the input would be 100 files each containing e.g. volt, ampere, watt, status code for one timestamp (2015_08_31_00_00_00.txt, 2015_08_31_00_00_05.txt ...).
 The output should be per electrical unit and e.g. one file per day
(c://ampere/2015_08_31.txt, c://volt/2015_08_31.txt ...).

Note that this is a simplified picture of the application. In reality there are several different input and output formats, directory structures etc.

What I want to do is, keep the calculated and ready for output values in memory and output them according to different strategies. This could be e.g. until all input files are processed.

As some strategies like this one can result in too much data in memory, I would like to monitor the memory usage and decide if I need to output sooner.

I do know how to get the used memory of my program, but how do I safely get an estimation on the available memory?

As far as I understand this is not a simple task due to memory fragmentation, paging, trashing and so on. I do know in this case that I got the 32-Bit induced memory limit with the current build settings, but I would like to get a general answer which could also be applied to a 64-Bit program.

How do I estimate when enough memory is still available to write to disk, but use a good amount of RAM to optimize I/O?

Update

I have not yet implemented this feature so I cannot tell if memory problems would occur under usual circumstances. Thanks to all your comments and answers I see it isn't easily accomplishable.

My current idea is to use a fixed input limit based on the size of the input files. This still would not protect against problems if other programs creates heavy load.
Each file is always just a few KB.

I will keep the SQLite idea in mind but I will have to check if I get an OK


问:
is OOP the dominant programming model in real world?
Objects Never? Well, Hardly Ever

In the VIEWPOINT section of Communications of The ACM, I found an
interesting article entitled "Objects Never? Well, Hardly Ever".
It’s a radically different perspective than objects-first or objects-late. He suggests "objects-never" or maybe "objects-graduate school".

The author talked about OOP and made a question about how OOP is used
in real world programming environments. He thinks that OOP is not the
dominant programming model. For example, he claims, 70% of
programmings are done for Embedded Systems where OOP is not really
suited.

When some professors in universities wants to talk about the benefits
of OOP, they talk about code-reuse. As another example, again, he
claims, this is not the real case in real world. code-reuse is harder
than what's claimed in universities:

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

It's interesting for me to know how people in stack-overflow think
about this? Is OOP the dominant programming model from programmers'
point of view?

If I should choose/learn/use just one approach, is it OOP or not? why?

答:
Of course it is, because it's the latest buzzword that management has latched on to.  It also offers better encapsulation and abstraction that imperative programming, so I think the leap from oop to whatever comes next might take even longer than imperative to oop took.

PS2: If I should choose/learn/use just one approach, is it OOP or not? why?

If you're only going to learn one you should pick a different field.

You should learn about types and encapsulation and all of the other benefits of OOP, and then learn how to accomplish those same things using a functional style of programming.

ContentLicense: CC BY-SA 2.5


问:
When to use generics in interface design
I have some interfaces that I intend third-parties to implement in the future, and I provide a base implementation myself. I'll only be using a couple to show the example.

Currently, they are defined as

Item:

```<code>public interface Item {

    String getId();

    String getName();
}
</code>```

ItemStack:

```<code>public interface ItemStackFactory {

    ItemStack createItemStack(Item item, int quantity);
}
</code>```

ItemStackContainer:

```<code>public interface ItemStackContainer {

    default void add(ItemStack stack) {
        add(stack, 1);
    }

    void add(ItemStack stack, int quantity);
}
</code>```

Now, Item and ItemStackFactory I can absolutely foresee some third-party needing to extend it in the future. ItemStackContainer could also be extended in the future, but not in ways that I can foresee, outside my provided default implementation.

Now, I'm trying to make this library as robust as possible; this is still in the early-stages (pre-pre-alpha) so this may be an act of over engineering (YAGNI). Is this an appropriate place to use generics?

```<code>public interface ItemStack<T extends Item> {

    T getItem();

    int getQuantity();
}
</code>```

And

```<code>public interface ItemStackFactory<T extends ItemStack<I extends Item>> {

    T createItemStack(I item, int quantity);
}
</code>```

I fear that this may end up making implementations and usage more difficult to read and understand; I think it's the recommendation to avoid nesting generics wherever possible.

答:
You use generics in your interface when your implementation is likely to be generic as well.

For example, any data structure that can accept arbitrary objects is a good candidate for a generic interface.  Examples: List<T> and Dictionary<K,V>.

Any situation where you want to improve type safety in a generalized way is a good candidate for generics.  A List<String> is a list that only operates on strings.

Any situation where you want to apply SRP in a generalized way and avoid type-specific methods is a good candidate for generics.  For example, a PersonDocument, PlaceDocument and ThingDocument can be replaced with a Document<T>.

The Abstract Factory pattern is a good use case for a generic, while an ordinary Factory Method would simply create objects that inherit from a common, concrete interface.


问:
Open Source PHP Encoder
Are there some recomendations on Open Source or Free PHP Encoder systems?
Is something available?

答:
Obfuscating PHP just makes it difficult for the casual observer to study the code. It will not keep someone who is determined at bay for very long. Granted, the unobfuscated version they're able to produce might not match your code line by line, but it will be close enough.

The only reason I could see to use one would be to ensure that people did not short circuit a licensing check, however even that is trivial to accomplish in most cases.

I recommend just trusting your customers, or build offerings that are designed to be delivered mostly, if not entirely as a service.

That being said, you can try actually compiling your PHP apps into native executables that work via FCGI dispatch or come complete with an embedded web server. Tools to help you do that are the PHP Compiler (phpcompiler.org) and Roadsend.

Still, you won't stop someone who is determined to modify their copy, or study how it works.

Title: Open Source PHP Encoder


问:
What is the most reliable session storage in PHP: Memcache, database or files?
What is the best and most safest way to handle PHP sessions. Is the best way to store sessions in:

Database (more reliable, but high bottleneck, slow speed, not good for high database usage websites)?

Memcache (super fast, but distributed more security problems, chances of loosing data when the server restarted and chances of loosing data when the cache is full)?

Files (default option, I guess slow since it reads and writes from file I/O, less security, etc).

Which method is the best? What are the problems and good things of each of those approaches?

答:
This blog post shows the results of a performance comparison of different session storage engines with Magento and they seem to have concluded that up to about 75 concurrent users there isn't really a performance difference between them.

I think that at these levels (they had about 5 transactions a second, which would be about 430k hits over a 12 hour period) the overhead in everything else dominates the performance numbers you see since file/DB/Memcache/Redis will all happily handle the traffic without breaking a sweat if used properly.

That leaves other factors such as scalability, reliability and security.

I'd first like to say that anything that compromises your file storage will also likely compromise anything else since an attacker can then just modify your application code or at the very least discover keys and storage access protocols/credentials even if they have read-only access. File storage will work well for a low volume site, is easy to set up and is easy to reason about. As much as you say you hit the disk, a DB read will also hit disk and if the DB can cache it, your OS will also likely have cached the session file. Also, its one file read, and your file system is brilliant at getting to it if you already know its name. If you're using PHP, do you know how many file reads the system has to do just to serve your application? The downside is that you can't go too far as you will quickly reach the limit of the number of files you can keep on a single disk.

Memcache is relatively fast and if you're considering Memcache class solutions more broadly (Redis, etc) there are some that will even promise persistence with in memory reads for speed so you get the most of both worlds. They are also relatively simple to reason about and the key-value nature of sessions is exactly what these have been designed to do. Do you know how much you would have to put into a session to fill one of these up? Either, way, all of your options will force you to compromise if you reach their capacity. Disks fill up with files (number and size factor in here), cache stores fill up in capacity and databases have limited numbers of rows and the same disk capacity limits as the file approach. Also, these systems are only distributed if you run them in a distributed fashion. Most work just fine with a single server setup. If you distribute them then you probably already have distributed web servers / database servers etc so your distributed system problems certainly won't be appearing from your session storage choice. However, when you want 10x the traffic/capacity etc, getting there is much more natural with this than it is with the file storage scheme. Some key/value stores will also allow you to conduct simple analyses of the session data relatively easily but most won't get you anywhere near what SQL can do.

I'm not sure why you propose that database may be more reliable than the other options, but I get the appeal of the database since your PHP application probably already makes use of it. This means you don't add another server dependency and you can probably reuse the same connection you use to fetch session data to get user data so you don't have to establish one for data, one for Memcache, etc. If you index the table well, it will also perform reasonably fast and provides pretty simple semantics you already familiar with for reaping old sessions or even analyzing session data (I'm not sure why you would want to and if you aren't either, this probably doesn't matter so much). Scaling to massive scales isn't as trivial as with something like Redis, but going from one PHP server to two both accessing the same DB is pretty simple.

I think this choice isn't so important in the beginning. Each approach has challenges and advantages and things you have to think about. Generally speaking, you can probably get away with just using the defaults of PHP/whatever framework you use or even just the easiest thing to get going with. If the choice turns out to be bad later on, your performance analytics will tell you and you will be armed with the data you need to make the appropriate choices given the specific nature of the traffic you get. Up front, all you can reasonably have is general speculation.


答:
Your plan of how to introduce generality to your interface appears to be correct to me.  However, your question of whether that would be a good idea or not requires a somewhat more complicated answer.

Over the years I have interviewed a number of candidates for Software Engineering positions on behalf of companies that I have worked for, and I have come to realize that the majority of job seekers out there are comfortable with using generic classes, (for example, the standard collection classes,) but not with writing generic classes.  Most have never written a single generic class in their career, and look as if they would be completely lost if asked to write one.  So, if you force the use of generics upon anyone wishing to implement your interface or extend your base implementations, you may be putting people off.

What you can try, however, is to provide both generic and non-generic versions of your interfaces and your base implementations, so that people who do not do generics can live happily in their narrow, type-cast-heavy world, while people who do generics can reap the benefits of their broader understanding of the language.

Title: When to use generics in interface design

Body:
I have some interfaces that I intend third-parties to implement in the future, and I provide a base implementation myself. I'll only be using a couple to show the example.

Currently, they are defined as

Item:

```<code>public interface Item {

    String getId();

    String getName();
}
</code>```

ItemStack:

```<code>public interface ItemStackFactory {

    ItemStack createItemStack(Item item, int quantity);
}
</code>```

ItemStackContainer:

```<code>public interface ItemStackContainer {

    default void add(ItemStack stack) {
        add(stack, 1);
    }

    void add(ItemStack stack, int quantity);
}
</code>```

Now, Item and ItemStackFactory I can absolutely foresee some third-party needing to extend it in the future. ItemStackContainer could also be extended in the future, but not in ways that I can foresee, outside my provided default implementation.

Now, I'm trying to make this library as robust as possible; this is still in the early-stages (pre-pre-alpha) so this may be an act of over engineering (YAGNI). Is this an appropriate place to use generics?

```<code>public interface ItemStack<T extends Item> {

    T getItem();

    int getQuantity();
}
</code>```

And

```<code>public interface ItemStackFactory<T extends ItemStack<I extends Item>> {

    T createItemStack(I item, int quantity);
}
</code>```

I fear that this may end up making implementations and usage more difficult to read and understand; I think it's the recommendation to avoid nesting generics wherever possible.


问:
Breaking ASP .NET MVC application into microservices
I have a big ASP .NET MVC application which consists of several different widgets. They all display some kind of data related to stock markets, but they're actually pretty separated from one another. I'd like to break the big monolithic app into several smaller services which should be easier to maintain.

It would be pretty simple if I had only server side code written in C#, but actually I also have quite a few javascript components and also some styles and other resources. I don't know where they should be put. From the separation perspective, if some javascript files are used only by one specific widget, they should be part of its service. On the other hand, I don't know how to later integrate all the widgets and their resources, especially when there might be some common scripts used by all components.

So far I've had two ideas, none of which seems ideal:

Separate only the server side code and leave all the client side components in one common project. Js integration, minimization and management would be easier, but developers still would need to work on two different projects when updating one specific service.

Create nuget packages for each microservice with both server and client side code. What about common scripts then and files dependent on them? If I made a breaking change in common infrastructure, I would need to manually update all the dependent code. It would be much more difficult that updating files when they all reside in the same project.

Are there any better solutions?

答:
You might consider merging your UI logic with server-side logic, and segmenting the results into Bounded Contexts that encapsulate Microservices. Here is a tutorial to get started.

Here is the summary:

UI logic should focus on rendering, but not managing, data. Migrating logic from UI to server allows you to group your entire feature-set within the same application tier. Abstract and sufficiently cover core feature logic in terms of unit-tests. This should yield a well-defined set of APIs that your Microservices can leverage. Then split the feature-set into Microservices.

Create a reusable Microservice template. This should be a boiler-plate structure that allows the rapid implementation of Microservices. Core feature logic should be hosted within Microservice templates.

Implement the queue-pooling concept to ensure reliable message delivery. This is a more advanced concept to guarantee reliable message delivery. Remember – you’ll likely leverage a service bus in order to interface your Microservices.


问:
Distributed application using RabbitMQ
I am on my way to create an application with 4 bounded context using CQRS & event sourcing.

In order to make these bounded context talk to each other I was planning on using Rabbit MQ.

My requisites are the following :

The bounded context must not know about each other

The bounded context must not be hindered if the other bounded context are down or if rabbitMQ is down

If a bounded context is not available the messages, that it should receive, must wait patiently for its return ie : every event published must be forwarded at least once to all the bc interested.

Therefore, I was thinking about having each of them referencing a queue : BandMasterQueue
and creates it if it is not.

When producing an event, the event store stores it and its dispatch consists of two steps :

project on itself this event to every little projection. Each projection has a little tiny store of events already projected to warrant  idempotency over some period of time.

publish this event to the queue BandMasterQueue

if it would fail on step 2 because of no rabbitmq available, then I expect my event store to try again to dispatch the message to the RabbitMQ after sometime (not really though precisely about this part, I must say...)

The bandMaster "bounded context" knows about every different BCs he looks after. He is the one reading the bandMasterQueue and decides which events are public and which are not.
He is also responsible to handle the "sagas" and can send corrective actions to each bc.

In order to do that, he will comunicate with each bounded context using the dedicated queue of the bounded context and creates it if it does not exits.

Each BC is bound to this specific queue, and add the event coming from outside in its own event store, and afterwards project it to its own projection.

Should this "architecture" work or do you see any major flaw in it?

答: You might consider using a Queue Pooling mechanism in order to manage RabbitMQ Queues, and also to determine necessary pool-size under load. Here is a tutorial on the subject.</p>

Title: Distributed application using RabbitMQ


问:
What should my user object know?
I have an architecture problem/doubt and I'd like some insight on this.

Context :

We're in a mobile app that solely relies on webservice calls to be used. There can only be one user logged in at any given time and all calls require a user. We're talking about (for the sake of examples and clarity) meetings (one user has a meeting) and visitors (a visitor is a contact, not another user).

The debate :

We've been arguing for about an hour. One side wants to have several "Managers" or "Services" that handle, say, the meetings and take a user in parameter. This service/manager is called when needed to get a list of meetings, and is given the current user. This looks clean, not coupled (well separated), and pretty clear without being cluttered and complicated.

The other side say that there are no actions that a user can make without being logged in, and all those services will need a user as parameter. So we might as well have all those services called by the user itself, and simply use user.GetMeetings(); when we want those meetings. This user would be able to check all that by itself, .isLoggedIn, or .logIn, and much more.

One one hand, this looks "simpler" on the outside, we always call a user method and our viewmodels don't know about anything but a user.
On the other hand this really just looks like a giant wrapper that pretty much covers the whole application (which extends further than meetigns and visitors).

There would be that user layer that does everything through the current user, and all those services would still exist but only the user would call it, and we're just turning in circle because " the user is everywhere anyway, and the services would be called everywhere anyway ". But the user doing everything looks so tightly coupled to the services that it feels wrong, even though only him uses it and ever will.

Anyway, I'd like to know what you guys think, is there something better? Is there a standard? Is there a wrong answer in my two situations? Note (and that's important) that we're only debating in the context of our app, not in general. Obviously if users had to interact with each other, if you had anonymous users or many more situations, this wouldn't work. But we know that this will always stay the same, the user will always be needed for the webservice calls, and there will always be only one user. I've been sitting there and listening to them and I'm just confused, and curious to have an external feedback on this.

I'm not talking about a massive big god-class for the User. In both cases all the calls are made in separate services/manager classes. The big difference are the following :

Case 1 : My model knows the current user and the service it needs (eg: MeetingService ), and simply asks the meeting service to get all the meetings and gives it the current user as a parameter.

Case 2 : My model only knows the current user and asks him to get all the meetings ( .GetMyMeetings();), without caring how he does it. The user itself simply knows all the different services he might need and, in that case, being calls the MeetingService and returns whatever was asked.

We're really just adding a layer into our hierarchy, so that they all combine in the user.

But code-wise, the user won't get that big, it'll probably end up being about 100 lines long, including properties and all the methods we'll need.

答:
Each service should be self-contained.

Most devs know that when something is "set in stone", it will change on you when you least expect it, forcing you to re-architect your solution.

You should always design your solutions to be correct from a technological stance even if it makes things a little more complicated in the beginning.

Separation of concerns is your greatest tool to preventing you from coding yourself into a corner.

Two years from now the requirements might change and suddenly you need to allow anonymous users to create a meeting (say you move to a freemium model).  Now you have to re-architect your User class to either have a anonymous User object or you have to move all those meeting function calls out of the User object, into the proper location in the Meeting service.

Or you setup continuous meetings where no one person is the creator of the meeting, now the User object is completely decoupled from the creation of a meeting.  The creator of a meeting may be a Company object or tied to a Room object.

You can always expect requirements to become more complex and convoluted, you should plan for that now.

Title: What should my user object know?


问:
What does your Technical Documentation look like?
I'm working on a large project and I would like to put together some technical documentation for other members of the team and for new programmers joining the project.

What sort of documentation should I have? Just /// code comments or some other file(s) explaining the architecture and class design?

I've never really done documentation except the occasional word doc to go with smaller apps, and I think this project is too large to doc in a single word file.

答:
I have written - and benefited from - the following:

Architecture documents that explain either the system or an individual component as a whole. These are great for new hires to read to get the "big picture" on how your stuff works. Typically these contain high-level diagrams that explain how different parts of the system communicate with one another, along with an explanation of each component of the system, what its role is, etc.

Formal design documents; when writing these, each is prepared with a specific feature in mind, and goes through a formal review process. Although these do not always stay up-to-date years down the road, they give good insight into each individual feature. This documentation lists the formal requirements, data flow diagrams, class diagrams, and details the modifications to the system by technical area (database, middleware, user interface, etc). It may be difficult (if not impossible) to write these after-the-fact, though. Your best bet with these documents is to include them as part of your development process, if it makes sense for your team.

Comments in the code that can be transformed into API documentation, such as JavaDoc. These are good to have for reference, to explain things at a much lower level.

You may not be the one preparing these, but they can be useful as well:

User Manuals, Guides, etc - For a new hire, these can be helpful to get a different perspective on how the actual product is indented to be used by your customers.

Test plans - Very tedious to read and more "interactive documentation", but sometimes the best way for a new hire to learn is to run through the test cases on an actual system.

Requirements documents may also be helpful depending on how well they are written, although honestly I have found other forms of documentation more useful for understanding how the system works. Requirements documents are better for driving your design efforts.


问:
Using Entity Framework, non-MVC project, need help with class structure
I'm working on a very large non-MVC project utilizing Entity Framework for database access.  This is a new project, so we've got a wide-open canvas for development.

The conceptual problem I'm running into is how to model the layer just above the EF Models.

At the database level I've got a Customer, Order, and Item table so there's a model for each.

Now I need to describe what the Customer can do.  For example, ultimately I want to say something like:

```<code> Order newOrder = customerObject.CreateOrder(itemList);
</code>```

Where does the method CreateOrder live?

My gut tells me that there's a sub-class of the Customer Model that has the methods needed by the Customer.  With an interface to that class up front to keep the cross-dependencies between modules low.

But this sounds too easy to be the correct way.

Some related questions I've found, but didn't exactly apply are:

Different kind of problem, and the proposed solution is to make the models into partial classes

This is discussing the full layer management, and obviously a smaller problem

答:
The one that I have used which worked quite nicely. Basically used repositories to house the methods called. Everything was divided into:

Context: Sets up your db context using the below, implements System.Data.Entity.DbContext. It contains DbSet's of your entities. So a sample will look like below:

```<code>public DbSet<Customer> Customers { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<CustomerDatabaseContext>(null);

    modelBuilder.Configurations.Add(new CustomerConfiguration());
}
</code>```

Entities: Literal mapping of db object

```<code>public class Customer
{
    public long Id {get; set;}

    public string Name {get; set;}
}
</code>```

Configurations: Setting up your entity

```<code>public class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
    public CustomerConfiguration()
    {
        this.Property(x => x.Id).HasColumnName("CustomerId");
        this.HasKey(x => x.Id);
        this.Property(x => x.Name);
    }
}
</code>```

Repositories: Holds all the methods e.g.

```<code>public Customer GetById(long identity)
{
    using (var context = CustomerDatabaseContext.Start())
    {
        return context.Customers.FirstOrDefault(x => x.Id == identity);
    }
}
</code>```

The repositories are initialised in code and used e.g.

```<code>var customer = this.repository.GetById(request.CustomerId);
</code>```

Body:
The one that I have used which worked quite nicely. Basically used repositories to house the methods called. Everything was divided into:

Context: Sets up your db context using the below, implements System.Data.Entity.DbContext. It contains DbSet's of your entities. So a sample will look like below:

public DbSet<Customer> Customers { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<CustomerDatabaseContext>(null);

    modelBuilder.Configurations.Add(new CustomerConfiguration());
}

Entities: Literal mapping of db object

public class Customer
{
    public long Id {get; set;}

    public string Name {get; set;}
}

Configurations: Setting up your entity

public class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
    public CustomerConfiguration()
    {
        this.Property(x => x.Id).HasColumnName("CustomerId");
        this.HasKey(x => x.Id);
        this.Property(x => x.Name);
    }
}

Repositories: Holds all the methods e.g.

public Customer GetById(long identity)
{
    using (var context = CustomerDatabaseContext.Start())
    {
        return context.Customers.FirstOrDefault(x => x.Id == identity);
    }
}

The repositories are initialised in code and used e.g.

var customer = this.repository.GetById(request.CustomerId);


答:
Now, Item and ItemStackFactory I can absolutely foresee some third-party needing to extend it in the future.

There's your decision made for you. If you do not provide generics they will need to up-cast to their implementation of Item every time they use:

```<code>class MyItem implements Item {
}
MyItem item = new MyItem();
ItemStack is = createItemStack(item, 10);
// They would have to cast here.
MyItem theItem = (MyItem)is.getItem();
</code>```

You should at least make ItemStack generic in the way you suggest. The deepest benefit of generics is that you almost never need to cast anything, and offering code that forces users to cast is IMHO a criminal offence.

Body:
Now, Item and ItemStackFactory I can absolutely foresee some third-party needing to extend it in the future.

There's your decision made for you. If you do not provide generics they will need to up-cast to their implementation of Item every time they use:

class MyItem implements Item {
}
MyItem item = new MyItem();
ItemStack is = createItemStack(item, 10);
// They would have to cast here.
MyItem theItem = (MyItem)is.getItem();

You should at least make ItemStack generic in the way you suggest. The deepest benefit of generics is that you almost never need to cast anything, and offering code that forces users to cast is IMHO a criminal offence.


答:
Everyone appears to be on the repository train. Given EF is already a repository, I would push to house business logic on a service layer. A service doesn't necessarily have to be in a new library (though it could), but does provide that additional logic atop the base entities. To illustrate:

```<code>public interface IOrderService : IDisposable
{
    Order Create(Customer customer, params Item[] items);
}

public class OrderService : IOrderService
{
    private DbContext context;

    public OrderService(DbContext context)
    {
        Contract.Requires(context != null);

        this.context = context;
    }

    public Order Create(Customer customer, params Item[] items)
    {
        Contract.Requires(customer != null);
        Contract.Requires(items != null);
        Contract.Requires(items.Length > 0);
        Contract.Ensures(Contract.Result<Order>() != null);

        Order order;

        //
        // Business logic building order;
        //

        return order;
    }
}
</code>```

Then usage would look something like:

```<code>// -- Existing variables --
var db = /* your EF context */;
var customer = /* your targetted customer */;
var items = /* the items to be added */;
// -- /Existing variables --

// Executing against new service
var orderSvc = new OrderService(db);
var newOrder = orderSvc.Create(customer, items);
</code>```

Commentary

All a repository pattern does (on top of an ORM) is abstract out the API that's already there. Now you're duplicating efforts, and, a lot of the time, losing some very cool features of the ORM itself (this is why you chose the ORM over using SqlConnection I would presume...). Sure, you might change out your ORM months/years from now, but is it worth the up-front effort? (That's for you to decide)

Title: Using Entity Framework, non-MVC project, need help with class structure

Body:
I'm working on a very large non-MVC project utilizing Entity Framework for database access.  This is a new project, so we've got a wide-open canvas for development.

The conceptual problem I'm running into is how to model the layer just above the EF Models.

At the database level I've got a Customer, Order, and Item table so there's a model for each.

Now I need to describe what the Customer can do.  For example, ultimately I want to say something like:

```<code> Order newOrder = customerObject.CreateOrder(itemList);
</code>```

Where does the method CreateOrder live?

My gut tells me that there's a sub-class of the Customer Model that has the methods needed by the Customer.  With an interface to that class up front to keep the cross-dependencies between modules low.

But this sounds too easy to be the correct way.

Some related questions I've found, but didn't exactly apply are:

Different kind of problem, and the proposed solution is to make the models into partial classes

This is discussing the full layer management, and obviously a smaller problem

Body:
Everyone appears to be on the repository train. Given EF is already a repository, I would push to house business logic on a service layer. A service doesn't necessarily have to be in a new library (though it could), but does provide that additional logic atop the base entities. To illustrate:

public interface IOrderService : IDisposable
{
    Order Create(Customer customer, params Item[] items);
}

public class OrderService : IOrderService
{
    private DbContext context;

    public OrderService(DbContext context)
    {
        Contract.Requires(context != null);

        this.context = context;
    }

    public Order Create(Customer customer, params Item[] items)
    {
        Contract.Requires(customer != null);
        Contract.Requires(items != null);
        Contract.Requires(items.Length > 0);
        Contract.Ensures(Contract.Result<Order>() != null);

        Order order;

        //
        // Business logic building order;
        //

        return order;
    }
}

Then usage would look something like:

// -- Existing variables --
var db = /* your EF context */;
var customer = /* your targetted customer */;
var items = /* the items to be added */;
// -- /Existing variables --

// Executing against new service
var orderSvc = new OrderService(db);
var newOrder = orderSvc.Create(customer, items);

Commentary

All a repository pattern does (on top of an ORM) is abstract out the API that's already there. Now you're duplicating efforts, and, a lot of the time, losing some very cool features of the ORM itself (this is why you chose the ORM over using SqlConnection I would presume...). Sure, you might change out your ORM months/years from now, but is it worth the up-front effort? (That's for you to decide)


问:
Design decisions while porting a non object-oriented C program to Java
Background:
My boss made a comment on porting a C program that acts as some a simulator that communicates with a remote process through sockets to Java. He didn't assign it to me, or to anyone for that matter, it was just a project he had in mind. He showed and gave me access to the C source code file for said program so I could take a look.

Now I'm an intern in this company and haven't really been assigned something in particular so I wanted to start this project on my own and then show it to my boss.

Problem:
The C program is ~4k lines long. It consists on many global variables and functions that use those variables; I guess this is mainly to avoid passing many parameters. There are even some goto statements (yeah, also most of the codebase is from 1980). So basically my question is: should I aim to replicate the structure of the C program in a single Java class so there is a visible mapping of behavior between both? Or should I come up with
a better object oriented design that may imply the creation of many components? What would be your approach to solving this problem?

Thanks.

答:
Do it both ways.

Make one new Java class to match as closely to the original C as you can, using static variables in the same way the C code does. In most cases do a direct one-to-one translate of each line of code. Even use the same loop types, parameter names, method names and variable names and even keep the gotos.

Test that code to the maximum possible, comparing it against the C version in every way you can.

Write tests for the new code that tests all of the functionality you can. Ideally testing the metrics you used in 2 above.

Take a copy of that class.

Refactor it into objects using patterns, interfaces and a good OOP design. Retain notes on every refactor, especially the gotos, trying to prove that your refactor cannot change the final result.

Test the new class with the old tests written in 3 above.

Repeat from 5 until satisfied.

With this approach you should achieve not only a perfect clone of the original code but it should also be both testably (from your tests) and provably (from your notes) correct.


答:
I would go with the Service.GetMeetings(user u) approach.

Here's my reasoning.

In my experience the only difference between these two approaches once you add DTOs and hosting projects for your services is naming.

If you keep the logic out of User, then User is equivalent to your what your UserDTO would have been

Your new Service Class seems like an extra 'Helper' function until you expose User.GetMeetings() through IUser and a hosting rest/wcf/own project in which case you end up with a bunch of extra classes anyway.

So overall, the Service.GetMeetings(user u) means less code and easier code reuse. you can stick your user and meeting classes in a portable class lib and share them with your app.

Title: What should my user object know?

Body:
I have an architecture problem/doubt and I'd like some insight on this.

Context :

We're in a mobile app that solely relies on webservice calls to be used. There can only be one user logged in at any given time and all calls require a user. We're talking about (for the sake of examples and clarity) meetings (one user has a meeting) and visitors (a visitor is a contact, not another user).

The debate :

We've been arguing for about an hour. One side wants to have several "Managers" or "Services" that handle, say, the meetings and take a user in parameter. This service/manager is called when needed to get a list of meetings, and is given the current user. This looks clean, not coupled (well separated), and pretty clear without being cluttered and complicated.

The other side say that there are no actions that a user can make without being logged in, and all those services will need a user as parameter. So we might as well have all those services called by the user itself, and simply use user.GetMeetings(); when we want those meetings. This user would be able to check all that by itself, .isLoggedIn, or .logIn, and much more.

One one hand, this looks "simpler" on the outside, we always call a user method and our viewmodels don't know about anything but a user.
On the other hand this really just looks like a giant wrapper that pretty much covers the whole application (which extends further than meetigns and visitors).

There would be that user layer that does everything through the current user, and all those services would still exist but only the user would call it, and we're just turning in circle because " the user is everywhere anyway, and the services would be called everywhere anyway ". But the user doing everything looks so tightly coupled to the services that it feels wrong, even though only him uses it and ever will.

Anyway, I'd like to know what you guys think, is there something better? Is there a standard? Is there a wrong answer in my two situations? Note (and that's important) that we're only debating in the context of our app, not in general. Obviously if users had to interact with each other, if you had anonymous users or many more situations, this wouldn't work. But we know that this will always stay the same, the user will always be needed for the webservice calls, and there will always be only one user. I've been sitting there and listening to them and I'm just confused, and curious to have an external feedback on this.

I'm not talking about a massive big god-class for the User. In both cases all the calls are made in separate services/manager classes. The big difference are the following :

Case 1 : My model knows the current user and the service it needs (eg: MeetingService ), and simply asks the meeting service to get all the meetings and gives it the current user as a parameter.

Case 2 : My model only knows the current user and asks him to get all the meetings ( .GetMyMeetings();), without caring how he does it. The user itself simply knows all the different services he might need and, in that case, being calls the MeetingService and returns whatever was asked.

We're really just adding a layer into our hierarchy, so that they all combine in the user.

But code-wise, the user won't get that big, it'll probably end up being about 100 lines long, including properties and all the methods we'll need.


答:
it feels like somewhere in my code there will have to be something that checks the type or knows about each type even if it is just in an IOC container configuration.

The Command Pattern

A nod to @Stephen comment.

The command pattern decouples the "request" from the requestor. Quoting the linked site:

encapsulate a request in an object

allows the parameterization of clients with different requests

allows saving the requests in a queue

Title: Fix a leaky abstraction (type checking)

Body:
I have a method that accepts an interface and does type checking on the parameter, and depending upon the type a decision is made to either send an email or an alert

```<code>    public void Bar(ISomeInterface someClass)
    {
        if (someClass is SomeClassToo)
        {
            Emailer.Send(someClass.Something());
        }
        else
        {
            Alerter.Alert(someClass.Something());
        }
    }
</code>```

I know this is bad for obvious reasons, but I would like to know what other options I have to resolve this, as one of the solutions I have is to put an abstraction on each of the classes that implements ISomeInterface for the emailer/alerter using an ICommunicator (see below) but I am not sure that is right as it feels like somewhere in my code there will have to be something that checks the type or knows about each type even if it is just in an IOC container configuration.

```<code>public class SomeClass : ISomeInterface
{
    private ICommunicator _communicator;

    public SomeClass(ICommunicator communicator)
    {
        _communicator = communicator;
    }

    public void Something()
    {
        if (_communicator != null)
        {
            _communicator.Send("yee ha");
        }
    }
</code>```


问:
Multiple Small Programs Connected via Sockets vs One Large Program
I am at the beginning of a project which involves reading from several sensors and fusing the data from those sensors together. Altogether there will be 4 sensors connected via USB and a webcam, also connected via USB.

One of my colleagues is very vocal about how nice it is to split up programs into smaller parts and have them communicate over the network. He suggests that we should have an executable for each sensor (or camera) and then a central controlling application which communicates with the others.

I intuitively don't like this idea. The colleague in question worked on another project which used that approach and had no end of problems that were hard to track down and debug.

It doesn't seem like a very state-ful design and strikes me as somewhat inelegant. I would like to write a library for dealing with each sensor and maybe run them in separate threads.

It should also be pointed out that the calculations we need to do will provide updates to another system at nearly 1000Hz. Adding in a layer of network communications seems like adding a potential bottleneck.

I would be interested to hear other peoples' opinions on this and perhaps some references regarding this type of practice.

答:
I intuitively don't like this idea.

Well, intuitively, I like the idea of splitting up programs into smaller parts. But if the different processes run always all on the same machine, network communication is probably not the optimal form of IPC. For highspeed communication between processes, shared memory might be the better option. But whatever approach you choose, you have to measure or at least estimate the performance before making any judgement calls.

The colleague in question worked on another project which used that approach and had no end of problems that were hard to track down and debug.

You have to check what kind of problems, and where the root causes were. If they had problems because of concurrency, you will pretty much encounter the same problems (if not more) when you try a multi-threaded solution.

provide updates to another system at nearly 1000Hz

If that is "high speed", depends on the speed of the production machines, and the size of operation involved in each update. When it comes to performance, gut feelings are extremely unreliable, you need to measure things. If your colleague believes his approach will be fast enough, and you believe it will not, at least one of you will have to proof or falsify his believe. For example, one of you could implement a small prototype to simulate the interprocess communication, and measure the speed. Everything else is looking into a glass bowl.


答:
Unless User must have a Service to do user things, do not make the user pretend to be the application context/ overall state.

"Convenience" and "LOC per class" are not design principles.

Focus your classes sharply. Fanatically adhere to single responsibility principle.

the user won't get that big

Irrelevant.

it'll probably end up being about 100 lines long

Irrelevant.

including properties and all the methods we'll need.

SRP violations in progress.

There can only be one user logged in at any given time and all calls require a user.

This is state that neither the User nor Service can possibly know by themselves, in isolation so to speak. This state is particular to the broader application context. So you need one or more other classes - ApplicationContext let's say, that knows this context and queries the participating objects for what they know (I, the user, am logged in for example) thus doing ApplicationContext things.

We're really just adding a layer into our hierarchy, so that they all combine in the user.

"combine in the user" is categorically not "adding a layer into our hierarchy". Adding a layer would be something like the above.

Title: What should my user object know?


答:
The approach your colleague is advocating is often referred to as a microservices architecture and is quite in vogue these days. It has a number of potential advantages:

Scalability: it can make it relatively easy to scale by simply adding extra machines / VM instances.

Robustness: with an appropriate design it can be made tolerant to individual microservice processes crashing, losing connectivity or otherwise becoming unavailable.

Extensibility: using standard Web technologies to interface between microservices (typically http REST requests with Json or XML responses) can make it relatively easy for third parties or customers to interface with your system and extend it for their own needs.

It also has a number of disadvantages:

Performance: generally you will pay a performance cost for the inter-process communication. This may be very significant if you build http REST style APIs.

Complexity: typically you will need quite a lot of extra code to marshall data between processes vs. just passing data around between threads in a single process. You will also introduce dependencies on libraries for network communication, http support, etc.

Debuggability: it is typically more complex to debug an application made up of multiple independent communicating processes vs. using an IDE's integrated debugger on a single process.

I'm not sure quite what you mean when you say the design "doesn't seem like a very state-ful design". Generally "state-ful" is considered a bad characteristic of a design and "stateless" microservices are considered good design.

Given the information on your requirements you provide in your post however, I think a microservices based design would be overkill for your use case and the benefits would not justify the additional complexity. The benefits of microservices architectures tend to only really come into play when building larger scale web services that place a premium on scalability, robustness and extensibility.

The potential benefits of a microservices architecture are only realized with a well thought out design as well. In my opinion, such an architecture requires more up-front design (particularly when it comes to the protocol for communicating between microservices) than a single process design if it is to be successful at solving the problem at hand.

Title: Multiple Small Programs Connected via Sockets vs One Large Program

Body:
I am at the beginning of a project which involves reading from several sensors and fusing the data from those sensors together. Altogether there will be 4 sensors connected via USB and a webcam, also connected via USB.

One of my colleagues is very vocal about how nice it is to split up programs into smaller parts and have them communicate over the network. He suggests that we should have an executable for each sensor (or camera) and then a central controlling application which communicates with the others.

I intuitively don't like this idea. The colleague in question worked on another project which used that approach and had no end of problems that were hard to track down and debug.

It doesn't seem like a very state-ful design and strikes me as somewhat inelegant. I would like to write a library for dealing with each sensor and maybe run them in separate threads.

It should also be pointed out that the calculations we need to do will provide updates to another system at nearly 1000Hz. Adding in a layer of network communications seems like adding a potential bottleneck.

I would be interested to hear other peoples' opinions on this and perhaps some references regarding this type of practice.


答:
They may or may not be relevant to your application, but some benefits to the multi-process solution you haven't seemed to consider are:

Finer-grained permission control.  You can have separate permissions for the webcam and the other sensors.

Easier to test sensors in isolation.

Easier to mock out a sensor at runtime.

Easier to get third parties to write code for their sensors without having to open your code.

Use of tools like wireshark for troubleshooting, both during development and in the field.

The only context I'm aware of where "stateful" is seen as a positive attribute is when the stateful parts of a system are restricted to a small scope like an actor, which seems to support your colleague's design more than yours.

Easier to release a lock and restart just one sensor's process without having to restart the entire system.

Can scale just by adding hardware.

Socket communication with source and dest on the same machine is relatively efficient.

Additional drawbacks to the multi-process solution:

Dealing with backpressure is more complex.

If you're essentially just passing on the raw data from each sensor without any filtering or processing, you've just changed your controller application from reading from a usb driver to reading from a network driver, without any real gain in abstraction.


问:
Monitoring a web service
I don't know how to phrase this question properly so please feel free to suggest edits.

I've helped develop an in-house RESTful service for a company I'm working for, and it seems to have hit a wall in terms of performance without saturating the network channel (I think). I need to make it run faster, but I don't have enough data to go on. How do I measure, collect and analyze performance metrics like network, disk, memory and CPU usage? Right now I only have timestamped logs so I could try and extract some timing data by parsing them, but it seems like there should be a more straightforward way. Also should I make the system distributed in the future, I'd have to aggregate this data somehow across multiple machines, and I'd have to make this process asynchronous and resistant to network glitches.

What existing tools or general approaches work best in this kind of setup? I'd appreciate any nudge in the right direction, I don't know where to look.

UPD: I'm targeting FreeBSD, my dev box is a MacBook; the heavy lifting parts are written in C++, the talk-to-client parts are written in PHP (currently Yii) run by Apache with an nginx proxy, although I'm considering porting them to C++ and splitting them into multiple parts along the separation of commands and queries line of thought. Currently the command queue is managed by PostgreSQL, and it's one of the things I'm itching to rewrite from scratch. There is a simplistic supervisor that allows me to see the stderr log of the heavy lifting daemon in real time, but otherwise it doesn't do much.

答: I think that you need fisrt isolate your envrioment, and deploy your web service. After that divide your web service in modules to see which module is your bottleneck and fix them or review. I dont know frameworks to do that, but you can use command line linux tools into your isolated envrioment to do that.</p>

Title: Monitoring a web service


问:
Understanding Flux pattern
I'm actually studying the flux pattern and there's something that I can't understand concerning the stores.

What are they exactly?

I have read many articles, and it seems that it concerns the domain.

Does it mean that this is the "abstract" part related to api calls or backend calls?

It's not very clear for me.

Edit: Could it be the same thing as the angular factory? Fetching remote data, making a business task or store some app states (current user connected for example)?

答:
Looking up a simple example (https://github.com/facebook/flux/tree/master/examples/flux-todomvc/), “stores manage the application state for a particular domain within the application.“  That is, they contain data about the state of an aspect of the application and all the code to change it.  Whenever there’s an new update from the Dispatcher, all the Stores see it, they decide how to update their data in response, and then they notify the Views that the data has changed.  In the examples, Stores contain things like “unseen threads list” (where the Dispatcher notifies them that a new message has arrived or an old one has been read, and the Views display the message threads to the user) and “current playback time and state.”

More technically: they’re the intermediate layer of the framework that registers callbacks with the Dispatcher to receive updates, then notifies the Views when the state of the data changes.  (The views might then send actions back to the Dispatcher.)  There’s an abstract interface they implement, where each Store registers a callback with the Dispatcher and broadcasts events to the Views, but each Store seems to represent a specific domain in a concrete way.  (Are there counterexamples?)

Title: Understanding Flux pattern


问:
Dynamic Forms: Pattern or AntiPattern?
I'm sure you've seen it.  The database has a bunch of tables called Forms, Controls,FormsControls, ControlSets, Actions and the program that queries these tables has a dynamically generated user interface.  It will read all the forms, load a home page that has links to them all, or embed them in some tabbed or paged home page, and for each of those forms it will read the various text boxes, check boxes, radio buttons, submit buttons, combo boxes, labels and whatnot from the controls and form-to-control join tables, lay those elements out according to the database and link all the controls to logic according to other rules in the database.

To me, this is an anti-pattern.  It actually make the application more difficult to maintain because the design of it is now spread out into multiple different systems.  Also, the database is not source controlled.  Sure, it may make one or two changes go more quickly, after you've analyzed the program anyway to understand how to change the data and as long as you don't stray from the sort of changes that were anticipated and accounted for, but that's often just not sustainable.

What say you?

答:
I consider the dynamically creation of forms a anti-pattern for tailor-made softwares, but for COTS or package softwares that user can't decide about the behavior or appearance, could be a good choice.
Although it's important to consider the rigidity brought by dynamic forms.

The reason is that for tailor-made sw a simple change request for a form could become a nightmare.

Title: Dynamic Forms: Pattern or AntiPattern?


答:
You can usually collect RAM / disk / CPU / network usage from SNMP data, just enable snmpd. Choose your monitoring solution; anything from something as small as Monit or Icinga to something large like OpenNMS will readily show you these.

Write more to logs, at least during the development and load testing; timestamps uncover a lot. But this may become slow if disk is your bottleneck.

You can collect more detailed data right in the program code and push it into an in-memory database like Redis, or a proper time-series database like OpenTSDB. This should be relatively easy to integrate into your C++ part, and have a reasonably small performance impact.

Title: Monitoring a web service

Body:
I don't know how to phrase this question properly so please feel free to suggest edits.

I've helped develop an in-house RESTful service for a company I'm working for, and it seems to have hit a wall in terms of performance without saturating the network channel (I think). I need to make it run faster, but I don't have enough data to go on. How do I measure, collect and analyze performance metrics like network, disk, memory and CPU usage? Right now I only have timestamped logs so I could try and extract some timing data by parsing them, but it seems like there should be a more straightforward way. Also should I make the system distributed in the future, I'd have to aggregate this data somehow across multiple machines, and I'd have to make this process asynchronous and resistant to network glitches.

What existing tools or general approaches work best in this kind of setup? I'd appreciate any nudge in the right direction, I don't know where to look.

UPD: I'm targeting FreeBSD, my dev box is a MacBook; the heavy lifting parts are written in C++, the talk-to-client parts are written in PHP (currently Yii) run by Apache with an nginx proxy, although I'm considering porting them to C++ and splitting them into multiple parts along the separation of commands and queries line of thought. Currently the command queue is managed by PostgreSQL, and it's one of the things I'm itching to rewrite from scratch. There is a simplistic supervisor that allows me to see the stderr log of the heavy lifting daemon in real time, but otherwise it doesn't do much.


答:
It has advantages and disadvantages.

Advantages:

Changes in forms go live without waiting for deployment or any downtime.

Non-programmers can edit the forms using a friendlier UI.

Disadvantages:

It's easier to break the forms and / or make them incompatible with the backend code.

It requires special custom tools to maintain (though these tools are the whole point).

It may be harder to see the system as a whole (depends on your tools).

It's hard to create a really flexible form editor.

A really flexible form editor becomes as hard to use as code-based editors, or harder.

So I see a few niches where this approach should do well:

When users need to edit forms, but significant constraints are in place (so flexibility is limited, and it's harder to break stuff);

During rapid prototyping, esp. by non-technical users;

When quick dynamic changes to the forms are very important (can't easily invent a case for that, but it may exist).

Everywhere else, I'd take a different approach.

Title: Dynamic Forms: Pattern or AntiPattern?

Body:
I'm sure you've seen it.  The database has a bunch of tables called Forms, Controls,FormsControls, ControlSets, Actions and the program that queries these tables has a dynamically generated user interface.  It will read all the forms, load a home page that has links to them all, or embed them in some tabbed or paged home page, and for each of those forms it will read the various text boxes, check boxes, radio buttons, submit buttons, combo boxes, labels and whatnot from the controls and form-to-control join tables, lay those elements out according to the database and link all the controls to logic according to other rules in the database.

To me, this is an anti-pattern.  It actually make the application more difficult to maintain because the design of it is now spread out into multiple different systems.  Also, the database is not source controlled.  Sure, it may make one or two changes go more quickly, after you've analyzed the program anyway to understand how to change the data and as long as you don't stray from the sort of changes that were anticipated and accounted for, but that's often just not sustainable.

What say you?


问:
What is meant by XML/XSLT/XPath and asynchronous programming?
I understand that (1) XML/XSLT/XPath and (2) asynchronous programming may not be related to one another. My questions are:

When a C# developer job is advertised saying: "the following skill is required as mentioned in 1 and 2", what does it actually mean?

Lets say I need to master these two topics (1 and 2). What do I need to do to accomplish that skill? Are there books for intermediates that actually teach that info with practical scenarios and case studies?

Answers are much appreciated.

I have worked XML packet crafting for message exchange over the network, developed some amateur XML parsers for some projects and done message exchange for a client/server-based messaging system using asynchronous calls. But I really need to know and learn what the companies are looking for when they write these things (1 and 2) as requirements in their job advertisment.

Aggregate skills required for the specific job were:

ASP.NET 2.0 (OK)

Web Services  and .Net Remoting (OK)

XML/XSLT/XPath (?)

Asynchoronous Programming (?)

Windows Services (OK)

Javascript/XML/AJAX (OK)

Microsoft Silverlight/WPF (OK)

So firstly, it's clear that AJAX is not related to Asynchronous programming (in this very specific context) as it is written as a separate required skill (and I hope that it's not a mere redundancy). In normal cases, my deductions would have been the same like asynchronous programming means working with AJAX (asynchronous JavaScript with XML).

Secondly, making a web service in C# does not require any extensive experience with XSLT. In fact, exposing functions from a DLL (encapsulating business logic) is the simplest of any task with web services in C#. I wonder if there is some extra skill or experience that is needed?

答:
I'd take anything in a computer job description written by an non-technical HR person with a grain of salt (if not an entire shaker of the stuff).

"Asynchronous" in this context is nebulous. It could mean "non-blocking I/O" or "multithreaded". For all you know, they might be putting Ajax on there for buzzword value and then putting asynchronous also on there when they're meaning the exact same thing.

Perhaps the XSLT part is for view-layer transformations. Or perhaps they're taking raw SOAP calls and transforming them into JSON on the fly using XSLT. Or maybe it's just another buzzword they thought to put on the requirement list.


问:
Should heavy initialization be stored as a static variable or instance variable?
I have a that class does not really specify any real object on its own but is more of a utility class. It has some data whose initialization is expensive. I see two options on how to store the data:

Store it in a static variable(initialized in a static block).

Pro: I can call the utility methods without having to create an
instance of this class.

Con: The heavy initialization code is run
when the class is loaded, independent of whether it is used or not.

Store it in an instance variable(initialized in the constructor):

Pro: The heavy initialization is only done if the class is used.

Con: In this case I will have to create an object of the class and then call the utility methods through this object. I will also need to avoid creating multiple objects of the utility class.

Which of these two approaches is better?

答:
There are other options. You could use a Singleton where you only initialize the static instance if you call getInstance().

MathUtils.java

```<code>public class MathUtils {

    private static MathUtils mathUtils;

    private MathUtils() {
        //initialization logic here
    }

    public static MathUtils getInstance() {
        if (mathUtils == null ) {
            mathUtils = new MathUtils();
        }
        return mathUtils;
    }

    public int add(int a, int b) {
        return a + b;
    }
}
</code>```

Main.java

```<code>public class Main {

    public static void main(final String[] args) {
        MathUtils mathUtils = MathUtils.getInstance();
        int addition = mathUtils.add(1, 3);
        System.out.println(addition);
    }
}
</code>```

Body:
There are other options. You could use a Singleton where you only initialize the static instance if you call getInstance().

MathUtils.java

public class MathUtils {

    private static MathUtils mathUtils;

    private MathUtils() {
        //initialization logic here
    }

    public static MathUtils getInstance() {
        if (mathUtils == null ) {
            mathUtils = new MathUtils();
        }
        return mathUtils;
    }

    public int add(int a, int b) {
        return a + b;
    }
}

Main.java

public class Main {

    public static void main(final String[] args) {
        MathUtils mathUtils = MathUtils.getInstance();
        int addition = mathUtils.add(1, 3);
        System.out.println(addition);
    }
}


问:
Algorithm for determining transactions among weekly data series?
I'm trying to develop a small reporting tool (with sqlite backend). I can best describe this tool as a "transaction" ledger. What I'm trying to do is keep track of "transactions" from weekly data extract:

"new" (or add) - resource is new to my app since my app may not have tracked this resource before as it hasn't been seen via extracts.

"update" (or hit) - there is a recent use of that resource, update retention period by another week.

"delete" (or drop) - this item saw no use since last report (optional, but would be nice to have for graphing week-to-week changes in demand for resources).

All I've got is a weekly data extract (pipe-delimited flat file) coming from a legacy archiving/record-management system that I have no control over.

Each line can be distilled to basically this:

resource_id | resource info | customer_id | customer_info

Sample data:

```<code>10| Title X       | 1 | Bob
11| Another title | 1 | Bob
10| Title X       | 2 | Alice
</code>```

The goal is make it easy to report on resources that haven't seen use for X-months (based on last hit). There is a retention period where resources are kept around for ease of access if they're popular. A resource that hasn't seen use for 18 months is marked for long-term archival elsewhere.

This must be a common problem. Wondering if there a general-purpose algorithm to determine what's new/same/removed between data sets (db vs. latest extract)?

答:
If you’re keeping the updates in a SQLite backend anyway, you could turn the weekly update into a new table and compare it to the archived data with queries, before merging it.

Example of using SQL to find new additions to a table: https://stackoverflow.com/questions/2077807/sql-query-to-return-differences-between-two-tables

If a field in your DB stores the date of the transaction, you could just query all users who have had transactions in the past 18 months.  Then the archive is just the full DB.  Alternatively, you could query all users who haven’t, extract their data, then drop them.  Updates are just any rows timestamped this week.


答:
Well, I can't speak to the job requirement that you're staring at, but we have a similar situation (at the job I'm leaving at the end of this month) that could probably be described much like your advert (although we use .NET 3.5, and use flash instead of silverlight). Without getting into too much details, many government forms are now electronically filed via XML. The validation rules are generally XPATH expressions, and in some cases we use XSLT to transform our internal schema to the government's schema. The government's schema usually changes annually due to changes in regulations and statutes.

Since one of our products is a collaborative workflow website, when the filings are completed, they get queued up to be filed electronically. Since the government's website is frequently down (they outsourced it to a 3rd party), we have to set up an asynchronous service (running as a windows service) that polls their site and submits the filing when it can. Also, since it can take up to 24 hours to get a response as to whether the filing was good or not, we have to poll their service from time to time. So there could be an asynchronous requirement like this in your job posting.

Lets say i need to master these two topics (1 and 2). What do i need to do to accomplish that skill? if there are some books for intermediates that actually teach that stuff with practical scenarios and case studies then please suggest some.

I don't think there are any single books that combine both topics at the same time.

I'm not fond of our home-grown asynch system as I think it should have been replaced with a much more sturdy framework such as BizTalk. If you need your messages to get there, and guarantee that they get there once and only once, you ought to look into message queuing (MSMQ, MQ or BizTalk). BizTalk excels at converting one XML schema to another (as one common usage is transforming one set of XML to others - including EDI).

Title: What is meant by XML/XSLT/XPath and asynchronous programming?

Body:
I understand that (1) XML/XSLT/XPath and (2) asynchronous programming may not be related to one another. My questions are:

When a C# developer job is advertised saying: "the following skill is required as mentioned in 1 and 2", what does it actually mean?

Lets say I need to master these two topics (1 and 2). What do I need to do to accomplish that skill? Are there books for intermediates that actually teach that info with practical scenarios and case studies?

Answers are much appreciated.

I have worked XML packet crafting for message exchange over the network, developed some amateur XML parsers for some projects and done message exchange for a client/server-based messaging system using asynchronous calls. But I really need to know and learn what the companies are looking for when they write these things (1 and 2) as requirements in their job advertisment.

Aggregate skills required for the specific job were:

ASP.NET 2.0 (OK)

Web Services  and .Net Remoting (OK)

XML/XSLT/XPath (?)

Asynchoronous Programming (?)

Windows Services (OK)

Javascript/XML/AJAX (OK)

Microsoft Silverlight/WPF (OK)

So firstly, it's clear that AJAX is not related to Asynchronous programming (in this very specific context) as it is written as a separate required skill (and I hope that it's not a mere redundancy). In normal cases, my deductions would have been the same like asynchronous programming means working with AJAX (asynchronous JavaScript with XML).

Secondly, making a web service in C# does not require any extensive experience with XSLT. In fact, exposing functions from a DLL (encapsulating business logic) is the simplest of any task with web services in C#. I wonder if there is some extra skill or experience that is needed?


问:
Is reinventing the wheel really all that bad?
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?

答: Maybe it's just as efficient, but is it as robust? I think the most compelling reason to use a library over rolling your own is that the framework has so many people using it that they can find and fix bugs quickly. In-house developed library, while they may provide just as much (or more) functionality, cannot compete with a library with millions of users to provide testing in pretty much every use-case. You just can't beat that kind of testing in-house.</p>