问:
How to design a database schema for a multi-user To-Do application in Azure?
I want to create a windows 10 universal to-do app with offline sync capability. So I checked out this tutorial which helped me to get started on the offline functionality. But I was wondering how should I design my Azure database to get data efficiently and moreover I also should have the ability to store images. So here are my questions:

Is it good to put all the users data in one table? Ex: (Content
Table): ID , FK(UserId), Title, Desc, Created , Edited.

Can I use any indexing technique to efficiently query for the user
data as CRUD operations will be very common since it has a sync
feature.

If the above is not really a good technique could you please tell me what is the right way to go about it. As I'm not so experienced when it comes to DB designing.

答:
For the tables you might want

User (User_Id, Name, and so on)

Category (Category_Id, Name)

Task (Task_Id, Category_FK, User_FK, Name, Date_Due)

This article will give you some background on indexes in Azure.

If you are going to have heavy hits to the database. It would be better to place the database into a caching system. This would take the load off the database.


问:
A practical use of "yield" keyword in C#
After almost 4 years of experience, I haven't seen a code where yield keyword is used. Can somebody show me a practical usage (along explanation) of this keyword, and if so, aren't there other ways easier to fullfill what it can do?

答:
Elastic Search .NET example repo has a great example of using yield return to partition a collection into multiple collections with a specified size:

https://github.com/elastic/elasticsearch-net-example/blob/master/src/NuSearch.Domain/Extensions/PartitionExtension.cs

