答:
So, you want to create a new language. Then do so, and do not cripple C++.

There are several reasons not to do it:

Every normal coding standard will suggest to avoid macros (here is why)

It is harder to maintain code with such macros. Everyone programming in C++ knows what this is, and by adding such macro, you are actually adding a new keyword. What if everyone introduces something they like? What would code look like?

You shouldn't use (*this). or this-> at all, except in some special cases (see this answer and search for "this->")

Your code is not different from #define R return, which I saw in the actual code. Reason? Less typing!

Going slightly off topic, but here I am going to expand on point 3 (do not use (*this). or this-> in a class).

First of all, (*this). or this-> are used to access member variables or functions of the the object. Using it is meaningless and means more typing. Also, reading such code is more difficult, because there is more text. That means harder maintenance.

So, what are the cases where you have to use this->?

(a) Unfortunate pick of the argument's name.

In this example, this-> is required, since the argument has the same name as the member variable :

```<code>struct A {
  int v;
  void foo( int v ) {
    this->v =v;
  }
};
</code>```

(b) When dealing with templates and inheritance (see this)

This example will fail to compile, because the compiler doesn't know which variable named v to access.

```<code>template< typename T >
struct A {
  A(const T& vValue):v(vValue){}

  T v;
};

template< typename T >
struct B : A<T>
{
    B(const T& vValue):A<T>(vValue){}

    void foo( const T & newV ) {
      v = newV;
    }
};
</code>```

Title: Is it a good idea to "#define me (*this)"?

Body:
This macro can be defined in some global header, or better, as a compiler command line parameter:

```<code>#define me (*this)
</code>```

And some usage example:

some_header.h:

```<code>inline void Update()
{
    /* ... */
}
</code>```

main.cpp:

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

class A {
public:
    void SetX(int x)
    {
        me.x = x;
        me.Update();
    }

    void SomeOtherFunction()
    {
        ::Update();
    }

    /*
        100 or more lines
        ...
    */

    void Update()
    {
        // ...
    }

    int x;
};
</code>```

So in a class method when I access a class member, I am always using me, and when accessing a global identifier I always use ::. This gives the reader which is not familiar with the code (probably myself after a few months) localized information of what is accessed without the need to look somewhere else. I want to define me because I find using this-> everywhere too noisy and ugly. But can #define me (*this) be considered a good C++ practice? Are there some practical problematic points with the me macro? And if you as C++ programmer will be the reader of some code using the me macro, would you like it or not?

Edit: Because many people arguing not specificaly contra using me, but generaly contra explicit this. I think it may not be clear what are benefits of "explicit this everywhere".

What are benefits of "explicit this everywhere"?

As a reader of the code you have certainty what is accessed and you can concentrate on different things than verify - in some distant code - that is really accessed what you think is accessed.

You can use search function more specifically. Search "this->x" can give you more wanted results than only search "x"

When you are deleting or renaming some member, compiler reliably notifies you at places where is this member used. (Some global function can have same name and exist chance you can introduce error if you are not using explicit this).

When you are refactoring code and making non-member function from member (to make better encapsulation) explicit this shows you place which you must edit and you can easily replace this with pointer to instance of class given as non-member function parameter

Generally when you are changing code, there are more posibilities to errors when you are not using explicit this than when you are use explicit this everywhere.

Explicit this is less noisy than explicit „m_“ when you are acessing member from outside (object.member vs object.m_member) (thanks to @Kaz to spot this point)

Explicit this solves problem universaly for all members – attributes and methods, whereas „m_“ or other prefix is practicaly usable only for attributes.

I would like to polish and extend this list, tell me if you know about other advantages and use cases for explicit this everywhere.

Body:
So, you want to create a new language. Then do so, and do not cripple C++.

There are several reasons not to do it:

Every normal coding standard will suggest to avoid macros (here is why)

It is harder to maintain code with such macros. Everyone programming in C++ knows what this is, and by adding such macro, you are actually adding a new keyword. What if everyone introduces something they like? What would code look like?

You shouldn't use (*this). or this-> at all, except in some special cases (see this answer and search for "this->")

Your code is not different from #define R return, which I saw in the actual code. Reason? Less typing!

Going slightly off topic, but here I am going to expand on point 3 (do not use (*this). or this-> in a class).

First of all, (*this). or this-> are used to access member variables or functions of the the object. Using it is meaningless and means more typing. Also, reading such code is more difficult, because there is more text. That means harder maintenance.

So, what are the cases where you have to use this->?

(a) Unfortunate pick of the argument's name.

In this example, this-> is required, since the argument has the same name as the member variable :

struct A {
  int v;
  void foo( int v ) {
    this->v =v;
  }
};

(b) When dealing with templates and inheritance (see this)

This example will fail to compile, because the compiler doesn't know which variable named v to access.

template< typename T >
struct A {
  A(const T& vValue):v(vValue){}

  T v;
};

template< typename T >
struct B : A<T>
{
    B(const T& vValue):A<T>(vValue){}

    void foo( const T & newV ) {
      v = newV;
    }
};


问:
Is it a good idea to "#define me (*this)"?
This macro can be defined in some global header, or better, as a compiler command line parameter:

```<code>#define me (*this)
</code>```

And some usage example:

some_header.h:

```<code>inline void Update()
{
    /* ... */
}
</code>```

main.cpp:

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

class A {
public:
    void SetX(int x)
    {
        me.x = x;
        me.Update();
    }

    void SomeOtherFunction()
    {
        ::Update();
    }

    /*
        100 or more lines
        ...
    */

    void Update()
    {
        // ...
    }

    int x;
};
</code>```

So in a class method when I access a class member, I am always using me, and when accessing a global identifier I always use ::. This gives the reader which is not familiar with the code (probably myself after a few months) localized information of what is accessed without the need to look somewhere else. I want to define me because I find using this-> everywhere too noisy and ugly. But can #define me (*this) be considered a good C++ practice? Are there some practical problematic points with the me macro? And if you as C++ programmer will be the reader of some code using the me macro, would you like it or not?

Edit: Because many people arguing not specificaly contra using me, but generaly contra explicit this. I think it may not be clear what are benefits of "explicit this everywhere".

What are benefits of "explicit this everywhere"?

As a reader of the code you have certainty what is accessed and you can concentrate on different things than verify - in some distant code - that is really accessed what you think is accessed.

You can use search function more specifically. Search "this->x" can give you more wanted results than only search "x"

When you are deleting or renaming some member, compiler reliably notifies you at places where is this member used. (Some global function can have same name and exist chance you can introduce error if you are not using explicit this).

When you are refactoring code and making non-member function from member (to make better encapsulation) explicit this shows you place which you must edit and you can easily replace this with pointer to instance of class given as non-member function parameter

Generally when you are changing code, there are more posibilities to errors when you are not using explicit this than when you are use explicit this everywhere.

Explicit this is less noisy than explicit „m_“ when you are acessing member from outside (object.member vs object.m_member) (thanks to @Kaz to spot this point)

Explicit this solves problem universaly for all members – attributes and methods, whereas „m_“ or other prefix is practicaly usable only for attributes.

I would like to polish and extend this list, tell me if you know about other advantages and use cases for explicit this everywhere.

答:
No, it is not.

Mind the programmer who will maintain your code several years from now long after you've left for greener pastures and follow common conventions of the language you use. In C++, you almost never have to write this, because the class is included in symbol resolution order and when a symbol is found in class scope, this-> is implied. So just don't write it like everybody does.

