答:
The bottom line is my brain has been wired to think about Objects, Encapsulation, Polymorphism, etc.. and I cant seem to wrap my head around anything else. How can I practice?

The biggest – if not the only – difference between procedural programming and object-oriented programming is the notion of inheritance.¹  For instance, it is straightforward to implement a polymorphic list type in C, but translating inheritance relations would involve a lot of work. As long as no inheritance relations are involved, writing

```<code>Car myCar;
myCar.start();
</code>```

in C++ is just a fancy way to write

```<code>Car myCar = car_construct();
car_start(myCar);
</code>```

in C.  So in procedural programming, you solve problems by defining data structures and treatments on these data structures, and this works pretty similarly as in OO-languages, except that you cannot use inheritance-based abstractions.²

If you want to progress in procedural programming, I would suggest studying programs written by others and writing similar programs yourselves.  You will learn a lot by comparing your solution to the other and asking yourself how important the differences are. Reading and writing shell scripts is probably a good step
to learn procedural programming, because this is a competence which is also useful on its own. You typically find a lot of scripts bundled with your operating system – and can find good quality scripts randomly on the internet.

It is also worth to note that one of the few³ widespread, of significant complexity and virtually bug-free program ever was written in a procedural language.  The program I think of is TeX which was written in a Pascal-like language, and the code source is described extensively in a book TeX: the program which you could consider reading. It is easy to legally find or produce electronic copies of the book, and the nearest scientific campus will have a hardcopy in its library.

¹ Which you do not mention on your question!

² Inheritance is great to solve software engineering problems but it does not solve any practical problem. So in view of the problem solved by the software, inheritance solves meta problems.

³ I actually do not know another one!

Title: Structuring Procedural vs OO code

Body:
The bottom line is my brain has been wired to think about Objects, Encapsulation, Polymorphism, etc.. and I cant seem to wrap my head around anything else. How can I practice?

The biggest – if not the only – difference between procedural programming and object-oriented programming is the notion of inheritance.¹  For instance, it is straightforward to implement a polymorphic list type in C, but translating inheritance relations would involve a lot of work. As long as no inheritance relations are involved, writing

Car myCar;
myCar.start();

in C++ is just a fancy way to write

Car myCar = car_construct();
car_start(myCar);

in C.  So in procedural programming, you solve problems by defining data structures and treatments on these data structures, and this works pretty similarly as in OO-languages, except that you cannot use inheritance-based abstractions.²

If you want to progress in procedural programming, I would suggest studying programs written by others and writing similar programs yourselves.  You will learn a lot by comparing your solution to the other and asking yourself how important the differences are. Reading and writing shell scripts is probably a good step
to learn procedural programming, because this is a competence which is also useful on its own. You typically find a lot of scripts bundled with your operating system – and can find good quality scripts randomly on the internet.

It is also worth to note that one of the few³ widespread, of significant complexity and virtually bug-free program ever was written in a procedural language.  The program I think of is TeX which was written in a Pascal-like language, and the code source is described extensively in a book TeX: the program which you could consider reading. It is easy to legally find or produce electronic copies of the book, and the nearest scientific campus will have a hardcopy in its library.

¹ Which you do not mention on your question!

² Inheritance is great to solve software engineering problems but it does not solve any practical problem. So in view of the problem solved by the software, inheritance solves meta problems.

³ I actually do not know another one!


问:
Role-based REST API?
I'm building a REST API for which several users with different roles will have access to the resources it contains.

To keep the scope simple let's take the "student/teacher/class" domain:

GET /students is the resource to access.

Users might have roles like Student and/or Teacher

Students will only have access to students of their classes. Teachers will have access to students of the classes they teach. Some uses may be a student AND teach other classes too. They must have access to the students of their classes AND the students of the classes they teach.

Ideally I want to implement this as two functions - one per role and then "union" if a user have multiple roles.

My question is: Which pattern should I use for implementing this?

Externally

Should I split up my API per role? GET /teacher/students and GET /student/students It doesn't seems right to me.

Keep it all I'm one resource (preferred)

Internally

How should it be implemented internally?

Should every method start with a BIG switch/if per role?

Should I implement a repository per role?

Is there a design pattern that will help me in achieving this?

As a side comment: I'm using ASP.NET Web API and Entity Framework 6, but it really doesn't matter for the conceptual implementation.

答:
Find a pen and a paper and start modelling your system.

You will find that you probably need a domain entity called PERSON. Since both STUDENTS and TEACHER "is-a" PERSON, you could create an abstract entity called PERSON with generic attributes like firstname, lastname, etc. A TEACHER -> is-a -> Person. Now you can try to find characteristics for a TEACHER that doesn't apply to STUDENTS; e.g. A TEACHER teaches CLASS(es) regarding one or more SUBJECT(s).

Enforcing security is considered a non-functional aspect of your application. It is a cross-cutting concern that should be handled outside of your "business logic". As @Robert Munn points out, the ROLE(s) should all be maintained in one place. Using roles to limit access to certain functions is rather coarse-grained, and the concept is called role-based access control (RBAC).

To verify whether or not a teacher should be allowed to see a students grades, should to be expressed in your domain model. Say a teacher has a class on the subject programming. You would probably express in your model that students  attends classes for different subjects. This is where the application/business logic kicks in. This is logic that you can verify using test-driven development.

You should split your resources to make your application testable and modular.

Anyway, the best way to really show what I mean is to show it with code :) Here is a GitHub page: https://github.com/thomasandersen77/role-based-rest-api

Good luck :)

ContentLicense: CC BY-SA 3.0

Title: Role-based REST API?


问:
Keeping lists of Objects, some with, some without inheritance
Let's say I have two classes, Foo and ExtendedFoo where ExtendedFoo inherits from Foo. Foo has a method .getValue() which returns a number, ExtendedFoo also has .increaseValue() which adds to the stored value (Of course, in this example, what they do is completely arbitrary). What I may want to do, is keep track of several objects from each class, and for all ExtendedFoo Objects, run .increaseValue() and then print out what is returned from .getValue() from every Object.

The way I'd do it, would be something like the following:

```<code>private ArrayList<Foo> foos;
private ArrayList<ExtendedFoo> eFoos;

public static void main(String [] args) {
    foos = new ArrayList<Foo>();
    eFoos = new ArrayList<ExtendedFoo>();

    // ...
}

public void addFoo(Foo f) {
    foos.add(f);
}

public void addExtendedFoo(ExtendedFoo f) {
    eFoos.add(f);
    foos.add(f);
}

public void updateAndPrint() {
    for(ExtendedFoo ef : eFoos) {
        ef.increaseValue();
    }
    for(Foo f: foos) {
        System.out.println(f.getValue());
    }
}
</code>```

Of course, the obvious problems with this are that the programmer could end up accidentally calling addFoo() and addExtendedFoo() without realising the real purpose. If I wasn't to include the foos.add(f) call to addExtendedFoo() then it could go the other way.

What way would you go about this to be as safe as possible?

答:
It sounds like the reason you inherit ExtendedFoo from Foo is just to reuse the method getValue(), seem like a "smell" to me. You might want to reconsider whether it's a true inheritance relationship. Inheritance should not be abused just to reuse some methods.

In case you still want to go with this design, why don't use instanceof, e.g.:

there's only one list and one way to add both Foo and ExtendedFoo

```<code>private ArrayList<Foo> foos;

public static void main(String [] args) {
    foos = new ArrayList<Foo>();

    // ...
}

public void addFoo(Foo f) {
    foos.add(f);
}

public void updateAndPrint() {
    for(Foo f: foos) {
        if(f instanceof ExtendedFoo) {
            f.increaseValue();
        }
    }

    for(Foo f: foos) {
        System.out.println(f.getValue());
    }
}
</code>```

Body:
It sounds like the reason you inherit ExtendedFoo from Foo is just to reuse the method getValue(), seem like a "smell" to me. You might want to reconsider whether it's a true inheritance relationship. Inheritance should not be abused just to reuse some methods.

In case you still want to go with this design, why don't use instanceof, e.g.:

there's only one list and one way to add both Foo and ExtendedFoo

private ArrayList<Foo> foos;

public static void main(String [] args) {
    foos = new ArrayList<Foo>();

    // ...
}

public void addFoo(Foo f) {
    foos.add(f);
}

public void updateAndPrint() {
    for(Foo f: foos) {
        if(f instanceof ExtendedFoo) {
            f.increaseValue();
        }
    }

    for(Foo f: foos) {
        System.out.println(f.getValue());
    }
}


问:
Average number of comparison for sort algorithms
I need to write different sort algorithms such as

bubbleSort

insertionSort

selectionSort

quickSort

mergeSort

And measure how many average comparison does each one for N number (averaging between N! tests). But I need some final results to compare my program results.

Is there any table giving the average of comparisons of these algorithms for a few N numbers?

This is what I have got for average of array length 10:

```<code>    Selection sort: 63
    Bubble sort: 49.4144
    Insertion sort: 31.5
    Merge sort: 31.6667
    Quick sort: 30.7706
</code>```

答:
Is there any table giving the average of comparisons of these algorithms for a few N numbers

The exact number of comparisons needed may depend on the specific implementation of the algorithm, not on the algorithm itself, and so will the average number. So even if you find something like what you requested, I find it very unlikely that you can compare it directly to your implementation of the algorithms.


问:
provability of while loop vs for loop
I have this teacher, he's quite smart (sometimes, haha) he said good programmers try to use while loops instead of for loops. the reason he gave for this is because while loops can be proven, as in, one can completely explain what happens in a while loop whereas you can't do that for a for loop. he also said something about NASA programmers only using while loops and not allowed to do for loops because of this.