```<code>public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> source, int size)
    {
        T[] array = null;
        int count = 0;
        foreach (T item in source)
        {
            if (array == null)
            {
                array = new T[size];
            }
            array[count] = item;
            count++;
            if (count == size)
            {
                yield return new ReadOnlyCollection<T>(array);
                array = null;
                count = 0;
            }
        }
        if (array != null)
        {
            Array.Resize(ref array, count);
            yield return new ReadOnlyCollection<T>(array);
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Elastic Search .NET example repo has a great example of using yield return to partition a collection into multiple collections with a specified size:

https://github.com/elastic/elasticsearch-net-example/blob/master/src/NuSearch.Domain/Extensions/PartitionExtension.cs

public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> source, int size)
    {
        T[] array = null;
        int count = 0;
        foreach (T item in source)
        {
            if (array == null)
            {
                array = new T[size];
            }
            array[count] = item;
            count++;
            if (count == size)
            {
                yield return new ReadOnlyCollection<T>(array);
                array = null;
                count = 0;
            }
        }
        if (array != null)
        {
            Array.Resize(ref array, count);
            yield return new ReadOnlyCollection<T>(array);
        }
    }


问:
Methods of "Code Softening" (Opposite of "Hardening") for C & C++
Some developers work on code hardening.

(protecting against errors, you can build with a stack protector for example).

However, if you're trying to redo a strange someone else reports, or find possible problems with the code, the reverse could be useful.

Are there well known ways to increase the chance an error in the code will lead to a crash?

Examples could include...

Pack structs so accidental out-of-bounds access don't access padding bytes.

Initialize stack & heap memory to random bits.

Re-arrange executable in memory layout to expose errors.
(For whatever reason or 'good luck', some bugs will only impact specific configurations).

Change thread scheduling to expose threading bugs.

So the question is:

Which existing methods of building software exist, that help expose errors in C/C++ applications?

Note, am aware of valgrind, address-sanitizer & rational-purify.

答:
I don't know if this is exactly what is requested, but once I received a system with a few thousands of pretty bad written lines of code. Among other bad practices, it was full of try{ ; } catch(...); so when an exception happened the system just kept going, sometimes erratically.
What I've decided was to remove completely the "protection" exposing the system to a crash, often in production, so I could get the dump. That move helped a lot.


答:
Actually I would say that what you want is still hardening. It will help you discover the bug - if it is there, it will manifest loudly and closer to the actual cause, rather than silently somewhere later.

If you are trying to reproduce a strange bug report, I would suggest to not alter the code at all. It's obviously best if you can get the same code, same build setup and run in the same environment as the reporter has. But if you can't or if the bug still doesn't happen:

valgrind is great, as you know, it has lot of attributes you can play with

this covers the initializing memory with random bits, valgrind knows that the data is unitialized and any read access will be reported

compiling and running the program on different architectures is easy way to make some bugs appear

on linux, compile with -fPIE and make sure ASLR is on

have automatic tests, units tests are great, but just a fuzzy test that will pump lot of random (valid) data in the program can help

Title: Methods of "Code Softening" (Opposite of "Hardening") for C & C++

Body:
Some developers work on code hardening.

(protecting against errors, you can build with a stack protector for example).

However, if you're trying to redo a strange someone else reports, or find possible problems with the code, the reverse could be useful.

Are there well known ways to increase the chance an error in the code will lead to a crash?

Examples could include...

Pack structs so accidental out-of-bounds access don't access padding bytes.

Initialize stack & heap memory to random bits.

Re-arrange executable in memory layout to expose errors.
(For whatever reason or 'good luck', some bugs will only impact specific configurations).

Change thread scheduling to expose threading bugs.

So the question is:

Which existing methods of building software exist, that help expose errors in C/C++ applications?

Note, am aware of valgrind, address-sanitizer & rational-purify.


问:
In CI, should tests be run against src or dist?
I've had a dispute with a colleague about when to run JavaScript unit tests in a CI environment at one of two different times. Let's call the two parties PE (pro-early) and PL (pro-late).

Early (against src)

Running the tests against the source code right out of the version control system.

PE says that we should run the riskiest code first and "fail fast." Both parties agree that we should run unit tests this way during development because the cycle time is much faster. PE says that since we need to have the build configured to run early in any case, an alternate configuration that runs the tests late constitues duplication and bloat.

Late (against dist)

Running the same tests against code has been packaged up (concatenated and minified).

PL says that we should test the code as it ships. PL claims to have experienced time-consuming scenarios where the code worked when run directly from source, but failed because of something that went wrong when the code was packaged for distribution.

PE says a hypothetical "something might go wrong" is a weak argument. And anyway it's not CI's job to catch that kind of problem. The distributable code is tested by QA before it's shipped.

Further details

"Early and late in CI" is not an option, much to PEL's dismay.

The code is modularized using AMD and RequireJS. We're using Karma for unit tests and Grunt for the build script.

So which is it -- early or late?

Is one side definitely right? Are we missing any considerations that may sway one person to the other side?

答:
Thanks for the responses. I'm surprised at the extent to which people think that "failing fast" is important within CI. There's a difference between the development (individual) cycle and the integration (team) cycle.

Development

A developer makes a small change. Runs the tests to ensure that change didn't break anything. If something did break, the developer inspects the code, notices an error, fixes it, and runs the tests again. That cycle can literally happen a couple of times a minute, provided the tests are able to run almost instantly. If it takes a few minutes for the tests to run that will blow out the cycle time and disrupt the developer's workflow.

Integration

A developer merges a change. The build runs and something fails. The entire team is notified of the failure. The team communicates to figure out who will work on the problem. A couple of developers put their heads together, pull down the latest code, run the build locally, figure out what went wrong, make a change, commit the code with a thoughtful commit message, push the code up to the server, and merge. There may be other time-consuming steps. That's generally the bare minimum.

In this case, if it takes several minutes longer for a failure to be discovered (the difference between "early" and "late") it doesn't have much impact on the overall cycle time.

If you choose not run tests against the final product during CI, and something about the concatenation / minification process causes a bug to be introduced, it may be hours, days, or even months before that bug is eventually discovered.

Running the tests "early" in CI is a "nice to have." The impact on overall cycle time is marginal. Running the tests "late" is a "must have". Failing to do so can be catastrophic.


问:
Are there flavours of OOP where some or all of the SOLID principles are antithetical to clean code?
I recently had a discussion with a friend of mine about OOP in video game development.

I was explaining the architecture of one of my games which, to my friend's surprise, contained many small classes and several abstraction layers.  I argued that this was the result of me focusing on giving everything a Single Responsibility and also to loosen the coupling between components.

His concern was that the large number of classes would translate to a maintenance nightmare.  My view was that it would have the exact opposite effect.  We proceeded to discuss this for what seemed like centuries, eventually agreeing to disagree, saying that perhaps there were cases where SOLID principles and proper OOP didn't actually mix well.

Even the Wikipedia entry on SOLID principles states that they're guidelines that help to writing maintainable code and that they are part of an overall strategy of agile and adaptive programming.

So, my question is:

Are there cases in OOP where some or all of the SOLID principles do not lend themselves to clean code?

I can imagine right away that the Liskov Substitution Principle could possibly conflict with another flavour of safe inheritance.  That is to say, if someone devised another useful pattern implemented through inheritance, it is quite possible the LSP might be in direct conflict with it.

Are there others?  Perhaps certain types of projects or certain target platforms work better with a less SOLID approach?

Edit:

I'd just like to specify that I'm not asking how to improve my code ;)  The only reason I mentioned a project in this question was to give a little context.  My question is about OOP and design principles in general.

If you're curious about my project, see this.

Edit 2:

I imagined this question would be answered in one of 3 ways:

Yes, there exist OOP design principles which partially conflict with SOLID

Yes, there exist OOP design principles which completely conflict with SOLID

No, SOLID is the bee's knees and OOP will forever be better with it.  But, as with everything, it's not a panacea.  Drink responsibly.

Options 1 and 2 would have likely generated long and interesting answers.  Option 3, on the other hand, would be a short, uninteresting, but overall reassuring, answer.

We seem to be converging onto option 3.

答:
I Always find it hard to draw the line between the 'S' of solid and the (may be old fashioned) need to let an object have all the knowledge of itself.

15 years ago I worked with Deplhi developers who had their holy grail to have classes which contained everything. So for a mortgage you could add insurances and payments and income and loans and tax info and you could calculate tax-to-pay, tax-to-deduct and it could serialize itself, persist itself to disk etc. etc.

And now I have the same object devided in lots and lots of smaller classes which have the advantage that they can be unit tested much easier and better but don't give a good overview of the entire businessmodel.

And yes I know you don't want to tie your objects to the database but you can inject a repository in the big mortgage class to solve that.

Besides that it isn't always easy to find good names for classes which only do a tiny thing.

So I'm not sure about the 'S' being always a good idea.


问:
call function once again after failure, without duplicate lines?
I have what is probably an over-engineering question. I have some PHP code that logs messages to a file. We've been having a problem with the file having the wrong perms from time to time. While we're troubleshooting that, I am writing a work-around for that in the logging function, changing the unix perms and owners on the log file.

So my code looks like this:

```<code>function log($message) {
  if ( FALSE === file_put_contents(log_path(), $message) ) {
    chown(log_path(), 'apache');
    chgrp(log_path(), 'www-data');
    chown(log_path(), 0770);

    // now I'm repeating this line
    if ( FALSE === file_put_contents(log_path(), $message) ) {
      // log error to database
      db_log($message);
    }
  }
}
</code>```

In the interest of DRY, can I somehow change the code to avoid repeating the line if ( FALSE === file_put_contents(log_path(), $message) ) {? Of course, I can't use recursion, because that would go on forever.

答:
A couple possibilities that haven't been mentioned:

If setting the permissions is always acceptable, always set the permissions, avoiding the first 'if' entirely.  Especially since this is a workaround.

Check the permissions, setting them if necessary, then call file_put_contents(...). This has the added benefit of distinguishing a permissions error from a real error in the call to file_put_contents(...), which may help with debugging.


问:
Why isn't there a true "Date-Only" data type?
I'm so ridiculously frustrated with having to use DateTime values for data sets that are truly "just a day." Birthdays being the most-common example, but this comes up in business applications all the time.

I've gotten used to just setting the Time part of "date-only" records to "noon" (which avoids the date ever changing no matter the timezone). This seems like a hack, and I'm forever finding bugs from junior devs that trip over this issue.

Time is always relative to a fixed point. 4PM is 4 hours post meridian, or noon. The sun's highest point in transit is observable, and allows us to set up a coordinate system. 3 hours before noon (Ante Meridian), 2 hours after noon, 1441899402938 milliseconds since January 1, 1970. To people raised in a Cartesian world, this is second nature.

But our Calendar predates Descartes. My argument is that it is more properly thought of as a enumeration over which a modulo function is applied. Monday follows Sunday, and so on until you get to the fact that Sunday follows Saturday. There is no positive and negative, it is a modulus, or absolute value.

Similarly with years repeating. Every 365 days (or so) there are several special days for me: birthdays, anniversaries, childrens' birthdays, etc. etc. Business scheduling applications are rife with examples of meetings every seven days, first Tuesday of the month, etc. Just because we CAN map this onto a floating point number, and in truth mapping it onto said number solves a LOT of problems that are really difficult the old way, but that doesn't mean it's the only way to do it.

Awareness and understanding of the "square peg in a round hole" nature of using DateTimes to store Dates makes you a better programmer in my opinion.

Is there value in an application explicitly intended as a scheduling application in defining a Date class, or is "set all times to noon" the best approach? What issues might there be with using DateTime and setting the Time component to Noon?  Can timezone shifting be accounted for in such an approach? I've used MomentJS, but I think that's just a better Date class.

答:
First of all, let's get one thing out of the way: birthdays are one thing, dates-of-birth are another.  A Birthday is an exotic data type because it lacks not only the components of hours, minutes etc but it also lacks the year component. If you really want to deal with birthdays, I would recommend inventing your own data type which contains nothing but a month number and a day number, and is not related to any of the built-in date-time data types.

On the other hand, if you want to also keep track of the year of birth, then what you have is not birthdays, it is dates-of-birth. So, the question now becomes why is there no date-only data type, so that you can conveniently represent dates-of-birth, and instead popular languages seem to force you to use some type that also includes a time component.

Let me briefly mention that it is not true that all programming languages only offer temporal data types which include a time component.  I have come across date-only data types in RDBMSes and in their corresponding SQL dialects. But that's irrelevant: the fact that these data types exist does not mean that they are a good thing to have, and RDBMSes have a long history of confusing storage with representation.

You will understand why it is a bad idea to have such date-only data types the moment you realize that time is a coordinate.  Most people have a very vague idea of what time is, and this idea contains arcane cultural notions such as years, months and days, without realizing that these notions are exclusively representational: They are only useful for representing time to a human, and to receive time as input from a human.  At any layer below the actual time-entry GUI control, time should be, and usually is, represented as a time coordinate, which is a single number of time units since some origin.

For example, in the DateTime data type of Microsoft Dotnet, the time unit is 100 nanoseconds, and the origin of time is 12:00 midnight, January 1, 0001 C.E.

Another example of an arcane, exclusively representational notation is angle measurements using degrees, minutes of a degree, and seconds of a degree. Of course, in order to get any useful calculation done, you have to internally use radians, and if need be, convert to and from degrees when interacting with a human user.

So, do not confuse the human-readable representation of a measurement with the actual nature of the measurement.  Quite often the ideal method for realizing a measurement, which most closely matches the nature of the measurement, is very different from the human-readable representation of that measurement.

In light of all this, your request for a temporal data type that represents only dates is akin to a request for an angular data type that would only be capable of representing degrees, explicitly preventing any greater precision. Such a data type would be quite limited, and ultimately useless, because you would have to convert it to and from radians anyway in order to get anything useful done with it.

Your problem with the date-of-birth is that you have an imprecise time coordinate: the person was, of course, born at a specific moment in time, but the hour and minute were either not recorded by the hospital, or we do not care about them. So, what is really happening is that your date-and-time-of-birth time coordinate has a margin of error, a tolerance or uncertainty if you wish, and it is best to treat it as such: put it at exactly the middle of the day, and consider an implied +12 -12 hour uncertainty.  And that's precisely the solution that you have intuitively arrived to.


问:
What would you think about a new Java persistence tool, that's not really an ORM?

Persistence in Java

Over the past years, I have gathered experience in the field of persistence abstraction in Java, using concepts such as EJB 2.0, Hibernate, JPA and home-grown ones. They seemed to me to have a steep learning curve and lots of complexity. In addition, as a big fan of SQL, I also thought that many abstraction models provide too much abstraction over SQL, creating concepts such as "criteria", "predicates", "restrictions" that are very good concepts, but not SQL.

The general idea of persistence abstraction in Java seems to be based on the Object-relational model, where RDBMS are somehow matched with the OO world. The ORM-debate has always been an emotional one, as there does not seem to exist a single solution that suits everyone - if such a solution can even exist.

jOOQ

My personal preference of how to avoid ORM-related problems is to stick to the relational world. Now the choice of data model paradigm should not be the topic of discussion as it is a personal preference, or a matter of what data model best suits a concrete problem. The discussion I would like to start is around my very own persistence tool called jOOQ. I designed jOOQ to provide most of the advantages modern persistence tools have:

A Domain Specific Language based on SQL

Source code generation mapping the underlying database schema to Java

Support for many RDBMS

Adding some features that few modern persistence tools have (correct me if I'm wrong):

Support for complex SQL - unions, nested selects, self-joins, aliasing, case clauses, arithmetic expressions

Support for non-standard SQL - stored procedures, UDT's, ENUMS, native functions, analytic functions

Please consider the documentation page for more details: http://www.jooq.org/learn.php. You will see that a very similar approach is implemented in Linq for C#, although Linq is not exclusively designed for SQL.

The Question

Now, having said that I'm a big fan of SQL, I wonder whether other developers will share my enthusiasm for jOOQ (or Linq). Is this kind of approach to persistence abstraction a viable one? What are the advantages / disadvantages you might see? How could I improve jOOQ, and what's missing in your opinion? Where did I go wrong, conceptually or practically?

Critical but constructive answers appreciated

I understand that the debate is an emotional one. There are many great tools out there that do similar things already. What I am interested in is critical but constructive feedback, based on your own experience or articles you may have read.

答:
I think you're on the right track and should continue with your solution.  Some of the previous criticism is overly harsh, but some valid points are made.

I too have searched long and hard for a full-featured ORM solution that would fit my needs, but every solution I looked at came up short.  Each has its pros and cons but none really did everything that I wanted.  I agree with your criticism of these solutions - namely that they generally are complex and have a steep learning curve.

The top contender would have to be the de facto standard, Hibernate.  It is full-featured, robust and well-tested.  I respect it and appreciate it for what it is.  Now, at the risk of offending half the programming community, I must also say that it is a bloated and complex piece of non-performant code.  I've spent a fair amount of time poking around in its bowels, trying to debug and understand it, and I was not impressed with what I saw.  Having said that, I would still recommend it as the starting point for anyone looking for a good ORM.  It excels at simple CRUD, but I would not use it for performant bulk queries, such as data mining or number crunching.

Unfortunately, my application is more of the number crunching variety (though there is some CRUD too), so I decided to roll my own.  I knew from the start that it would be sub par compared to the other solutions out there, but it would be good enough and give me the performance I needed.  Now here's the really great part: it looks very much like your solution!

This is what I think you did most right: You stated your underlying beliefs as a kind of mission statement, and those beliefs are correct.  I've obviously spent a fair amount of time thinking about this problem too, and it is a difficult one to solve.  But as time goes on, I think the programming community comes to understand it better, and we will create better solutions.  Kudos to all previous efforts (especially Hibernate), but I think we can do better.

Your solution better refines the problem, but it only solves part of it.  I think that a layered approach may give us everything we want.  What you have come up with/ IMO, is the foundation layer.  As you have suggested, I think this layer is best automatically generated based on a database schema.  It should be a very simple relational object model that maps directly onto the database and no more.  You're right that data persists much longer than code, so at this level, data should drive code and not vice versa.  It would support CRUD as well as performant bulk querying.  I would probably implement some kind of L1 cache at this layer.

However, the thing that other ORM solutions excel at is the ability to define your objects in a manner that does not depend so much on the actual structure of the underlying database.  For this functionality, I would create another layer.  By necessity this layer becomes more abstract, hopefully simpler (at the expense of lost functionality), and builds on the previous layer.  It might utilize an L2 cache.

I'm open to having more layers, but the key point for me is that by providing multiple entry points into the library, you can fulfill every need.  For those that want a simple CRUD solution that maps directly to objects of their choosing, they can build on the top layer.  For those looking for something more powerful and performant but willing to incur the added complexity, they can plug into the lower layer.  I would not create a special query language, but instead would expose your query builder object for this purpose.  And since the code is layered, that functionality naturally exists without special pass-through.

I think you do have an understanding of the space and aren't reinventing the wheel but rather have hit a slightly different niche.  And frankly, this is a wheel that could use improvement anyway.  You face an uphill battle contending against powerhouses of the past, but if your solution is good, and I think it's heading that way, then it will gain popularity on its own merits.

ContentLicense: CC BY-SA 2.5


问:
Lots of independent data structures into one big one
I have 10 independent data structures that contain unsigned bytes and bit fields from different data sources. I am using C++, and was looking for a way to combine all these data structures into one data structure for the purpose of passing all the data around between different methods.

For example I have an object that uses data from all 10 data structures, but I have references similar to:

method(datastructure1 &d1, datastructure &d2, datastructure &d3, datastructure &d4, ...)

I want to avoid this, because it is getting hard to keep track and maintain. I would prefer to have:

```<code>method(superStructure &allData);
</code>```

I just cant think of how to combine all the data so I can still uniquely access the data from each individual structure.

答: Well, that's exactly the purpose of a  struct  so why not use one ? A struct, in essence, is just a grouping of other data types, and thus it doesn't need memory for itself. It is only a convenience thing.</p>


问:
Writing comments for some small code with rather large background
So I had to write some code related to splitting Bezier curves into parts. I read through several references and particularly referred this rather  detailed one.

The final code outcome is however around 20-30 LOC. But without having this kind of background, it would be really difficult for someone to figure out what the code is doing.

Explaining it in details would require me to write too much comments as the function's explanation.

Putting a link to this document into comments did not seem a very nice an idea (links might break in future)

Q. Should I rather generate this as a doc, keep it locally with project docs, and give a reference to it in the comments ?

Q. Any other nicer way in general to give comments about some rather complex/large area of work associated with a particular functionality.

P.S. I don't want some body reading this code later to curse me for what it is, so, you see :p

答:
It seems like all the other answers are "put it into the comments!"

I'm going to go against the grain and recommend keeping it in a separate document alongside the code instead, for this reason: it looks like your code is doing something that requires complicated math to understand. Math can be hard enough to understand in the best of cases; it can be even harder to understand without proper standard notation, and code comments are not a very easy place to put fancy mathematical notation. ASCII-art can only get you so far.

Instead, I would briefly state the algorithm in the code comments and refer to the document which you create in an appropriate tool that can display the fancy math for details. Make sure this document is placed into the same repository as the code, and store it in a location unlikely to be omitted from any future moves of the code from one repository to another, or from one version control system to another. These things happen!

Where I work, every official document associated with a project gets a part number which can be used to retrieve the document later. If you have similar processes where this application is being developed, consider getting a number assigned to the document, and reference that number in the code comments so there is always a way to track down that document even if it gets lost.


问:
When are subclasses redundant?
I am working on a ML project that will involve malware and I want to represent the statistics files used for training the classifier via StatsFile objects. However, I am wondering whether I should use a IStatsFile and subclass as such:

```<code>IStatsFile
TrainingMWStatsFile
TrainingBWStatsFile
TestingMWStatsFile
TestingBWStatsFile
</code>```

Now MW and BW and testing and training files have no fundamental difference except how they are used by the system. So basically all of these just inherit methods from the base class and contain no additional code.

Is this overkill? Would it be better just to have a StatsFile that contained this information in variables? i.e.:

```<code>statsfile.training = True
statsfile.MW = true
</code>```

My instince is to say that the second way is better. But I do really like being able to do the following:

```<code>if type(statsfile) is not MWStatsFile:
</code>```

versus

```<code>if statsfile.MW == false
</code>```

Thoughts on best practice here?

答:
Really, neither way is better.

I think the true problem does not originate in the IStatsFile class hierarchy. The code that contains the if statements testing the stats file objects for which type they are is truly to blame for this. You have a stats file, but several different things you can do with it. The Strategy Pattern can help out here.

From Wikipedia:

In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime.

...

For instance, a class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed. The validation strategies, encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.

Another, probably more common, use of the Strategy Pattern is formatting log messages. Consider log messages with this information:

Log level: INFO

Message: "The quick brown fox"

Date: "2015-09-10 01:05 PM EDT"

There are a number formats in which you could log this information to a file:

```<code>INFO 2015-09-10 01:05 PM EDT: The quick brown fox