If you often get confused which symbols come from class scope, the usual approach is using common naming pattern for members (fields and sometimes private methods; I haven't seen it used for public methods). Common ones include suffixing with _ or prefixing with m_ or m.

ContentLicense: CC BY-SA 3.0


问:
Microsoft Visual C++ Redistributables, Software Requirement?
When compiling with Visual Studio C++, I noticed that you need a specific MSV C++ Redist, depending on the version of Visual Studio you compile with. The required redistributable is necessary on machines without it. Otherwise without the redists missing MSVCPxxx.dll errors are prompt.

Is there a way to by-pass needing the necessity of the redistributable? Or is there a way to package that inside of the program you're creating, be it DLL, executable, etc.?

答:
Statically linked executables don't need this redistributable.

You create statically linked executable by switching the runtime type from "Multi-threaded DLL" to "Multi-threaded" (compiler option /MT instead of /MD).

It is subject to the following limitations:

All libraries the executable is linked to have to be compiled with the same setting. So if you use third-party libraries and don't have variant for static compilation nor sources, you can't get rid of the redistributable.

Compiling shared libraries (DLL) with static runtime will cause problems due to multiple definitions of some things. In some cases with small interfaces the problems can be avoided, but most of the time it does not work. So if you need DLLs, you will probably need the redistributable too.

If you need the redistributable, the common option is to create installer that will include it.

It should be also possible to create a small starter that will install the redistributable (carried in resources) and than start the main program (also carried in resources, possibly as DLL to avoid new process). I've never done it. I know Python does it with the py2exe, but I don't know whether there is any simple wrapper for doing it with your own C++ program.


问:
How big can the binary code be?
Where does binary go in a computer? When you turn the computer on it points to the bios and runs through it. I get that. Then it loads data off something ( disk, flash, etc. ). But where does it go? Does the binary go in ram? Does that mean if my program is 2mb and ram is 32mb I can only address 30mb? I mainly want to know so I can tell how big my bin can be.

I'm just a little confused on this issue. I know it's platform specific. But in general where would it go, and in general what document would I look at to check this information?

答: Your program can get as big as the virtual memory on your system. To get a more specific answer, please give more specific information. Are you just interested? Struggling with an embedded system? Doing homework?</p>

Title: How big can the binary code be?


问:
Sequence diagrams and the Implementation
In the design phase we create UML Sequence diagrams (in OOD). My understanding is that after creating an Use Case diagram if we need to show further information in terms of time sequence of events of that Use Case, we can go for sequence diagrams.

My question is, should a sequence diagram represent exact implementation details? If I ask in another way, should all method calls and object interactions in the implementation be shown in the Sequence Diagram? Or else it should present a high level picture of the implementation?

Normally in the implementation, things could be implemented with slight differences than specified in design diagrams. So that if a sequence diagram should show exact implementation details, we might have to revise them after the implementation.

Another related question would be, who are the audiences of these sequence diagrams other than the author? An answer for this question might answer the original question as well.

答:
Although I haven't tried it, one might be able to make a high level sequence diagram with fairly high level messages like "Send alarm to server"  and then use UML allocation to assign these to more detailed sequence diagrams that got as granular is needed in terms of showing login sequences, acknowledgements, and so on. This approach might be a reasonable way to link the "easy to understand for the stakeholders" version to (a number of) "detailed enough to generate code" versions.

I would be curious to know if anyone has actually tried something like that.


问:
What should be used to diagram an application's internal architecture?
I have an application that has several dependencies, including a Matlab library and a Microsoft Windows Media Player ActiveX control. How would I graphically depict the internal architecture of this application for documentation purposes? Would a UML structure diagram be appropriate? If so, would it be as simple as the following:

答:
No.

All diagrams showing more structure than behaviour, are called together "structure diagrams". But it is merely a classification term. You can't create a structure diagram, that is not a class diagram, a component diagram, an object diagram etc... You MUST choose.

The word "structure" is also in the name of Composite Structure Diagram. It shows the coordination of inner parts of classes and objects. It is the lowest level diagram of the UML. Obviously it is not what you need.

You are thinking on the highest level. The most common structure diagrams are Component diagram and Deployment diagram. They are intended for modelling of the whole architecture of the product. The second one shows also the HW structure of the product.


问:
Parsing mathematical expressions with two values that have parentheses and minus signs
I'm trying to parse equations like the ones below, which only have two values or the square root of a certain value, from a text file:

100+100

-100-100

-(100)+(-100)

sqrt(100)
```

<p>by the minus signs, parentheses and the operator symbol in the middle and the square root, and I have no idea how to start off... I've got the file part done and the simple calculation parts except that I couldnt get my program to solve the equations in the above.</p>

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

main(){
    FILE *fp;
    char buff[255], sym,sym2,del1,del2,del3,del4;
    double num1, num2;
    int ret;
    fp = fopen("input.txt","r");

    while(fgets(buff,sizeof(buff),fp)!=NULL){
        char *tok = buff;
        sscanf(tok,"%lf%c%lf",&num1,&sym,&num2);

        switch(sym){
            case '+': printf("%lf\n", num1+num2);
                    break;
            case '-': printf("%lf\n", num1-num2);
                    break;
            case '*': printf("%lf\n", num1*num2);
                    break;
            case '/': printf("%lf\n", num1/num2);
                    break;
            default: printf("The input value is not correct\n");
                    break;
        }
    }
    fclose(fp);
}
</code>```

That is what I have written for the other basic operations without parentheses and the minus sign for the second value and it works great for the simple ones. I'm using a switch statement to calculate the add, sub, mul and div operations but I'm not sure how to properly use the sscanf function (if I am not using it properly) or if there is another way, such as using a function like strtok to properly parse the parentheses and the minus signs. Any kind help?

答:
A better approach
There are many ways to parse and evaluate expressions as a recursive data structure.
Any expression can be defined as following:

expression -> term + term - term

term -> factor*factor/factor

factor -> variabler، number، expression as 10 +5*B consist of 2 terms 10، 5*B.

Second term contains 2 factors 5 and B.

Here is a sequence you will follow

input an expression as 9/3-(100 5)

the parser gets the first term 9/3.

get each factor and divide the integers the result is 3

get the second term term (100 56). Start recursively analysing the second sub expression.

get each terms and add them. The result is 156:
return from the recursive call, 3-156 =3.

This is complex concept that takes time to get used to.

If you want an example tell me. (I didn't give example because it will be very long). But if you want an example I will happily give you one).

If you feel confused you can google " recursive expression parsing".


问:
How much information about an error should be shown to the user?
Applications can always throw errors. If such an error occurs, the user should be notified, because what he asked the application to do has not succeeded.

However, how much information should the user be given? I think most of us agree on not showing a stack trace (Should a stack trace be in the error message presented to the user?), but I can't find a question about the rest of the error contents or what to show to the user.

For example, a language supporting exceptions (.net, java) has the exception type to share, where the exception occured, and a somewhat clarifying message to go along with the exception. Should this also be hidden from the user? Or should we show this anyway? Or should we show a generic message? or should we show one of a number of messages based on what the underlying exception is?

答:
This is a common theme:

How can you help the uninformed / computer illiterate at the same time as showing information that more advanced users such as programmers, developer, testers, etc. can use.

I think the answer is you do both!

The order is important though and I recommend you have:

What happened.

What to do now

Technical Details

Technical Details is the part that has information for either advanced orders or for regular users when reporting an issue


答:
Does the binary go in ram?

On most systems: yes. Though on many today systems there is an additional abstraction layer between the physical RAM and the RAM your processor "believes it has" - it is called virtual memory, as the other answer already pointed out. So if for example your machine has 32MB of physical RAM, but 64MB of virtual memory, as soon as the running programs need more than 32MB in total, the operating system tries to "swap out" least recently used areas of the physical memory to disk, and loads memory which needs to be accessed immediately from disk again into physical memory. For your program (including other programs on the machine) it looks like as if there are 64MB of physical ram, besides the fact that things become a hell lot slower when crossing the 32MB boundary often.

Does that mean if my program is 2mb and ram is 32mb I can only address 30mb?

Assumed your program has a code size of 2MB, and your system has only 32MB of memory (either physical with no virtual mem, or 32MB of virtual memory), this leaves 30MB for anything else - working space for your own program, as well as code and working memory for any other processes or programs running at the same time.

in general what document would I look at to check this information

The amount of physical RAM is typically documented in your systems hardware documentation (and also in advertisement catalogues, but I would actually not recommend to take these as a serious reference). The amount of virtual RAM can typically be parametrized in the system's settings. And if you want to know how much RAM your program can really use for itself, you have to inspect a running system with some kind of systems monitor and see how much physical or virtual memory is still free when there are no other running processes besides the ones of the operating system.

Title: How big can the binary code be?

Body:
Where does binary go in a computer? When you turn the computer on it points to the bios and runs through it. I get that. Then it loads data off something ( disk, flash, etc. ). But where does it go? Does the binary go in ram? Does that mean if my program is 2mb and ram is 32mb I can only address 30mb? I mainly want to know so I can tell how big my bin can be.

I'm just a little confused on this issue. I know it's platform specific. But in general where would it go, and in general what document would I look at to check this information?


答:
You should build AST(Abstract Syntax Tree). Build it with respect for precedence so multiplication/division comes first before subtraction or addition. Parentheses also should be handled but that only sound complex in theory.

My simple parser I wrote some time ago

As you can see from the source code I am using templates. Just simple linked lists which let me distinguish input such as VALUE OPERATION VALUE(1+2 or 3*6).

When I meet parentheses like 1+2*(4+5) only 1+2 and 4+5 matches a template, so I reduce them and I have VAL*(VAL). Now OPEN_PAREN VALUE CLOSE_PAREN) matches a template and so I reduce it into VAL. Now I have VAL*VAL. And that's all.

The source code was written for learning purposes by me so I tried to keep it clean and small. In case you need an explanation, feel free to ask in the comments.

Title: Parsing mathematical expressions with two values that have parentheses and minus signs

Body:
I'm trying to parse equations like the ones below, which only have two values or the square root of a certain value, from a text file:

100+100

-100-100

-(100)+(-100)

sqrt(100)
```

<p>by the minus signs, parentheses and the operator symbol in the middle and the square root, and I have no idea how to start off... I've got the file part done and the simple calculation parts except that I couldnt get my program to solve the equations in the above.</p>

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

main(){
    FILE *fp;
    char buff[255], sym,sym2,del1,del2,del3,del4;
    double num1, num2;
    int ret;
    fp = fopen("input.txt","r");

    while(fgets(buff,sizeof(buff),fp)!=NULL){
        char *tok = buff;
        sscanf(tok,"%lf%c%lf",&num1,&sym,&num2);

        switch(sym){
            case '+': printf("%lf\n", num1+num2);
                    break;
            case '-': printf("%lf\n", num1-num2);
                    break;
            case '*': printf("%lf\n", num1*num2);
                    break;
            case '/': printf("%lf\n", num1/num2);
                    break;
            default: printf("The input value is not correct\n");
                    break;
        }
    }
    fclose(fp);
}
</code>```

That is what I have written for the other basic operations without parentheses and the minus sign for the second value and it works great for the simple ones. I'm using a switch statement to calculate the add, sub, mul and div operations but I'm not sure how to properly use the sscanf function (if I am not using it properly) or if there is another way, such as using a function like strtok to properly parse the parentheses and the minus signs. Any kind help?


答:
With the processors used for embedded devices, there are three possibilities:

The processor executes the code directly from flash/ROM. In this case, the code doesn't take any RAM away from the system at all. In this setup, the RAM and flash/ROM are typically mapped to different portions of the address space that the processor can address, so the maximum size of your binaries is bounded by the physical amount of flash/ROM you have and the total amount of memory (RAM + ROM) needed by your software is bounded by the addressing capabilities of the processor.

The binary is copied to RAM and there is no virtual memory available. In this case, the binary does take RAM away from the system and the software will have that much less memory to work with. The size of your binaries is bounded by the physical amount of RAM you have and the total amount of memory (RAM + ROM) needed by your software.

The binary is copied to RAM and there is virtual memory available. This is similar to the second option, with the main difference that the amount of RAM is seemingly increased by copying parts of it out to secondary memory (flash, SD card, hard-disk, etc.). From a memory point-of-view, such a system is comparable to a desktop computer.

The datasheet for the processor should state if it supports execution directly from flash/ROM. The datasheet for the board you are using should state how much memory and of which type the board has (it might also mention if the processor can/will execute the code directly from flash). The documentation of the OS you are using should mention if the OS provides virtual memory capabilities. The large OSes (Linux, WinCE, etc.) typically do.

Title: How big can the binary code be?


问:
Socket connection to external IP through server
I am working on an application using sockets. Essentially I want to stream data between two clients. Since I can't connect the two clients together directly (they aren't on the same network), I will need to connect the two through a server.

