问:
which style of member-access is preferable
the purpose of oop using classes is to encapsulate members from the outer space. i always read that accessing members should be done by methods. for example:

```<code>template<typename T>
class foo_1 {
  T state_;
public:
  // following below
};
</code>```

the most common doing that by my professor was to have a get and set method.

```<code>  // variant 1
  T const& getState() { return state_; }
  void setState(T const& v) { state_ = v; }
</code>```

or like this:

```<code>  // variant 2
  // in my opinion it is easier to read
  T const& state() { return state_; }
  void state(T const& v) { state_ = v; }
</code>```

assume the state_ is a variable, which is checked periodically and there is no need to ensure the value (state) is consistent. Is there any disadvantage of accessing the state by reference? for example:

```<code>  // variant 3
  // do it by reference
  T& state() { return state_; }
</code>```

or even directly, if I declare the variable as public.

```<code>template<typename T>
class foo {
public:
  // variant 4
  T state;
};
</code>```

In variant 4 I could even ensure consistence by using c++11 atomic.

So my question is, which one should I prefer?, Is there any coding standard which would decline one of these pattern?

for some code see here

答:
Instead of chasing guidelines for implementation nuances I suggest to look for the root motivation to have the setters and getter in the first place.

Once you understand how they help, what are the cases where there is practical difference between the forms and how it manifests, you probably can answer your question for good.

And from that point see why chasing guidelines instead of just writing the particular code to a sensible form is a bad idea.

Also if you start writing actually OO code instead of the usual faked structs related to the 'anaemic model' antipattern, you will see that a setter is an extremely rare beast, and even raw getters are not so common.


问:
Would learning any natural language in particular further your programming career?
It seems apparent that English is the dominant international language for programming based on previous P.SE questions (though a highly upvoted comment correctly points out that asking a question like that on a predominantly English site will skew the results).

However, is there benefit in learning a foreign language for software development? For example, do the Chinese have completely different software tools, languages, technologies, etc? How about Japanese, Russian, and other non-latin based languages? Is there an entire world of software development languages, tools and so on that only exist in these other languages?

Or do people that know these languages use the tools and languages we know and love?

答:
The only direct benefit to learning a different language is to give you a better appreciation of the issues around i18n. That is, just like date formats, there are different rules for grammar, such that localisation can't be done by just adding placeholders for strings.

If you just want to improve your programming career, there are much more effective uses of your time, such as brushing up your existing skills, or learning a different programming language, preferably from a different paradigm.

Having said that, there are many beneficial direct and side effects to learning a different language, especially if you are monolingual. A lot of things that seem obvious to multilingual people are actually not so obvious if you haven't been exposed to different languages, for instance I've noticed a lot of monolingual people don't seem to realise that language-dependent jokes (such as puns) don't work at all when translated. This can help stop you from making insensitive blunders, of which my favourite example is the apocryphal story of Pepsi's "come alive" ad being mistranslated in Chinese as "bringing your dead ancestors alive". Having this extra sensitivity is helpful in any career.

In conclusion, I think learning a new language provides great benefits; I just question if it's an efficient use of your time.

ContentLicense: CC BY-SA 3.0


问:
Flowchart with subroutine
I am not really sure how to correctly describe my question, so please forgive me if this is a duplicate. I am creating a flowchart for my program where I implement a method. Let's assume I call this method someMethod.

The C code could look something like this:

```<code>bool someMethod(int Foo, int Bar)
{
    foo += 5;
    bar -= 5;
    return (foo == bar);
}
</code>```

This means that my flowchart will have a subroutine block where I call this function. But how do I correctly show the reader which integers I pass?

And when I create the flowchart of "someMethod", I face a similar problem: how do I correctly show the reader that Foo and Bar are passed parameters?

EDIT:

From what I have found so far, people have solved it by using the Start block as some sort of function declaration block, where they would replace Start with someMethod and place foo and bar on a new line. But from what I understand this isn't good practice since the start and end of every flowchart should be blocks containing respectively Start and Stop.

I also have seen people using an IO-block as the first non-start block where they would "read" the passed parameters but that just seems like a hack.

But unless there are better ideas, I suppose I'll have to go with that.

EDIT 2:

I am starting to wonder if this question is actually valid for this site. Is nobody using flowcharts anymore as a project preparation method?

答:
I've not drawn a flowchart in over 20 years. Thank goodness. By the time the chart is done the code could have been written, debugged, and deployed. Flowcharts were OK at a time when everything was card-punched and batch processed on mainframe computers that were doing priority production runs w/ your development work squeezed in between; computer time was very limited and very in demand. Turn-around time sometimes was days. Anyway, now a days the time and effort is simply a waste of time and effort.

Don't show a flowchart to a manager

It's too much detail and information. All trees, no forest.

Show Management Unified Modeling Language (UML) Diagrams

Here's an overview

There are 14 different diagrams but none are for line by line code detail. That's what the code is for! But you will find diagrams for different aspects and perspectives of your system.

Title: Flowchart with subroutine


问:
Type dependencies vs directory structure
Something I've been wondering about recently is how to organize types in directories/namespaces w.r.t. their dependencies.

One method I've seen, which I believe is the recommendation for both Haskell and .NET (though I can't find the references for this at the moment), is:

```<code>Type
Type/ATypeThatUsesType
Type/AnotherTypeThatUsesType
</code>```

My natural inclination, however, is to do the opposite:

```<code>Type
Type/ATypeUponWhichTypeDepends
Type/AnotherTypeUponWhichTypeDepends
</code>```

Questions:

Is my inclination bass-ackwards?

Are there any major benefits/pitfalls of one over the other?

Is it just something that depends on the application, e.g. whether you're building a library vs doing normal coding?

答: I also feel an urge to put lower level types in lower level folders. In practice, however, you may need to put lower level types in higher level folders. By .net convention, more specialized types tend to be found in more deeply nested namespaces, and the namespace hierarchy is reflected in the directory hierarchy. More general types go into higher level namespaces. The rationale behind this convention: to shield the API user from excessive details, until those details are needed. The API user begins exploration at the higher level namespace.</p>


问:
How do you plan your asynchronous code?
I created a library that is a invoker for a web service somewhere else. The library exposes asynchronous methods, since web service calls are a good candidate for that matter.

At the beginning everything was just fine, I had methods with easy to understand operations in a CRUD fashion, since the library is a kind of repository.

But then business logic started to become complex, and some of the procedures involves the chaining of many of these asynchronous operations, sometimes with different paths depending on the result value, etc.. etc..

Suddenly, everything is very messy, to stop the execution in a break point it is not very helpful, to find out what is going on or where in the process timeline have you stopped become a pain... Development becomes less quick, less agile, and to catch those bugs that happens once in a 1000 times becomes a hell.

From the technical point, a repository that exposes asynchronous methods looked like a good idea, because some persistence layers could have delays, and you can use the async approach to do the most of your hardware. But from the functional point of view, things became very complex, and considering those procedures where a dozen of different calls were needed... I don't know the real value of the improvement.

After read about TPL for a while, it looked like a good idea for managing tasks, but in the moment you have to combine them and start to reuse existing functionality, things become very messy. I have had a good experience using it for very concrete scenarios, but bad experience using them broadly.

How do you work asynchronously? Do you use it always? Or just for long running processes?

答: I would design a state machine for each set of related, linked processes, and keep track of the state somewhere in a high level object, so it is easier to debug. State transitions can be traced, and invalid state transitions can be detected.</p>

OwnerDisplayName: NullOrEmpty

Title: How do you plan your asynchronous code?


答:
As Frank says, write a state machine for each chunk of business logic that requires multiple async calls. Then, it's easy to interrogate the state when debugging, because you enumerated it.

In fact, start by just drawing out the state diagram. If the diagram is too complex (especially if you have multiple async calls in-flight which could return in various orders), write it out as a table to make sure you handled every possible combination.

Title: How do you plan your asynchronous code?

Body:
I created a library that is a invoker for a web service somewhere else. The library exposes asynchronous methods, since web service calls are a good candidate for that matter.

At the beginning everything was just fine, I had methods with easy to understand operations in a CRUD fashion, since the library is a kind of repository.

But then business logic started to become complex, and some of the procedures involves the chaining of many of these asynchronous operations, sometimes with different paths depending on the result value, etc.. etc..

Suddenly, everything is very messy, to stop the execution in a break point it is not very helpful, to find out what is going on or where in the process timeline have you stopped become a pain... Development becomes less quick, less agile, and to catch those bugs that happens once in a 1000 times becomes a hell.

From the technical point, a repository that exposes asynchronous methods looked like a good idea, because some persistence layers could have delays, and you can use the async approach to do the most of your hardware. But from the functional point of view, things became very complex, and considering those procedures where a dozen of different calls were needed... I don't know the real value of the improvement.

After read about TPL for a while, it looked like a good idea for managing tasks, but in the moment you have to combine them and start to reuse existing functionality, things become very messy. I have had a good experience using it for very concrete scenarios, but bad experience using them broadly.

How do you work asynchronously? Do you use it always? Or just for long running processes?


答:
I don't see any strong grounds for choosing between 1 & 2 (although the getter should be const-qualified) - just choose a style and stick with it (or follow the style of your existing code base).

In variant 3, you're still hiding some information. For example, you could change to

```<code>template<typename T>
class foo {
  std::unique_ptr<T> state_;
public:
  foo() : state_(new T()) {}
  T& state() { return *state_; }
  T const& state() const { return *state_; }
};
</code>```

without affecting your callers. So, it may still be useful. You lose the option to add validation (or logging, or breakpoints, or ...) to the setter later if you need it, at least without changing your client code too, so be aware you have lost some flexibility in exchange for a little less typing.