[INFO, 2015-09-10 01:05 PM EDT] The quick brown fox

INFO (2015-09-10 01:05 PM EDT) The quick brown fox
</code>```

And the list goes on. The Strategy Pattern can be used to provider your logger class with a format strategy, so changing the format of the log files doesn't require changing the logger class itself. Just provide a different Format Strategy object.

A quick code example is in store. Interfaces are a good starting point for the Strategy Pattern, because it abstracts away the implementation of the strategy -- which is the whole point of the Strategy Pattern:

```<code>public interface LogFormatStrategy {
    String formatLogMessage(String level, String message, LocalDateTime date);
}
</code>```

(Note, I'm using Java for this example)

The LogFormatStrategy interface is dead simple. It just specifies a single method to do what it needs to do.

Now we can create as many log formatters as we desire:

```<code>// [INFO, YYYY-MM-DD HH:MM:SS] The quick brown fox
public class SquareBracesLogFormatStrategy implements LogFormatStrategy {
    public String formatLogMessage(String level, String message, LocalDateTime date) {
        return "[" + level.toUpperCase() + ", " + date + "] " + message;
    }
}

// INFO (YYYY-MM-DD HH:MM:SS) The quick brown fox
public class ParenthesisLogFormatStrategy implements LogFormatStrategy {
    public String formatLogMessage(String level, String message, LocalDateTime date) {
        return level.toUpperCase() + " (" + date + ") " + message;
    }
}

// INFO YYYY-MM-DD HH:MM:SS The quick brown fox
public class SimpleLogFormatStrategy implements LogFormatStrategy {
    public String formatLogMessage(String level, String message, LocalDateTime date) {
        return level.toUpperCase() + " " + date + " " + message;
    }
}
</code>```

And a quick, mostly incomplete Logger class to use the format strategies:

```<code>public class Logger {
    private LogFormatStrategy formatter;

    public Logger(LogFormatStrategy formatter) {
        setFormatter(formatter);
    }

    public void info(message) {
        String logMessage formatter.formatLogMessage("INFO", message, LocalDateTime.now());

        // write logMessage to a file
    }

    public void setFormatter(LogFormatStrategy formatter) {
        this.formatter = formatter;
    }
}
</code>```

Now we can log in different formats with the same logger object, or give two different logger objects different format strategies.

```<code>Logger logger = new Logger(new SimpleLogFormatStrategy());

// INFO YYYY-MM-DD HH:MM:SS The quick brown fox
logger.info("The quick brown fox");

logger.setFormatter(new SquareBracesLogFormatStrategy());

