3 ms·
> I use c# and will usually create a class where it makes sense for there to be a “state” managed by a bunch of methods. Where you don’t want anyone outside dir
by replwoacause 5y ago
> I use c# and will usually create a class where it makes sense for there to be a “state” managed by a bunch of methods. Where you don’t want anyone outside directly playing with that state.
Are the methods that are managing the state of that object apart of that same class or a different one? Or doesn't that matter? When you say "anyone outside" do you mean, for example, another developer who might be using your code as a library? If so, couldn't they just modify your code to work with it however they want irrespective of how you wrote it?
> I very rarely use inheritance. I can’t remember the last time I added inheritance but I sometimes come across it in code bases. Normally when there are something resembling UI widgets that have a common base.
This is helpful to know.
> My first advice is don’t worry - if your code works and is understandable all is good.
Thank you, that is encouraging.
- quickthrower2 5y agoUsually the state is managed by methods of the class only, with these methods providing the public access or “api”. This is like a facade or a shop front. The menu you order from but not the kitchen or the chef. This means you interact with the class just through the methods. Sometimes the methods are simple - it can be a get and set method wrapping a state. Why bother? Why not just make the state public? Because then other classes start to depend on the inner workings of the class in order to not be broken. For example suddenly you realise a string has to be valid e.g. it is an email address. With a getter and setter later on you can add validation to the setter if you wish. —- When I said “Anyone outside” this might be misleading. I should say any code outside the class. This is not really for security - as you said if the other developer has the source they can change it and use the changed source. You don’t enforce security with classes. Rather than security, the purpose of classes is abstraction: the goal of reducing the cognitive load. The load on your brain. For example most programming languages will provide classes to open a file. You can now work with the file system in an abstract way without writing code that cares about Unix/windows file system differences in your code that is doing something else. This means someone can write a program to scan your disk for mp3 files and catalog them without knowing the details of the files stem, and in such a way that if in the future the file system classes are updated to handle say NAS your mp3 hunter program still works. Even better it gets a new feature for free!