I have quite a hard time understand this, for both loops one can explain how they work in detail right? for both you would always know what is going to happen?

can someone explain to me why while loops can be proven (And because of it, might be better than for loops, in some cases at least).

EDIT:

maybe he was reffering to:

2: All loops must have a fixed upper bound. It must be trivially possible for a checking tool to statically prove that a preset upper bound on the number of iterations of a loop cannot be exceeded. If the loop-bound cannot be proven statically, the rule is considered violated.

Though this still doesn't say anything about the difference between while and for loops.

答:
I would like to say that in reality, there is no difference .Your question is irrelevant.
May be your teacher might have meant to use while-loop when no. of iterations is not known beforehand.In many cases we need to use a while loop to extract digits of a no. when the user enters the no. which can be of any length. Technically speaking, the similarity between for & while loop is that both are entry-controlled loops wherein the (test-expression/condition) is evaluted before entering into the loop body.This is the distinction between while & do-while loops.</p>

Title: provability of while loop vs for loop


问:
One symbol - one meaning?
It's well known recomendations that:

1) class or function should have one responsibility

2) variable should not be reused in different contexts

We can generalize this recomendations to general rule:

Symbol should have one meaning.

Then, for example in crossplatform development is often used similar code:

```<code>#ifdef _WIN32

    class CFoo {
        /* ... */
    };

#elif _LINUX

    class CFoo {
        /* ... */
    };

#endif
</code>```

With this code, when you later refer to CFoo, it can have three meanings:

CFoo as Win32 platform specific class

CFoo as Linux platform specific class

CFoo as crossplatform class

So, when you use CFoo symbol somewhere, its not exactly clear which CFoo it is.

Violates similar code "essence" of recomendations 1) or 2) ?

答:
A question about the word "meaning" should not be discussed in meaningless terms like CFoo.

Lets make a better example:

```<code>#ifdef _WIN32
    class MyUsbDriver {
        /* ... a public API to access a special USB devcice.. */
        /* ... internal implementation: Windows sepecific.. */
    };
#elif _LINUX
    class MyUsbDriver {
        /* ... exactly the same API as in the WIN32 version.. */
        /* ... internal implementation: Linux sepecific.. */
    };
#endif
</code>```

That way you create an abstraction for an Usb-Driver, so for the code actually using that class both variants have the same meaning - from that point of view. Ideally, for the calling code, there should be no visible difference between the two classes.

Note that in C++, you have much better means for creating such abstractions than using the preprocessor. For such a situation it would probably be preferable to make MyUsbDriver an abstract interface class, with derived classes MyUsbDriverWin32 and MyUsbDriverLinux. However, you will probably have to encapsulate those two derived classes in #ifdef blocks, since otherwise you might not be able to compile each class in the environment it was not designed for.

What you should avoid is something like

```<code>#ifdef _WIN32
    class MyUsbDriver {
        /* ... a public API to access a special USB devcice.. */
    };
#elif _LINUX
    class MyUsbDriver {
        /* ... a completely different API as in the WIN32 version.. */
        /* ... or (worse): a similar looking API, with a different behaviour  */
    };
#endif
</code>```

that would be somehow similar to "reusing the same variable in different contexts twice".

Title: One symbol - one meaning?

Body:
A question about the word "meaning" should not be discussed in meaningless terms like CFoo.

Lets make a better example:

#ifdef _WIN32
    class MyUsbDriver {
        /* ... a public API to access a special USB devcice.. */
        /* ... internal implementation: Windows sepecific.. */
    };
#elif _LINUX
    class MyUsbDriver {
        /* ... exactly the same API as in the WIN32 version.. */
        /* ... internal implementation: Linux sepecific.. */
    };
#endif

That way you create an abstraction for an Usb-Driver, so for the code actually using that class both variants have the same meaning - from that point of view. Ideally, for the calling code, there should be no visible difference between the two classes.

Note that in C++, you have much better means for creating such abstractions than using the preprocessor. For such a situation it would probably be preferable to make MyUsbDriver an abstract interface class, with derived classes MyUsbDriverWin32 and MyUsbDriverLinux. However, you will probably have to encapsulate those two derived classes in #ifdef blocks, since otherwise you might not be able to compile each class in the environment it was not designed for.

What you should avoid is something like

#ifdef _WIN32
    class MyUsbDriver {
        /* ... a public API to access a special USB devcice.. */
    };
#elif _LINUX
    class MyUsbDriver {
        /* ... a completely different API as in the WIN32 version.. */
        /* ... or (worse): a similar looking API, with a different behaviour  */
    };
#endif

that would be somehow similar to "reusing the same variable in different contexts twice".


问:
Why is there no 'finally' construct in C++?
Exception handling in C++ is limited to try/throw/catch. Unlike Object Pascal, Java, C# and Python, even in C++ 11, the finally construct has not been implemented.

I have seen an awful lot of C++ literature discussing "exception safe code". Lippman writes that exception safe code is an important but advanced, difficult topic, beyond the scope of his Primer - which seems to imply that safe code is not fundamental to C++. Herb Sutter devotes 10 chapters to the topic in his Exceptional C++ !

Yet it seems to me that many of the problems encountered when attempting to write "exception safe code" could be quite well solved if the finally construct was implemented, allowing the programmer to ensure that even in the event of an exception, the program can be restored to a safe, stable, leak-free state, close to the point of allocation of resources and potentially problematic code. As a very experienced Delphi and C# programmer I use try.. finally blocks quite extensively in my code, as do most programmers in these languages.

Considering all the 'bells and whistles' implemented in C++ 11, I was astonished to find that 'finally' was still not there.

So, why has the finally construct never been implemented in C++? It's really not a very difficult or advanced concept to grasp and goes a long ways towards helping the programmer to write 'exception safe code'.

答:
Well, you could sort of roll-your-own finally, using Lambdas, which would get the following to compile fine (using an example without RAII of course, not the nicest piece of code):

```<code>{
    FILE *file = fopen("test","w");

    finally close_the_file([&]{
        cout << "We're closing the file in a pseudo-finally clause." << endl;
        fclose(file);
    });
}
</code>```

See this article.

Body:
Well, you could sort of roll-your-own finally, using Lambdas, which would get the following to compile fine (using an example without RAII of course, not the nicest piece of code):

{
    FILE *file = fopen("test","w");

    finally close_the_file([&]{
        cout << "We're closing the file in a pseudo-finally clause." << endl;
        fclose(file);
    });
}

See this article.


问:
Learning to Program in Assembly - Useful Resources
Following on from a previous thread, it has got me interested in learning a little about Assembly programming.  Not so much for wanting to program useful apps in, just to get a feel for low level programming to better understand what is happening.

Can anybody recommend any books or online resources for beginners?

Thanks.

答:
Is this an academic exercise, or are you intending to use the assembly language you learn? This is pretty specialized stuff, these days. Compiler optimization has become so good, that even something like a high performance hard disk drive would typically have around 1% of its code base written in assembler. Going way down the food chain to 4bit or some 8bit processors you'll see much more assembly language being used.

If you really want to have a go at assembly language, pick a processor that has a nice instruction set. I'm a former ARM employee so I'm probably biased, but I found that the ARM instruction set was particularly easy to learn - I was able to write an efficient FIR filter in asm on my third day at the company. ARM's semiconductor partners are shipping about a billion ARM cores per quarter these days, so it is pretty easy to find a company that is willing to use your ARM ASM expertise.

There are plenty of ARM eval boards available for around $50 to try your code out on - it looks like ARM Cortex M3 is going to be immensely popular. It uses ARM's Thumb2 instruction set, which is a little more obscure than plain ol' ARM32 code, but still pretty easy, and very powerful.

This little board looks very cool, for 80 euros: http://www.olimex.com/dev/stm32-103stk.html

ContentLicense: CC BY-SA 2.5


问:
In C++, should I ever declare a local variable in the corresponding header?
So for example, I create a class with two functions:

foo.h

```<code>class foo
{
public:
    foo();
    void bar();
    void ey();
    bool m_memberBool;
    bool localBool; // ??? Should I put this here?
};
</code>```

foo.cpp

```<code>#include "foo.h"

foo::foo() {
    bool m_memberBool = true;
}
void foo::bar() {
    bool localBool = true;
    if (localBool && m_memberBool) {
        ey();
    }
}
void foo::ey() {
    m_memberBool = false;
}
</code>```

Should I ever include that local variable, or any local variable ever in a header? If not, should I ever document it in the header?

答:
Technically, the correct answer to your question is that it's a contradiction in terms. As soon as you raise a variable into the class definition, it is no longer a local variable, it is a member variable.

But I assume you're asking whether or not there's ever a good reason to raise a local variable up into member variable status. This question comes down to the purpose of your class and that variable.

The general rule of thumb is: all variables should be declared in the narrowest possible scope. In other words, do not declare it where all of foo can use it if only foo::bar needs to use it. It's generally a bad idea for code to have access to variables it doesn't actually need, because that increases the risk that they will eventually depend or rely on those variables having certain values at certain times, which couples them to all the other code using those variables, making it harder to change one part without breaking others.

Do the other methods of foo actually need to access this bool? If not, keep it local. You can always raise it later if a good reason presents itself.


问:
Should I consider uncertain future requirement while development?
I have one text box across multiple pages which is used to enter multiple customerids (as comma separated) . But in current page due to some subsequent implementation difficulties we make it as customerid so that user can enter only one customer not multiple customerids as comma separated.

But coding styles and naming of variables across all pages are same since we are assuming that multiple customerids could be entered in future.

we are having array instead of string to store customerid as given below:

