问:
Database model for keeping track of likes/shares/comments on blog posts over time
My goal is to keep track of the popular posts on different blog sites based on social network activity at any given time. The goal is not to simply get the most popular now, but instead find posts that are popular compared to other posts on the same blog.

For example, I follow a tech blog, a sports blog, and a gossip blog. The tech blog gets waaay more readership than the other two blogs, so in raw numbers every post on the tech blog will always out number views on the other two. So let's say the average tech blog post gets 500 fb likes and the other two get an average of 50 likes per post. Then when there is a sports blog post that has 200 Facebook likes and a gossip blog post with 300 while the tech blog posts today have 500 likes I want to highlight the sports and gossip blog posts (more likes than average vs tech blog with more # of likes but just average for the blog)

The approach I am thinking of taking is to make an entry in a database for each blog post. Every x minutes (say every 15 minutes) I will check how many likes/shares/comments an entry has received on all the social networks (Facebook, Twitter, Google+, LinkedIn). So over time there will be a history of likes for each  blog post, i.e

```<code>   post 1234

        after 15 min: 10 fb likes, 4 tweets, 6 g+
        after 30 min: 15 fb likes, 15 tweets, 10 g+
        ...
        ...
        after 48 hours: 200 fb likes, 25 tweets, 15 g+
</code>```

