There is a lot of code in one of our projects that looks like this:
internal static class Extensions
{
public static string AddFoo(this string s)
{
if (!string.IsNullOrEmpty(s)) return s + "Foo";
return "Foo";
}
}
Is there any explicit reason to do this other than "it is easier to make the type public later?"
I suspect it only matters in very strange edge cases (reflection in Silverlight) or not at all.
I think I have an additional opinion on this. At first, I was wondering about how it makes sense to declare something to public in an internal class. Then I have ended up here, reading that it could be good if you later decide to change the class to public. True. So, a pattern formed in my mind: If it does not change the current behavior, then be permissive, and allow things that does not makes sense (and does not hurt) in the current state of code, but later it would, if you change the declaration of the class.
Like this:
According to the "pattern" I have mentioned above, this should be perfectly fine. It follows the same idea. It behaves as a
private
method, since you can not inherit the class. But if you delete thesealed
constraint, it is still valid: the inherited classes can see this method, which is absolutely what I wanted to achieve. But you get a warning:CS0628
, orCA1047
. Both of them is about do not declareprotected
members in asealed
class. Moreover, I have found full agreement, about that it is senseless: 'Protected member in sealed class' warning (a singleton class)So after this warning and the discussion linked, I have decided to make everything internal or less, in an internal class, because it conforms more that kind of thinking, and we don't mix different "patterns".
I suspect that "it is easier to make the type public later?" is it.
The scoping rules mean that the method will only be visible as
internal
- so it really doesn't matter whether the methods are markedpublic
orinternal
.One possibility that comes to mind is that the class was public and was later changed to
internal
and the developer didn't bother to change all the method accessibility modifiers.If the class is
internal
, it doesn't matter from an accessibility standpoint whether you mark a methodinternal
orpublic
. However it is still good to use the type you would use if the class werepublic
.While some have said that this eases transitions from
internal
topublic
. It also serves as part of the description of the method.Internal
methods typically are considered unsafe for unfettered access, whilepublic
methods are considered to be (mostly) free game.By using
internal
orpublic
as you would in apublic
class, you ensure that you are communicating what style of access is expected, while also easing the work required to make the classpublic
in the future.It's the same, the public method will be really marked as internal since it's inside a internal class, but it has an advantaje(as you guested), if you want to mark the class as public, you have to change fewer code.