```<code>customerIds.push(tbxval);
</code>```

whereas customerids array always having only one element inside that as of now in that particular page.

I guess if that future requirement not asked from product owner, this code could make some problem or at least until that requirements comes.

But I'm not sure what kind of negative or positive impact it could make.

答:
If we interpret this question in its most general sense, the proposed duplicate question has perhaps the best answer you could ever get:

Too often when you try to design for the future, your predictions
  about future needs turn out to be wrong. It's usually better to
  refactor when you actually know how the needs have changed than to
  overdesign your system on day one. At the same time, don't shoot
  yourself in the foot, either. There's certainly a middle ground, and
  knowing where that is is more art than science.

To boil it down to one rule of thumb: less is more.

But we can expand on this a bit. There's a big difference between trying to predict the future, and actually knowing the future.

It is important for developers to be aware of the long-term vision of the product because once in a while, you really do know for sure that you will need to do X at some point in the future. For instance, I know that our application will have to support color themes someday, so I try to avoid relying on the current default color values as much as possible. But I haven't written any code to change the default colors, because we won't need it for a very long time, and I have no idea how exactly we'll want it to work. We also knew from the start that our application would need internationalization, so we (mostly) kept user-facing strings and "code-only" strings clearly separated from day one, even when we didn't have a system for translating the user-facing ones yet.

In your example, it's not clear whether dealing with an array instead of a single number would result in you writing additional code you don't need yet, or just slightly different code. It's also not clear whether you know you'll need this in the future or if you're just guessing. Only you and your product manager can answer that. If the odds are high that you will need arrays, and using arrays doesn't make the code significantly more complicated right now, then it's probably a good idea to start using arrays early.

The only time it might be worth trying to predict the future and be more generic than necessary is when you're designing an API, schema or file format that needs to be backwards compatible. For example, if you have a web service API with a method getPublicUserStats(), making it only accept a single user id instead of an array is needlessly restrictive, even if you only need one at a time right now. But you shouldn't go out of your way to optimize for requests with a thousand user ids until you actually have a performance issue.


问:
How do you organize your usability testings?

What is your process?

How do you get feedback?

What software do you use? (like Morae from TechSmith)

Who does them?

Have you measured how it positively affected the quality of your software?

I'm looking for your experience on the subject. This is something I want to improve.

答:
I use a pair process, in order to capture natural conversations.

After giving your subjects a questionnaire for background, set them in front of a machine in a natural office environment and give them a task to perform. My work covers programming tools, so the subjects do pair programming, but the pair approach can work for other programs just as well. The advantage of using pairs is that they will ask each other questions and try to work out the instructions together.

Using pairs is more natural than the common "think out loud" approach, where you tell subjects to say what they are thinking. The problem with that approach is that you won't as easily capture the metaphor that subjects use, which gives you insight into their thinking. E.g., for a compiler tool, "Oh, why is it showing that?", "Hmm, I guess it's like when you are finding a match, but enter the wrong directory?" The trick is that when subjects have to explain their confusion to each other they will have a good reason to make an honest effort.

I use Camtasia with microphones to capture what's on the screen and what they say. I then transcribe the session and annotate with particular actions that happened on-screen. [Camtasia is from TechSmith, the makers of Morae.] You may wish to use a camera to capture the subjects and see where they point their fingers. Going over the transcripts is much more helpful when you are trying to write up what the result might be. [Further: The writing up process itself is helpful to get you to ask the right questions, even if you aren't looking to publish your results.]

After they perform the task, ask them to describe their experience, what they think they would use the program for, what they liked, and what they would like to see improved. Getting this feedback isn't necessarily so that you take their literal suggestions to go implement them. Rather, look deeper to see what their expectations were, and if they were conceptualizing the program differently than you intended; again, to see what metaphors they used.

Also, look at the performance of the task itself. Did they accomplish what they were supposed to? Based on what program you are testing, you may want to time how long specific tasks took them.

Start with a pilot test with what you believe to be a very basic task. You'd be surprised to find that even the simple tasks will take longer than you thought they might. Thus far, I've used what I've gained to change the syntax in my tool, and tweak some features here and there. But the biggest gains I've found is in how I write the tutorial and frame the tool.


问:
Down Sides to Using Properties as Opposed to Method Variables
I am debating the pros and cons of a couple of utility classes I have. The classes have a couple of properties which are set prior to calling the class methods. However, I was wondering if there are any cons to this approach rather than sending a variable along with the method call? There are typically only one or two methods in these classes.

Thank you.

答:
If I'm reading the question correctly, you're asking whether to use

```<code>obj.Foo(bar);
</code>```

or

```<code>obj.Bar = x;
obj.Foo();
</code>```

Most of the time, the former is better, because it makes it much clearer that bar is required for the Foo() operation, it makes it impossible (in a statically typed language) to forget to provide a bar value, and it makes the behavior of Foo() easier to reason about when each call only depends on its parameters and not the "state of the world" at the time it was called.

Body:
If I'm reading the question correctly, you're asking whether to use

obj.Foo(bar);

or

obj.Bar = x;
obj.Foo();

Most of the time, the former is better, because it makes it much clearer that bar is required for the Foo() operation, it makes it impossible (in a statically typed language) to forget to provide a bar value, and it makes the behavior of Foo() easier to reason about when each call only depends on its parameters and not the "state of the world" at the time it was called.