Variant 4 is also perfectly reasonable: for example, there may be no reason to restrict access to some POD aggregates. Note that a class with only public members is just a struct, so you might as well call it one.  However, now you definitely can't change any detail without also changing the client. So, this aggregate type is just a convenient bundle of data but doesn't reduce coupling at all.

Title: which style of member-access is preferable

Body:
the purpose of oop using classes is to encapsulate members from the outer space. i always read that accessing members should be done by methods. for example:

```<code>template<typename T>
class foo_1 {
  T state_;
public:
  // following below
};
</code>```

the most common doing that by my professor was to have a get and set method.

```<code>  // variant 1
  T const& getState() { return state_; }
  void setState(T const& v) { state_ = v; }
</code>```

or like this:

```<code>  // variant 2
  // in my opinion it is easier to read
  T const& state() { return state_; }
  void state(T const& v) { state_ = v; }
</code>```

assume the state_ is a variable, which is checked periodically and there is no need to ensure the value (state) is consistent. Is there any disadvantage of accessing the state by reference? for example:

```<code>  // variant 3
  // do it by reference
  T& state() { return state_; }
</code>```

or even directly, if I declare the variable as public.

```<code>template<typename T>
class foo {
public:
  // variant 4
  T state;
};
</code>```

In variant 4 I could even ensure consistence by using c++11 atomic.

So my question is, which one should I prefer?, Is there any coding standard which would decline one of these pattern?

for some code see here

Body:
I don't see any strong grounds for choosing between 1 & 2 (although the getter should be const-qualified) - just choose a style and stick with it (or follow the style of your existing code base).

In variant 3, you're still hiding some information. For example, you could change to

template<typename T>
class foo {
  std::unique_ptr<T> state_;
public:
  foo() : state_(new T()) {}
  T& state() { return *state_; }
  T const& state() const { return *state_; }
};

without affecting your callers. So, it may still be useful. You lose the option to add validation (or logging, or breakpoints, or ...) to the setter later if you need it, at least without changing your client code too, so be aware you have lost some flexibility in exchange for a little less typing.

Variant 4 is also perfectly reasonable: for example, there may be no reason to restrict access to some POD aggregates. Note that a class with only public members is just a struct, so you might as well call it one.  However, now you definitely can't change any detail without also changing the client. So, this aggregate type is just a convenient bundle of data but doesn't reduce coupling at all.


问:
Do teams get more productive by adding more developers?
Suppose you've got a project that is running late. Is there any proof or argument that teams become much more productive by adding more people?  I am looking for answers that can be supported by facts and references if possible.

What I'm thinking about is that existing devs have to teach the new ones (thus losing overall development time), and then the new developers have to study the code (and tasks) before they can become fully productive.

答:
Your questions has the answer in it.

Adding man-power to a project that is running late, only makes it worse because the communication overhead increases in a non-linear way.

It's already been studied.

Read "The Mythical Man-Month".


答:
Fred Brooks in his book The Mythical Man Month discusses this issue.

The conclusion is clear - communication overheads make this a bad idea.

This is known as Brooks' law: "adding manpower to a late software project makes it later".

Title: Do teams get more productive by adding more developers?

Body:
Suppose you've got a project that is running late. Is there any proof or argument that teams become much more productive by adding more people?  I am looking for answers that can be supported by facts and references if possible.

What I'm thinking about is that existing devs have to teach the new ones (thus losing overall development time), and then the new developers have to study the code (and tasks) before they can become fully productive.


问:
How do functional languages handle random numbers?
What I mean about that is that in nearly every tutorial I've read about functional languages, is that one of the great things about functions, is that if you call a function with the same parameters twice, you'll always end up with the same result.

How on earth do you then make a function that takes a seed as a parameter, and then returns a random number based on that seed?

I mean this would seem to go against one of the things that are so good about functions, right? Or am I completely missing something here?

答:
It's the same for non functional languages. Ignoring the slightly separate problem of truly random numbers here.

A random number generator always takes a seed value and for the same seed returns the same sequence of random numbers (very helpful if you need to test a program that uses random numbers). Basically it starts with the seed you choose and then uses the last result as seed for the next iteration. So most implementations are "pure" functions as you describe them: Take a value and for the same value always return the same result.


问:
"Gödel, Escher, Bach" still valid today?
I have just completed a course on computability and logic which was an interesting course. The lecturer recommend a few books on his slides, which include "Gödel, Escher, Bach". I can see the book is quite famous, and looks very interesting. But I have a few questions to ask regarding its content.

Is the content still valid today? I guess most theoretical stuff doesn't change over night, but are there any major points which no longer hold today that I should be aware of?

I assume we actually HAVE made some progress in the last 30 years or so. Can any of you recommend a book on the subject which includes this progress (logic, AI, computability)?

Another question: Do I have to know about Escher and Bach?

答:
There are a few outdated references in the book, but most of the content is still valid.  One particular point I'm thinking of is his discussion about AI and how computers can't even beat human's in chess, and he's not sure if that will ever happen.  Of course, that DID happen, but it was due to faster harder and larger databases of moves, not any revolutionary new algorithms in AI.

His ideas about logic and such are still quite valid and good though.  If you have any interest in computer languages, the entire book is very useful as he discusses a lot of the fundamental concepts behind the design of language and symbolic notations.

ContentLicense: CC BY-SA 2.5


答:
You're not wrong. If you give the same seed to a RNG twice, then the first pseudo-random number it returns will be the same. This is nothing to do with functional vs. side-effect programming; the definition of a seed is that a specific input causes a specific output of well-distributed but decidedly non-random values. That's why it's called pseudo-random, and it's often a good thing to have, e.g. to write predictable unit tests, to reliably compare different optimisation methods on the same problem, etc.