My client-side is written in Java but the server-side could be written in any language. I have already explored using socket.io etc. but the issue I ran in to is that Java doesn't have a nice websocket solution. What other options are there out there to achieve the same effect?

The solution I have in mind right now is basically "forwarding" the stream from one client to the other through the server, but there could be a better way out there...

答:
There are a few ways you could solve this problem.I understand from your diagram and question your one of your client say client 1 is the server and your server is actually a proxy to redirect connections.The following solutions are in order of their complexity.

First is a networking solution: If connectivity between client 1 and client 2 is all you need to achieve. All you need to do in your clients is to add a route to the other client,add a route to client 1 to reach client 2 and vice versa.you do not have to change design of your program.

Second is a web proxy server:If you are running a web server in your server then you can configure web server to act as a reverse proxy.(Apache proxy instructions).This is useful if you do not have a lot of control over networking but have administrative privilege to your servers

Third is a programming solution:I guess you have the right solution in mind to write a program to "forward" the packets to the client.This is called proxy server so what proxy will do is receive requests from the client forward it to the server and receives the response from the server and forwards it to the client.But this does not guarantee performance you might have some performance issue.I would choose this way only when I have privileges that will allow me to change only the application I wrote and have restricted access to networking or servers and I will absolutely avoid going this road If at all possible for production systems.

Your statement about Java not having nice web socket is not true, Java's socket API is probably one of the most useful sockets out there.


问:
Should arguments always be passed to an Action in a MVC controller?
I have a number of controllers that take a 'site' as a parameter within their actions, like so:

```<code>[AuthoriseSite]
public ActionResult Index(string site) {
    var model = gvmFactory.CreateAnIndexViewModel(site);
    return View("Index", model);
}
</code>```

I have been passing the site as a parameter but I could also calculate it from a user's Membership profile, so my code could look like:

```<code>[AuthoriseSite]
public ActionResult Index() {
    string site = UserProfileService.GetUsersSite();
    var model = gvmFactory.CreateAnIndexViewModel(sitename);
    return View("Index", model);
}
</code>```

The site parameter can vary according to the role a user is in. Users that are admins can choose many different sites, whilst non-admins can only use the one they belong to.

My question is, which is the better practice?

I favour the first, it feels more like MVC, although this could just be I've always tended to do this. The second has some advantages in that URLs can not be adjusted so as non-admins get to see sites they shouldn't. However, the filter [AuthoriseSite] prevents this.

答:
If its common to many controllers and you use it in a lot of places, sounds like you need a baseController that your controllers can inherit from, and then put that logic there.

If you do that, you don't need to pass unnecessary arguments to your actions, and your actions don't need the same code copy pasted everywhere.


问:
.NET Properties - Use Private Set or ReadOnly Property?
In what situation should I use a Private Set on a property versus making it a ReadOnly property?  Take into consideration the two very simplistic examples below.

First example:

```<code>Public Class Person

    Private _name As String

    Public Property Name As String
        Get
            Return _name
        End Get
        Private Set(ByVal value As String)
            _name = value
        End Set
    End Property

    Public Sub WorkOnName()

        Dim txtInfo As TextInfo = _
            Threading.Thread.CurrentThread.CurrentCulture.TextInfo

        Me.Name = txtInfo.ToTitleCase(Me.Name)

    End Sub

End Class

// ----------

public class Person
{
    private string _name;
    public string Name
    {
        get { return _name; }
        private set { _name = value; }
    }

    public void WorkOnName()
    {
        TextInfo txtInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
        this.Name = txtInfo.ToTitleCase(this.Name);
    }
}
</code>```

Second example:

```<code>Public Class AnotherPerson

    Private _name As String

    Public ReadOnly Property Name As String
        Get
            Return _name
        End Get
    End Property

    Public Sub WorkOnName()

        Dim txtInfo As TextInfo = _
            Threading.Thread.CurrentThread.CurrentCulture.TextInfo

        _name = txtInfo.ToTitleCase(_name)

    End Sub

End Class

// ---------------

public class AnotherPerson
{
    private string _name;
    public string Name
    {
        get { return _name; }
    }

    public void WorkOnName()
    {
        TextInfo txtInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
        _name = txtInfo.ToTitleCase(_name);
    }
}
</code>```

They both yield the same results.  Is this a situation where there's no right and wrong, and it's just a matter of preference?

答:
And there's virtually no performance penalty...

But to clarify, accessing a property is slower than accessing its backing variable. A property's getter and setter are methods that require a Call and a Return, whereas a property's backing variable is accessed directly.

That's why, in cases where a property's getter may be accessed many times within a block of code, the property's value is sometimes cached first (saved in a local variable) and the local variable used instead. Of course, that assumes the property can't be changed asynchronously while the block is executing.


问:
How far to go with Domain Driven Design?
I've read a little about domain driven design and the usage of a rich domain model, as described by Martin Fowler, and I've decided to put it in practice in a personal project, instead of using transaction scripts.

Everything went fine until UI implementation started. The thing is some views will use rich components that are backed up by unusual models and, thus, I must transform the domain model into what is used by those components. And that transformation is specially "complex" in the view-to-domain portion, up to the point that some business logic is involved.

Wich brings me to the questioning: where should I do these adaptations? So far I've got the following conclusions:

Doing it in the presentation layer is good because, well, if that layer imposes restrictions in it's model, then it should be the one to handle them. But it's bad because there'll be some business leakage.

If I do it on the services objects (controllers, actions, whatever), then it'd be good because there won't be any change to the domain API just because of presentation layer, but it's bad because then I'd have transaction scripts, wich is not the intended design.

Finally, if I do it on the domain model, there'd be no leakage of business logic at all. But in the future I could expect an explosion of the API into a series of methods designed just to handle that view-model <-> domain-model adaptation.

I hope I could make myself clear on this.

答:
In DDD (plus Onion Architecture), View is an infrastructural concern - and must be treated as so. It means that, likely, you're gonna need a Anti-corruption layer between the Domains and the View, so as to guarantee that the Domain doesn't get polluted by Views needs.

You might need to model how you expose your data in the modelling, but in agnostic way. Thus, if you are exposing the Domain in a Web interface or RESTful interface, it should not matter, qualitatively.


问:
Automatically propagating changes
When working on multiple similar projects there are often changes that can't be extracted into a library, but should be applied to most of the projects. I mean changes like a modified directory structure, some common configuration, similar ui code, etc.

The most basic strategy is to copy a new project from the last finished one and throw out the business logic. The problem is that the improvements to the newest project won't move back to the older ones.

A slightly better strategy is to set up a boilerplate repository, clone every new project from it. Then the reusable bits can be extracted form the newest project  into the boilerplate and then pulled to the older projects. Of course, merging might be complicated, but I've had this strategy work quite well for me. Pushing the changes is still too much work though.

Is there a strategy to automate propagation of some changes across multiple projects?

答:
What you're essentially referring to is a platform.  While I see that it is used to "push off" from a certain project skeleton, with a little work, you can turn this into a platform library.  The advantages are that you can simply update the library to apply the changes to any project you're working on, and any project that is better left untouched can stay with a specific version of the platform.