// [INFO, YYYY-MM-DD HH:MM:SS] The quick brown fox
logger.info("The quick brown fox");
</code>```

This design pattern would alleviate, if not eliminate, the need for sub classes.

Title: When are subclasses redundant?

Body:
Really, neither way is better.

I think the true problem does not originate in the IStatsFile class hierarchy. The code that contains the if statements testing the stats file objects for which type they are is truly to blame for this. You have a stats file, but several different things you can do with it. The Strategy Pattern can help out here.

From Wikipedia:

In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime.

...

For instance, a class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed. The validation strategies, encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.

Another, probably more common, use of the Strategy Pattern is formatting log messages. Consider log messages with this information:

Log level: INFO

Message: "The quick brown fox"

Date: "2015-09-10 01:05 PM EDT"

There are a number formats in which you could log this information to a file:

INFO 2015-09-10 01:05 PM EDT: The quick brown fox

[INFO, 2015-09-10 01:05 PM EDT] The quick brown fox

INFO (2015-09-10 01:05 PM EDT) The quick brown fox

And the list goes on. The Strategy Pattern can be used to provider your logger class with a format strategy, so changing the format of the log files doesn't require changing the logger class itself. Just provide a different Format Strategy object.

A quick code example is in store. Interfaces are a good starting point for the Strategy Pattern, because it abstracts away the implementation of the strategy -- which is the whole point of the Strategy Pattern:

public interface LogFormatStrategy {
    String formatLogMessage(String level, String message, LocalDateTime date);
}

(Note, I'm using Java for this example)

The LogFormatStrategy interface is dead simple. It just specifies a single method to do what it needs to do.

Now we can create as many log formatters as we desire:

// [INFO, YYYY-MM-DD HH:MM:SS] The quick brown fox
public class SquareBracesLogFormatStrategy implements LogFormatStrategy {
    public String formatLogMessage(String level, String message, LocalDateTime date) {
        return "[" + level.toUpperCase() + ", " + date + "] " + message;
    }
}

// INFO (YYYY-MM-DD HH:MM:SS) The quick brown fox
public class ParenthesisLogFormatStrategy implements LogFormatStrategy {
    public String formatLogMessage(String level, String message, LocalDateTime date) {
        return level.toUpperCase() + " (" + date + ") " + message;
    }
}

// INFO YYYY-MM-DD HH:MM:SS The quick brown fox
public class SimpleLogFormatStrategy implements LogFormatStrategy {
    public String formatLogMessage(String level, String message, LocalDateTime date) {
        return level.toUpperCase() + " " + date + " " + message;
    }
}

And a quick, mostly incomplete Logger class to use the format strategies:

public class Logger {
    private LogFormatStrategy formatter;

    public Logger(LogFormatStrategy formatter) {
        setFormatter(formatter);
    }

    public void info(message) {
        String logMessage formatter.formatLogMessage("INFO", message, LocalDateTime.now());

        // write logMessage to a file
    }

    public void setFormatter(LogFormatStrategy formatter) {
        this.formatter = formatter;
    }
}

Now we can log in different formats with the same logger object, or give two different logger objects different format strategies.

Logger logger = new Logger(new SimpleLogFormatStrategy());

// INFO YYYY-MM-DD HH:MM:SS The quick brown fox
logger.info("The quick brown fox");

logger.setFormatter(new SquareBracesLogFormatStrategy());

// [INFO, YYYY-MM-DD HH:MM:SS] The quick brown fox
logger.info("The quick brown fox");

This design pattern would alleviate, if not eliminate, the need for sub classes.


问:
What are you telling yourself if you can't understand new concept, paradigm, feature ...?
Programming always required to learn new concepts, paradigms, features and technologies and I always have been failed at first attempt to understand new concept what i encounter. I start to blame and humiliate myself without remember before how i understood new concept which i hadn't understand it before.

I can hardly stop to tell myself "why i cant understand ? Am i stupid or idiot ? Yes, i am stuppiiddddd!!!"

What your inner voice tells if you can not understand new concept after spend long time till been tired or hopeless ?

How do you handle your self-esteem in such situations ?

答:
If I don't understand something I find someone who does and tell them to explain it to me.  Once it's been explained I cement my understanding by playing with the concept for a bit.

I almost never think I'm stupid just because I seen plenty of smart people miss completely obvious things.


问:
What's best practice when putting an abstraction layer over an ORM?
When working with an ORM such as Entity Framework, I've fallen into a comfortable habit. Make an interface with get/add methods on it, put this on a "Repository" class then add a constructor to each class that accepts the interface. Use the interface's methods in the class.

It seems the most straightforward way to gain an abstraction layer that I can then mock out for unit tests.

However, doing a bit of reading around the subject, there seems to be a lot of confusion over what the best approach is. Some examples include:

Using your ORM with the repository pattern (seems a bad idea, since most ORM's are already their own repository patterns).

Creating a reusable repository using generics and sharing it across projects (seems like overkill unless you're working with a vast amount of different projects).

Having a repository that includes more detailed data logic. I.e. with methods like "GetUsersWhereAdminIsTrue" rather than the more generic "GetUsers" (this would seem to lead to a repository with a massive list of methods).

Using IOC to allow unit testing of code without an external source without the need for an extra wrapper layer (I've seen this mentioned several times, but I don't understand it. Surely even with IOC you still need to inject an interface?)

The answer may be partly circumstantial. But I'd like to understand why people are proposing solutions in spite of the shortcomings that I've bracketed above?

答:
I used the generic repository approach with a repository factory/provider that I got from a pluralsight class by John Papa (also used in this article). It did feel like overkill at first (and I wasn't even aware that EF used the repo pattern at that point) but was very easy to work with and ramp up the rest of the team.

Some benefits that I saw:

Separation of abstraction levels - I kept my db access within these repos and kept the repo usage in the service layer. There are clearly other ways to accomplish this, but this pattern felt like a guide to do so.

Unit tests were easy to implement with the amount of injection going on

The factory was helpful for only creating repos that I needed for the specific task

Such a large number of the model objects are just simple look-up items that using a generic repo felt so natural. More complexity can be added if you create a custom repo, also included in the article.

Very few changes (and well documented) to make changes to the model

The one drawback that isn't EF specific was that the dbsets for each entity are exposed publicly in the DBContext in order to seed the DB in the initializer. This means that you have to make sure that everyone is using the repos to access the data, rather than just grabbing a dbset.


问:
C++: Should class own or observe its dependencies?
Say I have a class Foobar that uses (depends on) class Widget. In good ol' days, Widget wolud be declared as a field in Foobar, or maybe as a smart pointer if polymorphic behavior was needed, and it would be initialized in constructor:

```<code>class Foobar {
    Widget widget;
    public:
    Foobar() : widget(blah blah blah) {}
    // or
    std::unique_ptr<Widget> widget;
    public:
    Foobar() : widget(std::make_unique<Widget>(blah blah blah)) {}
    (…)
};
</code>```

And we'd be all set and done. Unfortunately, today, Java kids will laugh at us once they see it, and rightfully, as it couples Foobar and Widget together. The solution is seemingly simple: apply Dependency Injection to take construction of dependencies out of Foobar class. But then, C++ forces us to think about ownership of dependencies. Three solutions come to mind:

Unique pointer

```<code>class Foobar {
    std::unique_ptr<Widget> widget;
    public:
    Foobar(std::unique_ptr<Widget> &&w) : widget(w) {}
    (…)
}
</code>```

Foobar claims sole ownership of Widget that is passed to it. This has following advantages:

Impact on performance is negligible.

It's safe, as Foobar controls lifetime od its Widget, so it makes sure that Widget doesn't suddenly disappear.

It's safe that Widget won't leak and will be properly destructed when no longer needed.

However, this comes at a cost:

It places restrictions on how Widget instances can be used, e.g. no stack-allocated Widgets can be used, no Widget can be shared.

Shared pointer

```<code>class Foobar {
    std::shared_ptr<Widget> widget;
    public:
    Foobar(const std::shared_ptr<Widget> &w) : widget(w) {}
    (…)
}
</code>```

This is probably closest equivalent ot Java and other garbage collected languages. Advantages:

More universal, as it allows sharing dependencies.

Maintains safety (points 2 and 3) of unique_ptr solution.

Disadvantages:

Wastes resources when no sharing is involved.

Still requires heap allocation and disallows stack-allocated objects.

Plain ol' observing pointer

```<code>class Foobar {
    Widget *widget;
    public:
    Foobar(Widget *w) : widget(w) {}
    (…)
}
</code>```

Place raw pointer inside class and shift the burden of ownership to someone else. Pros:

As simple as it can get.

Universal, accepts just any Widget.

Cons:

Not safe anymore.

Introduces another entity that is responsible for ownership of both Foobar and Widget.

Some crazy template metaprogramming

The only advantage I can think of is that I'd be able to read all those books I didn't find time for while my software is builing;)

I lean towards the third solution, as it is most universal, something has to manage Foobars anyway, so managing Widgets is simple change. However, using raw pointers bothers me, on the other hand smart pointer solution feel wrong to me, as they make consumer of dependency restrict how that dependency is created.

Am I missing something? Or is just Dependency Injection in C++ not trivial? Should class own its dependencies or just observe them?

答:
You are missing at least two more options that are available to you in C++:

One is to use 'static' dependency injection where your dependencies are template parameters. This gives you the option of holding your dependencies by value while still allowing compile time dependency injection. STL containers use this approach for allocators and comparison and hash functions for example.

Another is to take polymorphic objects by value using a deep copy. The traditional way to do this is using a virtual clone method, another option that's become popular is to use type erasure to make value types that behave polymorphically.

Which option is most appropriate really depends on your use case, it's hard to give a general answer. If you only need static polymorphism though I'd say templates are the most C++ way to go.


答:
Maybe you could add some code to illustrate the different methods?

ORMs are great in that they give you easy access to a DB without having to type a load of boiler plate code and SQL, but they cause problems if you are a lazy and dont wrap them in a repository class.

A. you can't inject a mock for testing

B. you create tight coupling with your ORM classes

C. you cant control the way in which the ORM is used ie. drop the tables, run a low performance query etc

the points you outline are ways people have tried to get around these problems

1: hides your ORM classes from the rest of the project and allows mocking

2: I agree with you on this, but it does reduce the number of methods in 3

3: gives you control over specific queries run and limits the scope of the object

4: I assume you mean using an IoC framework as a kind of repo? sounds bad to me, but I've seen some crazy stuff done with IoC frameworks

Title: What's best practice when putting an abstraction layer over an ORM?

Body:
When working with an ORM such as Entity Framework, I've fallen into a comfortable habit. Make an interface with get/add methods on it, put this on a "Repository" class then add a constructor to each class that accepts the interface. Use the interface's methods in the class.

It seems the most straightforward way to gain an abstraction layer that I can then mock out for unit tests.

However, doing a bit of reading around the subject, there seems to be a lot of confusion over what the best approach is. Some examples include:

Using your ORM with the repository pattern (seems a bad idea, since most ORM's are already their own repository patterns).

Creating a reusable repository using generics and sharing it across projects (seems like overkill unless you're working with a vast amount of different projects).

Having a repository that includes more detailed data logic. I.e. with methods like "GetUsersWhereAdminIsTrue" rather than the more generic "GetUsers" (this would seem to lead to a repository with a massive list of methods).

Using IOC to allow unit testing of code without an external source without the need for an extra wrapper layer (I've seen this mentioned several times, but I don't understand it. Surely even with IOC you still need to inject an interface?)

The answer may be partly circumstantial. But I'd like to understand why people are proposing solutions in spite of the shortcomings that I've bracketed above?


问:
Working with shader code
I am starting my first project in OpenGL/GLSL and I was wondering, how do you work with code of shaders?

Because it needs to be const char and syntax higlighting shows everything in the same color (as string) and so its difficult to navigate in code.

```<code>const char *shader = ..."void main()\n"...;
</code>```

Do you edit the code and then add quotation marks or do you just write it with quotation marks from the start? Thanks

edit: using VS2012

答: You can use the newly released ShaderFrog to work with GLSL shaders directly in the browser, with full syntax highlighting and debugging information. I am the author of this tool, and created it for an accessible way to edit GLSL shaders for use in OpenGL applications.</p>

Title: Working with shader code


问:
What's RAII? Examples?
Always when the term RAII is used, people are actually talking about deconstruction instead of initialisation. I think I have a basic understanding what it might mean but I'm not quite sure. Also: is C++ the only RAII language? What about Java or C#/.NET?</p>

答:
Resource Acquisition Is Initialization means that objects should look after themselves as a complete package and not expect other code to tell an instance "hey by the way, you're going to be cleaned up soon - please tidy up now." It does usually mean there is something meaningful in the destructor. It also means you write a class specifically to manage resources, knowing that under certain hard-to-predict circumstances, like exceptions being thrown, you can count on destructors executing.

Say you want to write some code where you're going to change the windows cursor to a wait (hourglass, donut-of-not-working, etc) cursor, do your stuff, and then change it back. And say also that "do your stuff" might throw an exception. The RAII way of doing that would be to make a class whose ctor set the cursor to wait, whose one "real" method did whatever it was you wanted done, and whose dtor set the cursor back. Resources (in this case the cursor state) are tied to the scope of an object. When you acquire the resource you initialize an object. You can count on the object getting destructed if exceptions are thrown, and that means you can count on getting to clean up the resource.

Using RAII well means you don't need finally. Of course, it relies on deterministic destruction, which you can't have in Java. You can get a sort of deterministic destruction in C# and VB.NET with using.

Title: What's RAII? Examples?


问:
FPGA device + networking + software kit
Sorry for the very abstract and uncertain question, but I guess if I could ask it better I would have answered it myself. Here is the thing.

I am getting more and more interested in FPGA. However, it is hard to tell where I should start off. What I want to do is to write a simple application that listens to UDP packets and sends TCP/IP packets. So I think something like Xinix Virtex®-7 FPGA will work for me as FPGA. How does that sound?

I will also need a PCI card that will host it with Ethernet card on it. Obviously I am not that good in hardware on that level and won't make it myself. Are there any out of the box solutions?

Also, I guess there must be a core for working with Ethernet adapter already. Am I right on that? Where should I look? Is there anything with interface close to POSIX sockets?

What is the best software kit I will need to achieve that?

Thank you!

答:
You should be aware that you are biting off a lot - writing a network stack is not a trivial exercise (not that you shouldn't try it - you'll learn a lot).

Googling some of the terms in your post, I found the "Xilinx Virtex-7 FPGA VC707 Evaluation Kit" - this seems to have everything you are after (and the kitchen sink besides!). It has PCIE to connect to your PC, ethernet (up to 1000mhz), 1gb of ram, and everything else you could want. It will set you back US$3,500.

If (like me) your budget doesn't include $3,500, and if (like me) you are just starting out, then maybe something like a Papilio would be more suitable - there are ethernet "wings" (plugin boards), and I suspect you are going to get much better (community) support for these. I got mine for US$50 for a 250k gate Papilio, delivered from AliExpress, and have spent a couple of nights hacking, learning etc. - depending on your soldering skills, you might be able to hack together a network "card" for next to nothing, just an optoisolator, a socket and some veroboard? and do the heavy lifting on the fpga. I have no idea how difficult this would be, or if it would work. I don't see why not. If anyone knows, post a comment below :)

Title: FPGA device + networking + software kit


答:
You can do the following:

Create a super class of the 10 data structures. The super class doesn't need to contain any functionality but it will need to contain the name of each one of the functions of the 10 data structures that you want to later use.

Implement your 10 data structures as sub classes of the previously created super class.

Count how many data items you want to send to the method you mentioned in your question and create an array with that size using the super class data type and pass the data array to the method.

Iterate over the array to carry out your operations.

If the function names for the 10 data structures are different you can create a variable in the super class called current_data_type to test which object is being processed in a conditional statement in step 4 from the array of objects passed.

This is an example of how the code would be structured:

```<code>    class SuperClass {
      public:

        static int current_data_type;

        // add all data type specific functions
        void set_values_d1 (int,double);
        void set_values_d2 (int,float);
        // ... add as many as necessary
        double get_values_d1 (void);
        float get_values_d2 (void);
        // ... add as many as necessary
    };

    class DataType1: public SuperClass {
      public:
        void set_values_d1 (int,double) { /* do something */ }
        double get_values_d1 (void) { /* do something */ }
        // ... add all the other functions
    };
    int DataType1::current_data_type = 1;

    class DataType2: public SuperClass {
      public:
        void set_values_d2 (int,float) { /* do something */ }
        float get_values_d2 (void) { /* do something */ }
        // ... add all the other functions
    };
    int DataType2::current_data_type = 2;

    int arrayItems = 100;
    SuperClass myDataArray [arrayItems] = {dataItem1, dataItem2, ... , dataItem100};

    method(SuperClass &myDataArray, int arrayItems) {
      for (int i = 0; i < arrayItems; i++) {
        switch(myDataArray.current_data_type){
          case 1 :
            // do all computations for DataType1
            break;

          case 2 :
            // do all computations for DataType2
            break;

          // create as many case statements as there are data types.
        }
      }
    }