If you actually want non-pseudo-random numbers from a computer, you have to hook it up to something genuinely random, such as a particle decay source, unpredictable events occurring within the network that the computer is on, etc. This is hard to get right and usually expensive even if it works, but it is the only way of not getting pseudo-random values (usually the values you receive from your programming language are based on some seed, even if you didn't explicitly provide one.)

This, and only this, would compromise the functional nature of a system. Since non-pseudo-random generators are rare, this doesn't come up often, but yes, if you really do have a method generating true random numbers, then at least that little bit of your programming language cannot be 100% pure functional. Whether a language would make an exception for it or not is just a question of how pragmatic the language implementer is.

Title: How do functional languages handle random numbers?

Body:
What I mean about that is that in nearly every tutorial I've read about functional languages, is that one of the great things about functions, is that if you call a function with the same parameters twice, you'll always end up with the same result.

How on earth do you then make a function that takes a seed as a parameter, and then returns a random number based on that seed?

I mean this would seem to go against one of the things that are so good about functions, right? Or am I completely missing something here?


问:
Should I force users to update an application?
I'm writing an application for a medium sized company that will be used by about 90% of our employees and our clients.

In planning for the future we decided to add functionality that will verify that the version of the program that is running is a version that we still support. Currently the application will forcequit if the version is not among our supported versions. Here is my concern.

Hypothetically, in version 2.0.0.1 method "A" crashes and burns in glorious fashion and method "B" works just fine. We release 2.0.0.2 to fix method A and deprecate version 0.1. Now if someone is running 0.1 to use method B they will be forced to update to fix something that isn't an issue for them right now.

My question is, will the time saved not troubleshooting old, unsupported versions outweigh the cost in usability?

答:
As with any question, the answer is "it depends".

If your application works as before after the update and the update is critical to the security of the user and the average user is not tech-savy enough to decide himself, then I think forced auto-updating is a good thing.

If your application connects different users in a competing scenario, it's absolutely critical that all are using the same software. Forced updates are the default behaviour here. Think of online games for example.

Nudging Users to update by themselves by softer means like only supporting the three most recent versions is quite normal.

Forcing the users to update in other scenarios is considered a Bad Thing (tm). The user bought the software he installed. If you change it without his consent, it will not make him a happy customer.


答:
You can't create a pure function called random that will give a different result every time it is called. In fact, you can't even "call" pure functions. You apply them. So you aren't missing anything, but this doesn't mean that random numbers are off-limits in functional programming. Allow me to demonstrate, I'll use Haskell syntax throughout.

Coming from an imperative background, you may initially expect random to have a type like this:

```<code>random :: () -> Integer
</code>```

But this has already been ruled out because random cannot be a pure function.

Consider the idea of a value. A value is an immutable thing. It never changes and every observation that you can make about it is consistent for all time.

Clearly, random can't produce a Integer value. Instead, it produces a Integer random variable. It's type might look like this:

```<code>random :: () -> Random Integer
</code>```

Except that passing an argument is completely unnecessary, functions are pure, so one random () is as good as another random (). I'll give random, from here on, this type:

```<code>random :: Random Integer
</code>```

Which is all well and fine, but not very useful. You may expect to be able to write expressions like random + 42, but you can't, because it won't typecheck. You can't do anything with random variables, yet.

This raises an interesting question. What functions should exist to manipulate random variables?

This function can't exist:

```<code>bad :: Random a -> a
</code>```

in any useful way, because then you could write:

```<code>badRandom :: Integer
badRandom = bad random
</code>```

Which introduces an inconsistency. badRandom is supposedly a value, but it is also a random number; a contradiction.

Maybe we should add this function:

```<code>randomAdd :: Integer -> Random Integer -> Random Integer
</code>```

But this just a special case of a more general pattern. You should be able to apply any function to random thing in order to get other random things like so:

```<code>randomMap :: (a -> b) -> Random a -> Random b
</code>```

Instead of writing random + 42, we can now write randomMap (+42) random.

If all you had was randomMap, you wouldn't be able to combine random variables together. You couldn't write this function for instance:

```<code>randomCombine :: Random a -> Random b -> Random (a, b)
</code>```

You might try to write it like this:

```<code>randomCombine a b = randomMap (\a' -> randomMap (\b' -> (a', b')) b) a
</code>```

But it has the wrong type. Instead of ending up with a Random (a, b), we end up with a Random (Random (a, b))

This can be fixed by adding another function:

```<code>randomJoin :: Random (Random a) -> Random a
</code>```

But, for reasons that may eventually become clear, I'm not going to do that. Instead I'm going to add this:

```<code>randomBind :: Random a -> (a -> Random b) -> Random b
</code>```

It's not immediately obvious that this actually solves the problem, but it does:

```<code>randomCombine a b = randomBind a (\a' -> randomMap (\b' -> (a', b')) b)
</code>```

In fact, it's possible to write randomBind in terms of randomJoin and randomMap. It's also possible to write randomJoin in terms of randomBind. But, I'll leave doing this as an exercise.

We could simplify this a little. Allow me to define this function:

```<code>randomUnit :: a -> Random a
</code>```

randomUnit turns a value into a random variable. This means that we can have random variables that aren't actually random. This was always the case though; we could have done randomMap (const 4) random before. The reason defining randomUnit is a good idea is that now we can define randomMap in terms of randomUnit and randomBind:

```<code>randomMap :: (a -> b) -> Random a -> Random b
randomMap f x = randomBind x (randomUnit . f)
</code>```

Ok, now we are getting somewhere. We have random variables that we can manipulate. However:

It's not obvious how we might actually implement these functions,

It's quite cumbersome.

Implementation

I'll tackle pseudo random numbers. It is possible implement these functions for real random numbers, but this answer is already getting quite long.

Essentially, the way this is going to work is that we are going to pass a seed value around everywhere. Whenever we generate a new random value, we will produce a new seed. At the end, when we're done constructing a random variable, we will want to sample from it using this function:

```<code>runRandom :: Seed -> Random a -> a
</code>```

I'm going to define the Random type like this:

```<code>data Random a = Random (Seed -> (Seed, a))
</code>```

Then, we just need to provide implementations of randomUnit, randomBind, runRandom and random which is quite straight-forward:

```<code>randomUnit :: a -> Random a
randomUnit x = Random (\seed -> (seed, x))

randomBind :: Random a -> (a -> Random b) -> Random b
randomBind (Random f) g =
  Random (\seed ->
    let (seed', x) = f seed
        Random g' = g x in
          g' seed')

runRandom :: Seed -> Random a -> a
runRandom seed (Random f) = (snd . f) seed
</code>```

For random, I'm going to assume there's already a function of the type:

```<code>psuedoRandom :: Seed -> (Seed, Integer)
</code>```

In which case random is just Random psuedoRandom.

Making things less cumbersome

Haskell has syntactic sugar to make things like this nicer on the eyes. It's called do-notation and to use it all we have to do it create an instance of Monad for Random.

```<code>instance Monad Random where
  return = randomUnit
  (>>=) = randomBind
</code>```

Done. randomCombine from before could now be written:

```<code>randomCombine :: Random a -> Random b -> Random (a, b)
randomCombine a b = do
  a' <- a
  b' <- b
  return (a', b')
</code>```

If I was doing this for myself, I would even go one step further than this and create an instance of Applicative. (Don't worry if this makes no sense).

```<code>instance Functor Random where
  fmap = liftM

instance Applicative Random where
  pure = return
  (<*>) = ap
</code>```

Then randomCombine could be written:

```<code>randomCombine :: Random a -> Random b -> Random (a, b)
randomCombine a b = (,) <$> a <*> b
</code>```

Now that we have these instances, we can use >>= instead of randomBind, join instead of randomJoin, fmap instead of randomMap, return instead of randomUnit. We also get a whole load of functions for free.

Is it worth it? You could argue, that getting to this stage, where working with random numbers isn't completely horrendous was quite difficult and long-winded. What did we get in exchange for this effort?

The most immediate reward is that we can now see exactly which parts of our program are dependent on randomness and which parts are entirely deterministic. In my experience, forcing a strict separation like this simplifies things immensely.

We've assumed so far that we just want a single sample from each random variable that we generate, but if it turns out that in the future we'd actually like to see more of the distribution, this is trivial. You can just use runRandom lots of times on the same random variable with different seeds. This is, of course, possible in imperative languages, but in this case, we can be certain that we aren't going to perform unanticipated IO every time we sample a random variable and we don't have to be careful about initializing state.

Body:
You can't create a pure function called random that will give a different result every time it is called. In fact, you can't even "call" pure functions. You apply them. So you aren't missing anything, but this doesn't mean that random numbers are off-limits in functional programming. Allow me to demonstrate, I'll use Haskell syntax throughout.

Coming from an imperative background, you may initially expect random to have a type like this:

random :: () -> Integer

But this has already been ruled out because random cannot be a pure function.

Consider the idea of a value. A value is an immutable thing. It never changes and every observation that you can make about it is consistent for all time.

Clearly, random can't produce a Integer value. Instead, it produces a Integer random variable. It's type might look like this:

random :: () -> Random Integer

Except that passing an argument is completely unnecessary, functions are pure, so one random () is as good as another random (). I'll give random, from here on, this type:

random :: Random Integer

Which is all well and fine, but not very useful. You may expect to be able to write expressions like random + 42, but you can't, because it won't typecheck. You can't do anything with random variables, yet.

This raises an interesting question. What functions should exist to manipulate random variables?

This function can't exist:

bad :: Random a -> a

in any useful way, because then you could write:

badRandom :: Integer
badRandom = bad random

Which introduces an inconsistency. badRandom is supposedly a value, but it is also a random number; a contradiction.

Maybe we should add this function:

randomAdd :: Integer -> Random Integer -> Random Integer

But this just a special case of a more general pattern. You should be able to apply any function to random thing in order to get other random things like so:

randomMap :: (a -> b) -> Random a -> Random b

Instead of writing random + 42, we can now write randomMap (+42) random.

If all you had was randomMap, you wouldn't be able to combine random variables together. You couldn't write this function for instance:

randomCombine :: Random a -> Random b -> Random (a, b)

You might try to write it like this:

randomCombine a b = randomMap (\a' -> randomMap (\b' -> (a', b')) b) a

But it has the wrong type. Instead of ending up with a Random (a, b), we end up with a Random (Random (a, b))

This can be fixed by adding another function:

randomJoin :: Random (Random a) -> Random a

But, for reasons that may eventually become clear, I'm not going to do that. Instead I'm going to add this:

randomBind :: Random a -> (a -> Random b) -> Random b

It's not immediately obvious that this actually solves the problem, but it does:

randomCombine a b = randomBind a (\a' -> randomMap (\b' -> (a', b')) b)

In fact, it's possible to write randomBind in terms of randomJoin and randomMap. It's also possible to write randomJoin in terms of randomBind. But, I'll leave doing this as an exercise.

We could simplify this a little. Allow me to define this function:

randomUnit :: a -> Random a

randomUnit turns a value into a random variable. This means that we can have random variables that aren't actually random. This was always the case though; we could have done randomMap (const 4) random before. The reason defining randomUnit is a good idea is that now we can define randomMap in terms of randomUnit and randomBind:

randomMap :: (a -> b) -> Random a -> Random b
randomMap f x = randomBind x (randomUnit . f)

Ok, now we are getting somewhere. We have random variables that we can manipulate. However:

It's not obvious how we might actually implement these functions,

It's quite cumbersome.

Implementation

I'll tackle pseudo random numbers. It is possible implement these functions for real random numbers, but this answer is already getting quite long.

Essentially, the way this is going to work is that we are going to pass a seed value around everywhere. Whenever we generate a new random value, we will produce a new seed. At the end, when we're done constructing a random variable, we will want to sample from it using this function:

runRandom :: Seed -> Random a -> a

I'm going to define the Random type like this:

data Random a = Random (Seed -> (Seed, a))

Then, we just need to provide implementations of randomUnit, randomBind, runRandom and random which is quite straight-forward:

randomUnit :: a -> Random a
randomUnit x = Random (\seed -> (seed, x))