In order to make this work, you have to take a look at a template class, and turn it into a class that can be simply extended to receive most of its benefits.  Or, in the case of specific usage of a class that you think could be useful in other projects, generalize all of its more common features and again, put it in a class that can be simply extended later.  If you have code generation (I would avoid it if possible, but assuming you can't), try to make it interact directly with your platform classes or at the least, doesn't prevent you later from extending functionality in classes that inherit from them.  Additionally, I strongly advise you to assign versions to your platforms, even if you don't use them at first.  They may come in handy later in order to know what features are permitted in the platform.

Resource files such as libraries can be loaded automatically by the platform, the code for which would be within the platform itself.  Therefore any project using that platform simply has to follow the guidelines for a standard platform hierarchy in order to properly load these resources.  For example, if my platform looks for libraries in a folder called lib, libraries that the platform uses are put in lib, and any additional libraries can be added in later with no extra hassle.

For any given project under a given platform, updating the platform is literally a question of updating its platform library.  For situations where a platform expects certain types of files in a given folder which has since changed from the previous version, the platform itself can be designed to rename older folders.  An example of this could be be that you've decided to handle multiple configuration profiles, one in each folder, but you start off with one configuration file.  Your platform, when run, could copy that configuration into its own folder with the names of default configuration profiles.  The platform, after this initialization phase, will then load the configuration in its own folder (perhaps designating one as a default profile when none is specified).

Unfortunately for situations where the platform cannot fill in the blanks, you will be obliged to correct these changes manually.  A good way to version platforms is to consider major version changes as changes to the platform which require manual intervention to make it work properly.

However also keep in mind that platforms are notoriously known for growing quite complex, due to trying to fulfill every project's requirements in the platform.  This can be avoided simply by asking yourself if a certain modification being made to the platform is one that most of your projects will use and the ones that don't will not be affected.

Also, another piece of advice before starting is, if you haven't already, get the input of your colleagues about what should be the de facto standard project hierarchy before establishing one yourself, otherwise you will likely see your programmer colleagues build their projects in the way that they prefer, which defeats the whole purpose of having a platform.

Title: Automatically propagating changes


问:
"Cross-cutting" domain in DDD
I've recently started studying Domain Driven Design and so far it looks like it will help tremendously with my team's current project. I'm running into a bit of a problem though actually determining what the domains are in our project.

After my inital pass, I ended up with something like this:

I have three domains: A, B, and C for different areas of the business. However, for each of those I need to track current data as well as create plans for the future. This led me to add a Planning domain, but I don't see a clear way to separate Planning from the other domains. Either A, B, and C need to have detailed knowledge of Planning or vice versa.

Example: Let's say Domain A is "inventory". The implementation has messages for things like ItemsAdded and ItemsRemoved and it tracks quantities of various products. Then if I want to allow for planning of future quantities of items I need to add classes to the model which will allow me to associate future product info with various time windows. This kind of feels like a new domain except the same planning and time window logic also applies to Domain B and C.

Essentialy, I have a cross-cutting domain. I feel like I must be looking at this the wrong way.

Maybe I actually have 6 domains and a library used by 3 of them?

答:
Cross-cutting domain can be a symptom of Shared-Kernel Domain. This is covered both in Evans' and Vernon's books.

But be careful, this Shared-Kernel domain should not be created by functional inspiration, but a domain which contents are relevant to other domains - and not because it does something useful for both.

It is tempting to create a Shared-Kernel domain that fulfils a functional role, therefore making the system tightly coupled instead of loosely coupled. A big no-no for source code scalability.

Title: "Cross-cutting" domain in DDD


问:
What is a good practice to push notifications in a "near real-time" delay in this case?
I want to enable some real-time notifications about friend's activities (social network).

Technical context is:  Webapp calling backend (REST API's).

Scenario is:

Kevin follows Bob.

When Bob posts a new comment, Kevin should be notified immediately (near real-time).

Besides, when Kevin logs in, he should be able to see some past notifications, similar to what Facebook does.

Meaning that notifications should be stored somewhere.

Here's the technical workflow:

Bob posting a new comment involves an insert in database of this new comment.

As following Domain-Driven-Design, the event CommentedItemEvent is triggered.

A distinct worker in the same bounded context (long-running process, polling the database each second) listening to this event captures it.

At the end of 3, I see 2 possibilities:

Creating the corresponding notification, storing it in database and THEN sending it to Redis Pub/sub. This one would feed some specific subscribers acting on the WebSocket connection to send the notification to Kevin's client.

Creating the corresponding notification, then sending it to Redis THEN storing them in database.

Regarding the first possibility, the advantage would be the transactional aspect. Indeed, no noticification could be sent if it wasn't saved before. => Integrity.

However, the drawback is that the database insertion could slow down the process of "near real-time notification".

Regarding the second possibility, notifications are immediately sent but if some failure happens regarding database insertion, Kevin might have wondered:

"Humm... I received the Bob's notification, I'm sure I saw it. So why a simple page refresh doesn't show it anymore?" => Indeed, it wasn't persist successfully, so can't query it.

What is a good practice regarding this use case?

Of course, one faster way would be to not involve an event listener for this case, but it would violate some principles regarding Domain-Driven Design. IMHO, listener polling database in its own bounded context is necessary. (evoked by Vaughn Vernon in this book IDDD - "Building an event store")

答:
Event handling is not necessarily something internal only to the Domain instance. Sometimes, an external service handles more appropriately such events needs than an internal implementation.

Text Messaging for instance, can be handled better by an XMPP or IRC services, which are interfaced as dependencies into the domain, through an common interface (i.e. notify(message) looks the same to the sender within the domain).

So you may have few domains: one for the Message Logic, another for Message Persistence and another for Message Sharing.

A specialised external service could accept connections from Message Sharing instances, which handles cases and events, putting them through Message Logic specifications and rules.

Message Persistence can connect to the same service, and just handle the storage of the messages in an appropriate database, and even update some search engine.

All related, yet uncoupled, domains. For sure, you will need to work more on the guarantees of each domain (like CAP theorem and latency).


答:
Off course i don't understand your domain with enough info, but planning sounds for me like a domain completely separated from the rest of your system.

This domain have the operations/rules/behaviors for planning things, for example, you can plan items from your inventory, but from the planning point of view this are not "inventory items" are something like "planItems" perhaps. Probably you don't need all the information of a inventory item for planning, why do you want to use this inventory item classes in your planning domain?

For me this is one key thing to understanding DDD and do a proper separation in bounded contexts, the same "thing" can be viewed completely different from different domains, you can have a InventoryProduct in the inventory domain and a PlannedProduct or PlannedItem in the Planning domains, this objects can have the same id or perhaps share a very little set of fields (Identification information like id, name etc,etc) but have completely different set of operations and completely different data, in one case the data that the inventory needs in the other case the data that the planning needs.

Title: "Cross-cutting" domain in DDD

Body:
I've recently started studying Domain Driven Design and so far it looks like it will help tremendously with my team's current project. I'm running into a bit of a problem though actually determining what the domains are in our project.

After my inital pass, I ended up with something like this:

I have three domains: A, B, and C for different areas of the business. However, for each of those I need to track current data as well as create plans for the future. This led me to add a Planning domain, but I don't see a clear way to separate Planning from the other domains. Either A, B, and C need to have detailed knowledge of Planning or vice versa.

Example: Let's say Domain A is "inventory". The implementation has messages for things like ItemsAdded and ItemsRemoved and it tracks quantities of various products. Then if I want to allow for planning of future quantities of items I need to add classes to the model which will allow me to associate future product info with various time windows. This kind of feels like a new domain except the same planning and time window logic also applies to Domain B and C.

Essentialy, I have a cross-cutting domain. I feel like I must be looking at this the wrong way.

Maybe I actually have 6 domains and a library used by 3 of them?


答:
Some environment / IDE allow for project templates.  Depending on your environment this is done differently but I'd be surprised it would not be available.

You can then create a project that contains this template and change it as you would any other projects.  Of course once a project has been started you would have to merge the changes manually but a least any new project would start with the latest and greatest, though sometimes it would also be possible to automate updates as well.

Project templates in Visual studio

Maven architypes are pretty good too

Nuget could do the job as well in the .Net world.  It has the additional advantage to update existing projects through some update powershell scripts.

Eclipse can provide templates as well, you could go as far as creating a plugin to keep your projects up-to-date.

These are the ones that come off the top of my mind, with a bit of research and more details on your specific situation we could come up with targeted solutions.

Title: Automatically propagating changes

Body:
When working on multiple similar projects there are often changes that can't be extracted into a library, but should be applied to most of the projects. I mean changes like a modified directory structure, some common configuration, similar ui code, etc.

The most basic strategy is to copy a new project from the last finished one and throw out the business logic. The problem is that the improvements to the newest project won't move back to the older ones.

A slightly better strategy is to set up a boilerplate repository, clone every new project from it. Then the reusable bits can be extracted form the newest project  into the boilerplate and then pulled to the older projects. Of course, merging might be complicated, but I've had this strategy work quite well for me. Pushing the changes is still too much work though.

Is there a strategy to automate propagation of some changes across multiple projects?


问:
Ensuring submitted hiscores are not fake
I have a small game that I would like to keep track og global hiscores for.
The basic is simple: username and score is submitted to a server for storage and later polling. However how do I ensure that these scores aren't faked?

Obviously, just accepting a submitted user+score blindly will allow people to telnet in their desired score. To combat this, I've thought up two approaches:

Checksumming - In addition to the score and the username, the application sends a checksum of the two using an obscure algorithm and salt. If the same checksum doesn't add up, the server will reject it. However, how easy is it to reverse engineer the checksumming used, considering that this is an android application?

Submitting the entire game - In addition to user+score, the steps taken to reach the score is also sent. The server then emulates the game to see if the steps result in the same score, and if not, rejects it. I consider this to be the safest, but for some types of games this can be very hard to do, as the factors are far too many.

Is there a middle road? Are there any other methods worth considering? It's not like this is vital to national security or anything, but I would prefer if the users aren't left with "HackedYourGame: 999999999 points" on top of the list.

答:
First remember that everything can be cracked given enough access. You can only make it expensive.

You can make sure the on-wire protocol cannot be hacked. You can encrypt it with a one-time password (from the server) so that mere wire snooping will see only gibberish, that changes every time. And you can include installation or user-specific data so a simple replay won't work. You can also include game-specific stats (other than the high score), just for interest and to raise the bar further.

Once you've reached the point where only the disassemblers and reverse engineers can make any progress, you're down to the real hard core. You can still make life hard by distributing parts of your algorithms in time (while the game progresses) and space (bits of code all over the place).

But bear in mind that what seems to be an impossible high score could actually be a bug or cheat in your software. No point guarding the protocol if the game itself can be hacked.


答:
Parsing expressions, with parentheses and unequal operator precedence, is THE standard parsing example in just about every compiler textbook in existence.  Function calls aren't USUALLY part of that example, but they are simple enough to add.  Rather than go trial-and-error, your life will be a lot easier in the long run if you learn how to do it for real.

The most accessible introduction to building hand-constructed parsers I have seen is Jack Crenshaw's "Let's Build A Compiler".

The most accessible textbook I've seen on compiler construction is Wirth's "Compiler Construction".  It describes hand-coded recursive descent parsing.

The canonical references on compiler construction are the various Dragon Books.  I personally used the Green Dragon Book and found it usable, although the focus is on mechanically-generated LALR parsers rather than hand-coded parsers.


问:
What is the best approach to storing a multi-dimensional array with unknown bounds?
I'm trying to store content scraped from several lyric and chord websites into separate variables into either a multi-dimensional array, or into separate string arrays, but I've been stuck trying some different approaches. I've searched through the site and have found many questions that were similar, though incompatible or difficult to adapt with my project.

If content was stored in a multi-dimensional array, it would look like this:

Search Site > Artist > Link to artist page > Song > Link to song page > Tab types (Chords, Lyrics, Tabs) > Link to tab type (Chords, Lyrics, Tabs) > Content

A good visual representation of this array would look like this:

Keep in mind the content is dynamic, so it is not possible for me to hard-code array bounds without first retrieving the size of the content I'm storing (e.g. amount of songs per artist)

Below are the approaches I've tried and their shortcomings, or where I failed to implement correctly:

Multi-dimensional (jagged) arrays required explicit bounds, and only the rightmost array can be resized. (This approach can be made to work by setting explicit bounds after all content has been captured, but creating temporary variables and passing them all to the multi-dimensional array requires a lot of code and seems like a "dirty" solution to my problem.)

Tuples seemed promising, but for some reason, I was not able to create a tuple containing different variable types, or the approach was confusing.

Individual arrays did not give me enough flexibility and required creating multiple new arrays dynamically. (e.g. an array for the list of songs for a specific artist, another for the tab links in a specific song, etc.)

I'm sure I've tried others, but I cannot remember at the moment, I've seen a similar approach done with Structures on a sample for a user control here and others who implemented a local database to contain all the elements.

All that is needed is an approach that is simplistic but functional.

Any help is gladly appreciated.

Another representation here:

答:
Seems as if your main difficulty is that you're using arrays instead of lists.  Lists do not have the problem of requiring an initial size; you can grow them or shrink them as needed.

I also have the impression that you think you have to store the entire content of the web site in a single data structure.  You don't; a relational database like SQL Server would suffice.   Artists, songs and song content would each go into its own table in the database.

Assuming that what you're really after is a ViewModel, it would look something like this:

```<code>Public Class ArtistSongViewModel
    Public Property Artist() As Artist
        Get
            Return m_Artist
        End Get
        Set
            m_Artist = Value
        End Set
    End Property
    Private m_Artist As Artist
    Public Property Hyperlink() As String
        Get
            Return m_Hyperlink
        End Get
        Set
            m_Hyperlink = Value
        End Set
    End Property
    Private m_Hyperlink As String
    Public Property Songs() As List(Of Song)
        Get
            Return m_Songs
        End Get
        Set
            m_Songs = Value
        End Set
    End Property
    Private m_Songs As List(Of Song)
End Class

Public Class Song
    Public Property Name() As String
        Get
            Return m_Name
        End Get
        Set
            m_Name = Value
        End Set
    End Property
    Private m_Name As String
    Public Property Hyperlink() As String
        Get
            Return m_Hyperlink
        End Get
        Set
            m_Hyperlink = Value
        End Set
    End Property
    Private m_Hyperlink As String
    Public Property Content() As List(Of SongContent)
        Get
            Return m_Content
        End Get
        Set
            m_Content = Value
        End Set
    End Property
    Private m_Content As List(Of SongContent)
End Class
</code>```

Body:
Seems as if your main difficulty is that you're using arrays instead of lists.  Lists do not have the problem of requiring an initial size; you can grow them or shrink them as needed.

I also have the impression that you think you have to store the entire content of the web site in a single data structure.  You don't; a relational database like SQL Server would suffice.   Artists, songs and song content would each go into its own table in the database.

Assuming that what you're really after is a ViewModel, it would look something like this:

Public Class ArtistSongViewModel
    Public Property Artist() As Artist
        Get
            Return m_Artist
        End Get
        Set
            m_Artist = Value
        End Set
    End Property
    Private m_Artist As Artist
    Public Property Hyperlink() As String
        Get
            Return m_Hyperlink
        End Get
        Set
            m_Hyperlink = Value
        End Set
    End Property
    Private m_Hyperlink As String
    Public Property Songs() As List(Of Song)
        Get
            Return m_Songs
        End Get
        Set
            m_Songs = Value
        End Set
    End Property
    Private m_Songs As List(Of Song)
End Class

Public Class Song
    Public Property Name() As String
        Get
            Return m_Name
        End Get
        Set
            m_Name = Value
        End Set
    End Property
    Private m_Name As String
    Public Property Hyperlink() As String
        Get
            Return m_Hyperlink
        End Get
        Set
            m_Hyperlink = Value
        End Set
    End Property
    Private m_Hyperlink As String
    Public Property Content() As List(Of SongContent)
        Get
            Return m_Content
        End Get
        Set
            m_Content = Value
        End Set
    End Property
    Private m_Content As List(Of SongContent)
End Class


问:
Strategy game, how do I calculate the parallel actions?
I am building a strategy game where multiple units(5 - 20) fighting each other.

I have a game logic that calculate all the actions that been done on each turn, and send it to the game engine to animate.

Those are the possible actions:

perform attack

perform taking damage

perform moving

perform missing

perform removing your self(dying)

How can I find what actions I can perform in parallel and what are not?

Those are the limitations that I have:

units can only perform one action at a time.

each action may have different times, even if its the same action

Unit can perform the action attack, only if the other unit performing the action taking damage or removing your self

after unit performed the action: removing your self, he cannot perform any other action.

Edit:
Those are the situations that might happened:

one unit is attacked by multiple units at once

one unit taking damage while no units are attacking him

all the units move at the same time

all the units perform miss at the same time

This question is not about game design, but a programmatic solution to how I can find those parallel tiles of actions?

Reply to FrustratedWithFormsDesign, answer

Hi man, you took it to completely different direction, so I want to reply you here to clear things up.

This questions is not about how to make units to move in parallel. I also don't think that your suggestion is a good idea.

What you did with your own game this is actually, the right direction. It will be also wise to work in MVC and separate the view and game logics.

So to implement a game engine I would use a game thread that will dispatch tick events, based on chosen frame rate. Only the views should be listening for that thread and implement they view logic based on it.

In my game I am using Adobe Air framework with some native Java and Objective-C support for mobiles, but it's Air mostly. So all my animations are listening to onEnterFrameEvent, this would be tick in your example, and implement their animation logic.

My game logic is using a different worker(air threads implementations, it's more like a process) to generate all the actions on particular turn. And than it sands it to the game engine to animate. I do not ask how to implement the animations, it's handled by Air apis, and it doesn't meter in here.

Think about those problems:

unit a attacks unit b while unit b attacks unit c, while unit c is moving.

This will resolute with a mess on the screen.

I want it to be:

unit a attack unit b, unit b waits for a to finish attacking him to
  start attacking unit c, while unit c is moving. After a finish attacking unit b, unit b attacks unit c.

So the input of actions I received was:

A attack

B take damage

B attack

C take damage

C move

And the output was two sets of animations

A attack, C move, B take damage

B attack, C take damage

This was a very simple example of how I would like to parallel my actions. I hope now it is more clear.

答:
If you are talking about having one thread for every game character, you're going to have some synchronization issues. And you might start running into performance issues if you have many game characters, each requiring its own thread.

If you really want to do things in parallel, you could do try to run multiple threads all performing the same task. For example:

create threads for all game characters (or up to a limit of n threads) and move the characters by one increment (the distance that a character could move in one unit of game time).

wait for all threads to complete.

create threads for all game characters and perform attacks.

wait for all threads to complete.

create threads for all game characters and calculate damage, and remove characters if they are dead.

wait for all threads to complete.

return to begining.

You could also try using one thread per type of game activity (move characters, attack, calculate damage, etc...). You'd have fewer threads to manage but I think the coordination and synchronization between them would be more difficult, because you'd be running the "move character" and "attack" threads in parallel.

These are just ideas though, I've never tried to build a game in this fashion, but it may help.

In my experience with game code (admittedly, it was a few years ago, and on simpler games than what you might be working on), we usually did everything in the context of a single event loop. The loop was usually driven by some kind of timer, and with every tick of the timer, all actions would be processed. So if there were 3 game characters attacking each other on the screen, a single timer tick would:

process any user input from the mouse or keyboard

move all units' on-screen image by a certain amount, if they were in motion.

move projectiles and other moveable objects.

check to see if they'd been hit by other projectiles, and if they had taken damage, and if so, how much.

calculate points earned by the player.

if time was important, check how much time has elapsed since the last mark and perform some action (such as end the game if they player was taking too long).

...any other necessary calculations.

This way, there was one master process that was in charge of everything. I suppose we could have used multiple threads if we'd had some complicated calculations, but they'd still be run from the main loop and the main loop would have had to wait until they all finished.


问:
Minimizability or readability?
I am authoring a lot of plugins for the content management system that I am writing. I believe it to be of utmost importance that script files (especially if they're plugins) should load quickly, which leads to me to the question that I've asked today?

What's more important for plugins, minimizability or readability?

Let's imagine that we live in an ideal world where code is always perfect. Should a plugin (which being perfect, the author doesn't expect the end user to read) be designed so that it takes up as little space as possible, or so that it readable by the end user.

For example, I'm writing a piece of code that spits out HTML and appends it to the body. I have replaced every instance of the tag 'div' with '!' and then used String[replace](/\!/g, 'div') to save four characters (therefore bytes?) for each declaration of a div element.

NB, [replace] is also a declared variable so that when it is minified it will read something to the effect of String[r](/\!/g,'div')

Am I caring too much about download speed or should care a bit more about readability. (IMO, most minifying techniques are easily reverse-engineered, but is it bad practice?)

Edit

Thanks for all the answers, you guys are great!

答:
If code were perfect, there would be no need for documentation because it is simple and straightforward, hence there would be no need to optimize for anything other than performance.

However, code is not perfect, and if you're like me, you'll have passed several days pulling your hair out trying to resolve a silly issue with a javascript library.  I think the best solution is simply to not decide on behalf of the programmer who is downloading it, but offer both versions equally.  The readable version is for those who wish to change existing code and the minified version would be to optimize performance because the code depending on it already does what it is supposed to.

Rarely will you see a programmer want to have code readable to debug, yet fast enough to put into production.  If you can get it faster still by reducing it beyond readable levels, you will see that version used in production instead.

The minified version can simply be your readable version that has been minified, so focus simply on writing readable code since the objective is to make your code, well,... readable.  Lets do a thought experiment for a moment.

Suppose you can minify your code from 50kb to 10kb.  This is a 80% reduction in size, and you could say that, from a bandwidth standpoint, this is 80% more performant.  Now suppose you can further reduce this reduction from 10k to 9k if you replace all if statements with tertiary operators.  Now rather than an 80% reduction in size, you've managed to achieve an 82% reduction in size.

This said, if you could gauge the readability of your code before and after this change, do you think you would have suffered only 2% change in readability?  Possibly, but I would argue that you've lost more.  Even if it were only 2% difference, readability is the scope here, not performance.  Most of the difference in performance comes from that 40k reduction using minified, and very little is gained for that single change.

That said, maybe don't create large blocks of code that will never be run.

Title: Minimizability or readability?


问:
Is it a good idea to "#define me (*this)"?
This macro can be defined in some global header, or better, as a compiler command line parameter:

```<code>#define me (*this)
</code>```

And some usage example:

some_header.h:

```<code>inline void Update()
{
    /* ... */
}
</code>```

main.cpp:

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

class A {
public:
    void SetX(int x)
    {
        me.x = x;
        me.Update();
    }

    void SomeOtherFunction()
    {
        ::Update();
    }

    /*
        100 or more lines
        ...
    */

    void Update()
    {
        // ...
    }

    int x;
};
</code>```

So in a class method when I access a class member, I am always using me, and when accessing a global identifier I always use ::. This gives the reader which is not familiar with the code (probably myself after a few months) localized information of what is accessed without the need to look somewhere else. I want to define me because I find using this-> everywhere too noisy and ugly. But can #define me (*this) be considered a good C++ practice? Are there some practical problematic points with the me macro? And if you as C++ programmer will be the reader of some code using the me macro, would you like it or not?

Edit: Because many people arguing not specificaly contra using me, but generaly contra explicit this. I think it may not be clear what are benefits of "explicit this everywhere".

What are benefits of "explicit this everywhere"?

As a reader of the code you have certainty what is accessed and you can concentrate on different things than verify - in some distant code - that is really accessed what you think is accessed.

You can use search function more specifically. Search "this->x" can give you more wanted results than only search "x"

When you are deleting or renaming some member, compiler reliably notifies you at places where is this member used. (Some global function can have same name and exist chance you can introduce error if you are not using explicit this).

When you are refactoring code and making non-member function from member (to make better encapsulation) explicit this shows you place which you must edit and you can easily replace this with pointer to instance of class given as non-member function parameter

Generally when you are changing code, there are more posibilities to errors when you are not using explicit this than when you are use explicit this everywhere.

Explicit this is less noisy than explicit „m_“ when you are acessing member from outside (object.member vs object.m_member) (thanks to @Kaz to spot this point)

Explicit this solves problem universaly for all members – attributes and methods, whereas „m_“ or other prefix is practicaly usable only for attributes.

I would like to polish and extend this list, tell me if you know about other advantages and use cases for explicit this everywhere.

答:
Please don't do it! I am trying to cope with a large code base where macros are all over the place to save typing.
The bad thing about redefining this to me is that the preprocessor will replace it everywhere even where this is not in scope/does not apply, for instance a stand-alone function, your fellow colleage might have a local variable called me somewhere else... (s)he won't be happy debugging... You end up having macros which you can't use in all scopes.</p>


问:
How to design an IDisposable that unconditionally needs to be disposed?
Consider a class that implements IDisposable, and that has members in such a way that it will never become eligible for garbage collection when it is not disposed. And as it will not be garbage collected, it will not have the chance to use the destructor for cleaning up.

As a result, when it is not disposed (e.g. unreliable users, programming errors), resources will be leaked.

Is there a general approach how such a class can be designed to deal with such a situation or to avoid it?

Example:

```<code>using System;

class Program
{
    static void Main(string[] args)
    {
        new Cyclical();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.ReadKey();
    }
}

class Cyclical
{
    public Cyclical()
    {
        timer = new System.Threading.Timer(Callback, null, 0, 1000);
    }

    System.Threading.Timer timer;

    void Callback(object state)
    {
        Console.Write('.');  // do something useful
    }

    ~Cyclical()
    {
        Console.WriteLine("destructor");
    }
}
</code>```

(Omitted IDisposable to keep example short.) This class uses a Timer to do something useful at certain intervals. It needs a reference to the Timer to avoid it is garbage collected.

Let’s assume the user of that class will not dispose it. As a result of the timer, somewhere some worker thread has a reference to the Cyclical instance via the callback, and as a result, the Cyclical instance will never become eligible for garbage collection, and its destructor will never run, and resources will leak.

In this example, a possible fix (or workaround) could be to use a helper class that receives callbacks from the Timer, and that does not have a reference, but only a WeakReference to the Cyclical instance, which it calls using that WeakReference.

However, in general, is there a design rule for classes like this that need to be disposed to avoid leaking resources?

For the sake of completeness, here the example including IDispose and including a workaround/solution (and with a hopefully less distracting name):

```<code>class SomethingWithTimer : IDisposable
{
   public SomethingWithTimer()
   {
      timer = new System.Threading.Timer(StaticCallback,
         new WeakReference<SomethingWithTimer>(this), 0, 1000);
   }

   System.Threading.Timer timer;

   static void StaticCallback(object state)
   {
      WeakReference<SomethingWithTimer> instanceRef
         = (WeakReference<SomethingWithTimer>) state;
      SomethingWithTimer instance;
      if (instanceRef.TryGetTarget(out instance))
         instance.Callback(null);
   }

   void Callback(object state)
   {
      Console.Write('.');  // do something useful
   }

   public void Dispose()
   {
      Dispose(true);
      GC.SuppressFinalize(this);
   }

   protected virtual void Dispose(bool disposing)
   {
      if (disposing)
      {
         Console.WriteLine("dispose");
         timer.Dispose();
      }
   }

   ~SomethingWithTimer()
   {
      Console.WriteLine("destructor");
      Dispose(false);
   }
}
</code>```

If disposed, the timer will be disposed.

If not disposed, the object will become eligible for garbage collection.

答:
One approach which can be helpful is to expose wrapper objects to the outside world, but don't hold any strong references to them internally.  Either have the internal objects keep weak references to the wrappers, or else have each wrapper hold the only reference anywhere in the world to a finalizable object which in turn holds a reference to the "real" object [I don't like having any outside-world-facing objects implement Finalize, since objects have no control over who can call things like GC.SuppressFinalize() on them].  When all outside-world references to the wrapper object have disappeared, any weak references to the wrapper object will be invalidated [and can be recognized as such], and any finalizable object to which the wrapper held the only reference will run its Finalize method.

For event handlers which are guaranteed to be triggered on some period basis (e.g. timer ticks) I like the WeakReference approach.  There's no need to use a finalizer to ensure the timer gets cleaned up; instead, the timer-tick event can notice that the outside-world link has been abandoned and clean itself up.  Such an approach may also be workable for things whose only resources are subscriptions to rarely-fired events from long-lived (or static) objects, if those objects have a CheckSubscription event which fires periodically when a subscriber is added (the rate at which those events fire should depend upon the number of subscriptions).  Event subscriptions pose a real problem is when an unbounded number of objects may subscribe to an event from a single instance of a long-lived object and be abandoned without unsubscribing; in that case, the number of abandoned-but-uncollectable subscriptions may grow without bound.  If 100 instances of a class subscribe to an event from a long-lived object and are subsequently abandoned, and nothing else ever subscribes to that event, memory used by those subscriptions may never get cleaned up, but the quantity of wasted memory would be limited to those 100 subscriptions.  Adding more subscriptions would at some point cause the CheckSubscription event to fire, which would in turn cause all the abandoned objects' subscriptions to get canceled.

PS--Another advantage of using weak references is that one can request that a WeakReference remain valid until the object to which it refers is 100% absolutely and irretrievably gone.  It's possible for an object to appear abandoned and have its Finalize method scheduled, but then get resurrected and returned to active use even before its Finalize method actually executes; this can happen completely outside the object's control.  If code holds a long weak reference to the public wrapper object, and if it makes sure the reference itself remains rooted, it can hold off on performing any cleanup until resurrection becomes impossible.


问:
What precisely do I/my company need to do "make available/publish" source code changes and satisfy GPL/LGPL
This seems like a basic question, but I have not found a definitive source.

I need to modify the source for an LGPL application for my employer to plug a security hole. Longer term we will upgrade to a later version of this application, but for now, this is the quickest solution.

(specifically: I will change a 2005-era version fork of Apache Tomcat'--jboss-web 2.0.1--to add allow "httpOnly" and 'secure' JSESSIONID cookie).

The question

What exactly must I/my company do to "make available" or "publish" the source code?

Must it be accessible from the company's own website or github repository?  Or can I have it on my own private github account and simply have the company link to it?

thanks

答:
Option (a): Source Alongside Binary

GPLv2 § 3(a) and v3 § 6(a) embody the easiest option for providing
source code: including Corresponding Source with every binary
distribution. While other options appear initially less onerous, this
option invariably minimizes potential compliance problems, because
when you distribute Corresponding Source with the binary, your GPL
obligations are satisfied at the time of distribution.

Option (b): The Offer

Many distributors prefer to ship only an offer for source with the
binary distribution, rather than the complete source package. This
option has value when the cost of source distribution is a true
per-unit cost. For example, this option might be a good choice for
embedded products with permanent storage too small to fit the source,
and which are not otherwise shipped with a CD but are shipped with a
manual or other printed material.

However, this option increases the duration of your obligations
dramatically. An offer for source must be good for three full years
from your last binary distribution (under GPLv2), or your last binary
or spare part distribution (under GPLv3). Your source code request and
provisioning system must be designed to last much longer than your
product life cycle.

In addition, if you are required to comply with the terms of GPLv2,
you cannot use a network service to provide the source code. For
GPLv2, the source code offer is fulfilled only with physical media.
This usually means that you must continue to produce an up-to-date
“source code CD” for years after the product’s end-of-life.

Under GPLv2, it is acceptable and advisable for your offer for source
code to include an Internet link for downloadable source in addition
to offering source on a physical medium. This practice enables those
with fast network connections to get the source more quickly, and
typically decreases the number of physical media fulfillment requests.
(GPLv3 § 6(b) permits provision of source with a public
network-accessible distribution only and no physical media.

http://www.softwarefreedom.org/resources/2008/compliance-guide.html


问:
Builder pattern inside interface. Bad design decision?
I am having trouble evaluating an implementation of the builder pattern I just came up with.

The context is an API library, so I am trying not to expose any implementations in order to have a stable interface while being able to change implementations later.

My thinking is that even though there is a reference to the implementation in the interface's file, the interface and the implementation are not actually coupled because

In effect, a static nested class is behaviorally a top-level class...

The benefit of this design is that clients can call

Person person = new Person.Builder().age(20).firstName("John")
                .lastName("Doe").build();

without the need for a dedicated Factory type class.

Am I missing something or is this a valid design decision?

Person.java

```<code>package net.mhi.rd;

public interface Person {

    int getAge();
    String getFirstName();
    String getLastName();

    public static class Builder {
        int age;
        String firstName;
        String lastName;

        public Builder age(int age) {
            this.age = age;
            return this;
        }

        public Builder firstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public Builder lastName(String lastName) {
            this.lastName = lastName;
            return this;
        }

        public Person build() {
            return new PersonImpl(this);
        }
    }
}
</code>```

PersonImpl.java

```<code>package net.mhi.rd;

class PersonImpl implements Person {

    private final int age;
    private final String firstName;
    private final String lastName;

    PersonImpl(Person.Builder builder) {
        this.age = builder.age;
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
    }

    @Override
    public int getAge() {
        return age;
    }

    @Override
    public String getFirstName() {
        return firstName;
    }

    @Override
    public String getLastName() {
        return lastName;
    }
}
</code>```

答:
The main problem is that you've created a circular dependency between Person and PersonImpl... Person shouldn't have any references to implementation classes, but the "new PersonImpl()" call in the builder creates a hard, compile-time dependency on the concrete class.

I think the fix is to either spin PersonBuilder off into it's own class, or else move PersonBuilder into PersonImpl. It's a little weird declaring a class inside an interface anyway -- I wouldn't say I've never done that, but it seems preferable to keep interfaces simple.

Passing the Builder as a constructor argument in PersonImpl couples the implementation class really tightly to the builder. You'd be better off keeping a cleaner separation between the builder and the buildee. The builder (obviously) needs to know about PersonImpl, but it would be best if PersonImpl didn't reference the builder.

Do you anticipate having more than one Person implementation? It's looks like a data class, and I'm not sure you need to extract an interface in the first place.

And... as a general pattern, if you're going to create a dozen or so classes like this, I think this pattern would become pretty cumbersome -- there's an interface, implementation, and builder for each class. That seems like a lot of extra code for something that may not need distinct interfaces.

Here's the variation to Builder that Josh Block came up with. It's similar in that it uses an inner class to access & set internal values, so that the class becomes effective immutable. I think the main difference with your code is that there's not a separate interface.

http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html

TL;DR:

the dependencies should go Builder --> Impl --> Interface

omitting the interface and nesting the Builder inside the Impl is a nice way to provide one-time access to the internal impl details, while hiding a circular dependency between builder and impl.


问:
Should I use different projects for building different layers in a 3-layer model?
I am creating a new project from scratch and have decided to use a 3-layer model.

I am using:

the 1st layer for business entities,

the 2nd layer for business logic,

and the 3rd layer for data logic layer.

Do I need to create different projects for these different layers or do I need to create different folders in one project?

What are the pros and cons of both approaches?

答:
The practice of putting each layer of your application in a separate project is a common one in the .net world, and is viewed by some as a "best practice," but in my experience, it actually causes more problems than it solves. In particular:

It makes it harder to upgrade third-party references, since you can all too easily end up with references to two different versions of the same assembly. NuGet alleviates the problem to an extent, but in my experience it doesn't eliminate it altogether.

It slows down compilation times.

It causes problems with circular dependencies: sooner or later there will be a set of classes that you have to add to your code, only to find that you're not sure whether they belong in your business layer, your DAL, or somewhere else altogether. Chances are high that you'll get this wrong for some reason the first time round and have to move them to a separate assembly, thereby compounding the problem.

It forces you to jump around through widely separated parts of your solution to follow through the flow of your code.

Putting your different layers into separate assemblies is also a violation of the Common Closure Principle, which says that classes that change together should be packaged together. Asssemblies -- and therefore Visual Studio projects -- are a unit of deployment, not a unit of organisation. If you want to organise your code by different layers, that's what namespaces are for.


答:
There are still some questions open regarding your game and your question.
So, I put in small answers here to questions already arising from what you have given as information:

Get your animations for your actions in the right schedule:

Write a scheduler that starts animations with a given start-up time so that
actions will have a smooth look. For example "attack" has start-up 2 seconds
and performance-time 1 second and "block" has start-up 1 second and performance
1 second. So "attack" should start 1 second before "block" can start.

As there is no information given about programming language or paradigma, only
an educated guess is left: would investigate on Command-Pattern and Chain-of-Command
for this

Find actions possible for your units in parallel:

There is some tiny environment model necessary to see which other units are "in reach"
Think that some coordinate system, depending on your game, will do the job.
Perhaps you can provide more information on that.

See results of actions of your units in parallel:

Again, I would write a scheduler to solve that, too. What I have seen in a game
was a small table leveraging time-stamps (e.g. time with second, date and so on).
This table is read from an eventhandler, which takes every second out of that table,
and handles the results. It is just some kind of message loop, but I think the idea
behind that is very clear.

Title: Strategy game, how do I calculate the parallel actions?

Body:
I am building a strategy game where multiple units(5 - 20) fighting each other.

I have a game logic that calculate all the actions that been done on each turn, and send it to the game engine to animate.

Those are the possible actions:

perform attack

perform taking damage

perform moving

perform missing

perform removing your self(dying)

How can I find what actions I can perform in parallel and what are not?

Those are the limitations that I have:

units can only perform one action at a time.

each action may have different times, even if its the same action

Unit can perform the action attack, only if the other unit performing the action taking damage or removing your self

after unit performed the action: removing your self, he cannot perform any other action.

Edit:
Those are the situations that might happened:

one unit is attacked by multiple units at once

one unit taking damage while no units are attacking him

all the units move at the same time

all the units perform miss at the same time

This question is not about game design, but a programmatic solution to how I can find those parallel tiles of actions?

Reply to FrustratedWithFormsDesign, answer

Hi man, you took it to completely different direction, so I want to reply you here to clear things up.

This questions is not about how to make units to move in parallel. I also don't think that your suggestion is a good idea.

What you did with your own game this is actually, the right direction. It will be also wise to work in MVC and separate the view and game logics.

So to implement a game engine I would use a game thread that will dispatch tick events, based on chosen frame rate. Only the views should be listening for that thread and implement they view logic based on it.

In my game I am using Adobe Air framework with some native Java and Objective-C support for mobiles, but it's Air mostly. So all my animations are listening to onEnterFrameEvent, this would be tick in your example, and implement their animation logic.

My game logic is using a different worker(air threads implementations, it's more like a process) to generate all the actions on particular turn. And than it sands it to the game engine to animate. I do not ask how to implement the animations, it's handled by Air apis, and it doesn't meter in here.

Think about those problems:

unit a attacks unit b while unit b attacks unit c, while unit c is moving.

This will resolute with a mess on the screen.

I want it to be:

unit a attack unit b, unit b waits for a to finish attacking him to
  start attacking unit c, while unit c is moving. After a finish attacking unit b, unit b attacks unit c.

So the input of actions I received was:

A attack

B take damage

B attack

C take damage

C move

And the output was two sets of animations

A attack, C move, B take damage

B attack, C take damage

This was a very simple example of how I would like to parallel my actions. I hope now it is more clear.


问:
IPv4 to IPv6. where is IPv5?
As all of us know that after IPv4 it came IPv6. How this transition happened?

I just want to know was there any IPv5 also? or there is any other logic in naming this version of IP as IPv6?

答:
The version numbers for the 'version' are part of the IP header field (described in RFC 791) and is 4 bits wide.  As with many of the numbers that find their way into the internet, the numbers for the version are part of the Internet Assigned Numbers Authority.

The list of the version numbers can be found at http://www.iana.org/assignments/version-numbers/version-numbers.xhtml which shows:

```
 0         Reserved                      https://www.rfc-editor.org/rfc/rfc4928 section 3
 1         Reserved                      https://www.rfc-editor.org/rfc/rfc4928 section 3
 2         Unassigned
 3         Unassigned
 4 IP    - Internet Protocol             https://www.rfc-editor.org/rfc/rfc791
 5 ST    - ST Datagram Mode              https://www.rfc-editor.org/rfc/rfc1190
 6 IPv6  - Internet Protocol version 6   https://www.rfc-editor.org/rfc/rfc1752
 7 TP/IX - TP/IX: The Next Internet      https://www.rfc-editor.org/rfc/rfc1475
 8 PiP   - The P Internet Protocol       https://www.rfc-editor.org/rfc/rfc1621
 9 TUBA  - TUBA                          https://www.rfc-editor.org/rfc/rfc1347
10         Unassigned
11         Unassigned
12         Unassigned
13         Unassigned
14         Unassigned
15         Reserved
```

And this is where the numbers come from and whats already out there.  If there is something after IPv6 that is not one of the already defined numbers, the next available internet protocol version number available is 10.

The specifics of ST can be read in RFC 1190.  This protocol was developed by Jim Forgie and was never more than experimental.  The wikipedia page about it can be found at Internet Stream Protocol.

Note that these assigned numbers were from days back when things were a bit more... care free with the internet.  Classful network /8 blocks were given out fairly freely (known as 'class A' networks) - a number of universities have network spaces of millions (16.7M) of IPv4 addresses.

Allocating versions numbers to experimental protocols was probably also a sign of the times (though IPv6 has made it to practical use).  IANA is much more conservative with assigning numbers today.

Title: IPv4 to IPv6. where is IPv5?

Body:
The version numbers for the 'version' are part of the IP header field (described in RFC 791) and is 4 bits wide.  As with many of the numbers that find their way into the internet, the numbers for the version are part of the Internet Assigned Numbers Authority.

The list of the version numbers can be found at http://www.iana.org/assignments/version-numbers/version-numbers.xhtml which shows:

 0         Reserved                      https://www.rfc-editor.org/rfc/rfc4928 section 3
 1         Reserved                      https://www.rfc-editor.org/rfc/rfc4928 section 3
 2         Unassigned
 3         Unassigned
 4 IP    - Internet Protocol             https://www.rfc-editor.org/rfc/rfc791
 5 ST    - ST Datagram Mode              https://www.rfc-editor.org/rfc/rfc1190
 6 IPv6  - Internet Protocol version 6   https://www.rfc-editor.org/rfc/rfc1752
 7 TP/IX - TP/IX: The Next Internet      https://www.rfc-editor.org/rfc/rfc1475
 8 PiP   - The P Internet Protocol       https://www.rfc-editor.org/rfc/rfc1621
 9 TUBA  - TUBA                          https://www.rfc-editor.org/rfc/rfc1347
10         Unassigned
11         Unassigned
12         Unassigned
13         Unassigned
14         Unassigned
15         Reserved

And this is where the numbers come from and whats already out there.  If there is something after IPv6 that is not one of the already defined numbers, the next available internet protocol version number available is 10.

The specifics of ST can be read in RFC 1190.  This protocol was developed by Jim Forgie and was never more than experimental.  The wikipedia page about it can be found at Internet Stream Protocol.

Note that these assigned numbers were from days back when things were a bit more... care free with the internet.  Classful network /8 blocks were given out fairly freely (known as 'class A' networks) - a number of universities have network spaces of millions (16.7M) of IPv4 addresses.

Allocating versions numbers to experimental protocols was probably also a sign of the times (though IPv6 has made it to practical use).  IANA is much more conservative with assigning numbers today.


问:
How to test and optimize when you can't reproduce the environment?
In the past, I've worked in a variety of environments. Desktop apps, games, embedded stuff, web services, command line jobs, web sites, database reporting, and so on. All of these environments shared the same trait: no matter their complexity, no matter their size, I could always have a subset or slice of the application on my machine or in a dev environment to test.

Today I do not. Today I find myself in an environment whose primary focus is on scalability. Reproducing the environment is prohibitively costly. Taking a slice of the environment, while plausible (some of the pieces would need to be simulated, or used in a single-instance mode that they're not made to do), kinda defeats the purpose since it obscures the concurrency and loading that the real system encounters. Even a small "test" system has its flaws. Things will behave differently when you've got 2 nodes and when you have 64 nodes.

My usual approach to optimization (measure, try something, verify correctness, measure differences, repeat) doesn't really work here since I can't effectively do steps 2 and 3 for the parts of the problem that matter (concurrency robustness and performance under load). This scenario doesn't seem unique though. What is the common approach to doing this sort of task in this sort of environment?

There are some related questions:

this question has to do with hardware (like spectrum analyzers) being unavailable, which can be (relatively) easily emulated.

this question is about tracking down bugs that only exist in production environments, which is helpful - but a different sort of activity.

答:
I'd suggest experiments.

Logging will find bottlenecks. You can then try an alternative implementation on some machines, or even on all machines with a certain probability, or for a limited time period. Then compare the logs again to check for improvements.

It's the same theory-experiment-measure cycle you're used to, but more expensive to set up - since hypotheses have to be run in production - and depending on your volume, receiving significant data from production may be slow as well.


问:
Is SourceSafe really safe?
Having spent all morning trying to check something in - I now realise I've lost a couple of days worth of work.

Its happened before - and is apparently common occurrence with SourceSafe.  Can SourceSafe be used successfully, without problems, and if so, how?

答:
used it for years - it was the default solution, as it was already there. Had it bite me quite a few times, but inertia is difficult to overcome

then i had to use it remotely over VPN, and even minor check-ins were like stuffing a brick through a pinhole. It was faster to manually find the files that changed, zip them up, email them, remote in to the source vault machine, unzip them, and check in the code from the source vault machine.

Switched to Mercurial. I can clone the entire source code base across the VPN in under a minute. And I no longer fear branching.

Never going back.

Title: Is SourceSafe really safe?

ContentLicense: CC BY-SA 2.5


问:
Designing database related methods, which is better to return: true/false or row affected?
I have some methods that perform some data changing in a database (insert, update, and delete). The ORM I'm using return row-affected int values for those type of method. What should I return for "my method", in order to indicate the success/failure state of the operation?

Consider the code that is returning an int:

A.1

```<code>public int myLowerLevelMethod(int id) {
    ...
    int affectedRows = myOrm.deleteById(id)
    ...

    return affectedRows;
}
</code>```

Then usage:

A.2

```<code>public void myOtherMethod() {
    ...
    int affectedRows = myLowerLevelMethod(id)

    if(affectedRows > 0) {
        // Success
    } else {
        // Fail
    }
}
</code>```

Compare to using boolean:

B.1

```<code>public boolean myLowerLevelMethod(int id) {
    ...
    int affectedRows = myOrm.deleteById(id)
    ...

    return affectedRows > 0;
}
</code>```

Then usage:

B.2

```<code>public void myOtherMethod() {
    ...
    boolean isSuccess = myLowerLevelMethod(id)

    if(isSuccess) {
        // Success
    } else {
        // Fail
    }
}
</code>```

Which one (A or B) is better? Or pros/cons of each?

答:
Two of the most important principles in maintainable software design are KISS and YAGNI.

KISS: Keep it Simple, Stupid

YAGNI: You Aren't Gonna Need It

It is almost never a good idea to put in logic you don't immediately need right now. Among many other people, Jeff Atwood (a co-founder of StackExchange) wrote about this, and in my experience he and other proponents of these concepts are completely right.

Any complexity you add to a program comes at a cost, paid over a long period of time. The program becomes more difficult to read, more complex to change, and easier for bugs to creep in. Don't fall for the trap of adding things "just in case". It's a false sense of security.

You are rarely ever going to get any code right the first time. Changes are inevitable; adding in speculative logic to defensively prepare for unknown future contingencies will not actually protect you from having to refactor your code when the future turns out to be different than you expected. Upkeep on unnecessary/contingent logic is more of a maintainability problem than refactoring later to add in missing functionality.

Thus, since it appears that all your program needs for now is to know whether the operation succeeded or failed, your proposed solution B (return a single boolean) is the correct approach. You can always refactor it later if the requirement changes. This solution is the simplest and has lowest complexity (KISS) and does just what you need and nothing more (YAGNI).