</code>```

Title: Lots of independent data structures into one big one

Body:
I have 10 independent data structures that contain unsigned bytes and bit fields from different data sources. I am using C++, and was looking for a way to combine all these data structures into one data structure for the purpose of passing all the data around between different methods.

For example I have an object that uses data from all 10 data structures, but I have references similar to:

method(datastructure1 &d1, datastructure &d2, datastructure &d3, datastructure &d4, ...)

I want to avoid this, because it is getting hard to keep track and maintain. I would prefer to have:

```<code>method(superStructure &allData);
</code>```

I just cant think of how to combine all the data so I can still uniquely access the data from each individual structure.

Body:
You can do the following:

Create a super class of the 10 data structures. The super class doesn't need to contain any functionality but it will need to contain the name of each one of the functions of the 10 data structures that you want to later use.

Implement your 10 data structures as sub classes of the previously created super class.

Count how many data items you want to send to the method you mentioned in your question and create an array with that size using the super class data type and pass the data array to the method.

Iterate over the array to carry out your operations.

If the function names for the 10 data structures are different you can create a variable in the super class called current_data_type to test which object is being processed in a conditional statement in step 4 from the array of objects passed.

This is an example of how the code would be structured:

    class SuperClass {
      public:

        static int current_data_type;

        // add all data type specific functions
        void set_values_d1 (int,double);
        void set_values_d2 (int,float);
        // ... add as many as necessary
        double get_values_d1 (void);
        float get_values_d2 (void);
        // ... add as many as necessary
    };

    class DataType1: public SuperClass {
      public:
        void set_values_d1 (int,double) { /* do something */ }
        double get_values_d1 (void) { /* do something */ }
        // ... add all the other functions
    };
    int DataType1::current_data_type = 1;

    class DataType2: public SuperClass {
      public:
        void set_values_d2 (int,float) { /* do something */ }
        float get_values_d2 (void) { /* do something */ }
        // ... add all the other functions
    };
    int DataType2::current_data_type = 2;

    int arrayItems = 100;
    SuperClass myDataArray [arrayItems] = {dataItem1, dataItem2, ... , dataItem100};

    method(SuperClass &myDataArray, int arrayItems) {
      for (int i = 0; i < arrayItems; i++) {
        switch(myDataArray.current_data_type){
          case 1 :
            // do all computations for DataType1
            break;

          case 2 :
            // do all computations for DataType2
            break;

          // create as many case statements as there are data types.
        }
      }
    }


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
I have a few favourites, but here are a couple that nearly always come up. Most of the time I'm doing final round technical (C++) interviews so favour longer and more open questions which lead to new areas of interest. There's no 'right' answer, just an opening to other conversation.

1) Implementing a basic shared pointer, explanations of where there's deficiencies compared to tr1 or boost's shared pointers in their implementation, how it should be used etc.

2) A code review. For experienced hires we expect them to be able to confidently review some provided code for design problems, errors, coding horrors and potential maintainability problems. Also, of course, how they'd fix it; and sometimes how they'd give that message to the junior developer they're shooting down.


问:
What is an Integration Point?
How is an Integration Point defined within the context of an application?

I've heard about it in a programming course but couldn't grasp the concept in a way that I could distinguish an integration point among other parts of the software.
The teacher in the course asked to make sure that software is responsive and stays stable when it comes to the operation in an integration point.

Sample integration points from the course:

When Software receives a user input

When Software makes an API call
to a remote server.

答:
TL; DR:

Please review all of the articles listed under "Object-Oriented Design" on  ObjectMentor.

The following is my personal opinion, provided for a discussion. It should not be treated as a definition. There may be errors in this personal opinion.

Integration point:

Any abstract "facility" 1, by design 2, where the behavior of the application might be modified in a way that cause newly written / customer-written code (code that is not originally shipped as part of the application) to be executed.

1 These facilities may include, but not limited to: callback functions (or any first-class function objects), dependency injection points, OOP interfaces defined by the applications that can be concretely implemented by client software, OOP inheritable base classes provided by the application.

2 A proper integration point is one which is intended 3 by the "owners" (designers or vendors) of the application.

Typical software may have some facilities which allow execution of new code, but which are not intended by the owners of the application.

In security, this is almost certainly a software defect, and potentially a vulnerability which allows a malicious person to subvert the security system or the original purposes of the application. This is why unintended ones would not be normally considered an integration point.

3 Because very little constraints can be placed on the customer-written code being invoked from an integration point, the "owners" of the application cannot make unilateral guarantees of correct operations unless the customer-written code is designed carefully to avoid interfering the correctness of the application.

Thus, some expectation of responsibility and diligence is placed on the customer who write code to be executed from the integration point.

Title: What is an Integration Point?


答:
I've been exposed to a lot of different projects in the past taking different approaches. The one I've liked the best was re-using an interface from the ORM to use throughout the code. In the case of entity framework we are normally using an DbContext with a bunch of DbSet< T>. Luckily DbSet implements IDbSet< T> which there exists in memory implementations of .

So we can define an interface and depend on the that throughout the code:

```<code>interface IFooContext
{
    IDbSet< Bar> Bars{get;}
    IDbSet< Baz> Baz{get;}
}
</code>```

This is a very lightweight approach because we don't have to write the wrappers. I'm aware not all ORMs have an interface we can use like this but for those that this is an easy approach.

Body:
I've been exposed to a lot of different projects in the past taking different approaches. The one I've liked the best was re-using an interface from the ORM to use throughout the code. In the case of entity framework we are normally using an DbContext with a bunch of DbSet< T>. Luckily DbSet implements IDbSet< T> which there exists in memory implementations of .

So we can define an interface and depend on the that throughout the code:

interface IFooContext
{
    IDbSet< Bar> Bars{get;}
    IDbSet< Baz> Baz{get;}
}

This is a very lightweight approach because we don't have to write the wrappers. I'm aware not all ORMs have an interface we can use like this but for those that this is an easy approach.


问:
Is “file” also participate in open closed principle?
I know according to open closed principle, something like class,interface,code.... should be unchanged when add new functions or contents, but is file also in this case?

I was designing a game, the game have some monster information, and the game (in client side) may download or replace some file if there are new monsters to add or update.

I was worrying what should be the format of monster information: 1 file with all monster information or each monster has individual file?

1.Store all monster information into a single file (e.g.:monsterlist.json),each time add new monster it will replace the file e.g.:

```<code>{
    "monsterList":[
        {
            "id":1,
            "hp":100,
            "attack":230,
        },
        {
            "id":2
            "hp":500
            "attack":980
        }
    ]
}
</code>```

2.Each monster has a individual file,each time add a new monster will also add a new monster json:

monster1.json

```<code>{
    "id":1,
    "hp":100,
    "attack":230,
}
</code>```

monster2.json

```<code>{
    "id":2,
    "hp":500,
    "attack":980,
}
</code>```

At start I think case 1 is most convenient, because when I add or update any monsters I only need to replace monsterlist.json, but for case 2, I need to know which json is new (may need extra row to store the update status in server database).

But suddenly I remember open closed principle, adding something new should not modify the current content, it seems not reasonable to replace a file when a new monster is added.

Note: I am not asking which format is better (which is opinion based), the example above is just the background information to illustrate why I would have this question. The thing I want to ask is just : is “file” also participate in open closed principle?

答:
Short answer

No. The Open/Closed principle applies to object-oriented software constructs such as classes, not data.

Long answer

When evaluating programming patterns and principles, it's important to understand why the principle was created in the first place, how it applies to programming, and what exactly it applies to.  Without that understanding, it's very easy to learn about a principle for the first time, think it applies to everything, and apply it indiscriminately or even in a way that causes harm.

For example, the phrase "premature optimization is the root of all evil" is misused all of the time to mean things like "don't optimize until later," or worse, applied to things for which it has no relevance, such as sensible software design.  What the phrase really means is "measure first, then optimize only those parts of your code which your measurements say will produce tangible benefits."  It doesn't say anything about not following sensible design principles from the start.  In addition, that's not actually the entire phrase, so some meaning is lost if that's all you quote.

That said, let's examine the Open/Closed principle.

In object-oriented programming, the open/closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification 1

Object-oriented programming, as the principle implies, primarily involves code, not data.  Some readers will argue that "code is data," or that "some data has object-oriented features such as inheritance," which are both true.  But the principle that we're talking about here is intended to be used within the context of object-oriented programming in the traditional sense, not as a principle to be applied to data.

The Open/Closed principle is the O in SOLID, the five principles that, when applied together in an object-oriented software design, intend to make it more likely that a programmer will create a system that is easy to maintain and extend over time.2

Single responsibility principle

A class should have only a single responsibility (i.e. only one potential change in the software's
  specification should be able to affect the specification of the class)

Open/closed principle

"Software entities should be open for extension, but closed for modification."

Liskov substitution principle

"Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program." See also Design By Contract.

Interface segregation principle

“Many client-specific interfaces are better than one general-purpose interface.”

Dependency Inversion Principle

“Depend upon Abstractions, not on concretions.”

Notice the wording of these principles.  They all refer to "software entities:" classes, modules, functions, interfaces and so on, all staples of the Object-Oriented paradigm.  These are not data, in the traditional sense, though they may contain data.  Data follows a different set of rules, and a different vocabulary: immutability, atomicity, durability, etc.

Read Robert C. Martin's Clean Code and you will get a very good perspective on the proper context in which these terms are used.

1Meyer, Bertrand (1988). Object-Oriented Software Construction. Prentice Hall. ISBN 0-13-629049-3.

2“SOLID Object-Oriented Design”, Sandi Metz (Duke University), Talk given at the 2009 Gotham Ruby Conference in May, 2009.


答:
Though I think @RobertHarvey's answer is really good, I would like to add an answer from a more practical point of view.

The answer to your question depends simply on how you map your OO constructs to files. If classes are in 1:1 relations to files, "change of class" means "change of file", there is no difference. If you store all classes of a specific layer or type in one file, and you want to add another class, you obviously must change the file when adding another class. And when you do not even have files (because your code is stored, for example, in a database), it is pretty obvious that files do not participate in the OCP.

Title: Is “file” also participate in open closed principle?

Body:
I know according to open closed principle, something like class,interface,code.... should be unchanged when add new functions or contents, but is file also in this case?

I was designing a game, the game have some monster information, and the game (in client side) may download or replace some file if there are new monsters to add or update.

I was worrying what should be the format of monster information: 1 file with all monster information or each monster has individual file?

1.Store all monster information into a single file (e.g.:monsterlist.json),each time add new monster it will replace the file e.g.:

```<code>{
    "monsterList":[
        {
            "id":1,
            "hp":100,
            "attack":230,
        },
        {
            "id":2
            "hp":500
            "attack":980
        }
    ]
}
</code>```

2.Each monster has a individual file,each time add a new monster will also add a new monster json:

monster1.json

```<code>{
    "id":1,
    "hp":100,
    "attack":230,
}
</code>```

monster2.json

```<code>{
    "id":2,
    "hp":500,
    "attack":980,
}
</code>```

At start I think case 1 is most convenient, because when I add or update any monsters I only need to replace monsterlist.json, but for case 2, I need to know which json is new (may need extra row to store the update status in server database).

But suddenly I remember open closed principle, adding something new should not modify the current content, it seems not reasonable to replace a file when a new monster is added.

Note: I am not asking which format is better (which is opinion based), the example above is just the background information to illustrate why I would have this question. The thing I want to ask is just : is “file” also participate in open closed principle?


问:
Does music increase your productivity?
I wanted to know whether you think and audio background is just a distraction or could be of some help while programming.

For me, it works like this:

when I'm writing pseudocode, or implementing procedures that are very clear in my mind in a language I can write without looking up docs, having music playing in the background (very straightforward electronics, mostly) helps me a lot: it kind of gives some rhythm to my coding and, if the procedures are trivial, avoids the distractions that boredom can cause.

When I incur in a problem, or I have to try to fix a bug, instead, it just distracts me.

Also, if the song is really regular and I know it well enough not to cause me to focus on it, it eliminates unexpected environmental noise that sometimes make me waste precious seconds before I can concentrate on the code again.

Guidelines checklist: 1 ok, 2 I hope; 3 I suppose; 4 Definitely; 5 I would like that to happen; 6 Doch (English should implement a way to disambiguate double negatives in answers)

答:
Well, some call it "muzak". Productive music is not a new concept and it being used from centuries ago (yes, centuries).
Personally what works for me for working as a programmer is lounge music. Specially, I program everyday with Groove Salad on and on all day long. It helps me a lot to focus 'n flow! Very recommended for programming.
Bye.</p>

Title: Does music increase your productivity?


问:
Distributed transactions with Kafka
I need to implement a transaction that spans over loosely coupled (SOA+MOM) components.

When a particular event is received, FOO and BAR need to do a transactional operation: that is, both the transactions on FOO-DB and BAR-DB need to be successful or none of them. The consistency here is very important.

When the event is received (1), FOO does an operation on a database (2).

If the operation fails, nothing more happen.

If the operation is successful, a message is sent to BAR through a MOM (Kafka) (3).

BAR does an operation on another database (4).

If the operation fails, the operation previously done on FOO-DB must be reverted (5, 6).

If the operation is successful, all is fine.

Right now I'm using Kafka. I like its simplicity and speed, but I'm open to consider other solutions if they would make this situation easier to implement/maintain/extend.

I'm quite new to SOA and MOM architectures and patterns, so I'm wondering:

is this a common scenario/pattern?

how is this commonly implemented?

the simple means offered by Kafka are enough to reliably implement this or I would be better considering other solutions?

is the distributed transaction manager usually provided by the MOM or by the database? and if it is the DB, how can this be done using different DBs?

Sorry for the many questions, I hope they're not too much for a single question.
Thank you!

答:
I am not familiar with either "Kafka" nor "MOM" but if not done yet, I'd probably start by making sure the ideas behind two-phase commit are understood, in order to guide / inform your design and implementation endeavor, depending on the level of consistency you want to achieve.

'Hope this helps.

Title: Distributed transactions with Kafka


问:
Is there an algorithm to avoid getting in hundreds of datapoints from API to represent a bar graph?
I am showing a graph on HTML5 canvas using the flot charting library for a between a start date and an end date. It's fine as long as the period is less than a year or so but if the user selects a big time period I will have to send large dataset and have browser process it every now and then.
We have data points on daily basis.

What would be a good approach to solve an issue like this ?
I am guessing it will require some normalization of data and rejecting certain datapoints based on how long the time period is.

Or I should restrict user to a max time period range ?

答:
If I understood well, you want to keep the number of your data points (for consideration) bounded under a computation-friendly threshold, including in the case of long periods of time, yet have your charting "pretend" as if it had processed many more / all of them. In that case, this might be a good use case for picking some type of interpolation method over your discrete input set.

'Hope this helps.


答: You can pre-compute the statistic you want to show for each date. Then you just send the user 360*years data points, which are few enough for the slowest computer.</p>

Title: Is there an algorithm to avoid getting in hundreds of datapoints from API to represent a bar graph?

Body:
I am showing a graph on HTML5 canvas using the flot charting library for a between a start date and an end date. It's fine as long as the period is less than a year or so but if the user selects a big time period I will have to send large dataset and have browser process it every now and then.
We have data points on daily basis.

What would be a good approach to solve an issue like this ?
I am guessing it will require some normalization of data and rejecting certain datapoints based on how long the time period is.

Or I should restrict user to a max time period range ?


问:
In a mutual credit network, how would you program an automatic jubilee?
A little explanation might be needed. I mean mutual credit the way that it's defined here:

a type of alternative currency in which the currency used in a transaction can be created at the time of the transaction

Imagine you have a network of accounts. Each starts out at zero and any account can extend a limited line of credit to any other account. My total balance would just be the sum of what others "owe" to me, minus the sum of what I owe to others.

Lines of credit can be represented with a simple table. In pseudo-code for some kind of ORM:

```<code>type LineOfCredit struct {
    IOURecipient  string, // Account ID of IOU recipient
    IOUIssuer     string, // Account ID of IOU issuer
    Owed          int,    // Amount owed to IOU recipient
    Limit         int,    // Maximum IOU amount
}
</code>```

To hopefully make the concept clearer: The "recipient" would generally be the person getting "paid" in a transaction; the "issuer" is the person "paying." For example:

Persons A requests service from person B

B agrees and extends a line of credit to A

A issues IOU to B

These debts may or may not be settled in some real-world currency, at some point, but the idea is that they eventually cancel out one another, either directly or indirectly.

I'll use "$" to represent the currency, though, of course, the units are arbitrary. Imagine that...

Bob owes $20 to Sally

Sally owes $20 to Joe

Joe owes $20 to Bob

It's clear that there's no actual debt here and they don't owe one another anything.

So, how would you detect these kinds of cycles in a balance sheet and then eliminate them? Is this a problem for graph theory? I imagine this can be represented as a directed network graph. My knowledge here is very limited, but I understand it's possible to detect cycles with Tarjan's strongly connected components algorithm, though that doesn't seem to offer much help, especially as those cycles get larger. I also thought that, maybe, shortest-paths could be crunched at the time of a transaction, with the reciprocals of outstanding "debts" represented as edge-weights/distances.

I think Ripple pay possibly did something like this, but I'm having trouble finding a precedent.

答:
The IOU trio you gave as an example, who are balancing each other out, down to zero debt when taken as a whole, evokes the typical counter-example of a (pathological) isolated cycle that defeats reference counting used in memory allocators: the mere existence of a (directed) reference between one node and another prevents those to be deallocated; because each having a use count greater than zero (1).

A classic, common way to garbage-collect such cycles nonetheless (to overcome the limitations of naive reference counting) is by a two-phase "mark-and-sweep" procedure: first, you mark all the nodes as being "dead". Then, from some root node (say, Jack), you recursively follow all the references, using a hop-by-hop from one node to another, and unmark ("revive") the nodes thus-reached after each hop, until all the references have been followed exactly once.

Eventually, some references will have never been followed (because their starting node is unreachable from any other in the first place), and the nodes they point to, will thus still be marked "dead". Just as for your Bob, Joe, Sally trio.

Of course, in your case, we must tweak the notions a bit and define a "reference type" by analogy with the notion of equivalence class:

say, for the equivalence class / reference type "has an IOU of $20 on someone else", each of the three Bob, Sally, and Joe has exactly one such "reference".

So, I believe you can leverage the mark-and-sweep algorithm, at the cost of maintaining, for each node, the set of (distinct) equivalence classes "has an IOU of $X on someone else" that it uses, along with the corresponding markers (1 bit per node and per equivalence class it uses is enough) and running it, mark-and-sweep, as many times over your entire graph as there are (distinct) equivalence classes in use, in total (*)

This may not be a good solution (at all) if there are many possible, distinct amounts of IOUs between any two nodes, though... say, if your graph is already millions of nodes-wide and your distinct IOUs are arbitrarily found in the range $1 to $1,000,000 with a normal distribution, for instance.

'Hope this helps.

(*) E.g.,

Bob owes Joe $20;
Jack owes Pete $15;
Joe owes Pete $30 and Sally $20;
Pete owes Bob $20 and Sally $15;
Sally owes Jack $15 and Pete $20:

```
[IOU...]Bob     Jack    Joe     Pete    Sally
Bob                     (20)

