4 ms·
I agree that if your private functionality has grown complex, that's a strong "code smell" that perhaps it needs to be extracted. But yeah, then you've changed
by JohnBooty 3y ago
I agree that if your private functionality has grown complex, that's a strong "code smell" that perhaps it needs to be extracted.
But yeah, then you've changed it from private to public.
- stouset 3y agoIn my experience refactoring and making things public is an entirely reasonable thing to do! I often find that when I have a very complicated structure with lots of behavior, there’s some other cohesive unit of functionality living inside. That part is often private, but extracting it into a separate structure with public interfaces makes complete sense. From the perspective of consumers of the original class, all of this is still implementation detail that can’t be directly accessed. But there’s nothing wrong about accessing that underlying bit directly through its own public interface.
- sverhagen 3y agoPrivate methods can benefit from knowledge about the class they live in, and be only good enough for their purpose in that class. When elevated to public methods, you may want them to be more defensive than when they were private, which is an investment that doesn't pay off in itself. People may also be tempted to reuse your public methods now, even if they were never intended for that. Java has package-private for that (I guess). I'm not a fan of package-private, but then again, I'm writing small micro-services and considering the code inside this service "friendly" to my class, i.e. not abusing public methods without looking inside them to see if they're up for the job.
- stouset 3y agoThat's not really what I'm talking about at all. Private methods are often useful for handling internal details. But often when you have a lot of private methods, you're bundling too much functionality into one object. I have found that it is very common that I get significant improvements in readability, testability, and comprehensibility when I decompose a large structure with a lot of private methods into a few smaller structures that operate on each others' public API.