问:
How can I avoid an SDK requirement for an end-user unless he uses a specific function?
One of the modes of my program uses Microsoft Kinect but the user may never decide use that mode. I want to make it so the libraries for that functionality are only looked for and loaded if he uses that mode of the program as opposed to it throwing an error because the kinect end-user runtime library (or whatever it's called) is not installed when the program is first opened. Is that possible in C#? If so, how is that done?

答:
We do this all the time on our software. All you need to do is make sure all of the references to that library are in a different class that is only ever called when the option is enabled. I think you also need to have your classes in a separate .cs file so that the using statements are also isolated. (I don't know for certain since we keep all our classes in separate files by policy.)

```<code>public class Application {
    public void InitOptions {
        if(optionWithThirdPartyDependency) {
            OptionalFunctionality.InitFeature();
        }
    }
}
</code>```

In a different .cs file....

```<code>using ThirdPartyLibrary

public class OptionalFunctionality {
    public static void InitFeature() {
        <init the feature using ThirdPartyLibrary>
    }
}
</code>```

Body:
We do this all the time on our software. All you need to do is make sure all of the references to that library are in a different class that is only ever called when the option is enabled. I think you also need to have your classes in a separate .cs file so that the using statements are also isolated. (I don't know for certain since we keep all our classes in separate files by policy.)

public class Application {
    public void InitOptions {
        if(optionWithThirdPartyDependency) {
            OptionalFunctionality.InitFeature();
        }
    }
}

In a different .cs file....

using ThirdPartyLibrary

public class OptionalFunctionality {
    public static void InitFeature() {
        <init the feature using ThirdPartyLibrary>
    }
}


答:
Should I ever include that local variable, or any local variable ever in a header?

The only case I can think of is if you write an inline or a template function: For those, the function/method body should be in the header. Then, obviously, local variables are in the header, too.

If not, should I ever document it in the header?

There might be rare instances when a caller must know about a local variable of a function. E.g. if stack space is scarce and the function uses a 100k local array variable. Or if it's a template function that non-obviously creates an instance of its template parameter - that information might be important to the caller.

But those are extreme and construed edge cases. In the general case, the header should only document the external "contract" your functions offer, behavior that the caller can rely on even in future versions of the code.

I guess another way to ask this, is if a variable that I am using is only used in one function; should I always just make it a local variable, or are there cases where that variable should be made a member?

As @Brandin said: You would make it a member, if you the need to preserve state between different calls.

However, it might be a cleaner design to split that member and function off into a separate class, and have a member of that class instead:

```<code>class BarState
{
private:
    bool localFlag;
public:
    void Bar();
    // or even:
    void operator()();
};

class Foo
{
    BarState bar;
};
</code>```

That way it's clear that:

the "function" Bar retains state between calls

the member localFlag is meant to be private to Bar

Title: In C++, should I ever declare a local variable in the corresponding header?

Body:
So for example, I create a class with two functions:

foo.h

```<code>class foo
{
public:
    foo();
    void bar();
    void ey();
    bool m_memberBool;
    bool localBool; // ??? Should I put this here?
};
</code>```

foo.cpp

```<code>#include "foo.h"

foo::foo() {
    bool m_memberBool = true;
}
void foo::bar() {
    bool localBool = true;
    if (localBool && m_memberBool) {
        ey();
    }
}
void foo::ey() {
    m_memberBool = false;
}
</code>```

Should I ever include that local variable, or any local variable ever in a header? If not, should I ever document it in the header?

Body:
Should I ever include that local variable, or any local variable ever in a header?

The only case I can think of is if you write an inline or a template function: For those, the function/method body should be in the header. Then, obviously, local variables are in the header, too.

If not, should I ever document it in the header?

There might be rare instances when a caller must know about a local variable of a function. E.g. if stack space is scarce and the function uses a 100k local array variable. Or if it's a template function that non-obviously creates an instance of its template parameter - that information might be important to the caller.

But those are extreme and construed edge cases. In the general case, the header should only document the external "contract" your functions offer, behavior that the caller can rely on even in future versions of the code.

I guess another way to ask this, is if a variable that I am using is only used in one function; should I always just make it a local variable, or are there cases where that variable should be made a member?

As @Brandin said: You would make it a member, if you the need to preserve state between different calls.

However, it might be a cleaner design to split that member and function off into a separate class, and have a member of that class instead:

class BarState
{
private:
    bool localFlag;
public:
    void Bar();
    // or even:
    void operator()();
};

class Foo
{
    BarState bar;
};

That way it's clear that:

the "function" Bar retains state between calls

the member localFlag is meant to be private to Bar


问:
Sharing info objects between objects?
I'm making a game and I have several cards that are created during the game. Each card needs some info, which is shared between cards of the same type.

So I have a class CardInfo, which holds a name among other things. Now I'm looking for the best way to get the existing CardInfo based on the name, or if none yet exists it is created at that time.

I currently tried two ways, which are quite the same.

First I had a CardInfoManager, which held a list of all known CardInfo, and when asked for one, it checked if it had one, and returned that or created a new one if none existed. I have this as a fully static class, and as a singleton with an Instance method.

I also made an alternative, in which my CardInfoManager (the static version) is basically inside my CardInfo class. So CardInfo had a ByName method, which then checked a static list in CardInfo. This is nice because I can then make the cosntructor private, making sure the info is never created elsewhere.

So I was wondering, what is the best way of doing it? Is there a good pattern for this kind of functionality?

I'm working in c#.

答:
To get an object by name, put your objects into a Dictionary.

```<code>var dict = new Dictionary<string, CardInfo>();
</code>```

There are a number of ways to add the CardInfo objects to the dictionary. Here's one:

```<code>dict.Add("cardname", new CardInfo { foo = 1, bar = 2 });
</code>```

You retrieve them like this:

```<code>var cardInfo = dict.Item("cardname");
</code>```

or

```<code>var cardInfo = dict["cardname"];
</code>```

Further Reading

Dictionary<TKey, TValue> Class

Title: Sharing info objects between objects?

Body:
To get an object by name, put your objects into a Dictionary.

var dict = new Dictionary<string, CardInfo>();

There are a number of ways to add the CardInfo objects to the dictionary. Here's one:

dict.Add("cardname", new CardInfo { foo = 1, bar = 2 });

You retrieve them like this:

var cardInfo = dict.Item("cardname");

or

var cardInfo = dict["cardname"];

Further Reading

Dictionary<TKey, TValue> Class


答:
I agree with Robert's suggestion for using Dictionary as a classic lookup for memory based collections.

On the point of the singleton.  Use singletons for resource contention ,performance and context
If you feel your application might create many instance of cardInfo over and over again and you can manage a singleton safely, then use it.
Consider the multiple thread issue when using singletons.

Title: Sharing info objects between objects?

Body:
I'm making a game and I have several cards that are created during the game. Each card needs some info, which is shared between cards of the same type.

So I have a class CardInfo, which holds a name among other things. Now I'm looking for the best way to get the existing CardInfo based on the name, or if none yet exists it is created at that time.

I currently tried two ways, which are quite the same.

First I had a CardInfoManager, which held a list of all known CardInfo, and when asked for one, it checked if it had one, and returned that or created a new one if none existed. I have this as a fully static class, and as a singleton with an Instance method.

I also made an alternative, in which my CardInfoManager (the static version) is basically inside my CardInfo class. So CardInfo had a ByName method, which then checked a static list in CardInfo. This is nice because I can then make the cosntructor private, making sure the info is never created elsewhere.

So I was wondering, what is the best way of doing it? Is there a good pattern for this kind of functionality?

I'm working in c#.


问:
If Scala runs on the JVM, how can Scala do things that Java seemingly cannot?
I just learned about Scala yesterday, and I'd like to learn more about it. One thing that came to mind, however, from reading the Scala website is that if Scala runs on the JVM, then how is it possible for bytecode compiled from Scala source to be able to achieve things that Java can't readily do, such as (but not limited to) reified generics?

I understand that the compiler is what generates the bytecode; so as long as the compiler can massage source code into valid bytecode supported by the JVM, then both should be equivalent. But I was under the impression that Java couldn't even reify its own generics, so how could another compiler be able to pull this off?

答:
"All" programming languages run on x86, so how can they be much different from each other?

Brainfuck and Haskell are both Turing complete, so they can both do the exact same tasks.

There's a bit of room for syntax changes, syntax sugar and compiler magic in between. You can do quite a lot in there, but there is always a limit. In your case, it's JVM byte code.

If Java can produce the same byte code as Scala, they are equivalent. It could, however, be the case that a new feature in the JVM gets implemented in only Scala. Very unlikely, but possible.


答:
JVM bytecode pretends to be a kind of generic machine code, and it is indeed, so... what makes you think it couldn't support any other language? JVM bytecode is a Turing complete language, and thus, every program, no matter in which language is written, can be compiled/translated into bytecode.

There are a lot of languages which already have a bytecode compiler (e.g. Jython for Python and JRuby for Ruby) and there are also quite different from Java.

Note that technically, every Turing complete programming language can be compiled into another. It could be possible to compile JS to C or Ruby to Python, for example.

Title: If Scala runs on the JVM, how can Scala do things that Java seemingly cannot?

Body:
I just learned about Scala yesterday, and I'd like to learn more about it. One thing that came to mind, however, from reading the Scala website is that if Scala runs on the JVM, then how is it possible for bytecode compiled from Scala source to be able to achieve things that Java can't readily do, such as (but not limited to) reified generics?

I understand that the compiler is what generates the bytecode; so as long as the compiler can massage source code into valid bytecode supported by the JVM, then both should be equivalent. But I was under the impression that Java couldn't even reify its own generics, so how could another compiler be able to pull this off?


问:
C#/.NET multithreaded application design
The application to be designed serves as a bridge between two different systems.

One natively speaks TCP (RS232 actually, but there's a COM->ETH server in the line of communication) - the other one is an ERP system (able to talk through web services).

So in a picture it would look like that:

||device|| <----TCP----> ||my application|| <----WCF----> ||ERP||

Now as a web developer I never had much to do with threads (changed a bit with MVC and Tasks but still...).

Now I am challenged with a proper "server" design.

I already realized while(true) with a Sleep inside is probably not the smartest choice. Been there, done that..

From what I have read so far I need something that blocks. Like Console.ReadKey() only that I don't want to run this as a console application. It should run as a service in the background (Windows Service for example).

I had a look at the consumer/producer pattern using a BlockingCollection which is pretty neat. I now have my producer (WCF server) which triggers creation of consumers.

My question now is... how do I - from my WCF self host (=producer) - access my multiple consumer instances? I need to query their internal state and also I need to be able to destroy single consumer instances if they become stuck - it happens.

OperationsManager:

```<code>using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using WindowsService2.Producer;

namespace WindowsService2
{
    internal class OperationsManager
    {
        private CancellationTokenSource _cts;
        private List<Task> _tasks;
        private ILogger _logger;

        internal OperationsManager()
        {
            _cts = new CancellationTokenSource();
            _tasks = new List<Task>();
            _logger = new Logger("OperationsManager");
        }

        //internal int ConsumerCount { get; set; }

        internal void Start()
        {
            _logger.Log("Start() called.");

            StartProducer();
            StartConsumers();
        }

        private void StartConsumers()
        {
            // NOP.
        }

        private void StartProducer()
        {
            BlockingCollection<ProducerMessage> blockingCollection = new BlockingCollection<ProducerMessage>();

            Task producerTask = Task.Factory.StartNew(() =>
            {
                ManagementService managementService = new ManagementService(blockingCollection, _cts.Token);
                managementService.Produce();
            }, _cts.Token);

            _tasks.Add(producerTask);
        }

        internal void Stop()
        {
            _logger.Log("Stop() called.");

            _cts.Cancel();
            Task.WaitAll(_tasks.ToArray(), Timeout.Infinite);

            _cts.Dispose();
        }
    }
}
</code>```

Producer

```<code>using System;
using System.Collections.Concurrent;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using WindowsService2.Producer.WCF;

namespace WindowsService2.Producer
{
    // this is my "producer"
    internal class ManagementService : Producer
    {
        private Logger _logger;
        private ServiceHost _serviceHost;

        internal ManagementService(BlockingCollection<ProducerMessage> blockingCollection, CancellationToken cancellationToken)
            : base(blockingCollection, cancellationToken)
        {
            _logger = new Logger("ManagementService");
            _cancellationToken.Register(ShutDownWcfEndpoint);
        }

        public override void Produce()
        {
            _logger.Log("Produce() called.");

            StartWcfEndpoint();
        }

        private void StartWcfEndpoint()
        {
            // see https://msdn.microsoft.com/en-us/library/ms731758%28v=vs.110%29.aspx
            Uri baseAddress = new Uri("http://localhost:8080/hello");

            // Create the ServiceHost.
            _serviceHost = new ServiceHost(typeof(HelloWorldService), baseAddress);

            // Enable metadata publishing.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            _serviceHost.Description.Behaviors.Add(smb);

            // Open the ServiceHost to start listening for messages. Since
            // no endpoints are explicitly configured, the runtime will create
            // one endpoint per base address for each service contract implemented
            // by the service.
            _serviceHost.Open();
        }

        private void ShutDownWcfEndpoint()
        {
            _logger.Log("Shutting down WCF endpoint...");
            _serviceHost.Close();

            _logger.Log("Shutting down WCF endpoint... completed.");
        }
    }
}
</code>```

Consumer

```<code>public class Consumer
{
    // No code yet.
    // It has an "internal state" and uses TcpListener to communicate with the device.
    // It should be able to take commands from the management service (producer)
    // (like: destroy yourself, what's your status?, ...)
}
</code>```

As you can see there are no consumers created yet. This is because I figured the design might not work after all.

The management service (producer) needs to trigger new consumers.
Therefore the management service needs to write into the BlockingCollection - but how? public static BlockingCollection?

The management service should provide a method which shows the "internal state" of each consumer => how many consumers even are there?

I think the producer/consumer pattern might be the wrong choice here.
What I need is "Hey I'm the management service and I have x number of "worker threads" and their state is collection[0].State.

How would you do that?

Before this question is being closed as too broad - it usually happens with this kind of question - at least on SO - please give me any advice on how to break the requirements into smaller more manageable pieces.

答:
I think you have a pretty good idea going here.

I had a look at the consumer/producer pattern using a
  BlockingCollection which is pretty neat. I now have my producer (WCF
  server) which triggers creation of consumers.

The backend Server equivalent of consumer/producer pattern is a Async communication model. That doesnt mean it needs to be slow or infrequent.
But rather than sleep, block threads etc. when condition "Full" is met, you wait for the client to say, send again now.

My question now is... how do I - from my WCF self host (=producer) -
  access my multiple consumer instances? I need to query their internal
  state and also I need to be able to destroy single consumer instances
  if they become stuck - it happens.

The async patterns is used in various models now.
One interesting one that has some aspects you could use is registration.

If the producer is spawning clients, it should know all clients ids.
I could then theoretically call , are you awake ? No response, kill it (using call to OS ?) and then respawn. At the risk of some data loss.

An example of how this kind of pattern works is SignalR  (minus the Kill part)
SignalR overview with Further reading

But I think it will provide enough example to model something similar to match your scenario.


问:
Should non-interface code be hidden from the client?
I am working on a library which had several headers that are meant to only be used by the library itself. I also have a few classes and functions in headers that I do not want the client to use. For instance, I have a header that contains debugging functions, but they should not be used outside of the library as it could cause problems.

Should this code be hidden from the client? If so, how?

答:
If there is any functionality which should not be reached by the client, it should be well hidden from them.

If you are going to distribute your library, without any debug symbols, you might consider taking the debug functionality out of your distribution as well, instead of encapsulating them.


问:
Loops in real-life problems
I'm learning C as my first programming language. I'm confused on how do loops work in real-life. In programming every function has a reason.

example - if/else statements are used if we have conditions. Nesting if/else statements are used if we have conditions inside a condition(more condition).

I am going to try my best answering this using a real-life problem. I tend to understand better using Facebook as an example.

Let's say a user is signing up for Facebook. We don't want users signing up of age less than 13 years old. If users age is less than 13, it should terminate the sign up page and give a reason saying "Sorry, you're too young". Do we use if/else statement behind situation? Please correct me if I'm wrong.

Now, Loops are used for shortening up the program/application. What's the real-life analogy behind this? Using Facebook as an example.

Can 'News Feed' be a strong example of using Loops?

答:
There are, including this one, 10 answers on this page as I post. So how would you display them? </p>

```<code>if (answerCount >= 1) displayAnswer (1);
if (answerCount >= 2) displayAnswer (2);
if (answerCount >= 3) displayAnswer (3);
if (answerCount >= 4) displayAnswer (4);
if (answerCount >= 5) displayAnswer (5);
if (answerCount >= 6) displayAnswer (6);
if (answerCount >= 7) displayAnswer (7);
if (answerCount >= 8) displayAnswer (8);
if (answerCount >= 9) displayAnswer (9);
if (answerCount >= 10) displayAnswer (10);
if (answerCount >= 11) displayAnswer (11);
if (answerCount >= 12) displayAnswer (12);
</code>```

<p>So how would you display a page with 13 answers? How would you display a page with 100 answers? That's where you use a loop. </p>

Title: Loops in real-life problems

Body:
There are, including this one, 10 answers on this page as I post. So how would you display them?

if (answerCount >= 1) displayAnswer (1);
if (answerCount >= 2) displayAnswer (2);
if (answerCount >= 3) displayAnswer (3);
if (answerCount >= 4) displayAnswer (4);
if (answerCount >= 5) displayAnswer (5);
if (answerCount >= 6) displayAnswer (6);
if (answerCount >= 7) displayAnswer (7);
if (answerCount >= 8) displayAnswer (8);
if (answerCount >= 9) displayAnswer (9);
if (answerCount >= 10) displayAnswer (10);
if (answerCount >= 11) displayAnswer (11);
if (answerCount >= 12) displayAnswer (12);

So how would you display a page with 13 answers? How would you display a page with 100 answers? That's where you use a loop.


问:
React and simple UI state
I'm starting to playing around with React and have a basic question regarding state.

I understand that in React state should only contain data which may change and cannot be computed from elsewhere, however what about simple UI state that is not determined from any particular data and does not need to persist long-term?

For example, I have a mobile menu which is collapsible on small screens via CSS. The initial state of this menu is closed, and a simple onClick handler is attached to the toggle button. Inside the handler I can either:

1) use getDOMNode and classList.toggle on the element;

2) include this as a state property, then call setState to trigger a re-render.

The second option appears to me like the React way, but overkill especially on an app with potentially lots of menus, drop-downs etc. What is the best pattern for handling this kind of basic UI?

答:
I understand that in React state should only contain data which may
  change and cannot be computed from elsewhere,

I think there is no need to store something that cannot change in a variable at all (use constants for that). And if something can be computed from elsewhere, you might wrap calculation into a function and call it when you need. So, this applies not to React component's state, but to a more wider scope of problems.

however what about simple UI state that is not determined from any
  particular data and does not need to persist long-term?

My opinion is that React component's state should contain everything, that affects the presentation of your component at any point in time.

For example, I have a mobile menu which is collapsible on small
  screens via CSS. The initial state of this menu is closed, and a
  simple onClick handler is attached to the toggle button.

Your onClick should do one of the following:

Long way: Send a message via an action to a datastore about user action. Datastore will consider the situation (can user click the item or not, for example) and will send state information into a components (using action or by triggering datastore (in Reflux). Component will modify its state using datastore information by calling setState (and rerendering afterwards).

Short way: call setState directly from your onClick handler.

In both cases component's state should definitely include the collapsed field (or whatever other field, affecting how the component is rendered).

Another important consideration: React philosophy (my point of view) disregards DOM modifications outside render() calls. Of course you can use jQuery from render() to modify components, but... this may soon cause problems if jQuery starts modifying something, that was just rendered by React.

It is always better not to touch DOM rendered by React outside render().

Title: React and simple UI state


问:
When to use def in Groovy?
I have been developing in Groovy for a little while now and I'm wondering how often I should be using the dynamic casting def? A co-worker of mine believes we should use it always as it helps Groovy in some way I don't understand.

Currently, when declaring method return types and arguments, I like to deliberately state which objects should be taken in and spit out (for code readability and I come from a Java background it makes sense to me) example:

```<code>String doSomething(String something){
    //code
}
// vs
def doSomething(def somthing){
    //code
}
// vs
def doSomething(somthing){
    // code
}
</code>```

So I guess my question is it just a preference of when to use def or is there a real advantage to using it all the time?  (I added the last example because I felt it fits in with the question as a viable option for Groovy)

答:
As good programming (even scripting) practice, always consider specifying a definite (though not necessarily concrete) type for a variable. Use def only if there's no definite type applicable to the variable.

Since the OP knows Java, it's no different from specifying a type of Object (though there seems to be a minor difference). The answer to this question then won't be different from answering a question like: "why not always use the Object type in Java?"

Being as definite about types as possible reduces the chances of bugs, and even serves as self-documentation. Whereas, if one is deliberately implementing a dynamic logic, then using def might make a lot of sense. That's in fact one of the biggest strengths of Groovy; the program can be as dynamically or statically typed as one needs it to be! Just don't let laziness be the reason to use def ;-)

E.g. this method makes sense with a definite argument type and return type:

// def val or Object val, opens up the possibility
// of the caller sending a non-numeric value
Number half(Number val) {
    val/2
}
```

<p>while this method makes sense with type <code>def</code> </p>

<pre class="lang-java prettyprint-override"><code>// I'd let them pass an argument of any type;
// type `Object` makes sense too
def getIdProperty(def val) {
    if(val?.hasProperty('id')) {
        // I don't know the type of this returned
        // value and I don't really need to care
        return val.id
    }
    else {
        throw new IllegalArgumentException("Argument doesn't have an 'id' property")
    }
}
</code>```

Title: When to use def in Groovy?

Body:
As good programming (even scripting) practice, always consider specifying a definite (though not necessarily concrete) type for a variable. Use def only if there's no definite type applicable to the variable.

Since the OP knows Java, it's no different from specifying a type of Object (though there seems to be a minor difference). The answer to this question then won't be different from answering a question like: "why not always use the Object type in Java?"

Being as definite about types as possible reduces the chances of bugs, and even serves as self-documentation. Whereas, if one is deliberately implementing a dynamic logic, then using def might make a lot of sense. That's in fact one of the biggest strengths of Groovy; the program can be as dynamically or statically typed as one needs it to be! Just don't let laziness be the reason to use def ;-)

E.g. this method makes sense with a definite argument type and return type:

// def val or Object val, opens up the possibility
// of the caller sending a non-numeric value
Number half(Number val) {
    val/2
}

while this method makes sense with type def

// I'd let them pass an argument of any type;
// type `Object` makes sense too
def getIdProperty(def val) {
    if(val?.hasProperty('id')) {
        // I don't know the type of this returned
        // value and I don't really need to care
        return val.id
    }
    else {
        throw new IllegalArgumentException("Argument doesn't have an 'id' property")
    }
}


问:
Mermaid problem (OOP)
A Mermaid is half fish and half human. It has upper human body and lower fish body. When under water its upper part swims like a human while its lower part swims like a fish. Please explain how can it swim like a human and a fish at the same time? Create C++ program using class(es) and OOP paradigm to solve this problem.

Note: I don't want the actual code but instead I wanna know the OOP Concepts that can be be used to solve this problem (like multiple inheritance, Composition & Aggregation, Overriding etc...) and why?

The question is how can we make a class "Mermaid" that depicts both human and fish functionality on upper and lower parts of its body (like Inheriting the properties of human and fish on the upper & lower parts of the body respectively). I don't need to know how the functionality would be performed.... Instead the concepts required to satisfy those properties (like swimming like humans and fish at the same time). So forget about the physics part. And as far as the content goes I just copy pasted the question from the OOP paper.

An example "It might be the answer actually" Just an example try:

```<code>Class Human{
/*some data members go here */
public:
 void swim()
{ /*functionality */ }
 };

Class Fish{
/*some data members go here */
public:
 void swim()
{ /*functionality */ }
 };

Class Mermaid:public Human, public Fish{
/*some data members go here */
public:
 void someFunction()
{ /*functionality */ }
 }; –
</code>```

答:
A Mermaid is neither a human nor a fish, so I would not try to shoehorn these classes into an inheritance hierarchy:

```<code>Class Mermaid{
/*some data members go here */
public:
 void swim()
 { /*functionality */ }
 };
</code>```

Implement "swim" as you like. If you want to reuse some code in all 3 implementations of swim, you could easily do this by creating a fourth class like SwimTools where you can place that code.

Of course, you might consider to create an interface class ISwimmer with an abstract swim method and derive Human, Fish, and Mermaid from that class. If you do this should depend on having a practical requirement of dealing with those three classes uniformly.

In C++, you can also combine "interface inheritance" with "implementation inheritance", name the base class "Swimmer" and put the reusable parts there instead of using a separate SwimTools class (however, it is debatable if that is a better or worse design).

Title: Mermaid problem (OOP)

Body:
A Mermaid is neither a human nor a fish, so I would not try to shoehorn these classes into an inheritance hierarchy:

Class Mermaid{
/*some data members go here */
public:
 void swim()
 { /*functionality */ }
 };

Implement "swim" as you like. If you want to reuse some code in all 3 implementations of swim, you could easily do this by creating a fourth class like SwimTools where you can place that code.

Of course, you might consider to create an interface class ISwimmer with an abstract swim method and derive Human, Fish, and Mermaid from that class. If you do this should depend on having a practical requirement of dealing with those three classes uniformly.

In C++, you can also combine "interface inheritance" with "implementation inheritance", name the base class "Swimmer" and put the reusable parts there instead of using a separate SwimTools class (however, it is debatable if that is a better or worse design).


答:
To address the specific issue that you raise, of reified generics . . .

In many contexts, type parameters are actually saved in class-files and exploitable via reflection, even despite erasure. For example, the following program prints class java.lang.String:

```<code>import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;

public class ErasureWhatErasure {
    private final ArrayList<String> foo = null;

    public static void main(final String... args) throws Exception {
        final Field fooField = ErasureWhatErasure.class.getDeclaredField("foo");
        final ParameterizedType fooFieldType =
            (ParameterizedType) fooField.getGenericType();
        System.out.println(fooFieldType.getActualTypeArguments()[0]);
    }
}
</code>```

All "erasure" means is that when you create an instance of a parameterized type, the type parameter is not recorded as part of the instance; new ArrayList<String>() and new ArrayList<Integer>() create identical instances. But even in Java, there are a few well-known workarounds, such as:

Something like new ArrayList<String>() { } actually creates a new instance of an anonymous subclass of ArrayList<String>, and the subclassing relationship does record the type parameter. So you can retrieve the String reflectively. (Specifically: ((ParameterizedType) new ArrayList<String>() { }.getClass().getGenericSuperclass()).getActualTypeArguments()[0] is String.class.) This is exploited by various frameworks, such as Guice and Gson.

If you're creating your own class, you can require the type parameter to be passed via the constructor, and store it in a field. (The compiler can help you enforce that the constructor argument matches the type parameter. And if the type argument is itself generic, you can combine this with workaround #1 to ensure that you have the whole type argument.)

Another language residing on the JVM could reify generics by making #2 happen implicitly; whenever you declared a generic class, the type-parameter field(s) and constructor-parameter(s) would be added implicitly, and whenever you instantiate or extend it, type-argument(s) would be implicitly copied to constructor-argument(s) to populate them. Java already does the same thing — implicit fields and constructor-parameters/arguments — in a different context, namely, for local classes that refer to final local variables in their containing methods.

The main limitation is that generic classes in the JDK — the collections framework, java.lang.Class, etc. — don't already have this setup, and alternative languages running in the JVM can't add it to them. So such languages would need to provide their own equivalents of the JDK classes. But they can still use the JVM itself.

Body:
To address the specific issue that you raise, of reified generics . . .

In many contexts, type parameters are actually saved in class-files and exploitable via reflection, even despite erasure. For example, the following program prints class java.lang.String:

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;

public class ErasureWhatErasure {
    private final ArrayList<String> foo = null;

    public static void main(final String... args) throws Exception {
        final Field fooField = ErasureWhatErasure.class.getDeclaredField("foo");
        final ParameterizedType fooFieldType =
            (ParameterizedType) fooField.getGenericType();
        System.out.println(fooFieldType.getActualTypeArguments()[0]);
    }
}

All "erasure" means is that when you create an instance of a parameterized type, the type parameter is not recorded as part of the instance; new ArrayList<String>() and new ArrayList<Integer>() create identical instances. But even in Java, there are a few well-known workarounds, such as:

Something like new ArrayList<String>() { } actually creates a new instance of an anonymous subclass of ArrayList<String>, and the subclassing relationship does record the type parameter. So you can retrieve the String reflectively. (Specifically: ((ParameterizedType) new ArrayList<String>() { }.getClass().getGenericSuperclass()).getActualTypeArguments()[0] is String.class.) This is exploited by various frameworks, such as Guice and Gson.

If you're creating your own class, you can require the type parameter to be passed via the constructor, and store it in a field. (The compiler can help you enforce that the constructor argument matches the type parameter. And if the type argument is itself generic, you can combine this with workaround #1 to ensure that you have the whole type argument.)

Another language residing on the JVM could reify generics by making #2 happen implicitly; whenever you declared a generic class, the type-parameter field(s) and constructor-parameter(s) would be added implicitly, and whenever you instantiate or extend it, type-argument(s) would be implicitly copied to constructor-argument(s) to populate them. Java already does the same thing — implicit fields and constructor-parameters/arguments — in a different context, namely, for local classes that refer to final local variables in their containing methods.

The main limitation is that generic classes in the JDK — the collections framework, java.lang.Class, etc. — don't already have this setup, and alternative languages running in the JVM can't add it to them. So such languages would need to provide their own equivalents of the JDK classes. But they can still use the JVM itself.

ContentLicense: CC BY-SA 4.0


问:
Is it considered good practice to declare base interfaces without mutators, supplying mutatators in a sub-interface
I asked a question on StackOverflow on how to properly implement an ImmutableMap that abides by the SOLID principles.

Due to Java's Map interface containing put and putAll, it violates the interface segregation princple by forcing us to implement the put and putAll methods for an ImmutableMap. If we were to define our own interface, it would fall under the code smell category "Alternative Classes with Different Interfaces".

This got me thinking on how would one properly declare an interface that abides by the Liskov Subsitution principle, while still abiding by the interface segregation principle.

The only way I can think of achieving this would to declare the base interface with only accessors, then supply a subinterface with mutators:

```<code>interface Map {
    //accessor methods
}

interface MutableMap extends Map {
    //mutator methods
}

class HashMap implements MutableMap {

}

class ImmutableMap implements Map {

}
</code>```

Is this considered "good practice"? It seems to be the only way to implement immutability while still abiding by the SOLID principles, but I've never heard of such a practice.

答: No, that is a violation of the Liskov Substitution Principle since you are expanding the implied contract (from immutable to mutable). You could have a Readable foo as the base class, but you need to make extra special care that the code does not imply immutability.


问:
Is there any reason not to make a webapp be client-side only?
I recently started writing a path-finding algorithm simulation application in python.

It takes user inputs, randomly generates a 2d graph, and shows displays the simulation via GUI.

Now, what I found was that Python, and stand-alone applications aren't very appropriate for sharing this kind of application, as you need to get people to run it on their own computer etc. It would be much more convienient to simply direct them to a website.

Obviously the display and control elements need to be written on the client side.

But the actual path finding algorithm could be written on either the client or server side.

Now, given that there's no need for a server side backend (ie. no database), it would be possible to do the entire webapp in client side HTML/JavaScript.

The question is, is there a good reason not to do this?

The way I see it, doing it client-side only would greatly reduce the complexity, because there's no need to handle on going interaction between the client and the server. The only thing the server is for, is to initially serve up the Javascript to the client.

On the other hand... I'd have to write the entire thing in  Javascript...

Also, the idea of having a reusable model module appeals to me. Eg. If I want to later have a standalone application, I'd just need to write the View/Control modules.

I'm wondering what generally the accepted practise would be here.

答:
You've outlined the pros of doing the app client side only. Here are some possible cons - if any or all of them apply, consider shifting to a server based solution:

Performance. Would a client based solution be noticeably slower than a server-based one (including traffic)? Javascript is fast nowadays, but a computationally expensive algorithm might require dedicated server-side hardware or HPC farms.

Productivity. If you're a Python dev with no JS background, the time required to learn a new language and its idioms might be prohibitive, or at least longer than implementing client/server logic. Additionally, there may be useful Python libraries you could use which are unavailable for JS, which would increase development time considerably.

Intellectual Property. If this algorithm is something you wish to protect, having the code available on client machines could be a problem.

Compatibility. More browser-based code means more browser compatibility issues. This is much easier these days, but could still be a concern, depending on your intended audience and reach.

In short, client-side Javascript is a perfectly viable platform for algorithmic computing, and can easily be deployed both to a browser and as a standalone app (using a browser engine like Awesomium), but it does have its caveats. Go over them to make an informed choice.


问:
Why was the Itanium processor difficult to write a compiler for?
It's commonly stated that Intel's Itanium 64-bit processor architecture failed because the revolutionary EPIC instruction set was very difficult to write a good compiler for, which meant a lack of good developer tools for IA64, which meant a lack of developers creating programs for the architecture, and so no one wanted to use hardware without much software for it, and so the platform failed, and all for the want of a horseshoe nail good compilers.

But why was the compiler stuff such a difficult technical problem?  It seems to me that if the explicit parallelism in EPIC was difficult for compiler vendors to implement... why put that burden on them in the first place?  It's not like a good, well-understood solution to this problem didn't already exist: put that burden on Intel instead and give the compiler-writers a simpler target.

Itanium came out in 1997.  By this point, the UCSD P-Code bytecode system was nearly 20 years old, the Z-machine just slightly younger, and the JVM was the hot new rising star in the world of programming languages.  Is there any reason why Intel didn't specify a "simple Itanium bytecode" language, and provide a tool that converts this bytecode into optimized EPIC code, leveraging their expertise as the folks who designed the system in the first place?

答:
A few things.

IPF was in-order, for one. This meant you couldn't rely on reorder to save you in the event of a cache miss or other long-running event. As a result, you ended up needing to rely on speculative features - namely, speculative loads (loads that were allowed to fail - useful if you didn't know if you'd need a load result) and advanced loads (loads that could be re-run, using recovery code, if a hazard occurred.) Getting these right was hard, advanced loads especially! There were also branch and cache prefetch hints that could really only be used intelligently by an assembly programmer or using profile-guided optimization, not generally with a traditional compiler.

Other machines at the time - namely UltraSPARC - were in-order, but IPF had other considerations too. One was encoding space. Itanium instructions were, by nature, not especially dense - a 128-bit bundle contained three operations and a 5-bit template field, which described the operations in the bundle, and whether they could all issue together. This made for an effective 42.6 bit operation size - compare to 32 bits for most of the commercial RISCs' operations at the time. (This was before Thumb2, et al - RISC still meant fixed-length rigidity.) Even worse, you didn't always have enough ILP to fit the template you were using - so you'd have to NOP-pad to fill out the template or the bundle. This, combined with the existing relative low density, meant that getting a decent i-cache hit rate was a) really important, and b) hard - especially since I2 only had a 16KB L1I (although it was quite fast.)

While i've always felt that the argument of "the compiler was the one and only problem" was overblown - there were legitimate microarchitectural issues that really did I2 no favors for general-purpose code - it was not especially fun to generate code for compared to the narrower, higher-clocked OoO machines of the day. When you could really properly fill it, which often involved either PGO or hand-coding, it did great - but a lot of the time, performance from compilers was really just uninspiring. IPF didn't make it easy to generate great code, and it was unforgiving when code wasn't great.


问:
Version controlling a database's contents
I'm working on a web project that involves user-editable content, and I'd like to be able to do version-tracking of the actual content, which lives in a database. Basically, I want to implement wiki-style change histories.

Doing some background research, I see a lot of documentation about how to version your database schema (mine is actually already controlled), but any existing strategies about how to track your database content changes are lost in the avalanche of schema versioning stuff, at least in my searches.

I can think of a few ways to implement my own change tracking, but they all seem rather crude:

Save the entire row on each change, relate row back to source id with a Primary key (what I'm leaning towards currently, it's the simplest). Lots of small changes could produce a lot of table bloat, though.

save before/after/user/timestamp for each change, with a column name to relate the change back to the relevant column.

save before/after/user/timestamp with a table for each column (would result in too many tables).

save diffs/user/timestamp for each change with a column (this would mean that you'd have to walk the entire intervening change history to go back to a certain date).

What is the best approach here? Rolling my own seems like I'm probably reinventing someone else's (better) codebase.

Bonus points for PostgreSQL.

答:
The technique I have normally used is to save the complete record, with an end_timestamp field. There is a business rule that only one row can have a null end_timestamp, and this is of course the currently active content.

If you adopt this system, I strongly recommend you add an index or constraint to enforce the rule. This is easy with Oracle, as a unique index can contain one and only one null. Other databases may be more of a problem. Having the database enforce the rule will keep your code honest.

You are quite correct that lots of small changes will create bloat, but you need to trade this off against code and reporting simplicity.


问:
How to determine what should get its own respective controller?
I'm using the MVC pattern in my web application built with PHP.

I'm always struggling to determine whether I need a new dedicated controller for a set of actions or if I should place them inside an already existing controller.

Are there any good rules of thumb to follow when creating controllers?

For example I can have:

AuthenticationController with actions:

index() to display login form.

submit() to handle form submission.

logout(), self-explanatory.

OR

LoginController with actions:

index() to display login form.

submit() to handle form submission.

LogoutController with action:

index() to handle logging out.

OR

AccountController with actions:

loginGet() to display login form.

loginPost() to handle login form submission.

logoutGet() to handle logging out.

registerGet() to display registration form.

registerPost() to handle form submission.

And any other actions that are are involved with an account.

答:
Controllers are usually created for a certain resource (an entity class, a table in the database), but can also be created to group together actions that are responsible with a certain part of the application. In your examples, that would be a a controller that handles the security for the application:

```<code>class SecurityController
{
    // can handle both the login page display and
    // the login page submission
    login();

    logout();

    register();

    // optional: confirm account after registration
    confirm();

    // displays the forgot password page
    forgotPassword();

    // displays the reset password page
    // and handle the form submission
    resetPassword();
}
</code>```

Note: don't put the security related actions and the user profile actions in the same controller; it might make sense because they are related to the user, but one should handle authentication and the other should handle email, name etc. updates.

With controllers created for resources(let's say Task), you would have the usual CRUD actions:

```<code>class TasksController
{
    // usually displays a paginated list of tasks
    index();

    // displays a certain task, based on an identifier
    show(id);

    // displays page with form and
    // handles form submission for creating
    // new tasks
    create();

    // same as create(), but for changing records
    update(id);

    // displays confirmation message
    // and handles submissions in case of confirmation
    delete()
}
</code>```

Of course, you have the possibility to add related resources to the same controller. Say for example you have the entity Business, and each one has several BusinessService entities.
A controller for it might look like this:

```<code>class BusinessController
{
    index();

    show(id);

    create();

    update(id);

    delete();

    // display the business services for a certain business
    listBusinessServices(businessId);

    // displays a certain business service
    showBusinessService(id);

    // create a new business service for a certain business
    createBusinessService(businessId);

    // updates a certain business service
    updateBusinessService(id);

    // deletes a certain business service
    deleteBusinessService(id);
}
</code>```

This approach makes sense when the related children entities cannot exists without the parent entity.

These are my recommendations:

create controllers based on a group of related operations (handling certain responsibilities like security, or CRUD operations on resources etc.);

for resource-based controllers, don't add unnecessary actions (if you are not supposed to update the resource, don't add the update action);

you can add "custom" actions to simplify things (e.g. you have a Subscription entity that has an availability based on a limited number of entries, you can add a new action to the controller named use() that has the single purpose of subtracting one entry from the Subscription)

keep things simple - don't clutter your controller with a huge number of actions and complex logic, try to simplify things by decreasing the number of actions or making two controller;

if you are using an MVC focused framework, follow their best-practice guidelines (if they have it).

Some resources for further reading here.

Body:
Controllers are usually created for a certain resource (an entity class, a table in the database), but can also be created to group together actions that are responsible with a certain part of the application. In your examples, that would be a a controller that handles the security for the application:

class SecurityController
{
    // can handle both the login page display and
    // the login page submission
    login();

    logout();

    register();

    // optional: confirm account after registration
    confirm();

    // displays the forgot password page
    forgotPassword();

    // displays the reset password page
    // and handle the form submission
    resetPassword();
}

Note: don't put the security related actions and the user profile actions in the same controller; it might make sense because they are related to the user, but one should handle authentication and the other should handle email, name etc. updates.

With controllers created for resources(let's say Task), you would have the usual CRUD actions:

class TasksController
{
    // usually displays a paginated list of tasks
    index();

    // displays a certain task, based on an identifier
    show(id);

    // displays page with form and
    // handles form submission for creating
    // new tasks
    create();

    // same as create(), but for changing records
    update(id);

    // displays confirmation message
    // and handles submissions in case of confirmation
    delete()
}

Of course, you have the possibility to add related resources to the same controller. Say for example you have the entity Business, and each one has several BusinessService entities.
A controller for it might look like this:

class BusinessController
{
    index();

    show(id);

    create();

    update(id);

    delete();

    // display the business services for a certain business
    listBusinessServices(businessId);

    // displays a certain business service
    showBusinessService(id);

    // create a new business service for a certain business
    createBusinessService(businessId);

    // updates a certain business service
    updateBusinessService(id);

    // deletes a certain business service
    deleteBusinessService(id);
}

This approach makes sense when the related children entities cannot exists without the parent entity.

These are my recommendations:

create controllers based on a group of related operations (handling certain responsibilities like security, or CRUD operations on resources etc.);

for resource-based controllers, don't add unnecessary actions (if you are not supposed to update the resource, don't add the update action);

you can add "custom" actions to simplify things (e.g. you have a Subscription entity that has an availability based on a limited number of entries, you can add a new action to the controller named use() that has the single purpose of subtracting one entry from the Subscription)

keep things simple - don't clutter your controller with a huge number of actions and complex logic, try to simplify things by decreasing the number of actions or making two controller;

if you are using an MVC focused framework, follow their best-practice guidelines (if they have it).

Some resources for further reading here.


答:
I see two antagonistic design "forces" (which are not exclusive to controllers):

cohesiveness - controllers should group related actions

simplicity - controllers should be as small as possible to manage their complexity

From cohesiveness point of view, all three actions (login, logout, registration) are related, but login & logout much more than registration. They are related semantically (one is an inversion of the other) and quite possibly will also use same service objects (their implementations are also cohesive).

My first instict would be to group login and logout into one controller. But if login & logout controller implementations are not so simple (e.g. login has captcha, more authentication methods etc.), I would have no problem to divide them into LoginController and LogoutController to maintain simplicity. Where this threshold of complexity (when you should start splitting the controller) lies is a bit personal.

Also remember, that whatever you design your code initially, you can (and should) refactor it as it changes. In this case it is quite typical to start with simple design (have one AuthenticationController) and with time you'll receive more requirements which will complicate the code. Once it crosses the complexity threshold, you should refactor it to two controllers.

BTW, your code suggests that you're logging out user with GET request. That's a bad idea since HTTP GET should be nullipotent (it shouldn't modify the state of the application).

Title: How to determine what should get its own respective controller?

Body:
I'm using the MVC pattern in my web application built with PHP.

I'm always struggling to determine whether I need a new dedicated controller for a set of actions or if I should place them inside an already existing controller.

Are there any good rules of thumb to follow when creating controllers?

For example I can have:

AuthenticationController with actions:

index() to display login form.

submit() to handle form submission.

logout(), self-explanatory.

OR

LoginController with actions:

index() to display login form.

submit() to handle form submission.

LogoutController with action:

index() to handle logging out.

OR

AccountController with actions:

loginGet() to display login form.

loginPost() to handle login form submission.

logoutGet() to handle logging out.

registerGet() to display registration form.

registerPost() to handle form submission.

And any other actions that are are involved with an account.


答:
Original interface design in the question suggested that Map interface mandated immutability, but this violates Liskov substitution principle. Consider its definition:

Let Φ(x) be a property provable about objects x of type T. Then Φ(y)
  should be true for objects y of type S where S is a subtype of T.

Consider immutability as the provable property about immutable interface Map. This property (immutability) is clearly not provable in MutableMap interface.

Interface design in the question was clarified and now it doesn't violate Liskov's. Absence of mutate methods alone doesn't mandate immutability.

This more explicit design doesn't violate Liskov's substitution principle:

```<code>/** Contract says nothing about (im)mutability, only that it provides read access */
interface Map {
    // accessor methods
}

/** This specialization explicitly allows mutation */
interface MutableMap extends Map {
    // mutator methods
}

/** This specialization adds an immutability constraint */
interface ImmutableMap extends Map {
    // could contain nothing (just marker interface)
}
</code>```

The key here is that immutable interface is not an ancestor of mutable interface, they are both "siblings" who clarify (specialize) constraints/features of the common generic ancestor.

Map interface says nothing about (im)mutability, that's why it's possible to specify this in its descendants without violating Liskov's substitution principle.

Title: Is it considered good practice to declare base interfaces without mutators, supplying mutatators in a sub-interface

Body:
I asked a question on StackOverflow on how to properly implement an ImmutableMap that abides by the SOLID principles.

Due to Java's Map interface containing put and putAll, it violates the interface segregation princple by forcing us to implement the put and putAll methods for an ImmutableMap. If we were to define our own interface, it would fall under the code smell category "Alternative Classes with Different Interfaces".

This got me thinking on how would one properly declare an interface that abides by the Liskov Subsitution principle, while still abiding by the interface segregation principle.

The only way I can think of achieving this would to declare the base interface with only accessors, then supply a subinterface with mutators:

```<code>interface Map {
    //accessor methods
}

interface MutableMap extends Map {
    //mutator methods
}

class HashMap implements MutableMap {

}

class ImmutableMap implements Map {

}
</code>```

Is this considered "good practice"? It seems to be the only way to implement immutability while still abiding by the SOLID principles, but I've never heard of such a practice.

Body:
Original interface design in the question suggested that Map interface mandated immutability, but this violates Liskov substitution principle. Consider its definition:

Let Φ(x) be a property provable about objects x of type T. Then Φ(y)
  should be true for objects y of type S where S is a subtype of T.

Consider immutability as the provable property about immutable interface Map. This property (immutability) is clearly not provable in MutableMap interface.

Interface design in the question was clarified and now it doesn't violate Liskov's. Absence of mutate methods alone doesn't mandate immutability.

This more explicit design doesn't violate Liskov's substitution principle:

/** Contract says nothing about (im)mutability, only that it provides read access */
interface Map {
    // accessor methods
}

/** This specialization explicitly allows mutation */
interface MutableMap extends Map {
    // mutator methods
}

/** This specialization adds an immutability constraint */
interface ImmutableMap extends Map {
    // could contain nothing (just marker interface)
}

The key here is that immutable interface is not an ancestor of mutable interface, they are both "siblings" who clarify (specialize) constraints/features of the common generic ancestor.

Map interface says nothing about (im)mutability, that's why it's possible to specify this in its descendants without violating Liskov's substitution principle.


答:
Note that if you use Microsoft SQL Server, there is already a feature for that called Change Data Capture. You still will need to write code to access the previous revisions later (CDC creates specific views for that), but at least you don't have to change the schema of your tables, nor implement the change tracking itself.

Under the hood, what happens is that:

CDC creates an additional table containing the revisions,

Your original table is used as it was before, that is any update is reflected in this table directly,

The CDC table stores only the changed values, meaning that data duplication is kept to a minimum.

The fact that changes are stored in a different table has two major consequences:

Selects from the original table are as fast as without CDC. If I remember well, CDC happens after the update, so updates are equally fast (although I don't remember well how CDC manages data consistency).

Some changes to the schema of the original table lead to CDC removal. For instance, if you add a column, CDC don't know how to handle that. On the other hand, adding an index or a constraint should be fine. This quickly becomes an issue if you enable CDC on a table which is subject to frequent changes. There might be a solution allowing to change the schema without losing CDC, but I haven't searched for it.

Title: Version controlling a database's contents

Body:
I'm working on a web project that involves user-editable content, and I'd like to be able to do version-tracking of the actual content, which lives in a database. Basically, I want to implement wiki-style change histories.

Doing some background research, I see a lot of documentation about how to version your database schema (mine is actually already controlled), but any existing strategies about how to track your database content changes are lost in the avalanche of schema versioning stuff, at least in my searches.

I can think of a few ways to implement my own change tracking, but they all seem rather crude:

Save the entire row on each change, relate row back to source id with a Primary key (what I'm leaning towards currently, it's the simplest). Lots of small changes could produce a lot of table bloat, though.

save before/after/user/timestamp for each change, with a column name to relate the change back to the relevant column.

save before/after/user/timestamp with a table for each column (would result in too many tables).

save diffs/user/timestamp for each change with a column (this would mean that you'd have to walk the entire intervening change history to go back to a certain date).

What is the best approach here? Rolling my own seems like I'm probably reinventing someone else's (better) codebase.

Bonus points for PostgreSQL.


问:
Learning to Program in Assembly - Useful Resources
Following on from a previous thread, it has got me interested in learning a little about Assembly programming.  Not so much for wanting to program useful apps in, just to get a feel for low level programming to better understand what is happening.

Can anybody recommend any books or online resources for beginners?

Thanks.

答:
I always found the toughest part was hello world, which is usually just a trivial assem function called from a higherlevel languare like adding two numbers. Once you get past that hurdle it is simply a matter of adding instructions and psuedo-ops (like defining data) to your repertoire.

I would second geekbrit, although I've never used ARM. A minimal architecture like that would be not only be easier, but might come closest to having a legitimate -as opposed to only a didactic purpose.


问:
What are the components of a process?
What exactly is a process and what all things is a process comprised of?
I have read the Wikipedia page and I found only abstract details over there.

I want to know what details are stored by a process - for eg., a process identifier, program counter, etc. What are the other things that are part of a process? Also, how is process memory organised? For eg., are all components of a process present in memory contiguously?

答:
A process is one coherent set of instructions that an OS is currently executing. Everything else pretty much follows from that.

For instance, a process resides in memory, and each one has its own state. If your computer is running four instances of Bash simultaneously (not an uncommon situation), they are all the same program, but four different processes. Each has its own program counter, its own entry in the OS's process table, and either can currently be scheduled or not scheduled independent of each other. They may or may not share the same memory segments to hold parts of their opcodes - that depends on things like static/dynamic linking.

What else is part of a process? For instance, dynamically allocated memory. Programs that allocate memory get that memory allocated to them specifically, in a dedicated data segment. Again, your four Bash processes won't share that memory, unless they perform a coordinated protocol to explicitly share some of it. Then there is the bookkeeping info that the OS keeps about a process: its number, its priority, its owning user id, the amount of cycles it has already used, etc.

Handling processes reasonably efficiently is in fact quite complicated, and a big reason why writing an O.S. is not a trivial task. But in the end, processes are just instances of programs, i.e. opcode streams, and everything else is just accounting to keep those streams flowing efficiently.  (Ask again if you have more specific questions or barriers to understanding.)

Title: What are the components of a process?