By keeping a history like this for each blog post I can know the average number of likes/shares/tweets at any give time interval. So for example the average number of fb likes for all blog posts 48hrs after posting is 50, and a particular post has 200 I can mark that as a popular post and feature/highlight it. A consideration in the design is to be able to easily query the values (likes/shares) for a specific time-frame, i.e. fb likes after 30min or tweets after 24 hrs in-order to compute averages with which to compare against (or should averages be stored in it's own table?)

If this approach is flawed or could use improvement please let me know, but it is not my main question. My main question is what should a database scheme for storing this info look like?

Assuming the approach above is taken, I am trying to figure out what a database schema for storing the likes over time would look like. I am brand new to databases, in doing some basic reading I see that it is advisable to make a 3NF database. I have come up with the following possible schema.

Schema 1

```<code>DB Popular Posts

  Table: Post
    post_id ( primary key(pk) )
    url
    title

  Table: Social Activity
    activity_id (pk)
    url (fk)
    type (i.e. facebook,twitter,g+)
    value
    timestamp
</code>```

This was my initial instinct (base on my very limited db knowledge). As far as I under stand this schema would be 3NF? I searched for designs of similar database model, and found this question on weight/height storage of multiple users. The scenario in that question is similar (recording weight/height of users overtime). Taking the accepted answer for that question and applying it to my model results in something like:

Schema 2 (same as above, but break down the social activity into 2 tables)

```<code>DB Popular Posts

  Table: Post
    post_id (pk)
    url
    title

  Table: Social Measurement
    measurement_id (pk)
    post_id (fk)
    timestamp

  Table: Social stat
    stat_id (pk)
    measurement_id (fk)
    type (i.e. facebook,twitter,g+)
    value
</code>```

The advantage I see in schema 2 is that I will likely want to access all the values for a given time, i.e. when making a measurement at 30min after a post is published I will simultaneous check the number of fb likes, fb shares, fb comments, tweets, G+, LinkedIn. So with this schema it may be easier get get all stats for a measurement_id corresponding to a certain time, i.e. all social stats for post 1234 at time x.

Another thought I had is since it doesn't make sense to compare number of fb likes with number of tweets or g+ shares, maybe it makes sense to separate each social measurement into its own table?

Schema 3

```<code>DB Popular Posts

  Table: Post
    post_id (pk)
    url
    title

  Table: fb_likes
    fb_like_id (pk)
    post_id (fk)
    timestamp
    value

  Table: fb_shares
    fb_shares_id (pk)
    post_id (fk)
    timestamp
    value

  Table: tweets
    tweets__id (pk)
    post_id (fk)
    timestamp
    value

  Table: google_plus
    google_plus_id (pk)
    post_id (fk)
    timestamp
    value
</code>```

As you can see I am generally lost/unsure of what approach to take.

I'm sure this typical type of database problem (storing measurements overtime, i.e temperature statistic) that must have a common solution. Is there a design pattern/model for this, does it have a name? I tried searching for "database periodic data collection" or "database measurements over time" but didn't find anything specific.

What would be an appropriate model to solve the needs of this problem?

答:
So, reading this, I see the following specs:

I want to track popularity of blogs. This is accomplished by comparing their aggregate "likes" or whatever (retweets, etc) over a 48 hour period to their "normal" level.

I want to update my current count of likes, retweets, on a configurable periodic interval.

I need to be able to compute the effect of likes, retweets, etc independent of each other.

Seems the simplest way would be to use your third schema. It still allows you to collect all stats simultaneously or independently. The only effect would be if independent, there will always be some window of time where your current rankings doesn't reflect the true ranking while if simultaneous, your rankings just lag the "truth" by at most the update rate.

Anyway, then, you can periodically run a query for each post_id, compute the fb likes metric over the previous 48 hours + tweets metric over the previous 48 hours, etc, and use that to update your ranking.

ContentLicense: CC BY-SA 4.0


问:
Exception handling in a program that needs to run 24/7
I have read that we should only catch exceptions that can be handled, which makes catching the base exception class (C# in this case) a bad idea (on top of other reasons). I am currently part of a project in which I so far have yet to see anything but the base exception being caught. I mentioned that it is considered bad practice to do so, but the response was "This service needs to run 24/7, so that is the way it is.".

Since I did not have a good response for how to properly handle exceptions in a program that needs to run 24/7, I am now here. I have not managed to find any information / suggestions on how to deal with exception handling in "critical" programs / services that needs to run around the clock (and in this case I believe it may be ok if the service is down for a minute or two, so not even critical). I understand it depends on the exact nature of the program. The requirements for a program that can cause life threatening issues are quite different compared to a log scanner for an online game.

Two examples:

1: A type-ahead service for customers of the Brittish railways, used when they searching online for railway stations.

2: A program that automatically controls the railway switches for the above railways based on realtime information provided from various sensors in the tracks, trains etc.

The first program would probably not cause a major issue if it went down for a minute or two, wheras the latter could cause human casualties. Suggestions on how to deal with each? Pointer to where I can find more information and thoughts on this issue?

答:
I so far have yet to see anything but the base exception being caught.

It sounds like there is a problem here, in as much as exceptions aren't being dealt with appropriately. Catching exceptions at the appropriate point and taking appropriate action (depending on the type of exception) will keep the service running in a much more reliable fashion.

If service must continue, presumably it's important that it is working as intended. Given your example, if a program which controls railway switches throws an exception it may indicate that there's a problem communicating with safety-related sensors. If you catch the base exception and continue the service may run, but may not function as intended leading to disaster.

Alternatively, if you catch the exception thrown when there's a communication failure with the sensor and deal with it appropriately (i.e. stop the trains in the affected area) your service is running and you haven't killed anyone.

So, as I understand the question, I'd suggest that in the first instance you would be better looking to add more specific exception handling rather than to remove the base-exception-type handlers.

ContentLicense: CC BY-SA 3.0


问:
What's the best way to show some of my code during an interview?
I realize that there are already a couple of questions about this, but they mostly are about if you should bring code to the interview, which is not the case here.

I have a job interview (at a startup) coming up next week and they requested to bring some code to the interview. I have two smaller open-source projects and a closed-source Android app, which I mentioned (and linked) in my skill sheet I sent along, so I wanted to show them some code of those projects. It's my first job after graduating, so I don't have any sources from previous employments and there won't be any issues regarding "spying", licensing issues, confidential code etc. All the code is completely mine and written by me.

I guess I have pretty much three options: print some interesting parts of the code on paper or have everything on my tablet or laptop to show. The latter two have the advantage that I can bring all my projects and basically show them everything they want to see. However you can't directly make notes/underline stuff etc. as if I had printed it out and it's less convenient than just handing out paper.

What's the best way to handle this professionally and do this as hassle-free as possible? I currently tend to print out some of the parts that I think are both interesting and well written, but have everything on my tablet in case they want to see more.

答:
Why don't you do both?  Bring paper print-outs and bring an electronic device to showcase the rest?

If they have let you know how many people you are interviewing with, bring print-outs for each interviewer plus two or three spares.  Extra interviewers get added on all the time and you want to be prepared for that.

If you can, bring a device with a screen that's easily seen from a distance.  You don't necessarily want to huddle around the 4" screen of your phone in order to show your code.

I would consider cherry picking separate sections of code to show.  For the print-out, a smaller, mostly self-contained routine would be ideal.  For the device, I would try to identify some thorny problems that you had to solve and have those loaded up and ready for show.

It's worth noting that you do not need to bring copies of your closed source application unless you want to do so.  Any potential employer should respect your copyright and understand that you may not be comfortable with handing out copies of that source.


问:
Martin Fowler's Refactoring book: switch statement is using other object's data, why is that bad ? A deeper explanation is sought for.
In the code sample below the Rental object is using Movie's fields to do a switch statement. Martin says : this is a bad idea but he does not give any deeper explanation as to why ?

Of course, you can say that this means a lot of coupling between Movie and Rental, or that Movie is badly encapsulated but those are just (almost meaningless) words, again, they don't explain the why? They don't go to the root of the question, so to say. They don't provide much understanding.

What I would like to know if there is a deeper, more general design principle why having a switch on Rental is a bad idea ?

In other words, how does Martin knows that the switch statement is on the wrong object ? Where does he get this insight from ? What is his thought process ?

答:
The core concept of OO is to encapsulate the operations close to the data. Fowler's idea is that movie should decide itself how much it is worth (may be through inheritance into multiple movies?).

I do not completely concur with Fowler's idea:

There are other ways to deal with this. What if 'rental policy' is an object in itself? Movie is supposed to represent the purest data about the movie, and not how a rental company considers a movie to be a rentable object.

This does not work in enterprise applications: data gets serialized, transformed, dissected, split, joined... ensuring Fowler's idea would be hard.

What is the unit of encapsulation? Is it better to consider renting as  a composite? This composite owns these data elements of movie and rental policies, and offers a service that would be the single point of decision making.

Many a times, Fowler's ideas are usually best suited for teaching how to build small applications. These principles should in turn help build clear thoughts of building larger applications that contain composites.

OwnerDisplayName: jhegedus


问:
Software on Budget and on time?
We've all (almost all) have heard about the horror stories as well as perhaps studied about them.

Its easy to find stories of software that is over budget and late.

I wanted to hear from developers the opposite story:

Question:

Do you know, or have worked on a project that was on budget and on time?

What is the most valuable lesson you learned from it?

答:
Yes, I've worked once in such a kind of project.
It was a not so little web application for documents managing, for a quite big company, in which the different documents could be categorized at different nodes, supporting meta-data for documents and nodes, different authorization levels, etc.
the key points for me were:

Clear, concise, and well defined requirements,

Management focused in ease the developers work, not in watch their work, control it, or urge developers. About this, in the final rush, the manager just told everybody "boys, we have to deliver next week. Let's try to get in time", and everybody did our part to reach the target. Trust is a key word for me at the team management.

Spending time at the system modeling phase, is not at all a waste, but a investment. A detailed design saves lots of development hours.

And last, but not least, a good relationships among the team members, and a friendly environment, do more for productivity than we are used to think.

ContentLicense: CC BY-SA 2.5

Title: Software on Budget and on time?


问:
To store data or not?
I'd like to ask you about one simple thing. I have class A that do something (for example counts something ). There is also one class B that handle some parameters to this class (class A is member of class B). Class B calls one method of class A that does something and writes value to database.

Class A uses parameters that got from Class B. Class A has few methods to made clean code  (it's good I think). But... Is it ok to save parameters as private members?? It's not necessary. I don't have to remember them after writing to Database. But if I don't have private data I have to handle it to every private method as parameters (during processing). I think that it's ok to save this parameters as members of this class. Am I right? Or maybe I should avoid this when it's not necessary (when I don't have to remember them)?

When I don't have private members my publicMethod (called from class B) is looked something like that:

```<code>void publicMethod(int param1, int param2, int param3, int param4)
{
    privateMethod1(param1, param2, param3, param4);
    privateMethod2(param1, param2, param3, param4);
    privateMethod3(param1, param2, param3, param4);
}
</code>```

and in private methods I call other private method and I have to handle parameters.... I think it doesn't look good... Am I right? When I have private members it looks like:

```<code>void method(int param1, int param2, int param3, int param4)
{
    privateMethod1();
    privateMethod2();
    privateMethod3();
}
</code>```

It's better I guess. But I'm not professional and I'm not sure...

(I write in C++)

答:
It's a little unclear exactly what the question is, but if you hold references to variables you don't need in the scope of the application, you will certainly encounter a memory leak and eventually run out of memory.

Consider a stateless model such as Ruby on Rails where the session is persisted in the db. Here any 'state' is readily discarded/garbage collected (depending on the platform for the stateless model) and then any subsequent request for the user session is retrieved again from the DB. While this has some overhead (performance) costs, it does offer more scalable solutions because the web applications don't need to share memory across a cluster.

I hope that somewhat answers the question.

Title: To store data or not?


答:
There are several goals to that:

To see that the person can code.

Don't be surprised: many programmers who come to an interview don't know how to write code. While it's indeed difficult to write code under pressure during an interview, some are also unable to write it outside an interview. If those copy-paste programmers are useless in a company, asking them to provide their own code is a good way to filter those candidates.

To see that the person has his own projects or participates to existent open source projects.

Many programmers I was interviewing had only source code they've written at work. This is a good sign that for them, programming is just a way to gain money, not a passion.

To see high quality code (or what the person thinks to be high quality code).

A non-negligible part of the candidates I interviewed was bringing code full of bugs, and by bugs, I mean clearly visible bugs such as infinite loops, dead code, etc. Nearly every candidate bringing C# code had his own style, or rather no style at all (remark: C# has well-established conventions created by Microsoft and enforced by StyleCop, a tool which integrates well within the IDE used to write C# on Windows).

A glance on the source code can tell you much more about the candidate than fifteen minutes of interview.

To check that the person is not bringing proprietary code.

I had done several interviews where the candidates were bringing proprietary code. They weren't even hiding the name of the company. One, to the question “Don't you think it's disturbing to show to a third party a piece of code for a project probably covered by NDA?”, answered: “I really don't bother, in all cases this company was lame!”.

To see that the person is able to handle or participate to a large-scale project.

Personally, I ask the interviewees to send me a piece of code before the interview. During the interview, I ask them questions, such as:

At line 27, you are using a stream without disposing it. Why? What are the two ways, in C#, to dispose it?

or:

You have code duplication between the line 14-18 and the line 55-59. Why? How can you easily avoid it?

or:

At line 62, you do a cast. Why?

Some of those questions are related to bugs: when I ask them, I want to know how the candidate would handle this situation (and if he would see the bug himself first). Some people are extremely bad at handling that. For example, answers such as: “It has bugs because this part wasn't written by me.” (well, I asked to bring your code, not your colleagues' one) are frequent.

Other questions are related to dark parts of the code. I was often surprised by candidates who were perfectly able to explain why they did it this way, and why a different approach would have been worse.

If you think that you may be subject to such questions, be sure to bring a short piece of code you know perfectly well: answering questions about the parts you don't know well is not easy. Try to bring a piece of code which may not be particularly challenging, but which is flawlessly written, clean and easy to explain.

If you don't think the interviewer will ask questions (but rather listen to you showing your code), bring larger pieces of code to be able to show architecture, as well as highlight technically challenging aspects.

Remember: if your projects are open source, putting the link to them in your CV can only be beneficial (unless there are reasons to be ashamed of your code).

Title: What's the best way to show some of my code during an interview?

Body:
I realize that there are already a couple of questions about this, but they mostly are about if you should bring code to the interview, which is not the case here.

I have a job interview (at a startup) coming up next week and they requested to bring some code to the interview. I have two smaller open-source projects and a closed-source Android app, which I mentioned (and linked) in my skill sheet I sent along, so I wanted to show them some code of those projects. It's my first job after graduating, so I don't have any sources from previous employments and there won't be any issues regarding "spying", licensing issues, confidential code etc. All the code is completely mine and written by me.

I guess I have pretty much three options: print some interesting parts of the code on paper or have everything on my tablet or laptop to show. The latter two have the advantage that I can bring all my projects and basically show them everything they want to see. However you can't directly make notes/underline stuff etc. as if I had printed it out and it's less convenient than just handing out paper.

What's the best way to handle this professionally and do this as hassle-free as possible? I currently tend to print out some of the parts that I think are both interesting and well written, but have everything on my tablet in case they want to see more.


答:
I believe Github is the best showcase for code these days, so be sure to create a repo for every interesting project. Bitbucket is an alternative if you want free private repos.

A tablet is really handy in this case, you could create a slideshow with screenshots and a few lines of text to showcase some projects (like closed source ones).

Show them the running applications and highlight the most interesting features. Nothing compares to experiencing a working product.


答:
If you'd have an object that you would construct, call one method on it and destroy it again, than you don't need an object and therefore shouldn't have it.

Of course for complex logic it makes sense to store the state in an object. But it can, and therefore should, be an implementation detail of the public function. So I'd do:

header:

```<code>void publicFunction(int param1, int param2, int param3, int param4);
</code>```

(most functions should return something, but if it writes the result to db, returning void on success and throwing on error is fine)

source:

```<code>namespace {
    class privateImplementation {
        friend void publicFunction(int, int, int, int);
        int param1;
        int param2;
        int param3;
        int param4;
        int state;
        // ...
        void privateMethod1();
        void privateMethod2();
        // ...
    };
};

void publicFunction(int param1, int param2, int param3, int param4)
{
     privateImplementation impl{param1, param2, param3, param4, 0};
     impl.privateMethod1();
     impl.privateMethod2();
     // ...
}
</code>```

This way the logic is internally structured, state encapsulated etc, but additionally the whole operation is encapsulated and hidden away.

The same technique applies also to functions that have good reasons to be member functions. If they have state that only exists until their end, it should be stored on the stack in an auxiliary internal object, not in the invocant.

On a side note, if it writes to database, it probably should be getting the database connection as one of the arguments.

Title: To store data or not?

Body:
I'd like to ask you about one simple thing. I have class A that do something (for example counts something ). There is also one class B that handle some parameters to this class (class A is member of class B). Class B calls one method of class A that does something and writes value to database.

Class A uses parameters that got from Class B. Class A has few methods to made clean code  (it's good I think). But... Is it ok to save parameters as private members?? It's not necessary. I don't have to remember them after writing to Database. But if I don't have private data I have to handle it to every private method as parameters (during processing). I think that it's ok to save this parameters as members of this class. Am I right? Or maybe I should avoid this when it's not necessary (when I don't have to remember them)?

When I don't have private members my publicMethod (called from class B) is looked something like that:

```<code>void publicMethod(int param1, int param2, int param3, int param4)
{
    privateMethod1(param1, param2, param3, param4);
    privateMethod2(param1, param2, param3, param4);
    privateMethod3(param1, param2, param3, param4);
}
</code>```

and in private methods I call other private method and I have to handle parameters.... I think it doesn't look good... Am I right? When I have private members it looks like:

```<code>void method(int param1, int param2, int param3, int param4)
{
    privateMethod1();
    privateMethod2();
    privateMethod3();
}
</code>```

It's better I guess. But I'm not professional and I'm not sure...

(I write in C++)

Body:
If you'd have an object that you would construct, call one method on it and destroy it again, than you don't need an object and therefore shouldn't have it.

Of course for complex logic it makes sense to store the state in an object. But it can, and therefore should, be an implementation detail of the public function. So I'd do:

header:

void publicFunction(int param1, int param2, int param3, int param4);

(most functions should return something, but if it writes the result to db, returning void on success and throwing on error is fine)

source:

namespace {
    class privateImplementation {
        friend void publicFunction(int, int, int, int);
        int param1;
        int param2;
        int param3;
        int param4;
        int state;
        // ...
        void privateMethod1();
        void privateMethod2();
        // ...
    };
};

void publicFunction(int param1, int param2, int param3, int param4)
{
     privateImplementation impl{param1, param2, param3, param4, 0};
     impl.privateMethod1();
     impl.privateMethod2();
     // ...
}

This way the logic is internally structured, state encapsulated etc, but additionally the whole operation is encapsulated and hidden away.

The same technique applies also to functions that have good reasons to be member functions. If they have state that only exists until their end, it should be stored on the stack in an auxiliary internal object, not in the invocant.

On a side note, if it writes to database, it probably should be getting the database connection as one of the arguments.


问:
Best practice or design patterns for retrieval of data for reporting and dashboards in a domain-rich application
First, I want to say this seems to be a neglected question/area, so if this question needs improvement, help me make this a great question that can benefit others! I'm looking for advice and help from people who have implemented solutions that solve this problem, not just ideas to try.

In my experience, there are two sides of an application - the "task" side, which is largely domain driven and is where the users interact richly with the domain model (the "engine" of the application) and the reporting side, where users get data based on what happens on the task side.

On the task side, it's clear that an application with a rich domain model should have business logic in the domain model and the database should be used mostly for persistence. Separation of concerns, every book is written about it, we know what to do, awesome.

What about the reporting side? Are data warehouses acceptable, or are they bad design because they incorporate business logic in the database and the very data itself? In order to aggregate the data from the database into data warehouse data, you must have applied business logic and rules to the data, and that logic and rules didn't come from your domain model, it came from your data aggregating processes. Is that wrong?

I work on large financial and project management applications where the business logic is extensive. When reporting on this data, I will often have a LOT of aggregations to do to pull the information required for the report/dashboard, and the aggregations have a lot of business logic in them. For performance sake, I have been doing it with highly aggregated tables and stored procedures.

As an example, let's say a report/dashboard is needed to show a list of active projects (imagine 10,000 projects). Each project will need a set of metrics shown with it, for example:

total budget

effort to date

burn rate

budget exhaustion date at current burn rate

etc.

Each of these involves a lot of business logic. And I'm not just talking about multiplying numbers or some simple logic. I'm talking about in order to get the budget, you have to apply a rate sheet with 500 different rates, one for each employee's time (on some projects, other's have a multiplier), applying expenses and any appropriate markup, etc. The logic is extensive. It took a lot of aggregating and query tuning to get this data in a reasonable amount of time for the client.

Should this be run through the domain first? What about performance? Even with straight SQL queries, I'm barely getting this data fast enough for the client to display in a reasonable amount of time. I can't imagine trying to get this data to the client fast enough if I am rehydrating all these domain objects, and mixing and matching and aggregating their data in the application layer, or trying to aggregate the data in the application.

It seems in these cases that SQL is good at crunching data, and why not use it? But then you have business logic outside your domain model. Any change to the business logic will have to be changed in your domain model and your reporting aggregation schemes.

I'm really at a loss for how to design the reporting/dashboard part of any application with respect to domain driven design and good practices.

I added the MVC tag because MVC is the design flavor du jour and I am using it in my current design, but can't figure out how the reporting data fits into this type of application.

I'm looking for any help in this area - books, design patterns, key words to google, articles, anything. I can't find any information on this topic.

EDIT AND ANOTHER EXAMPLE

Another perfect example I ran across today. Customer wants a report for Customer Sales Team. They want what seems like a simple metric:

For each Sales person, what is their annual sales to date?

But that is complicated. Each sales person participated in multiple sales opportunities. Some they won, some they didn't. In each sales opportunity, there are multiple sales people who are each allocated a percentage of credit for the sale per their role and participation. So now imagine going through the domain for this...the amount of object rehydration you would have to do to pull this data from the database for every Sales person:

Get all the SalesPeople->

  For each get their SalesOpportunities->

  For each get their percentage of the sale and calculate their Sales amount

  then Add up all their SalesOpportunity Sales amount.

And that's ONE metric. Or you can write a SQL query which can do it quickly and efficiently and tune it to be fast.

EDIT 2 - CQRS Pattern

I've read about the CQRS Pattern and, while intriguing, even Martin Fowler says it's not tested. So how has this problem BEEN solved in the past. This has to have been faced by everyone at some point or another. What is an established or well-worn approach with a track record of success?

Edit 3 - Reporting Systems/Tools

Another thing to consider in this context is reporting tools. Reporting Services/Crystal Reports, Analysis Services and Cognoscenti, etc. all expect data from SQL/database. I doubt your data will come through your business later for these. And yet they and others like them are a vital part of the reporting in a lot of large systems.
How is the data for these properly handled where there is even business logic in the data source for these systems as well as possibly in the reports themselves?

答:
Reporting is a bounded context, or a subdomain, to speak loosely. It solves a business need of gathering/aggregating data and processing it to gain business intelligence.

How you implement this subdomain will likely be a balance between the (most) architecturally correct way you can do this, and what your infrastructure will allow. I like to start on the former side, and move towards the latter only as necessary.

You can probably split this up into two primary problems that you are solving:

Aggregating, or warehousing data. This should process some data source, and combine the information in such a way that it is stored in another data source.

Querying the aggregated datasource to provide business intelligence.

Neither of those problems reference any specific database or storage engine. Your domain layer should just be dealing with interfaces, implemented in your infrastructure layer by various storage adapters.

You may have various workers or some scheduled job run, that is split into a few moving parts:

Something to query

Something to aggregate

Something to store

Hopefully you can see some of the CQRS shine through there.

On the reporting side, it should only need to do querying, but never directly into the database. Go through your interfaces and through your domain layer here. This is not the same problem domain as your primary tasks, but there should still be some logic here you want to adhere to.

As soon as you dive directly into the database, you depend on it more, and it may eventually interfere with your original application's data needs.

Also, at least for me, I definitely prefer writing tests and developing in code rather than queries or stored procedures. I also like not locking myself into specific tools until absolutely necessary.

OwnerDisplayName: Richard DesLonde


问:
What's the best way to explain branching (of source code) to a client?
The situation is that a client requested a number of changes about 9 months ago which they then put on hold with them half done.  They've now requested more changes without having made up their mind to proceed with the first set of changes.  The two sets of changes will require alterations to the same code modules.

I've been tasked with explaining why them not making a decision about the first set of changes (either finish them or bin them) may incur additional costs (essentially because the changes would need to be made to a branch then if they proceed with the first set of changes we'd have to merge them to the trunk - which will be messy - and retest them).

The question I have is this:

How best to explain branching of code to a non-technical client?

答:
Explain it like writing two research papers. You might want to go with several different thoughts. In order to do this you create a copy and continue work on the "branches" simultaneously. This issue comes up when you have work done on various different papers and you need to "merge" them into a deliverable.

This explanation has always worked for me.


问:
Is it a bad idea to return different data types from a single function in a dynamically typed language?
My primary language is statically typed (Java).  In Java, you have to return a single type from every method.  For example, you can't have a method that conditionally returns a String or conditionally returns an Integer.  But in JavaScript, for example, this is very possible.

In a statically typed language I get why this is a bad idea.  If every method returned Object (the common parent all classes inherit from) then you and the compiler have no idea what you're dealing with.  You'll have to discover all your mistakes at run time.

But in a dynamically typed language, there may not even be a compiler.  In a dynamically typed language, it's not obvious to me why a function that returns multiple types is a bad idea.  My background in static languages makes me avoid writing such functions, but I fear I'm being close minded about a feature that could make my code cleaner in ways I can't see.

Edit: I'm going to remove my example (until I can think of a better one).  I think it's steering people to reply to a point I am not trying to make.

答:
The "bad practice" exists regardless of whether your language is statically typed. The static language does more to steer you away from these practices, and you might find more users who complain about "bad practice" in a static language because it's a more formal language. However, the underlying problems are there in a dynamic language, and you can determine whether they're justified.

Here is the objectionable part of what you propose. If I don't know what type is returned, then I can't use the return value immediately. I have to "discover" something about it.

```<code>total = sum_of_array([20, 30, 'q', 50])
if (type_of(total) == Boolean) {
  display_error(...)
} else {
  record_number(total)
}
</code>```

Often this kind of switch in code is simply bad practice. It makes the code harder to read. In this example, you see why throwing and catching exception cases is popular. Put another way: if your function cannot do what it says it does, it should not return successfully. If I call your function, I want to do this:

```<code>total = sum_of_array([20, 30, 'q', 50])
display_number(total)
</code>```

Because the first line returns successfully, I assume that total actually contains the sum of the array. If it doesn't return successfully, we jump to some other page of my program.

Let's use another example that's not just about propagating errors. Maybe sum_of_array tries to be smart and return a human-readable string in some cases, like "That's my locker combination!" if and only if the array is [11,7,19]. I'm having trouble thinking of a good example. Anyway, the same problem applies. You have to inspect the return value before you can do anything with it:

```<code>total = sum_of_array([20, 30, 40, 50])
if (type_of(total) == String) {
  write_message(total)
} else {
  record_number(total)
}
</code>```

You might argue that it would be useful for the function to return an integer or a float, e.g.:

```<code>sum_of_array(20, 30, 40) -> int
sum_of_array(23.45, 45.67, 67.789044) -> float
</code>```

But those results aren't different types, as far as you're concerned. You're going to treat them both as numbers, and that's all you care about. So sum_of_array returns the number type. This is what polymorphism is about.

So there are some practices you might be violating if your function can return multiple types. Knowing them will help you determine if your particular function should return multiple types anyway.

Body:
The "bad practice" exists regardless of whether your language is statically typed. The static language does more to steer you away from these practices, and you might find more users who complain about "bad practice" in a static language because it's a more formal language. However, the underlying problems are there in a dynamic language, and you can determine whether they're justified.

Here is the objectionable part of what you propose. If I don't know what type is returned, then I can't use the return value immediately. I have to "discover" something about it.

total = sum_of_array([20, 30, 'q', 50])
if (type_of(total) == Boolean) {
  display_error(...)
} else {
  record_number(total)
}

Often this kind of switch in code is simply bad practice. It makes the code harder to read. In this example, you see why throwing and catching exception cases is popular. Put another way: if your function cannot do what it says it does, it should not return successfully. If I call your function, I want to do this:

total = sum_of_array([20, 30, 'q', 50])
display_number(total)

Because the first line returns successfully, I assume that total actually contains the sum of the array. If it doesn't return successfully, we jump to some other page of my program.

Let's use another example that's not just about propagating errors. Maybe sum_of_array tries to be smart and return a human-readable string in some cases, like "That's my locker combination!" if and only if the array is [11,7,19]. I'm having trouble thinking of a good example. Anyway, the same problem applies. You have to inspect the return value before you can do anything with it:

total = sum_of_array([20, 30, 40, 50])
if (type_of(total) == String) {
  write_message(total)
} else {
  record_number(total)
}

You might argue that it would be useful for the function to return an integer or a float, e.g.:

sum_of_array(20, 30, 40) -> int
sum_of_array(23.45, 45.67, 67.789044) -> float

But those results aren't different types, as far as you're concerned. You're going to treat them both as numbers, and that's all you care about. So sum_of_array returns the number type. This is what polymorphism is about.

So there are some practices you might be violating if your function can return multiple types. Knowing them will help you determine if your particular function should return multiple types anyway.


答:
First some terminology, what you call the task side is known as Transactional and the Reporting side is Analytics.

You've already mentioned CQRS which is a great approach but there is little documented practical application of the approach.

What has been heavily tested is supplementing your Transactional processing with an Analytical processing engine. This is sometimes referred to as Data Warehousing or Data Cubes. The biggest gotcha with regard to analytics is that attempting to run queries against your transactional data in real-time is inefficient at best because it's really only possible to optimize a database for reading or writing. For transactions, you want high write speeds to avoid delays in processing/doing things. For reporting, you want high read speeds so decisions can be made.

How to account for these issues? The simplest approach to understand is using a flattened schema for your reporting and ETL (extract transform load) to shuttle data from the normalized transactional schema to the denormalized analytical schema. The ETL is run via an agent on a regular basis and preloads the analytics table so that it's ready for a quick read from your reporting engine.

A great book to get up to speed on data warehousing is the Data Warehouse Toolkit by Ralph Kimball. For a more hands on approach. Download the trial of SQL Server and pick up the Microsoft Data Warehouse toolkit which takes the general discussion of the first book but shows how to apply the concepts using SQL Server.

There are several linked books from those pages that go into more details about ETL, Star Schema Design, BI, Dashboards and other topics to help you go along.

The quickest way to get from where you are to where you want to be, is to hire a BI Expert and shadow him while he implements what you need.

Title: Best practice or design patterns for retrieval of data for reporting and dashboards in a domain-rich application

Body:
First, I want to say this seems to be a neglected question/area, so if this question needs improvement, help me make this a great question that can benefit others! I'm looking for advice and help from people who have implemented solutions that solve this problem, not just ideas to try.

In my experience, there are two sides of an application - the "task" side, which is largely domain driven and is where the users interact richly with the domain model (the "engine" of the application) and the reporting side, where users get data based on what happens on the task side.

On the task side, it's clear that an application with a rich domain model should have business logic in the domain model and the database should be used mostly for persistence. Separation of concerns, every book is written about it, we know what to do, awesome.

What about the reporting side? Are data warehouses acceptable, or are they bad design because they incorporate business logic in the database and the very data itself? In order to aggregate the data from the database into data warehouse data, you must have applied business logic and rules to the data, and that logic and rules didn't come from your domain model, it came from your data aggregating processes. Is that wrong?

I work on large financial and project management applications where the business logic is extensive. When reporting on this data, I will often have a LOT of aggregations to do to pull the information required for the report/dashboard, and the aggregations have a lot of business logic in them. For performance sake, I have been doing it with highly aggregated tables and stored procedures.

As an example, let's say a report/dashboard is needed to show a list of active projects (imagine 10,000 projects). Each project will need a set of metrics shown with it, for example:

total budget

effort to date

burn rate

budget exhaustion date at current burn rate

etc.

Each of these involves a lot of business logic. And I'm not just talking about multiplying numbers or some simple logic. I'm talking about in order to get the budget, you have to apply a rate sheet with 500 different rates, one for each employee's time (on some projects, other's have a multiplier), applying expenses and any appropriate markup, etc. The logic is extensive. It took a lot of aggregating and query tuning to get this data in a reasonable amount of time for the client.

Should this be run through the domain first? What about performance? Even with straight SQL queries, I'm barely getting this data fast enough for the client to display in a reasonable amount of time. I can't imagine trying to get this data to the client fast enough if I am rehydrating all these domain objects, and mixing and matching and aggregating their data in the application layer, or trying to aggregate the data in the application.

It seems in these cases that SQL is good at crunching data, and why not use it? But then you have business logic outside your domain model. Any change to the business logic will have to be changed in your domain model and your reporting aggregation schemes.

I'm really at a loss for how to design the reporting/dashboard part of any application with respect to domain driven design and good practices.

I added the MVC tag because MVC is the design flavor du jour and I am using it in my current design, but can't figure out how the reporting data fits into this type of application.

I'm looking for any help in this area - books, design patterns, key words to google, articles, anything. I can't find any information on this topic.

EDIT AND ANOTHER EXAMPLE

Another perfect example I ran across today. Customer wants a report for Customer Sales Team. They want what seems like a simple metric:

For each Sales person, what is their annual sales to date?

But that is complicated. Each sales person participated in multiple sales opportunities. Some they won, some they didn't. In each sales opportunity, there are multiple sales people who are each allocated a percentage of credit for the sale per their role and participation. So now imagine going through the domain for this...the amount of object rehydration you would have to do to pull this data from the database for every Sales person:

Get all the SalesPeople->

  For each get their SalesOpportunities->

  For each get their percentage of the sale and calculate their Sales amount

  then Add up all their SalesOpportunity Sales amount.

And that's ONE metric. Or you can write a SQL query which can do it quickly and efficiently and tune it to be fast.

EDIT 2 - CQRS Pattern

I've read about the CQRS Pattern and, while intriguing, even Martin Fowler says it's not tested. So how has this problem BEEN solved in the past. This has to have been faced by everyone at some point or another. What is an established or well-worn approach with a track record of success?

Edit 3 - Reporting Systems/Tools

Another thing to consider in this context is reporting tools. Reporting Services/Crystal Reports, Analysis Services and Cognoscenti, etc. all expect data from SQL/database. I doubt your data will come through your business later for these. And yet they and others like them are a vital part of the reporting in a lot of large systems.
How is the data for these properly handled where there is even business logic in the data source for these systems as well as possibly in the reports themselves?


答:
In dynamic languages, you shouldn't ask whether return different types but objects with different APIs. As most dynamic languages don't really care about types, but use various versions of duck typing.

When returning different types make sense

For example this method makes sense:

```<code>def load_file(file):
    if something:
       return ['a ', 'list', 'of', 'strings']
    return open(file, 'r')
</code>```

Because both file, and a list of strings are (in Python) iterables that return string. Very different types, the same API (unless someone tries to call file methods on a list, but this is different story).

You can conditionally return list or tuple (tuple is an immutable list in python).

Formally even doing:

```<code>def do_something():
    if ...:
        return None
    return something_else
</code>```

or:

```<code>function do_something(){
   if (...) return null;
   return sth;
}
</code>```

returns different types, as both python None and Javascript null are types on their own right.

All these use cases would have their counterpart in static languages, function would just return a proper interface.

When returning objects with different API conditionally is a good idea

As to whether returning different APIs is a good idea, IMO in most cases it doesn't make sense. Only sensible example that comes to mind is something close to what @MainMa said: when your API can provide varying amount of detail it might make sense to return more detail when available.

Title: Is it a bad idea to return different data types from a single function in a dynamically typed language?

Body:
My primary language is statically typed (Java).  In Java, you have to return a single type from every method.  For example, you can't have a method that conditionally returns a String or conditionally returns an Integer.  But in JavaScript, for example, this is very possible.

In a statically typed language I get why this is a bad idea.  If every method returned Object (the common parent all classes inherit from) then you and the compiler have no idea what you're dealing with.  You'll have to discover all your mistakes at run time.

But in a dynamically typed language, there may not even be a compiler.  In a dynamically typed language, it's not obvious to me why a function that returns multiple types is a bad idea.  My background in static languages makes me avoid writing such functions, but I fear I'm being close minded about a feature that could make my code cleaner in ways I can't see.

Edit: I'm going to remove my example (until I can think of a better one).  I think it's steering people to reply to a point I am not trying to make.

Body:
In dynamic languages, you shouldn't ask whether return different types but objects with different APIs. As most dynamic languages don't really care about types, but use various versions of duck typing.

When returning different types make sense

For example this method makes sense:

def load_file(file):
    if something:
       return ['a ', 'list', 'of', 'strings']
    return open(file, 'r')

Because both file, and a list of strings are (in Python) iterables that return string. Very different types, the same API (unless someone tries to call file methods on a list, but this is different story).

You can conditionally return list or tuple (tuple is an immutable list in python).

Formally even doing:

def do_something():
    if ...:
        return None
    return something_else

or:

function do_something(){
   if (...) return null;
   return sth;
}

returns different types, as both python None and Javascript null are types on their own right.

All these use cases would have their counterpart in static languages, function would just return a proper interface.

When returning objects with different API conditionally is a good idea

As to whether returning different APIs is a good idea, IMO in most cases it doesn't make sense. Only sensible example that comes to mind is something close to what @MainMa said: when your API can provide varying amount of detail it might make sense to return more detail when available.


问:
available methods change with object state
I'm programming a graph object which can be in either a mutable or immutable state. In both states, it has a get method, but only in the mutable state is the set method allowed. The transition occurs when one invokes a method compress which optimizes the storage of the graph.

How do I deal with the fact that some methods are legal in some states but not others?

I can think of two approaches. The blunt way is to use the state pattern. If you invoke set when the graph is mutable, it executes as normally; but, if you invoke set when the graph is immutable, an error is thrown. This looks ugly to me because an immutable object still has a set method.

Alternatively, I can make a graph type with a mutable_graph sub-type; only the second one has a set method. The state change is effected by changing the type of the graph. However, this also looks ugly to me; for every implementation of graph (of which there are several), I now have to make two types instead of just one.

EDIT: I'm using the state pattern and throwing an exception; if neither solution is especially preferable, this one involves writing the least code. Thanks for the advice!

答:
Assuming compiled language from the Java/C#/C++ family.

Do you know if the graph is mutable or not at compile time? If yes - introduce a subtype (C++ also has "const" for objects). Otherwise - throw an exception and the state pattern.


问:
Low level programming - what's in it for me?
For years I have considered digging into what I consider "low level" languages. For me this means C and assembly. However I had no time for this yet, nor has it EVER been neccessary.

Now because I don't see any neccessity arising, I feel like I should either just schedule some point in time when I will study the subject or drop the plan forever.

My Position

For the past 4 years I have focused on "web technologies", which may change, and I am an application developer, which is unlikely to change.

In application development, I think usability is the most important thing. You write applications to be "consumed" by users. The more usable those applications are, the more value you have produced.

In order to achieve good usability, I believe the following things are viable

Good design: Well-thought-out features accessible through a well-thought-out user interface.

Correctness: The best design isn't worth anything, if not implemented correctly.

Flexibility: An application A should constantly evolve, so that its users need not switch to a different application B, that has new features, that A could implement. Applications addressing the same problem should not differ in features but in philosophy.

Performance: Performance contributes to a good user experience. An application is ideally always responsive and performs its tasks reasonably fast (based on their frequency). The value of performance optimization beyond the point where it is noticeable by the user is questionable.

I think low level programming is not going to help me with that, except for performance. But writing a whole app in a low level language for the sake of performance is premature optimization to me.

My Question

What could low level programming teach me, what other languages wouldn't teach me? Am I missing something, or is it just a skill, that is of very little use for application development? Please understand, that I am not questioning the value of C and assembly. It's just that in my everyday life, I am quite happy that all the intricacies of that world are abstracted away and managed for me (mostly by layers written in C/C++ and assembly themselves). I just don't see any concepts, that could be new to me, only details I would have to stuff my head with. So what's in it for me?

My Conclusion

Thanks to everyone for their answers. I must say, nobody really surprised me, but at least now I am quite sure I will drop this area of interest until any need for it arises.

To my understanding, writing assembly these days for processors as they are in use in today's CPUs is not only unneccesarily complicated, but risks to result in poorer runtime performance than a C counterpart. Optimizing by hand is nearly impossible due to OOE, while you do not get all kinds of optimizations a compiler can do automatically. Also, the code is either portable, because it uses a small subset of available commands, or it is optimized, but then it probably works on one architecture only.

Writing C is not nearly as neccessary anymore, as it was in the past. If I were to write an application in C, I would just as much use tested and established libraries and frameworks, that would spare me implementing string copy routines, sorting algorithms and other kind of stuff serving as exercise at university. My own code would execute faster at the cost of type safety. I am neither keen on reeinventing the wheel in the course of normal app development, nor trying to debug by looking at core dumps :D

I am currently experimenting with languages and interpreters, so if there is anything I would like to publish, I suppose I'd port a working concept to C, although C++ might just as well do the trick.

Again, thanks to everyone for your answers and your insight.

答:
In a word, fun. When I used to play around with assembler (having worked down from VB to C++, C etc) it was just awesome to be moving data from one part of the processor to another. It was a great feeling to know exactly what was happening inside the CPU, with no worries about what was going on underneath which you didn't know about. Plus a great feeling of freedom - you can do just about anything, because there aren't inbuilt limitations which you find in higher level languages.

Also, being able to turn round to anyone who programmed in any other language whatsoever and go 'well, if you're not hardcore enough...' was childish, childish fun.


问:
Why are the Java 8 java.time classes missing a getMillis() method?
Java 8 has a whole new library for dates and times in the package java.time which is very welcome thing to anyone who has had to use JodaTime before or hassle with making it's own date processing helper methods. Many classes in this package represent timestamps and have helper methods like getHour() to get hours from timestamp, getMinute() to get minutes from timestamp, getNano() to get nanos from timestamp etc...

I noticed that they don't have a method called getMillis() to get the millis of the time stamp. Instead one would have to call method get(ChronoField.MILLI_OF_SECOND). To me it seems like an inconsistency in the library. Does anyone know why such a method is missing, or as Java 8 is still in development is there a possibility that it will be added later?

https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

The classes defined here represent the principal date-time concepts, including instants, durations, dates, times, time-zones and periods. They are based on the ISO calendar system, which is the de facto world calendar following the proleptic Gregorian rules. All the classes are immutable and thread-safe.

Each date time instance is composed of fields that are conveniently made available by the APIs. For lower level access to the fields refer to the java.time.temporal package. Each class includes support for printing and parsing all manner of dates and times. Refer to the java.time.format package for customization options...

Example of this kind of class:

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime...

答:
The classes that represent unambiguous UTC times (those are Instant, OffsetDateTime, ZonedDateTime) have two helper methods for accessing the absolute offset from the Java epoch, i.e. what you call 'millisecond time' in the java.util.Date, which you could use to get at milliseconds

```<code>long getEpochSecond()
int getNano()

1000L*getEpochSecond() + getNano() / 1000000L;
</code>```

Some reasons as to why this has been chosen instead of long getEpochMillis() were discussed on the jsr 310 mailing list, some of which I've extracted for convenience:

it seems reasonable to suppose that
  milliseconds precision won't be sufficient. However, anything greater
  than nanosecond precision seems excessive

...

In order to implement this, my preferred option would be 64 bit long
  seconds (signed) + 32 bit int nanoseconds (unsigned).

...

I prefer the split to be at the second level as that is the official
  SI unit of time in science, and the most universally agreed standard.

Splitting at the days level is problematic for instants as it doesn't
  handle leap seconds. Splitting at the milliseconds level, while
  integrating slightly better with the rest of Java, seems really rather
  odd. Plus it loses in the supported range.

Splitting at the second as proposed, gives a range of instants of
  nanoseconds over 290 billion years. While nobody should ever use that
  precision over that range of the time-line, I'd suggest its easier to
  support it than to block it.splitting at the days level is problematic for instants as
  it doesn't handle leap seconds

I have a feeling that another reason was to intentionally make it hard to convert from java.util.Date to JSR310 classes, hoping that developers would try to understand the differences between the various options and not just blindly (mis)use the new classes.

As to why the LocalDateTime class doesn't have those methods - they can't possibly exist there because LocalDateTime is not tied to the UTC timeline until you decide which zone you're in or what your UTC offset is, at which point you have yourself an OffsetDateTime or ZonedDateTime (both of which have the needed methods).

Alternatively, you could define you own LOCAL_EPOCH constant to 1970-01-01T00:00:00 and then do a MILLIS.between(LOCAL_EPOCH, localTime) to get some sort of duration in milliseconds. This value, however, will not be compatible with any value returned by System.currentTimeMilliseconds() or java.util.Date.getTime(), unless of course you define your local time to be UTC time; but in this case you might as well use Instant directly or OffsetDateTime with ZoneOffset.UTC.

Body:
The classes that represent unambiguous UTC times (those are Instant, OffsetDateTime, ZonedDateTime) have two helper methods for accessing the absolute offset from the Java epoch, i.e. what you call 'millisecond time' in the java.util.Date, which you could use to get at milliseconds

long getEpochSecond()
int getNano()

1000L*getEpochSecond() + getNano() / 1000000L;

Some reasons as to why this has been chosen instead of long getEpochMillis() were discussed on the jsr 310 mailing list, some of which I've extracted for convenience:

it seems reasonable to suppose that
  milliseconds precision won't be sufficient. However, anything greater
  than nanosecond precision seems excessive

...

In order to implement this, my preferred option would be 64 bit long
  seconds (signed) + 32 bit int nanoseconds (unsigned).

...

I prefer the split to be at the second level as that is the official
  SI unit of time in science, and the most universally agreed standard.

Splitting at the days level is problematic for instants as it doesn't
  handle leap seconds. Splitting at the milliseconds level, while
  integrating slightly better with the rest of Java, seems really rather
  odd. Plus it loses in the supported range.

Splitting at the second as proposed, gives a range of instants of
  nanoseconds over 290 billion years. While nobody should ever use that
  precision over that range of the time-line, I'd suggest its easier to
  support it than to block it.splitting at the days level is problematic for instants as
  it doesn't handle leap seconds

I have a feeling that another reason was to intentionally make it hard to convert from java.util.Date to JSR310 classes, hoping that developers would try to understand the differences between the various options and not just blindly (mis)use the new classes.

As to why the LocalDateTime class doesn't have those methods - they can't possibly exist there because LocalDateTime is not tied to the UTC timeline until you decide which zone you're in or what your UTC offset is, at which point you have yourself an OffsetDateTime or ZonedDateTime (both of which have the needed methods).

Alternatively, you could define you own LOCAL_EPOCH constant to 1970-01-01T00:00:00 and then do a MILLIS.between(LOCAL_EPOCH, localTime) to get some sort of duration in milliseconds. This value, however, will not be compatible with any value returned by System.currentTimeMilliseconds() or java.util.Date.getTime(), unless of course you define your local time to be UTC time; but in this case you might as well use Instant directly or OffsetDateTime with ZoneOffset.UTC.


答:
If you really don't want to leak details of "privileged" operations then the cleanest answer in popular OO languages like Java and .NET is multiple interface inheritance.

One that I've used semi-frequently goes something like:

IFooRepository - contains methods GetFoo, DeleteFoo, SaveFoo

IReadOnlyFooRepository - contains only method GetFoo

In the example above, IFooRepository might subclass IReadOnlyFooRepository. Also, if there is a well-defined way to transition between the read-only and writable state, then you might put an Edit method on the IReadOnlyFooRepository that returns an instance of IFooRepository, and/or an AsReadOnly method on the IFooRepository that returns an instance of IReadOnlyFooRepository.

This is not without precedent, at least in .NET. One of the most common interfaces, IList<T>, has a method AsReadOnly that returns a ReadOnlyCollection<T>, which as you might guess, does not expose any kind of write operations.

It's not hard to implement - generally you only need one class to implement both interfaces, and the Edit/AsReadOnly methods can just return this (or self or whatever it is in your chosen language). Of course, if you do this, don't fool yourself into thinking that it's a form of security, as a caller could potentially just cast between types - but assuming you just want to protect against stupid mistakes rather and not intentional abuse, it's good enough.

You can get more granular if you want - for example, you don't necessarily need one interface to derive from the other, you could have IFooReader and IFooWriter with no methods in common. Or you might define an IFooComponent (or something along those lines) at the root if you only want to share a few methods, but have most of them be unique. Sky's the limit, but the basic idea stands - use interfaces to carve out specific blocks of functionality that are specific to a particular state.

This takes a lot more design work and adds a lot more types to the code if your states and transitions are complex, so be sure that it's really worth the effort. It's perfectly fine and in fact common in a lot of architectures (like most MVVM frameworks) to just throw an exception if an operation isn't valid for the current state, and also provide convenience "guard" methods like CanWrite, to avoid strewing try-catch loops all over the place. That's good if you have 2 or 3 discrete states; if you have 10 or 20 then you might want to think about either a state pattern or a design such as the above that makes the transitions more explicit.

Title: available methods change with object state

Body:
I'm programming a graph object which can be in either a mutable or immutable state. In both states, it has a get method, but only in the mutable state is the set method allowed. The transition occurs when one invokes a method compress which optimizes the storage of the graph.

How do I deal with the fact that some methods are legal in some states but not others?

I can think of two approaches. The blunt way is to use the state pattern. If you invoke set when the graph is mutable, it executes as normally; but, if you invoke set when the graph is immutable, an error is thrown. This looks ugly to me because an immutable object still has a set method.

Alternatively, I can make a graph type with a mutable_graph sub-type; only the second one has a set method. The state change is effected by changing the type of the graph. However, this also looks ugly to me; for every implementation of graph (of which there are several), I now have to make two types instead of just one.

EDIT: I'm using the state pattern and throwing an exception; if neither solution is especially preferable, this one involves writing the least code. Thanks for the advice!


问:
constants/enums in API
What are a few ways constants and enums are dealt with when creating an API Client?  I'm writing a client in python for our API and I've hit a sticking point with this.  We use a lot of mappings to numbers (to save space) and I was wondering what the best technique is.  I can hard code them into the client, but if a new enum/constant gets added, the consumer would have to update his version of the client.  I also thought about grabbing the maps/enums when the client is first initialized and cached until there is an update.  Are these typical approaches, or is there a more effective way to do this?

Edit:
This is a REST API but I'm making a python client (so platform specific I suppose) for it to make it easier to work with.  For a little more detail, when I say enums, I just mean using a constant (like an integer) to represent a certain choice a consumer has for a certain attribute.  So lets say someone using the API is saving what type of video game system they have. 1 = xbox, 2 = playstation, 3= wii, etc...
Do I hardcode those into the python client for the consumer to use?  Do I grab them from the server when the client is initialized and then cache them client side?

答:
I cannot think of any reason to require numeric values in a REST API. Use strings, and in your specification, identify what the valid values are.

If you want to go the extra mile and write enums (or equivalent) for a platform-specific client then go for it, but you will of course have to maintain it. If at all possible, you should make these API clients part of the same build process, or set your build system to automatically build the API clients whenever you do a release build. That way, a new version of the client is automatically available whenever you publicly release a new version of the API.

I realize this isn't necessarily easy to do, but such is the nature of maintaining platform-specific clients. That's why most maintainers don't do it. Oracle may need to do it but you probably don't. Twitter, GitHub, PayPal, etc. - they don't maintain "clients", just the API and its specs/documentation. Sometimes there will be open-source clients maintained by completely separate teams, but the owners of the service itself take no responsibility for them.

Typically an API client that is completely customized for a particular platform could more accurately be called an SDK. Treat it with that level of care and respect and the rest of the pieces should fall into place. Are you really prepared to maintain an SDK?

Title: constants/enums in API


答: Have you considered a Builder pattern?  The user starts with a FooGraphBuilder, with getters and setters.  Calling compress() returns an immutable FooGraph, making the transition fairly clear.


问:
Advice on which storage technology for an Image repository
At this point, I'm not much of a programmer, solid html/css, familiar with JS but not a programmer by any means. I'm looking to pick up whatever is necessary for an upcoming project.

I need to build an online image repository that will host around 15k photos. Those photos will need to have user entered data associated with them. They will need to be searchable by tags, and batch downloadable.

Would you guys do filesystem or db storage?  Basically, what type of storage solution would you use?

答:
The approach I would use typically for such a constellation is

store the images in the file system

use a database for the meta data (including references to the related image file names)

The reason for this is that you will need indexing and transactional security for your meta data, but typically not for "parts" of your images (I guess they will be updated only by adding new ones or deleting old ones, the only thing for images you need transactional securrity for is that two different images won't get the same file name, but that is a meta data operation).

Note that there are some databases out there which can handle the storage exactly that way for you, so you can access all the data, including images, by SQL in a transactional manner, but the DB stores the images in separate files in the background.


答:
This might be one of those rare situations where I recommend considering a 3rd party solution that you can modify.  In addition to open source gallery software, there's plenty of gallery plugins for various CMS's.

If you must write this yourself, for the volume you are talking about it doesn't really matter where you put the images - either way it will work.  But, if you are expecting high traffic, it'd be better for them to be on the file system, so that your database server doesn't have to handle the overload of serving the files.  Also, keeping the images in the file system can provide you more flexibility regarding backups.

Title: Advice on which storage technology for an Image repository

Body:
At this point, I'm not much of a programmer, solid html/css, familiar with JS but not a programmer by any means. I'm looking to pick up whatever is necessary for an upcoming project.

I need to build an online image repository that will host around 15k photos. Those photos will need to have user entered data associated with them. They will need to be searchable by tags, and batch downloadable.

Would you guys do filesystem or db storage?  Basically, what type of storage solution would you use?


答:
The one place where I see myself sending different types is for invalid input or "poor mans exceptions" where the "exceptional" condition isn't very exceptional. For example, from my repository of PHP utility functions this abridged example:

```<code>function ensure_fields($consideration)
{
        $args = func_get_args();
        foreach ( $args as $a ) {
                if ( !is_string($a) ) {
                        return NULL;
                }
                if ( !isset($consideration[$a]) || $consideration[$a]=='' ) {
                        return FALSE;
                }
        }

        return TRUE;
}
</code>```

The function nominally returns a BOOLEAN, however it returns NULL on invalid input. Note that since PHP 5.3, all internal PHP functions behave this way as well. Additionally, some internal PHP functions return FALSE or INT on nominal input, see:

```<code>strpos('Hello', 'e');  // Returns INT(1)
strpos('Hello', 'q');  // Returns BOOL(FALSE)
</code>```

Body:
The one place where I see myself sending different types is for invalid input or "poor mans exceptions" where the "exceptional" condition isn't very exceptional. For example, from my repository of PHP utility functions this abridged example:

function ensure_fields($consideration)
{
        $args = func_get_args();
        foreach ( $args as $a ) {
                if ( !is_string($a) ) {
                        return NULL;
                }
                if ( !isset($consideration[$a]) || $consideration[$a]=='' ) {
                        return FALSE;
                }
        }

        return TRUE;
}

The function nominally returns a BOOLEAN, however it returns NULL on invalid input. Note that since PHP 5.3, all internal PHP functions behave this way as well. Additionally, some internal PHP functions return FALSE or INT on nominal input, see:

strpos('Hello', 'e');  // Returns INT(1)
strpos('Hello', 'q');  // Returns BOOL(FALSE)


答: Developing software is basically an art and a craft of managing complexity. You try to narrow down the system at the points you can afford to, and limit the options at other points. Function's interface is contract which helps to manage complexity of the code by limiting a knowledge required to work with any piece of code. By returning different types you significantly expand the function's interface by adding to it all the interfaces of different types you return AND adding unobvious rules as to which interface is returned.</p>


答:
You can actually group parameters into a separate object and manage them as a single entity. This way a lot of questions are much easier to answer.

Like, what are these parameters? Is it some configuration? Then I should just configure the object once. Or is it some parameters of a query? Then I should make query object explicit, configure it with parameters, and let my new Query process all the Query-related stuff itself. Et cetera.

Because if your parameters always go together, most probably there is some abstraction/entity that you are missing, and which is represented by the grouping of this parameters. And its behaviour is spread thin between objects using this grouping of parameters.

Title: To store data or not?


答:
Don't bother. It isn't your job to educate them on your job.

Just say that not having a decision on the first set of features will complicate the project management which might have repercussions in terms of time and expense. That's all that is relevant to them.

Title: What's the best way to explain branching (of source code) to a client?

Body:
The situation is that a client requested a number of changes about 9 months ago which they then put on hold with them half done.  They've now requested more changes without having made up their mind to proceed with the first set of changes.  The two sets of changes will require alterations to the same code modules.

I've been tasked with explaining why them not making a decision about the first set of changes (either finish them or bin them) may incur additional costs (essentially because the changes would need to be made to a branch then if they proceed with the first set of changes we'd have to merge them to the trunk - which will be messy - and retest them).

The question I have is this:

How best to explain branching of code to a non-technical client?


问:
How should I introduce a new programmer to a complex project?
We have a pretty complex project with 100 or so classes, multiple custom elements, etc. We have a new senior programmer who will work on this project.

How should we approach the task of introducing the senior programmer to the project? How can we make sure the programmer does not break some other feature while fixing the current one? I have seen too many similar situation.s Sometimes, new bugs are not noticed immediately -- but pop up months later.

Shall I direct the programmer by first giving them smaller tasks and waiting for them to finish them? Or there is a better solution?

I am asking this because I don't want to become micromanager but I also don't want to have nasty bugs created because of my bad approach to the new programmer.

答:
Get him to run a regression test pack on parts of the system that he'll be working on. I would do that prior to allowing them make any changes in code.

Once they are comfortable with how the application works, get them bug fixing. Peer review bug fixes to get a good idea on their skill set.

He will break your application, but that's what regression and unit tests are for. If you don't have these, then be prepared to take a hit.


答:
I don't think this is a bad idea! In contrast to this most common opinion, and as already pointed out by Robert Harvey, Statically typed languages like Java introduced Generics exactly for situations like the one you are asking. Actually Java try to keep (wherever possible) typesafety at compile time, and sometimes Generics avoid code duplication, why? Because you can write the same method or the same class that handle/return different types. I'll make just a very brief example to show this idea:

Java 1.4

```<code>public static Boolean getBoolean(String property){
    return (Boolean) properties.getProperty(property);
}
public static Integer getInt(String property){
    return (Integer) properties.getProperty(property);
}
</code>```

Java 1.5+

```<code>public static <T> getValue(String property, Class<T> clazz) throws WhateverCheckedException{
    return clazz.getConstructor(String.class).newInstance(properties.getProperty(property));
}
//the call will be
Boolean b = getValue("useProxy",Boolean.class);
Integer b = getValue("proxyPort",Integer.class);
</code>```

In a dynamic typed language, since you have no typesafety at compile time, you are absolutely free to write the same code that works for many types.
Since even in a statically typed language Generics were introduced to solve this problem, it's clearly a hint that writing a function that returns different types in a dynamic language is not a bad idea.

Body:
I don't think this is a bad idea! In contrast to this most common opinion, and as already pointed out by Robert Harvey, Statically typed languages like Java introduced Generics exactly for situations like the one you are asking. Actually Java try to keep (wherever possible) typesafety at compile time, and sometimes Generics avoid code duplication, why? Because you can write the same method or the same class that handle/return different types. I'll make just a very brief example to show this idea:

Java 1.4

public static Boolean getBoolean(String property){
    return (Boolean) properties.getProperty(property);
}
public static Integer getInt(String property){
    return (Integer) properties.getProperty(property);
}

Java 1.5+

public static <T> getValue(String property, Class<T> clazz) throws WhateverCheckedException{
    return clazz.getConstructor(String.class).newInstance(properties.getProperty(property));
}
//the call will be
Boolean b = getValue("useProxy",Boolean.class);
Integer b = getValue("proxyPort",Integer.class);

In a dynamic typed language, since you have no typesafety at compile time, you are absolutely free to write the same code that works for many types.
Since even in a statically typed language Generics were introduced to solve this problem, it's clearly a hint that writing a function that returns different types in a dynamic language is not a bad idea.


答:
Perl uses this a lot because what a function does depends on its context. For instance, a function could return an array if used in list context, or the length of the array if used in a place where a scalar value is expected. From the tutorial that is the first hit for "perl context", if you do:

```<code>my @now = localtime();
</code>```

Then @now is an array variable (that's what the @ means), and will contain an array like (40, 51, 20, 9, 0, 109, 5, 8, 0).

If instead you call the function in a way where its result will have to be a scalar, with ($ variables are scalars):

```<code>my $now = localtime();
</code>```

then it does something completely different: $now will be something like "Fri Jan  9 20:51:40 2009".

Another example I can think of is in implementing REST APIs, where the format of what is returned depends on what the client wants. E.g, HTML, or JSON, or XML. Although technically those are all streams of bytes, the idea is similar.

Body:
Perl uses this a lot because what a function does depends on its context. For instance, a function could return an array if used in list context, or the length of the array if used in a place where a scalar value is expected. From the tutorial that is the first hit for "perl context", if you do:

my @now = localtime();

Then @now is an array variable (that's what the @ means), and will contain an array like (40, 51, 20, 9, 0, 109, 5, 8, 0).

If instead you call the function in a way where its result will have to be a scalar, with ($ variables are scalars):

my $now = localtime();

then it does something completely different: $now will be something like "Fri Jan  9 20:51:40 2009".

Another example I can think of is in implementing REST APIs, where the format of what is returned depends on what the client wants. E.g, HTML, or JSON, or XML. Although technically those are all streams of bytes, the idea is similar.


问:
How best to format text files of statutes in HTML with specific IDs
I'm trying to find the best way to process about 20,000 lines of a statute in text format into HTML so that it can be displayed and manipulated in a granular fashion, i.e. by clause. The format is essentially a nested list like (a)(1)(A)(i)(II)(aa) and is fairly consistent. Each clause begins with a new line and is enclosed in parenthesis like above.

The goal is for each clause to be enclosed in a paragraph tag with a unique id like p id="sec101a1AiI" (sorry I can't figure out the code formatting). The point is to be able to refer to a specific clause later on. I've played with regular expressions but they don't seem to allow me to iterate through the entire statute and tag things in a unique fashion. I'm sure there are better options using a custom script but I don't know where to start looking for that. Any suggestions would be appreciated.

答:
This is fairly simple to do, depending on how the input is structured. Let's assume we have a file like

```<code>Legalese Introduction

(1) Some Legalese Section

    With another paragraph inside it

    (a) With some sub-paragraph

        (I) Some other statutes

        (II) Some other statutes

(2) Another Section
</code>```

We can easily split this file into paragraphs and then loop through them. For each paragraph with some enumeration, we can check whether this increments the counter of the current numbering level. If so, we perform that operation and emit an ID.

Otherwise, this either adds another level or closes one or more levels.

We do this by modelling the counters with a stack. On each enumerated paragraph, we pop or push stuff onto the stack.

The difficulty is deciding whether two enumerations are of the same numbering scheme, e.g. L and I could be uppercase latin (A, B, C, …) or roman numerals (I, II, III, …). You might therefore want to transform both into their numeric value and assert that they are not only of the same scheme but are also consecutive.

Here is a basic Perl script that would parse the above example, but would have difficulties with more complex input for the mentioned reasons:

use strict;
use warnings;
use HTML::Entities qw< encode_entities >;

local $/ = ''; # paragraph mode
my @stack;
while(my $section = <>) {
    $section =~ s/^\s+//;
    $section =~ s/\s+$//;

    my ($number) = $section =~ m/[(] ([A-Z]+|[a-z]+|[0-9]+|[IVXLCDM]+) [)]/x;
    if (not $number) {
       print "
", encode_entities($section), "
\n";
       next;
    }

    # check if the numbering is a continuation of the current or another level
    if (@stack and grep { compatible($_, $number) } @stack) {
      pop @stack until compatible($stack[-1], $number);
      $stack[-1] = $number
    }
    # open a new level
    else {
      push @stack, $number;
    }

    my $id = join "-", "section", @stack;
    print qq(
), encode_entities($section), "
\n";
}

sub compatible {
   my ($prev, $this) = @_;
   (my $expected = $prev)++; # increment is magic and works on strings too.
   no warnings 'numeric';
   # numbers
   return 1 if not (grep /[^0-9]/, $prev, $this) and $expected == $this;
   # upper latin
   return 1 if not (grep /[^A-Z]/, $prev, $this) and $expected eq $this;
   # lower latin
   return 1 if not (grep /[^a-z]/, $prev, $this) and $expected eq $this;
   # roman numerals
   return 1 if not (grep /[^IVXLCDM]/, $prev, $this); # TODO check consecutive
   return 0;
}
```

Body:
This is fairly simple to do, depending on how the input is structured. Let's assume we have a file like

Legalese Introduction

(1) Some Legalese Section

    With another paragraph inside it

    (a) With some sub-paragraph

        (I) Some other statutes

        (II) Some other statutes

(2) Another Section

We can easily split this file into paragraphs and then loop through them. For each paragraph with some enumeration, we can check whether this increments the counter of the current numbering level. If so, we perform that operation and emit an ID.

Otherwise, this either adds another level or closes one or more levels.

We do this by modelling the counters with a stack. On each enumerated paragraph, we pop or push stuff onto the stack.

The difficulty is deciding whether two enumerations are of the same numbering scheme, e.g. L and I could be uppercase latin (A, B, C, …) or roman numerals (I, II, III, …). You might therefore want to transform both into their numeric value and assert that they are not only of the same scheme but are also consecutive.

Here is a basic Perl script that would parse the above example, but would have difficulties with more complex input for the mentioned reasons:

use strict;
use warnings;
use HTML::Entities qw< encode_entities >;

local $/ = ''; # paragraph mode
my @stack;
while(my $section = <>) {
    $section =~ s/^\s+//;
    $section =~ s/\s+$//;

    my ($number) = $section =~ m/[(] ([A-Z]+|[a-z]+|[0-9]+|[IVXLCDM]+) [)]/x;
    if (not $number) {
       print "<p>", encode_entities($section), "</p>\n";
       next;
    }

    # check if the numbering is a continuation of the current or another level
    if (@stack and grep { compatible($_, $number) } @stack) {
      pop @stack until compatible($stack[-1], $number);
      $stack[-1] = $number
    }
    # open a new level
    else {
      push @stack, $number;
    }

    my $id = join "-", "section", @stack;
    print qq(<p id="$id">), encode_entities($section), "</p>\n";
}

sub compatible {
   my ($prev, $this) = @_;
   (my $expected = $prev)++; # increment is magic and works on strings too.
   no warnings 'numeric';
   # numbers
   return 1 if not (grep /[^0-9]/, $prev, $this) and $expected == $this;
   # upper latin
   return 1 if not (grep /[^A-Z]/, $prev, $this) and $expected eq $this;
   # lower latin
   return 1 if not (grep /[^a-z]/, $prev, $this) and $expected eq $this;
   # roman numerals
   return 1 if not (grep /[^IVXLCDM]/, $prev, $this); # TODO check consecutive
   return 0;
}


问:
Is functional programming actually used to create applications?

Possible Duplicate:

  What are some well known applications written in F#?

I see a lot of people talking about how cool functional programming is, how awesome Lisp and Haskell and F# are, etc, but what I don't see is them actually being used.  Just about every program on my computer is written in either something in the C family, Delphi, or Python.  I see tutorials talking about how easy it is to use functional languages to do complicated math problems, but no one talking about using them to do things most people actually care about using computers for, like business applications and games.

Does anyone have any examples of actual programs that people have heard of and are using, written in a functional language?  The only one I can think of off the top of my head is Abuse, from almost 15 years ago.  (Things like Emacs, where the core program is written in C with a functional language scripting layer on top, don't count.)

答: Lots of financial analysis used to be done in APL, from earlier responses it sounds like they've transitioned to F# today.</p>


问:
Is this how dynamic language copes with dynamic requirement?
The question is in the title. I want to have my thinking verified by experienced people. You can add more or disregard my opinion, but give me a reason.

Here is an example requirement: Suppose you are required to implement a fighting game. Initially, the game only includes fighters, who can attack each other. Each fighter can punch, kick or block incoming attacks. Fighters can have various fighting styles: Karate, Judo, Kung Fu... That's it for the simple universe of the game. In an OO like Java, it can be implemented similar to this way:

```<code>abstract class Fighter {
    int hp, attack;

    void punch(Fighter otherFighter);
    void kick(Fighter otherFighter);
    void block(Figther otherFighter);
};

class KarateFighter extends Fighter { //...implementation...};
class JudoFighter extends Fighter { //...implementation... };
class KungFuFighter extends Fighter { //...implementation ... };
</code>```

This is fine if the game stays like this forever. But, somehow the game designers decide to change the theme of the game: instead of a simple fighting game, the game evolves to become a RPG, in which characters can not only fight but perform other activities, i.e. the character can be a priest, an accountant, a scientist etc... At this point, to make it more generic, we have to change the structure of our original design: Fighter is not used to refer to a person anymore; it refers to a profession. The specialized classes of Fighter (KaraterFighter, JudoFighter, KungFuFighter) . Now we have to create a generic class named Person. However, to adapt this change, I have to change the method signatures of the original operations:

```<code>class Person {
    int hp, attack;
    List<Profession> skillSet;
};

abstract class Profession {};

class Fighter extends Profession {
    void punch(Person otherFighter);
    void kick(Person otherFighter);
    void block(Person otherFighter);
};

class KarateFighter extends Fighter { //...implementation...};
class JudoFighter extends Fighter { //...implementation... };
class KungFuFighter extends Fighter { //...implementation ... };

class Accountant extends Profession {
     void calculateTax(Person p) { //...implementation...};
     void calculateTax(Company c) { //...implementation...};
};
//... more professions...
</code>```

Here are the problems:

To adapt to the method changes, I have to fix the places where the changed methods are called (refactoring).

Every time a new requirement is introduced, the current structural design has to be broken to adapt the changes. This leads to the first problem.

Rigid structure makes it hard for code reuse. A function can only accept the predefined types, but it cannot accept future unknown types. A written function is bound to its current universe and has no way to accommodate to the new types, without modifications or rewrite from scratch. I see Java has a lot of deprecated methods.

OO is an extreme case because it has inheritance to add up the complexity, but in general for statically typed language, types are very strict.

In contrast, a dynamic language can handle the above case as follow:

```<code>;;fighter1 punch fighter2
(defun perform-punch (fighter1 fighter2) ...implementation... )

;;fighter1 kick fighter2
(defun perform-kick (fighter1 fighter2) ...implementation... )

;;fighter1 blocks attacks from fighter2
(defun perform-block (fighter1 fighter2) ...implementation... )
</code>```

fighter1 and fighter2 can be anything as long as it has the required data for calculation; or methods (duck typing). You don't have to change from the type Fighter to Person. In the case of Lisp, because Lisp only has a single data structure: list, it's even easier to adapt to changes. However, other dynamic languages can have similar behaviors as well.

I work primarily with static languages (mainly C and Java, but working with Java was a long time ago). I started learning Lisp and some other dynamic languages this year. I can see how it helps improving my productivity.

答:
A dynamic language can be great when faced with dynamic requirements.  Personally, I prefer Python to C when I'm faced with a lot of changes.  There is far less ceremony compared with C++, C#, Java.  But ...

Regardless of the language, the architecture of the system / project has a massive impact upon how well we can adapt to changes, such as those that you mention.  For me the bigger question is "How quickly can we refactor to accommodate the changes."  For your example, base classes would need changes and I would prefer to have multiple inheritance.

In our projects, the external analysis and design documents are massively revisited when big changes come about.  We prefer to issue revised documents and from that make a big list of change requests.  And yes, the test suites need a lot of extra work too.


答:
What about the reporting side? Are data warehouses acceptable, or are
  they bad design because they incorporate business logic in the
  database and the very data itself?

I don't think you are talking about business logic, this is more reporting logic. What do users do with the information on this screen, is it simply for status updates? Your domain model is used to model transactional operations, reporting is a different concern. Pulling the data from SQL Server or putting it into a data warehouse is fine for reporting scenarios.

Your domain model should enforce the invariants of your domain such as a project member can't book to the same project at the same time, or can only book x number of hours a week. Or you can't book to this project as it is complete etc etc the state of your domain model (the data) can be copied for reporting separately.

To improve query performance you can use a materialised view. When an operation is committed against your model (e.g. Book 4 hour of this persons time to project x) and it is successful it can throw an event that you can then store in a reporting database and make the necessary calculates for your report. It will then be very fast to query on it.

Keep your transaction and reporting contexts separate, a relational database was built for reporting a domain model was not.

EDIT

Useful blog post on the subject http://se-thinking.blogspot.se/2012/08/how-to-handle-reporting-with-domain.html