randomBind :: Random a -> (a -> Random b) -> Random b
randomBind (Random f) g =
  Random (\seed ->
    let (seed', x) = f seed
        Random g' = g x in
          g' seed')

runRandom :: Seed -> Random a -> a
runRandom seed (Random f) = (snd . f) seed

For random, I'm going to assume there's already a function of the type:

psuedoRandom :: Seed -> (Seed, Integer)

In which case random is just Random psuedoRandom.

Making things less cumbersome

Haskell has syntactic sugar to make things like this nicer on the eyes. It's called do-notation and to use it all we have to do it create an instance of Monad for Random.

instance Monad Random where
  return = randomUnit
  (>>=) = randomBind

Done. randomCombine from before could now be written:

randomCombine :: Random a -> Random b -> Random (a, b)
randomCombine a b = do
  a' <- a
  b' <- b
  return (a', b')

If I was doing this for myself, I would even go one step further than this and create an instance of Applicative. (Don't worry if this makes no sense).

instance Functor Random where
  fmap = liftM

instance Applicative Random where
  pure = return
  (<*>) = ap

Then randomCombine could be written:

randomCombine :: Random a -> Random b -> Random (a, b)
randomCombine a b = (,) <$> a <*> b

Now that we have these instances, we can use >>= instead of randomBind, join instead of randomJoin, fmap instead of randomMap, return instead of randomUnit. We also get a whole load of functions for free.

Is it worth it? You could argue, that getting to this stage, where working with random numbers isn't completely horrendous was quite difficult and long-winded. What did we get in exchange for this effort?

The most immediate reward is that we can now see exactly which parts of our program are dependent on randomness and which parts are entirely deterministic. In my experience, forcing a strict separation like this simplifies things immensely.

We've assumed so far that we just want a single sample from each random variable that we generate, but if it turns out that in the future we'd actually like to see more of the distribution, this is trivial. You can just use runRandom lots of times on the same random variable with different seeds. This is, of course, possible in imperative languages, but in this case, we can be certain that we aren't going to perform unanticipated IO every time we sample a random variable and we don't have to be careful about initializing state.


答:
None of the above.

Properties on classes is an anti-pattern. Sure, you've heard somewhere that accessing members directly is a bad thing, so you to wrap them in a method or two to access them indirectly.. but think for a moment what you've just done - nothing of any real substance.

The trouble starts when you need to modify any of them, the concept of wrapping the property in a method so you can change the underlying type is just plain wrong. You can do this if you wrap the properties in a real method but not if you have a stupid method that pretends to be the member directly (ie a property).

eg. See this blog post for an example.

the point is that, if you have internal state, you should never allow access to that state in terms of the state itself. You need to always think of accessing the object as a whole.

Too often languages and standards (and IDE helper autocompletions) say you must wrap member access in a property method, they're wrong. You should never even think of the members as something to access, directly or indirectly, from outside the class. Think of the class and think what kind of interface it should support to provide its functionality to clients.


问:
How should I architect a personal schedule manager that runs 24/7?
I've developed an ADHD management system for myself that's attempting to change multiple habits at once. I know this is counter to conventional wisdom, but I've tried the conventional for years & am now trying it my way. (just wanted to say that to try and prevent it from distracting people from the actual question)

Anyway, I'd like to write something to run on a remote server that monitors me, helps me build/avoid certain habits, etc.

What this amounts to is a system that:

runs 24/7

may have multiple independent tasks to run at once

may have tasks that require other tasks to run first

lets tasks be scheduled by specific time, recurrence (ie. "run every 5 mins"), or interval (ie. "run from 2pm to 3pm")

My first naive attempt at this was just a single PHP script scheduled to run every minute by cron (language was chosen in order to use a certain library, but no longer necessary). The logic behind when to run this or that portion of code got hairy pretty quick.

So my question is how should I approach this from here? I'm not tied to any one language, though I'm partial to python/javascript.

Thoughts:

Could be done as a set of scripts that include a scheduling mechanism with one script per bit of logic...but the idea just feels wrong to me.

Building it as a daemon could be helpful, but still unsure what to do about dozens of if-else statements for detecting the current time

答:
I would go about it like this:

Every Task is encapsulated in its own class

A task only contains of a single method: Execute. This method executes the action of the task.

A task is not responsible for checking its requirements.

Scheduling is done via Jobs

A job references a task

A job defines when its task is allowed to run

You would have one class per job type, i.e. you would have

a RecurringJob ("every 5 minutes")

an IntervalJob ("from 2pm to 3pm")

A job is an implementation of the Tester/Doer pattern.

You would have a Job Registry. That is basically the scheduler that executes the jobs.

It periodically checks (every 10 seconds, every minute or whatever you need) all registered jobs if they can be executed.

The requirement "may have tasks that require other tasks to run first" can be implemented using the Composite pattern and passing the tasks in the correct order.

The requirement "may have multiple independent tasks to run at once" can be implemented by making the execution of a task asynchronous.

ContentLicense: CC BY-SA 4.0


问:
use of Enum with flags in practice?
I just have read some stuff on enum today. Use of flags with enum was something interesting and new for me. But often practice and theoretical uses are different. I go through many articles they examples they quoted were good to get the concept but am still wondering in what situations one can use Enums with flag to store multiple values?

Will highly appreciate if you please can share your practical experience of using enum with flags.

答:
In C#, the example that sticks out in my head is accessing a directory of files. System.IO.FileAttributes is a flag enumeration of every attribute that a file can have. It makes more sense to contain all of this information in one place then have a bunch of properties that have to be set.

```<code>File.SetAttributes(file, FileAttributes.ReadOnly | FileAttributes.System);
</code>```

This is much more concise than code that would have you individually set each boolean field on on the file's attributes. Since every flag value is valid in any combination (except Normal, which is valid only by itself), combining them works. Now if files could only ever be of two different values with complex rules governing which combinations worked, then I would make FileAttributes a structure that could do the logic necessary to sort out those requirements.

Title: use of Enum with flags in practice?

Body:
In C#, the example that sticks out in my head is accessing a directory of files. System.IO.FileAttributes is a flag enumeration of every attribute that a file can have. It makes more sense to contain all of this information in one place then have a bunch of properties that have to be set.

File.SetAttributes(file, FileAttributes.ReadOnly | FileAttributes.System);

This is much more concise than code that would have you individually set each boolean field on on the file's attributes. Since every flag value is valid in any combination (except Normal, which is valid only by itself), combining them works. Now if files could only ever be of two different values with complex rules governing which combinations worked, then I would make FileAttributes a structure that could do the logic necessary to sort out those requirements.


问:
Documenting mathematical logic in code
Sometimes, although not often, I have to include math logic in my code. The concepts used are mostly very simple, but the resulting code is not - a lot of variables with unclear purpose, and some operations with not so obvious intent. I don't mean that the code is unreadable or unmaintainable, just that it's waaaay harder to understand than the actual math problem. I try to comment the parts which are hardest to understand, but there is the same problem as in just coding them - text does not have the expressive power of math.

I am looking for a more efficient and easy to understand way of explaining the logic behind some of the complex code, preferably in the code itself. I have considered TeX - writing the documentation and generating it separately from the code. But then I'd have to learn TeX, and the documentation will not be in the code itself. Another thing I thought of is taking a picture of the mathematical notations, equations and diagrams written on paper/whiteboard, and including it in javadoc.

Is there a simpler and clearer way?

P.S. Giving descriptive names(timeOfFirstEvent instead of t1) to the variables actually makes the code more verbose and even harder too read.

答:
The right thing to do in such circumstances is to implement the algorithm, formula or whatever with exactly the same variable names as in the primary real-world source (as far as the programming language allows this), and have a succinct comment above it saying something like "Levenshtein distance computation as described in [Knuth1968]", where the citation links to a readily accessible description of the math.

(If you don't have such a reference, but your math is sound and useful, maybe you should consider publishing it yourself. Just sayin'.)

Title: Documenting mathematical logic in code


答: If the late projects problematic part can be easily isolated - then adding additional resources will help. Adding resources for parallel tasks will complicated things even further</p>


答:
First - you plan out and develop a synchronous code that works perfectly alone. Then you isolate parts which should be re entrant and create access points for those parts of code.

This approach is best, because you will only add synchronization mechanism on demand.

Title: How do you plan your asynchronous code?


问:
Should I fully parenthesize expressions or rely on precedence rules?
Let's say I have a boolean condition a AND b OR c AND d and I'm using a language where AND has a higher order of operation precedence than OR. I could write this line of code:

```<code>If (a AND b) OR (c AND d) Then ...
</code>```

But really, that's equivalent to:

```<code>If a AND b OR c AND d Then ...
</code>```

Are there compelling arguments in favor or against including the extraneous parentheses?

Does practical experience suggest that including them significantly improves readability?

Or is wanting them a sign that a developer really needs to sit down and become conversant in the  basics of their language?

答: Yes. You should use in any case when you feel your code will be more clear. Remember your code should be clear enough so that others can understand without reading your comments inside the code. So it is a good practice to use parentheses and braces. Also keep in mind that it may be depends on the particular practice of your company/team. Just maintain one approach and do not mix.</p>


答:
text does not have the expressive power of math

You are right. Since you already are looking for a way to do it outside code, and Tex is an overkill besides having a steep learning curve, my recommendation is as follows:

Use OpenOffice.org/LibreOffice Math Equation Editor.

It's free. It's open.

You can use it either visually or you can write the equations in a special language.

You don't have to learn the language right away because when you use the GUI, the  "code" is generated in a panel for you to see.

In the upper panel you can "draw" the equations using a pallete. In the lower panel the equivalent notation is generated. You can do it the other way around once you've got a grasp of the notation, writing in notation in the lower panel and seeing the graphical output in the top panel.

Title: Documenting mathematical logic in code

Body:
Sometimes, although not often, I have to include math logic in my code. The concepts used are mostly very simple, but the resulting code is not - a lot of variables with unclear purpose, and some operations with not so obvious intent. I don't mean that the code is unreadable or unmaintainable, just that it's waaaay harder to understand than the actual math problem. I try to comment the parts which are hardest to understand, but there is the same problem as in just coding them - text does not have the expressive power of math.

I am looking for a more efficient and easy to understand way of explaining the logic behind some of the complex code, preferably in the code itself. I have considered TeX - writing the documentation and generating it separately from the code. But then I'd have to learn TeX, and the documentation will not be in the code itself. Another thing I thought of is taking a picture of the mathematical notations, equations and diagrams written on paper/whiteboard, and including it in javadoc.

Is there a simpler and clearer way?

P.S. Giving descriptive names(timeOfFirstEvent instead of t1) to the variables actually makes the code more verbose and even harder too read.


问:
Why do we need private variables?
Why do we need private variables in classes?

Every book on programming I've read says this is a private variable, this is how you define it but stops there.

The wording of these explanations always seemed to me like we really have a crisis of trust in our profession. The explanations always sounded like other programmers are out to mess up our code. Yet, there are many programming languages that do not have private variables.

What do private variables help prevent?

How do you decide if a particular property should be private or
not? If by default every field SHOULD be private then why are there
public data members in a class?

Under what circumstances should a variable be made public?

答:
You should first understand the concept of object oriented programming. It has abstraction, encapsulation etc.

Abstraction - You get the idea of the logic without need to know underline details of the implementation.

Encapsulation - You can not see the underline implementation of the object. Only you can see the public interface of the object.

Now in specific implementation with one of object oriented program like C#, Java, C++ you can implement these concepts.

private - The implementation which should be hidden from the outside world. So that you can change that and the user of your class are not affected.

public - This is the interface by which one can use your object.

Title: Why do we need private variables?


问:
Named output parameters vs return values
Which code is better:

```<code>// C++
void handle_message(...some input parameters..., bool& wasHandled)
void set_some_value(int newValue, int* oldValue = nullptr)

// C#
void handle_message(...some input parameters..., out bool wasHandled)
void set_some_value(int newValue, out int oldValue)
</code>```

or

```<code>bool handle_message(...some input parameters...) ///< Returns -1 if message was handled
                                                //(sorry, this documentation was broken a year ago and we're too busy to fix it)
int set_some_value(T newValue) // (well, it's obvious what this function returns, so I didn't write any documentation for it)
</code>```

The first one doesn't have any documentation, but it doesn't need it. It's a self-documenting code. Output value clearly says what it means, and it's really hard to make a change like this:

```<code>- void handle_message(Message msg, bool& wasHandled) {
-    wasHandled = false;
-    if (...) { wasHandled = true; ...
+ void handle_message(Message msg, int& wasHandled) {
+    wasHandled = -1;
+    if (...) { wasHandled = ...;
</code>```

When the code uses return values, it's easy to change them and leave the comments broken:

```<code>  /// Return true if message was handled
- bool handle_message(Message msg) {
+ int handle_message(Message msg) {
...
-     return true;
+     return -1;
</code>```

Most of compilers don't (and can't) check the documentation which is written in comments. Programmers also tend to ignore comments when they edit the code.

So the question is:

if a subroutine has a single output value,

should it be a procedure with well-named self-documenting output parameter,

or should it be a function which returns an unnamed value with a comment describing it?

答:
Edit (since the question has changed)

If your method only has one output, of course you return that value.

```<code>bool DoStuff(...)
</code>```

is much more readable when you use it than

```<code>void DoStuff(..., out bool success)
</code>```

Look at the sample usage:

```<code>if(DoStuff(....))
</code>```

vs

```<code>DoStuff(..., out success)
if (success)
</code>```

Also, it allows in-lining and chaining (if the language supports it):

```<code>ProcessRequest(GetRequest(reqID))
newval = ProcessString(oldval).Replace("/t","")
</code>```

Converting these to "out" params would lead to much uglier code, plus it's just wrong.

For 1 return, always use return values.

Body:
Edit (since the question has changed)

If your method only has one output, of course you return that value.

bool DoStuff(...)

is much more readable when you use it than

void DoStuff(..., out bool success)

Look at the sample usage:

if(DoStuff(....))

vs

DoStuff(..., out success)
if (success)

Also, it allows in-lining and chaining (if the language supports it):

ProcessRequest(GetRequest(reqID))
newval = ProcessString(oldval).Replace("/t","")

Converting these to "out" params would lead to much uglier code, plus it's just wrong.

For 1 return, always use return values.


答:
Make functions return values. This isn't any sort of functional thing or even relatively modern. If you're unclear about what the function is returning, then your function needs a better name. If your code is doing the wrong things, fix and/or test it.

In a vacuum, the only time that modifying your inputs is acceptable is when that input is this in object oriented languages or when the return value is taken by someother part of the function call (things like TryParse).

edit: (because the question changed)

So, again, the question is: if subroutine has single output value, should it be a procedure with well-named self-documenting output parameter, or should it be a function which returns an unnamed value and have a comment describing it?

Neither. It should be a function that is well named so that its output is clear at the call-site. The comment at the declaration only helps in the declaration. Making comments at all the call-sites is inane and unmaintainable.

If you can't make a good function name to describe its output, rethink your design.

Title: Named output parameters vs return values

Body:
Which code is better:

```<code>// C++
void handle_message(...some input parameters..., bool& wasHandled)
void set_some_value(int newValue, int* oldValue = nullptr)

// C#
void handle_message(...some input parameters..., out bool wasHandled)
void set_some_value(int newValue, out int oldValue)
</code>```

or

```<code>bool handle_message(...some input parameters...) ///< Returns -1 if message was handled
                                                //(sorry, this documentation was broken a year ago and we're too busy to fix it)
int set_some_value(T newValue) // (well, it's obvious what this function returns, so I didn't write any documentation for it)
</code>```

The first one doesn't have any documentation, but it doesn't need it. It's a self-documenting code. Output value clearly says what it means, and it's really hard to make a change like this:

```<code>- void handle_message(Message msg, bool& wasHandled) {
-    wasHandled = false;
-    if (...) { wasHandled = true; ...
+ void handle_message(Message msg, int& wasHandled) {
+    wasHandled = -1;
+    if (...) { wasHandled = ...;
</code>```

When the code uses return values, it's easy to change them and leave the comments broken:

```<code>  /// Return true if message was handled
- bool handle_message(Message msg) {
+ int handle_message(Message msg) {
...
-     return true;
+     return -1;
</code>```

Most of compilers don't (and can't) check the documentation which is written in comments. Programmers also tend to ignore comments when they edit the code.

