Can I prevent future developers from making an object constructible?

you have a class A where you set the ctor to be private so the client cannot call "A a"; to create object obj. But someday another developer adds a new ctor: "A (INT)" and try calling "A a (1)"; inside main (). So this will create a stack obj. How do you prevent this?

+2


a source to share


4 answers


Nothing you can do to C ++ source code can restrict the future behavior of other people with permission to modify C ++ source code. This other developer could have removed the "private:" line as easily as adding a public constructor with a different signature. All you can do is carefully comment on the reasons why this class should not be allocated directly, and expect other developers to read and pay attention.



+4


a source


If, as you imply, your class gets edited, then you can't do anything that you can't "edit" - you only have a private ctor, but it was edited by another developer. Just document very clearly that a class should never be edited to have public ctors, and as the comment says, don't hire people to flout such requirements! -)



+11


a source


Well, I can think of several ways:

  • If you are using some kind of source control software (and you should!), You can tweak the commit commits to prevent any changes to that file (or create a regex to make it impossible to add new constructors).

  • You can also wrap the entire class in a DLL and require the project to reference it and use the public interface that you export from the DLL. They cannot go to the source if they cannot see it.

  • Hire a guy with a big baseball bat standing next to a developer. He should be wearing a T-shirt with a "constructor of class X must not be changed" on it.

0


a source


The error is the statement that "no one in the future could use this in some way that I hadn't thought of."

Compose your object and make it fail if it doesn't work as expected. Don't arbitrarily say "don't create this on the stack" and then make the ctor private; maybe I have a good reason to want to aggregate this object in another.

Programmers need to focus on making the code they write works the way it intended to work, and they also need to tweak everything so it's obvious when something goes wrong like a problem. Programmers should not code arbitrary expected or desired or intended usage patterns into their software. Making a private constructor is just yelling at the user that they can't be smart enough to create things on their own. As a result, a lot of people will use your factory interface or whatever you provide, but you don't know every possible future requirement, so just be left alone.

If you're worried about others making changes and then you're on the hook for debugging, write some unit tests. If you get a bug report that doesn't fit your tests, then either write a test, fix the bug, or find out who made the change and bounced that person.

0


a source







All Articles