Jack                            (15)

Joe                             (30)    (20)

Pete    (20)                            (15)

Sally           (15)            (20)
```

After reduction:

```
[IOU...]Bob     Jack    Joe     Pete    Sally
Bob

Jack

Joe                             (30)

Pete

Sally
```

(Only remaining: Joe owes Pete $30)

Body:
The IOU trio you gave as an example, who are balancing each other out, down to zero debt when taken as a whole, evokes the typical counter-example of a (pathological) isolated cycle that defeats reference counting used in memory allocators: the mere existence of a (directed) reference between one node and another prevents those to be deallocated; because each having a use count greater than zero (1).

A classic, common way to garbage-collect such cycles nonetheless (to overcome the limitations of naive reference counting) is by a two-phase "mark-and-sweep" procedure: first, you mark all the nodes as being "dead". Then, from some root node (say, Jack), you recursively follow all the references, using a hop-by-hop from one node to another, and unmark ("revive") the nodes thus-reached after each hop, until all the references have been followed exactly once.

Eventually, some references will have never been followed (because their starting node is unreachable from any other in the first place), and the nodes they point to, will thus still be marked "dead". Just as for your Bob, Joe, Sally trio.

Of course, in your case, we must tweak the notions a bit and define a "reference type" by analogy with the notion of equivalence class:

say, for the equivalence class / reference type "has an IOU of $20 on someone else", each of the three Bob, Sally, and Joe has exactly one such "reference".

So, I believe you can leverage the mark-and-sweep algorithm, at the cost of maintaining, for each node, the set of (distinct) equivalence classes "has an IOU of $X on someone else" that it uses, along with the corresponding markers (1 bit per node and per equivalence class it uses is enough) and running it, mark-and-sweep, as many times over your entire graph as there are (distinct) equivalence classes in use, in total (*)

This may not be a good solution (at all) if there are many possible, distinct amounts of IOUs between any two nodes, though... say, if your graph is already millions of nodes-wide and your distinct IOUs are arbitrarily found in the range $1 to $1,000,000 with a normal distribution, for instance.

'Hope this helps.

(*) E.g.,

Bob owes Joe $20;
Jack owes Pete $15;
Joe owes Pete $30 and Sally $20;
Pete owes Bob $20 and Sally $15;
Sally owes Jack $15 and Pete $20:

[IOU...]Bob     Jack    Joe     Pete    Sally
Bob                     (20)

Jack                            (15)

Joe                             (30)    (20)

Pete    (20)                            (15)

Sally           (15)            (20)

After reduction:

[IOU...]Bob     Jack    Joe     Pete    Sally
Bob

Jack

Joe                             (30)

Pete

Sally

(Only remaining: Joe owes Pete $30)


问:
Why can't I call a constructor in itself?
I am currently porting the class NumberRange from Java to C#.

I am writing this constructor and I wonder whether I can call a constructor in itself. Something like this:

```<code>public NumberRange(Double num1, Double num2)
{
    if (num1 <= num2)
    {
        Min = num1;
        Max = num2;
    }
    else
    {
        NumberRange(num2, num1);
        // Min = num2;
        // Max = num1;
    }
}
</code>```

.NETFiddle

This is not a big deal, but I am curious. I think it is to prevent messing with constructor by creating a Stack Overflow during a class creation.

So, why can't I call a constructor in itself?

Edit:

I remind that my question was about the "why" and not the "how". If you ask yourself how I implemented this, just read my code here.

答:
EDIT2: It's seems like it's not possible and I was mistaken. Probably confused two things I did in the past. I apologise.

You can call a constructor in itself, but you call it by writing

```<code>new ClassName(arg1, arg2);
</code>```

like in writing

```<code>public Constructor(int a1, int a2)
{
    if(a1<a2) return new Class(a2, a1);
}
</code>```

EDIT:
Sorry I was wrong about the this();

ContentLicense: CC BY-SA 4.0

Body:
EDIT2: It's seems like it's not possible and I was mistaken. Probably confused two things I did in the past. I apologise.

You can call a constructor in itself, but you call it by writing

new ClassName(arg1, arg2);

like in writing

public Constructor(int a1, int a2)
{
    if(a1<a2) return new Class(a2, a1);
}

EDIT:
Sorry I was wrong about the this();


问:
How to do external API testing (blackbox)
Assume you are using APIs from a vendor, how to make sure their API is working as expected?

My main concern is sometimes the vendor pushed the changes to their code and break the API, we want to have some sort of automatic software to test them continually. How to deal with this?

答:
There are 2 approaches for this issue...

your app is live in production with real user traffic:

if you have an app in production that has live traffic and depends on an external api you have no choice but to closely monitor and have good thresholds to know as fast as possible when the external api makes changes without notifying.

you should always take into account that :

api's change over time

the api vendor can have bugs

api vendors test-kits can have bugs or not fully cover all the production api's functionality

your app is an installation and has planned version/releases:

in this case you have a grace period to fail... live user aren't effected immediately of the external api breaking changes.

in my opinion this is a more easy task. write a test (full end-to-end test) that makes real transactions/http/requests to you application that invoke the external api and check that there are no failures. no test-kits no mocks real transaction.

after this task is done you can choose to run this every 24H , 1 min etc...

good practices:

automate everything

have a person you can quickly contact from the vendor of the external api

dont blindly trust the vendor test everything

fail fast - if your service depends heavily on the external api dont let your service crash. fail fast and return proper error messages

tools:

monitoring live application : hyperic new-relic

api testing: apimetrics runscope soapui


答:
The issue seems to be not the recursion, but with invoking the constructor at all.  See below:

```<code>class NumberRange
{
    public double Min { get; set; }
    public double Max { get; set; }

    public NumberRange(double num1, double num2)
    {
        if (num1 <= num2)
        {
            Min = num1;
            Max = num2;
        }
        else
            NumberRange(num2, num1); // illegal!!
    }

    public void AFunction()
    {
        NumberRange(1, 2); // also illegal!!
        this.NumberRange(1, 2); // 'this' keyword doesn't help
    }
}
</code>```

And:

```<code>new NumberRange(1, 2).NumberRange(2, 1); // can't invoke the constructor on an object either
</code>```

Obviously in your case the recursion was completely unnecessary, but if you have code which must be "recursable" - or just available outside of the context of instantiating a class - that code must be in a non-constructor function.

See this answer for why it is OK to call methods from constructors in C#.  (In short, C# handles virtual method calls in ctors as one might hope.)

Title: Why can't I call a constructor in itself?

Body:
I am currently porting the class NumberRange from Java to C#.

I am writing this constructor and I wonder whether I can call a constructor in itself. Something like this:

```<code>public NumberRange(Double num1, Double num2)
{
    if (num1 <= num2)
    {
        Min = num1;
        Max = num2;
    }
    else
    {
        NumberRange(num2, num1);
        // Min = num2;
        // Max = num1;
    }
}
</code>```

.NETFiddle

This is not a big deal, but I am curious. I think it is to prevent messing with constructor by creating a Stack Overflow during a class creation.

So, why can't I call a constructor in itself?

Edit:

I remind that my question was about the "why" and not the "how". If you ask yourself how I implemented this, just read my code here.

Body:
The issue seems to be not the recursion, but with invoking the constructor at all.  See below:

class NumberRange
{
    public double Min { get; set; }
    public double Max { get; set; }

    public NumberRange(double num1, double num2)
    {
        if (num1 <= num2)
        {
            Min = num1;
            Max = num2;
        }
        else
            NumberRange(num2, num1); // illegal!!
    }

    public void AFunction()
    {
        NumberRange(1, 2); // also illegal!!
        this.NumberRange(1, 2); // 'this' keyword doesn't help
    }
}

And:

new NumberRange(1, 2).NumberRange(2, 1); // can't invoke the constructor on an object either

Obviously in your case the recursion was completely unnecessary, but if you have code which must be "recursable" - or just available outside of the context of instantiating a class - that code must be in a non-constructor function.

See this answer for why it is OK to call methods from constructors in C#.  (In short, C# handles virtual method calls in ctors as one might hope.)


问:
Can I have two aggregations between two classes?
Note: this question is different from Can a UML class diagram show two different relationships between two classes? which is about two relations of different type.

I have a Menu class which contains:

A bunch of children, which are instances of MenuItem class.

An instance of a MenuItem class which corresponds to a very specific menu item (and is not necessarily set for every instance of Menu class.)

How am I expected to represent such relation? In other words, is this representation correct:

or should I remove the second aggregation as being redundant?

答:
In your description, you are talking about two ways in which a Menu instance contains MenuItem instances: A set of children and a separate customization item.

This implies that there are two separate, independent, relations between Menu and MenuItem and that each of them plays an important role in the design.

Your UML diagram should contain all the relations that are needed to convey the ideas of your design. If you omit a relation here, then you are removing important information from your diagram and you will likely end up with software that does not match what you intended to build.

The main difference here with the question you linked to (Can a UML class diagram show two different relationships between two classes?) is that there one of the relations (the nesting of the classes) can be regarded as incidental and not representing a core design concept. Such incidental relations can be omitted from a diagram if they would mostly create clutter.


答:
Currently, where I work, we use a repository that sits on top of EntityFramework so that we can mock it out relatively easily. It isn't quite a repository like in the Repository Pattern, however, it acts as a go between for objects using that pattern an EntityFramework.

The important part here is that it doesn't have equivalents to "GetUsers" and "GetUsersWhereAdminIsTrue", instead, we use a generic method that takes an generic object that builds its own IQueryable for that which we call Criteria. This means that this go between consists of the following generic methods, where the type is the EntityFramework object:

Add (takes a Users object, and adds it to the Users table)

Remove (takes a Users object, and remove it from the Users table)

Matches (takes a generic Criteria object of Users and returns a set of Users matching that criteria)

Save (doesn't take any parameters, but saves any pending changes)

One of the helpful parts of the Matches method is that it finalises the collection, which skips over some concerns when it comes to n+1 ORM issues.

When it comes to our actual repository objects, our equivalent to a UsersRepository may well have GetUsers and GetAdmins methods, but all these will do is create a Criteria for that requirement and pass it to our main repository. Then, the UsersRepository can sit on a mock instead of EntityFramework and still pass the same criteria through which we can test.

It's not perfect for testing EntityFramework (due to things like DbFunctions which we use Shims for), but it covers most situations without too much concern.