So the question is:

if a subroutine has a single output value,

should it be a procedure with well-named self-documenting output parameter,

or should it be a function which returns an unnamed value with a comment describing it?


答:
When I have had to implement algorithms like that, there are a couple of things I do.

As much as possible, isolate the algorithm to its own method or preferably class.  My current project has it's own equivalent Math class to add complex algorithms to.

Provide a summary of what the algorithm is supposed to do in lay terms including any common acronyms or shorthand references to the term.  I do this in the method itself, so it lives with the code.

Provide a summary of the algorithm in technical / mathematical terms and include any external references that I know of.  Again, I do this with the method itself so it has a better chance of staying relevant.  Plain text isn't great in this case, so I'll cite the mathematical term as best I can and clarify in a parenthetical comment beside it.  For example,  x^y (x raised to the power y)

Document how I'm breaking the algorithm apart into components and indicate what each variable represents in the algorithm.  eg. t1 is time of first event

Code up the algorithm and comment the complex parts.  Essentially, I'll add a comment anywhere I take a step that wasn't obvious or straightforward within the algorithm itself. I especially make sure I comment any non-obvious shortcuts and why they are okay that I may take within the implementation.

Write up some unit tests that will validate the operation of the algorithm.

Finally, if it's really, really, really complex then I resign myself to the fact that I own that code for the remainder of my time on that project.

I don't like relying upon an external document for someone else to understand the code.  Yes, it can be necessary sometimes especially when getting into arcane details.  But whenever possible, I try to keep everything within the code itself so it has a chance of staying updated and easily located.  In this case, I value accessibility to information over expressiveness of the documentation.

Title: Documenting mathematical logic in code


问:
Effective way of keeping past projects with their working development environment?
I find that whenever I want to go run a past project, it will take a long time before I can find it and before I have everything set-up again for it to be able to run.

For example, I have python projects I created in Linux, and it depends on software packages that are easily installed in Linux, yet I no longer have the Linux VM I was using.  And some of my other projects depend on other variables like web server configuration, PATH variables, sdk, IDE, OS version, device, etc.

Does someone have an effective way of handling this issue?  As of now I have only concerned myself with keeping the source code backed up yet it is difficult re-establish the working development environment and it is also difficult to keep the working development environment around as well.

答: What I have done in the past is either convert the physical development machine to a VM, or if it is already a VM, retain it for future use. It's not as efficient as I'd like for disk space usage, but space is cheap. Also, this process is so much less expensive time-wise than trying to re-configure an environment in the future should the need arise.</p>


答:
My current favorite methodology is to maintain a script that installs ALL needed dependencies for a project, downloads the source, and hooks everything up. Some scripts have two modes - one for production, which usually is pretty much a subset of the other mode: development.

Some environments only take about 5 minutes to install with a script - in that case I keep a local VM with a fresh install of the target OS onto which I deploy the project script when I arrive at work in the morning - and then do all coding related work on that VM instance. Before I leave, I push all the changes via git to either my physical machine or our central repository, and terminate the VM.

If the environment takes longer to setup (long running installs, big files to download, anything like that) I do the above procedure once a week.

The benefit is that it is very easy to deploy to a new machine and/or production server, it is all documented in the script, and the script is verified very often.

Title: Effective way of keeping past projects with their working development environment?

Body:
I find that whenever I want to go run a past project, it will take a long time before I can find it and before I have everything set-up again for it to be able to run.

For example, I have python projects I created in Linux, and it depends on software packages that are easily installed in Linux, yet I no longer have the Linux VM I was using.  And some of my other projects depend on other variables like web server configuration, PATH variables, sdk, IDE, OS version, device, etc.

Does someone have an effective way of handling this issue?  As of now I have only concerned myself with keeping the source code backed up yet it is difficult re-establish the working development environment and it is also difficult to keep the working development environment around as well.


问:
What did Rich Hickey mean when he said, "All that specificity [of interfaces/classes/types] kills your reuse!"
In Rich Hickey's thought-provoking goto conference keynote "The Value of Values" at 29 minutes he's talking about the overhead of a language like Java and makes a statement like, "All those interfaces kill your reuse."  What does he mean?  Is that true?

In my search for answers, I have run across:

The Principle of Least Knowledge AKA The Law of Demeter which encourages airtight API interfaces.  Wikipedia also lists some disadvantages.

Kevlin Henney's Imperial Clothing Crisis which argues that use, not reuse is the appropriate goal.

Jack Diederich's "Stop Writing Classes" talk which argues against over-engineering in general.

Clearly, anything written badly enough will be useless.  But how would the interface of a well-written API prevent that code from being used?  There are examples throughout history of something made for one purpose being used more for something else.  But in the software world, if you use something for a purpose it wasn't intended for, it usually breaks.

I'm looking for one good example of a good interface preventing a legitimate but unintended use of some code.  Does that exist?  I can't picture it.

答:
In an (i.e. my) ideal world classes and interfaces would always describe behavior, but the fact is that all too often they really just end up describing data. Only yesterday I watched video of someone build a so-called BankAccount class that was nothing more than a glorified int (indeed it was much less useful than an int, thus 'killing' the reuse I would've had had it simply been left as an int), all in the name of 'good' design. The amount of code, sweat and tears wasted on continually reinventing convoluted representations of data is staggering; if you're not using the data in a meaningful way then please just let it be.

Now, this is the stage where Rich Hickey is content to throw the baby out with the bathwater and say that we should all go live in the land of values (a neighbor to the kingdom of nouns). I think, on the hand, that OOP can and does promote reuse (and importantly discoverability, which I find lacking in functional programming) when employed judiciously. If you're looking for an OOP principle that best captures this tension I think it might be http://c2.com/cgi/wiki?TellDontAsk (which of course is a close cousin of Demeter)


答:
In our projects, which are revolving around research in quantitative financial economics, we utilize a LOT of math, and we follow a combination of what has already been posted:

Provide a link to the main source you're using. For us, the easiest way of doing that is using the BibTex-handle, which is basically an ID for a paper that can be looked up by everybody involved. Depending on the specific source, we regularly add the equation reference as well.

Provide explanations for all variables. Again, we use Tex for that if the original paper uses Greek or other letters. The Reason for this is that often enough papers and books use different notations. If someone needs to rework the math, this makes it a lot easier.

Attempt to code the equation in one piece. It is much easier to recognize that way. DO NOT post the Tex-Code of the full equation into the code - either the equation is very short, and posting tex is messy and superfluous, or the equation is huge, and the tex code is useless, unless you compile it (Use a reference instead). Disassembling an equation into small pieces makes it really hard to understand whats going on (if you're good at math at least).

IMHO, the most important realization is that formulas often depend on context. Every math paper  i know takes its time to set up the environment of the model; You should do the same.

Title: Documenting mathematical logic in code


问:
Secure an Application/Software by expiration with Date?
I have been working on some software application and I update them every 6 months. Currently, the way I track the date is by extracting the date from the system when the user installs the application, encrypt it and store it in a file locally. Whenever the application is started, it checks if 6 months have passed, then it works or it doesn't, in which case it shows an error message telling the user to update.

If the user finds the encrypted date in the file they can simply replace it with one from a more recent install. I am wondering if there's a more secure way to do this?

答:
Is there a specific problem you're having with the current model?

If the application is installed on systems that normally have internet access, you could do this on a server to avoid the situation where someone plays with their system clock and runs the application longer than 6 months.

When the application is installed, it registers itself with your service, and your service logs an application identifier (maybe a licence key) and the date of installation. Every time it starts, it checks with the server to see if 6 months have elapsed and then tells the user to update if it's been more than 6 months.

Possible disadvantages: It's a little more complicated. You now will need to build and maintain the registration/validation service. You also need to decide what should happen if the application cannot connect to the service. And someone who's really keen on getting around this could try and sniff the data you send to and from your service and then build their own service that always validates the application, and then reroute traffic intended to your service to their service instead. So of course, you'd want all traffic with this service to be encrypted.

If the user finds the encrypted date in the file they can simply replace it with one from a more recent install. I am wondering if there's a more secure way to do this?

So you're concerned that they will figure out that if they replace their existing file with a copy of the same file but from a newer installation, they will be able to bypass the 6-month limit? The answer above could still help with this problem, another idea posted below.

I don't know exactly how you're creating or encrypting the file, but one idea might be to include the installation datetime in the key that is used to encrypt/decrypt the file. That way, a file from a different installation would have a key that's different and so cannot be shared with other installations. Now the problem is storing this key somewhere safe, so that the user can't access it.


答:
If you have the ability to use coroutines (with yields at arbitrary depths of the call-stack) or continuations, these allow you to write asynchronous code that looks very much like synchronous code; all an asynchronous call has to do to look synchronous is to suspend the execution after doing the call and schedule the resumption of execution for when the response to the asynchronous call becomes available. This greatly reduces the overall apparent complexity. (The complexity doesn't actually go away, but the language/runtime handles the majority of the tricky parts so you don't have to.)

It's possible to simulate this sort of thing with threads. That always leaves me feeling a bit dirty though, as I consider having lots of I/O-bound threads to be an indication that the system design is not right.

Failing that, your best approach is to use continuation-passing style in which you split your code up into synchronous pieces and pass any necessary shared state between them (across the periods when you're waiting for the asynchronous processing to produce a result) using a context object of some sort. This is a little bit awkward to understand in abstract: here's a little bit more concrete example. Consider this synchronous (pseudo-)code:

```<code>function DoWork() {
    let A = "foo";
    let B = 1.23;
    Call1(the.arguments);
    A.append(B);
    Call2(the.arguments);
    B += A.length;
}

DoWork();
print "finished";
</code>```

If we change this to continuation-passing style, we get something like this:

```<code>function DoWork(doneCallback) {
    let state = new Context();
    state.A = "foo";
    state.B = 1.23;
    state.done = doneCallback;
    DoAsyncCall1(the.arguments, callback=fn()=>DoMoreWork(state));
}
function DoMoreWork(state) {
    state.A.append(state.B);
    DoAsyncCall2(the.arguments, callback=fn()=>DoneTheWork(state));
}
function DoneTheWork(state) {
    state.B += state.A.length;
    state.done(state.A, state.B);
}

DoWork(fn(…)=>print "finished");
</code>```

Each section between the to-be-asynchronous calls becomes its own function (you should also make the start of any loop you've got — provided it has an async call in it — be the start of a function so that you can model the loop by calling back). The state that is getting passed around is the key to making this all work, and it's possible (assuming a non-horrific asynchronous call mechanism) to then have multiple sets of processing going on at once, as each part only knows about its little world. It is, however, important to try to avoid using global state when doing this, if for no other reason than it will leave you very confused. It's much easier to make this all work if you are using largely functional programming techniques.

Title: How do you plan your asynchronous code?

Body:
If you have the ability to use coroutines (with yields at arbitrary depths of the call-stack) or continuations, these allow you to write asynchronous code that looks very much like synchronous code; all an asynchronous call has to do to look synchronous is to suspend the execution after doing the call and schedule the resumption of execution for when the response to the asynchronous call becomes available. This greatly reduces the overall apparent complexity. (The complexity doesn't actually go away, but the language/runtime handles the majority of the tricky parts so you don't have to.)

It's possible to simulate this sort of thing with threads. That always leaves me feeling a bit dirty though, as I consider having lots of I/O-bound threads to be an indication that the system design is not right.

Failing that, your best approach is to use continuation-passing style in which you split your code up into synchronous pieces and pass any necessary shared state between them (across the periods when you're waiting for the asynchronous processing to produce a result) using a context object of some sort. This is a little bit awkward to understand in abstract: here's a little bit more concrete example. Consider this synchronous (pseudo-)code:

function DoWork() {
    let A = "foo";
    let B = 1.23;
    Call1(the.arguments);
    A.append(B);
    Call2(the.arguments);
    B += A.length;
}

DoWork();
print "finished";

If we change this to continuation-passing style, we get something like this:

function DoWork(doneCallback) {
    let state = new Context();
    state.A = "foo";
    state.B = 1.23;
    state.done = doneCallback;
    DoAsyncCall1(the.arguments, callback=fn()=>DoMoreWork(state));
}
function DoMoreWork(state) {
    state.A.append(state.B);
    DoAsyncCall2(the.arguments, callback=fn()=>DoneTheWork(state));
}
function DoneTheWork(state) {
    state.B += state.A.length;
    state.done(state.A, state.B);
}

DoWork(fn(…)=>print "finished");

Each section between the to-be-asynchronous calls becomes its own function (you should also make the start of any loop you've got — provided it has an async call in it — be the start of a function so that you can model the loop by calling back). The state that is getting passed around is the key to making this all work, and it's possible (assuming a non-horrific asynchronous call mechanism) to then have multiple sets of processing going on at once, as each part only knows about its little world. It is, however, important to try to avoid using global state when doing this, if for no other reason than it will leave you very confused. It's much easier to make this all work if you are using largely functional programming techniques.


问:
VPS versus Shared Hosting
Is there any compelling reason a programmer would host on a shared platform versus just having a VPS account somewhere?</p>

答:
Advantage Shared Hosting

Generally cheap so ideally for doing development or running smaller sites with low traffic

A lot of features are pre setup among other a basic security model (hopefully)

In general you get a lot of extra goodies like one-click installs that have been tested in the environment you are running it on and sometimes even configured

When there is more traffic in general peaks are handled: with VPS your server is dead
e.g. on mediatemple there is a Grid based model which can scale . Even if there is a peak it just runs along though you get a mail that you will have to pay extra

It is save you TIME investing in learning e.g. security (firewall on linux, ssh security, how to read the performance indicators e.g. what do these sockets indicators mean)

And therefore saves TIME each month in maintenance (and this INCLUDES: issues means just mailing the helpdesk, outtages just waiting and shouting at support)

Diskspace is often a lot more e.g. look at Dreamhost

Disadvantages Shared Hosting

Security is often less. E.g. a lot of users are running around in that same environment and when you have your files wrongly CHMOD'ded they can read them. If ever there is a general security breach...

Often Peaks lead to scaling your performance down after that which is never really clear

At some point with enough steady traffic / cpu usage / socket usage you run against the boundaries no matter what you simply have to switch

You have not complete control over your server e.g. you can not really install another operation system (or something on top of that that is out of line) e.g. running some kind of server.

Disadvantage VPS

Unmanaged AND managed VPS requires you to have the knowledge to secure the thing this costs you TIME (all knowledge is out there) but YOU are responsible for  it. You need to learn about linux firewalls for example (and a lot more). Maybe you do not want to spend your time on that.

VPS requires also enough knowledge on OS level, maintain it, patching software you specifically installed and learning how to patch the specific software e.g. upgrade Apache with dependencies. This costs TIME learning but also TIME doing it each month

ISSUES on VPS are YOUR responsibility (well ... for the most part) e.g. if your server is slow you need to go out there and check not only the software part but also the OS part and the Database performance part. E.g. if both CPU and Memory are ok... what the heck can it be. This also cost TIME. (also think of user management, email setup, etc...)

Also it more expensive. And this is really a lot more expensive than shared hosting because the upper limit of what you can do on shared hosting is not the bottom limit of what VPS can offer. E.g. if your WordPress Multisite is on its max on your shared hosting account you can not get that 1mb cheap slice. You need to possible get immediately that 4 GIG memory thing. (ok this probably means go dedicated) (since database performance plays and issue here) OR if your facebook alike ajax chat application ran against its limit on your shared hosting account... go get something much bigger because probably the max sockets are your pain point.

I just wanted to summarize ALL of this as : more TIME needed from yourself and possible A LOT if you still need to learn al lot and on the second place MONEY (since I assume that the revenue behind it would cover that larger need for infra).

If you VPS runs against its limit e.g. 512mb memory (...) your site is DEAD (ok depending on how you set it up but lets assume worst case you need to go to the panel you put on it and restart the whole lot) as said on most shared hosting they will scale it and bill you afterwards unless your page hit the front page of digg then they will think some kind of ddos attack is taking place.

Advantage VPS

More secure: YOU are on top of it ;)

from a certain level MORE memory, MORE cpu, MORE sockets, MORE everything (except possibly disk space) so at some stage you HAVE to

You learn a lot of stuff which you need to learn anyway (i think)

You can run anything you want as long as you have the resources for it

Personally I think: run on a good shared account as long as possible, then switch to dedicated if it no longer goes on the shared platform unless the thing you are runnning can be confined on VPS. (such as : development environment that needs own server stuff).

Title: VPS versus Shared Hosting


答:
One reason to write proper functions with return values (as opposed to procedures-in-disguise with "output" variables) is composability.

If you have functions (excuse my pseudocode) void f(in: int x, out: int y) and  int g(in: int x), how do you compose them?

You cannot apply g to f applied to... say, 42:

```<code>int y = g(f(42));
</code>```

Instead, you need to write:

```<code>int x = 0;
f(42, x);
int y = g(x);
</code>```

Which is definitely clumsier and more error-prone. And composability matters a lot in languages with first-class functions.

Here is another example, hopefully more convincing: I'd like to be able to write

```<code>int maxSum = max(sumOfArray(array1), sumOfArray(array2)));
</code>```

instead of jumping through hoops to achieve the same:

```<code>int sum1 = 0;
sumOfArray(array1, sum1);

int sum2 = 0;
sumOfArray(array2, sum2);

int maxSum = 0;
max(sum1, sum2, maxSum);
</code>```

Hopefully this is a less contrived scenario illustrating why function composition is useful, and why it requires that the function returns its result instead of modifying an "out" variable.

Body:
One reason to write proper functions with return values (as opposed to procedures-in-disguise with "output" variables) is composability.

If you have functions (excuse my pseudocode) void f(in: int x, out: int y) and  int g(in: int x), how do you compose them?

You cannot apply g to f applied to... say, 42:

int y = g(f(42));

Instead, you need to write:

int x = 0;
f(42, x);
int y = g(x);

Which is definitely clumsier and more error-prone. And composability matters a lot in languages with first-class functions.

Here is another example, hopefully more convincing: I'd like to be able to write

int maxSum = max(sumOfArray(array1), sumOfArray(array2)));

instead of jumping through hoops to achieve the same:

int sum1 = 0;
sumOfArray(array1, sum1);

int sum2 = 0;
sumOfArray(array2, sum2);

int maxSum = 0;
max(sum1, sum2, maxSum);

Hopefully this is a less contrived scenario illustrating why function composition is useful, and why it requires that the function returns its result instead of modifying an "out" variable.


问:
Placeholders in strings
I find that I sometimes use placeholders in strings, like this:

```<code>$ cat example-apache
<VirtualHost *:80>
    ServerName ##DOMAIN_NAME##
    ServerAlias www.##DOMAIN_NAME##
    DocumentRoot /var/www/##DOMAIN_NAME##/public_html
</VirtualHost>
</code>```

Now I am sure that it is a minor issue if the placeholder is ##DOMAIN_NAME##, !!DOMAIN_NAME!!, {{DOMAIN_NAME}}, or some other variant. However, I now need to standardize with other developers on a project, and we all have a vested interest in having our own placeholder format made standard in the organization. Are there any good reasons for choosing any of these, or others? I am trying to quantify these considerations:

Aesthetics and usability. For example, __dict__ may be hard to read as we don't know how many underscores are in there.

Compatibility. Will some language try to do something funny with {} syntax in a string (such as PHP does with "Welcome to {$siteName} today!")? Actually, I know that PHP and Python won't, but others? Will a C++ preprocessor choke on ## format? If I need to store the value in some SQL engine, will it not consider something a comment? Any other pitfalls to be wary of?

Maintainability. Will the new guy mistake ##SOME_PLACEHOLDER## as a language construct?

The unknown. Surely the wise folk here will think of other aspects of this decision that I have not thought of.

I might be bikeshedding this, but if there are real issues that might be lurking then I would certainly like to know about them before mandating that our developers adhere to a potentially-problematic convention.

答:
Take a look at some projects that you admire and follow their convention.

Don't make up something new, try to find out what a typical convention is and go with it.

Make sure to include a way to escape that character sequence so you can include it as a literal without it being interpreted as a token.

Title: Placeholders in strings


答:
You can make your function return something that is obviously a return value. It's also useful to send error message back to the UI when something fails.</p>

```<code>ReturnValue myFunction(object newValue)

class ReturnValue
{
    public bool Success {get;set;}
    public object OldValue {get;set;}
    public string Message {get;set;}
}
</code>```

Body:
You can make your function return something that is obviously a return value. It's also useful to send error message back to the UI when something fails.

ReturnValue myFunction(object newValue)

class ReturnValue
{
    public bool Success {get;set;}
    public object OldValue {get;set;}
    public string Message {get;set;}
}


答:
I use placeholders myself, and over the years have sedimented the following considerations, in descending priority:

absolutely no shell metacharacters, for I often use scripts. Avoid: $ < > ( ) { } |

no escape sequences: \

no regexp-risky characters, searching which could be an escape nightmare: . - * ? ' "

no common and mathematical operators: + - / *

This leaves few candidates: % : ^ # _ @    (where ^ and % are often operators and ought to be excluded).

Personally, I use the last three - # _ @

Language constructs would probably lead to eschew %, @ and ^ (even if @@@DOMAIN_NAME@@@ is a nice kick in the teeth: you can't miss it).

Using fixed length fonts, I use indifferently _ and #. Maybe I'm more inclined on __THIS_FORM__ which is even legal in C (danger Will Robinson! You might have C constants formatted like that!).

I think that # is a better choice if you have legibility issues. ###DOMAIN_NAME### looks pretty good and is unlikely to come by in any language I'm familiar with. And ###_DOMAIN_NAME_### is more complicated, but maybe more readable.

Of course in some specific domains you might actually want to ape some existing schemes (e.g. use shell metacharacters), either to make it clearer that those strings are really placeholders, or because you can leverage (with all due care) some tool to expand them: hence e.g. {{ varname }}, ${ varname }, $(varname) or [[ varname ]].

In scripts such as VirtualHosts, I tend to use @@@NAMES@@@... maybe I shouldn't have attempted to answer, since I'm unable to agree on one standard even with myself!

Title: Placeholders in strings

Body:
I find that I sometimes use placeholders in strings, like this:

```<code>$ cat example-apache
<VirtualHost *:80>
    ServerName ##DOMAIN_NAME##
    ServerAlias www.##DOMAIN_NAME##
    DocumentRoot /var/www/##DOMAIN_NAME##/public_html
</VirtualHost>
</code>```

Now I am sure that it is a minor issue if the placeholder is ##DOMAIN_NAME##, !!DOMAIN_NAME!!, {{DOMAIN_NAME}}, or some other variant. However, I now need to standardize with other developers on a project, and we all have a vested interest in having our own placeholder format made standard in the organization. Are there any good reasons for choosing any of these, or others? I am trying to quantify these considerations:

Aesthetics and usability. For example, __dict__ may be hard to read as we don't know how many underscores are in there.

Compatibility. Will some language try to do something funny with {} syntax in a string (such as PHP does with "Welcome to {$siteName} today!")? Actually, I know that PHP and Python won't, but others? Will a C++ preprocessor choke on ## format? If I need to store the value in some SQL engine, will it not consider something a comment? Any other pitfalls to be wary of?

Maintainability. Will the new guy mistake ##SOME_PLACEHOLDER## as a language construct?

The unknown. Surely the wise folk here will think of other aspects of this decision that I have not thought of.

I might be bikeshedding this, but if there are real issues that might be lurking then I would certainly like to know about them before mandating that our developers adhere to a potentially-problematic convention.


问:
How can I pull data from PeopleSoft on demand?
I work in IT at a university and I'm working with about 5 different departments to develop a new process for students to apply to a specific school within the university (not the university as a whole).  We're using a  web-based college application vendor and adding the applicant questions for the school itself to the main university application.  Currently the main application feeds into PeopleSoft.  The IT staff here is building a new table to hold just our school's applicant data.  I want to be able to access that data from PeopleSoft for use in external applications, but our IT staff doesn't really seem to understand what I'm requesting, as they simply tell me I can have access to the PS query tools.  The problem is, I don't want to run just ad hoc queries, I want to be able to connect from outside PeopleSoft and show current data within the external app.

I am unable to find documentation or get a clear answer to my question.  Does PeopleSoft support access via a web services API or anything similar, and does that sound like the right direction for me to take?

答:
PeopleSoft's Integration Broker has supported XML over HTTP for a good decade. As web services standardized, PeopleSoft's Integration Broker provided SOAP/WSDL based integrations, as well as plain text (allowing for JSON, CSV, or whatever). This has all been possible as of PeopleTools 8.42. PeopleTools 8.48 made web services based operations (WSDL, etc) easier. PeopleTools 8.52 delivered a REST listening connector. PeopleTools 8.53 delivered JSON support to the Documents module.

Query and direct database access aren't the only way. Customers have been building the types of integrations you require for a long time.


问:
Loose Coupling in Object Oriented Design
I am trying to learn GRASP and I found this explained (here on page 3) about Low Coupling and I was very surprised when I found this:

Consider the method addTrack for an Album class, two possible methods are:

addTrack( Track t )

and

addTrack( int no, String title, double duration )

Which method reduces coupling?
  The second one does, since the class using the Album class does not have to know a Track class.
  In general, parameters to methods should use base types (int, char ...) and classes from the java.* packages.

I tend to diasgree with this; I believe addTrack(Track t) is better than addTrack(int no, String title, double duration) due to various reasons:

It is always better for a method to as fewer parameters as possible (according to Uncle Bob's Clean Code none or one preferably, 2 in some cases and 3 in special cases; more than 3 needs refactoring - these are of course recommendations not holly rules).

If addTrack is a method of an interface, and the requirements need that a Track should have more information (say year or genre) then the interface needs to be changed and so that the method should supports another parameter.

Encapsulation is broke; if addTrack is in an interface, then it should not know the internals of the Track.

It is actually more coupled in the second way, with many parameters. Suppose the no parameter needs to be changed from int to long because there are more than MAX_INT tracks (or for whatever reason); then both the Track and the method need to be changed while if the method would be addTrack(Track track) only the Track would be changed.

All the 4 arguments are actually connected with each other, and some of them are consequences from others.

Which approach is better?

答:
Coupling is just one of many aspects to try to obtain in your code.  By reducing coupling, you're not necessarily improving your program.  In general, this is a best practice, but in this particular instance, why shouldn't Track be known?

By using a Track class to be passed to Album, you are making your code easier to read, but more importantly, as you mentioned, you're turning a static list of parameters into a dynamic object.  That ultimately makes your interface far more dynamic.

You mention that encapsulation is broke, but it is not.  Album must know the internals of Track, and if you did not use an object, Album would have to know each and every piece of information passed to it before it could make use of it all the same.  The caller must know the internals of Track as well, since it must construct a Track object, but the caller must know this information all the same if it were passed directly to the method.  In other words, if the advantage of encapsulation is not knowing an object's contents, it could not possibly be used in this case since Album must make use of Track's information just the same.

Where you wouldn't want to use Track is if Track contains internal logic that you wouldn't want the caller to have access to.  In other words, if Album were a class that a programmer using your library were to use, you wouldn't want him to use Track if you use it to say, call a method to persist it on the database.  The true problem with this lies in the fact that the interface is entangled with the model.

To fix the problem, you would need to separate Track into its interface components and its logic components, creating two separate classes.  To the caller, Track becomes a light class which is meant to hold information and offer minor optimizations (calculated data and/or default values).  Inside Album, you would use a class named TrackDAO to perform the heavy lifting associated with saving the information from Track to the database.

Of course, this is just an example.  I'm sure this is not your case at all, and so feel free to use Track guilt-free.  Just remember to keep your caller in mind when you're constructing classes and to create interfaces when required.


答:
I would argue that the second example method most likely increases coupling, since it most likely is instantiating a Track object and storing it in the current Album object.  (As suggested in my comment above, I would assume it to be inherent that an Album class would have the concept of a Track class somewhere inside it.)

The first example method assumes that a Track is getting instantiated outside the Album class, so at the very least, we can assume that the instantiation of the Track class is not coupled to the Album class.

If best practices suggested that we never have one class reference a second class, the entirety of object-oriented programming would be thrown out the window.

Title: Loose Coupling in Object Oriented Design

Body:
I am trying to learn GRASP and I found this explained (here on page 3) about Low Coupling and I was very surprised when I found this:

Consider the method addTrack for an Album class, two possible methods are:

addTrack( Track t )

and

addTrack( int no, String title, double duration )

Which method reduces coupling?
  The second one does, since the class using the Album class does not have to know a Track class.
  In general, parameters to methods should use base types (int, char ...) and classes from the java.* packages.

I tend to diasgree with this; I believe addTrack(Track t) is better than addTrack(int no, String title, double duration) due to various reasons:

It is always better for a method to as fewer parameters as possible (according to Uncle Bob's Clean Code none or one preferably, 2 in some cases and 3 in special cases; more than 3 needs refactoring - these are of course recommendations not holly rules).

If addTrack is a method of an interface, and the requirements need that a Track should have more information (say year or genre) then the interface needs to be changed and so that the method should supports another parameter.

Encapsulation is broke; if addTrack is in an interface, then it should not know the internals of the Track.

It is actually more coupled in the second way, with many parameters. Suppose the no parameter needs to be changed from int to long because there are more than MAX_INT tracks (or for whatever reason); then both the Track and the method need to be changed while if the method would be addTrack(Track track) only the Track would be changed.

All the 4 arguments are actually connected with each other, and some of them are consequences from others.

Which approach is better?


答:
My recommendation is:

Use

```<code>addTrack( ITrack t )
</code>```

but be sure that ITrack is an interface and not a concrete class.

Album doesn't know the internals of ITrack implementors. It's only coupled to the contract defined by the ITrack.

I think this is the solution that generates the least amount of coupling.

Body:
My recommendation is:

Use

addTrack( ITrack t )

but be sure that ITrack is an interface and not a concrete class.

Album doesn't know the internals of ITrack implementors. It's only coupled to the contract defined by the ITrack.

I think this is the solution that generates the least amount of coupling.


答:
One way is to think of it as an infinite sequence of random numbers:

```<code>IEnumerable<int> randomNumberGenerator = new RandomNumberGenerator(seed);
</code>```

That is, just think of it as a bottomless data structure, like a Stack where you can only call Pop, but you can call it forever.  Like a normal immutable stack, taking one off the top gives you another (different) stack.

So an immutable (with lazy evaluation) random number generator might look like:

```<code>class RandomNumberGenerator
{
    private readonly int nextSeed;
    private RandomNumberGenerator next;

    public RandomNumberGenerator(int seed)
    {
        this.nextSeed = this.generateNewSeed(seed);
        this.RandomNumber = this.generateRandomNumberBasedOnSeed(seed);
    }

    public int RandomNumber { get; private set; }

    public RandomNumberGenerator Next
    {
        get
        {
            if(this.next == null) this.next = new RandomNumberGenerator(this.nextSeed);
            return this.next;
        }
    }

    private static int generateNewSeed(int seed)
    {
        //...
    }

    private static int generateRandomNumberBasedOnSeed(int seed)
    {
        //...
    }
}
</code>```

That's functional.

Body:
One way is to think of it as an infinite sequence of random numbers:

IEnumerable<int> randomNumberGenerator = new RandomNumberGenerator(seed);

That is, just think of it as a bottomless data structure, like a Stack where you can only call Pop, but you can call it forever.  Like a normal immutable stack, taking one off the top gives you another (different) stack.

So an immutable (with lazy evaluation) random number generator might look like:

class RandomNumberGenerator
{
    private readonly int nextSeed;
    private RandomNumberGenerator next;

    public RandomNumberGenerator(int seed)
    {
        this.nextSeed = this.generateNewSeed(seed);
        this.RandomNumber = this.generateRandomNumberBasedOnSeed(seed);
    }

    public int RandomNumber { get; private set; }

    public RandomNumberGenerator Next
    {
        get
        {
            if(this.next == null) this.next = new RandomNumberGenerator(this.nextSeed);
            return this.next;
        }
    }

    private static int generateNewSeed(int seed)
    {
        //...
    }

    private static int generateRandomNumberBasedOnSeed(int seed)
    {
        //...
    }
}

That's functional.