In Swift, I have historically used extensions to extend closed types and provide handy, logic-less functionality, like animations, math extensions etc. However, since extensions are hard dependencies sprinkled all over your code-base, I always think three times before implementing something as an extension.
Lately, though, I have seen that Apple suggests using extensions to an even greater extent, e.g. implementing protocols as separate extensions.
That is, if you have a class A that implement protocol B, you end up with this design:
class A {
// Initializers, stored properties etc.
}
extension A: B {
// Protocol implementation
}
As you enter that rabbit-hole, I started seeing more extension-based code, like:
fileprivate extension A {
// Private, calculated properties
}
fileprivate extension A {
// Private functions
}
One part of me likes the building-blocks you get when you implement protocols in separate extensions. It makes the separate parts of the class really distinct. However, as soon as you inherit this class, you will have to change this design, since extension functions cannot be overridden.
I think the second approach is...interesting. Once great thing with it is that you do not have to annotate each private property and function as private, since you can specify that for the extension.
However, this design also splits up stored and non-stored properties, public and private functions, making the "logic" of the class harder to follow (write smaller classes, I know). That, together with the subclassing issues, makes me halt a bit on the porch of extension wonderland.
Would love to hear how the Swift community of the world looks at extensions. What do you think? Is there a silverbullet?
This is only my opinion, of course, so take what I'll write easy.
I'm currently using the extension-approach in my projects for few reasons:
The code is much more clean: my classes are never over 150 lines and the separation through extensions makes my code more readable and separated by responsibilities
This is usually what a class looks like:
final class A {
// Here the public and private stored properties
}
extension A {
// Here the public methods and public non-stored properties
}
fileprivate extension A {
// here my private methods
}
The extensions can be more than one, of course, it depends on what your class does. This is simply useful to organize your code and read it from the Xcode top bar
It reminds me that Swift is a protocol-oriented-programming language, not an OOP language. There is nothing you can't do with protocol and protocol extensions. And I prefer to use protocols for adding a security layer to my classes / struct. For example I usually write my models in this way:
protocol User {
var uid: String { get }
var name: String { get }
}
final class UserModel: User {
var uid: String
var name: String
init(uid: String, name: String) {
self.uid = uid
self.name = name
}
}
In this way you can still edit your uid and name values inside the UserModel class, but you can't outside since you'll only handle the User protocol type.
I use a similar approach, which can be described in one sentence:
Sort a type's responsibilities into extensions
These are examples for aspects I'm putting into individual extensions:
A type's main interface, as seen from a client.
Protocol conformances (i.e. a delegate protocol, often private).
Serialization (for example everything NSCoding related).
Parts of a types that live on a background thread, like network callbacks.
Sometimes, when the complexity of a single aspect rises, I even split a type's implementation over more than one file.
Here are some details that describe how I sort implementation related code:
The focus is on functional membership.
Keep public and private implementations close, but separated.
Don't split between var and func.
Keep all aspects of a functionality's implementation together: nested types, initializers, protocol conformances, etc.
Advantage
The main reason to separate aspects of a type is to make it easier to read and understand.
When reading foreign (or my own old) code, understanding the big picture is often the most difficult part of diving in. Giving a developer an idea of a context of some method helps a lot.
There's another benefit: Access control makes it easier not to call something inadvertently. A method that is only supposed to be called from a background thread can be declared private in the "background" extension. Now it simply can't be called from elsewhere.
Current Restrictions
Swift 3 imposes certain restrictions on this style. There are a couple of things that can only live in the main type's implementation:
stored properties
overriding func/var
overidable func/var
required (designated) initializers
These restrictions (at least the first three) come from the necessity to know the object's data layout (and witness table for pure Swift) in advance. Extensions can potentially be loaded late during runtime (via frameworks, plugins, dlopen, ...) and changing the type's layout after instances have been created would brake their ABI.
A modest proposal for the Swift team :)
All code from one module is guaranteed to be available at the same time. The restrictions that prevent fully separating functional aspects could be circumvented if the Swift compiler would allow to "compose" types within a single module. With composing types I mean that the compiler would collect all declarations that define a type's layout from all files within a module. Like with other aspects of the language it would find intra file dependencies automatically.
This would allow to really write "aspect oriented" extensions. Not having to declare stored properties or overrides in the main declaration would enable better access control and separation of concerns.
I hate it. It adds extra complexity and muddies the use of extensions, making it unclear on what to expect that people are using the extensions for.
If you're using an extension for protocol conformance, OK, I can see that, but why not just comment your code? How is this better? I don't see that.
Related
I tried to declare an enum inside the class and it gave me an error stating can't have enum inside a class. I wanted to know the reason why but I didn't find anything on the internet. Declaring enum inside a class is allowed by major languages why not dart?
Dart does not allow nested type declarations in general. You can only declare types at top-level. This includes classes, mixins, typedefs and enums.
I believe the original reason was that it was not necessary, and implementing it inadequately was worse than not doing allowing it at all.
There is nothing inherently preventing Dart from allowing static types declared inside other types. Obviously, if Dart allowed classes statically declared inside classes, it would allow in arbitrary nesting of classes, so it really is a matter of allowing zero, one or an infinite amount of nesting. Dart currently has "one'.
Still, it's something that can be easily remedied if deemed wort the effort and a higher priority than other language changes.
The other option is to have non static nested types. That's a much bigger can of worms, and probably not something that's going to happen any time soon, if ever.
Dart doesn't allow declaring of Enum inside the class as far as I know. I've made that error before and it took me a minute to figure out what was wrong with my code. Declare/setup your Enum before your class like so:
enum Gender {
male,
female,
}
/// Then declare your class next
class MyClass {
/// The rest of your code goes here, and you still have access to your enum
}
In Java, it is very common to have a list of utility functions
public class Utils {
private Utils() {
}
public static void doSomething() {
System.out.println("Utils")
}
}
If I were in Swift, should I use class or struct to achieve the similar thing? Or, it really doesn't matter?
class
class Utils {
private init() {
}
static func doSomething() {
print("class Utils")
}
}
struct
struct Utils {
private init() {
}
static func doSomething() {
print("struct Utils")
}
}
I think a conversation about this has to start with an understanding of dependancy injection, what it is and what problem it solves.
Dependancy Injection
Programming is all about the assembly of small components into every-more-abstract assemblies that do cool things. That's fine, but large assemblies are hard to test, because they're very complex. Ideally, we want to test the small components, and the way they fit together, rather than testing entire assemblies.
To that end, unit and integration tests are incredibly useful. However, every global function call (including direct calls to static functions, which are really just global functions in a nice little namespace) is a liability. It's a fixed junction with no seam that can be cut apart by a unit test. For example, if you have a view controller that directly calls a sort method, you have no way to test your view controller in isolation of the sort method. There's a few consequences of this:
Your unit tests take longer, because they test dependancies multiple times (e.g. the sort method is tested by every piece of code that uses it). This disincentivizes running them regularly, which is a big deal.
Your unit tests become worse at isolating issues. Broke the sort method? Now half your tests are failing (everything that transitively depends on the sort method). Hunting down the issue is harder than if only a single test-case failed.
Dynamic dispatch introduces seams. Seams are points of configurability in the code. Where one implementation can be changed taken out, and another one put in. For example, you might want to have a an MockDataStore, a BetaDataStore, and a ProdDataStore, which is picked depending on the environment. If all 3 of these types conform to a common protocol, than dependant code could be written to depend on the protocol that allows these different implementations to be swapped around as necessary.
To this end, for code that you want to be able to isolate out, you never want to use global functions (like foo()), or direct calls to static functinos (which are effectively just global functions in a namespace), like FooUtils.foo(). If you want to replace foo() with foo2() or FooUtils.foo() with BarUtils.foo(), you can't.
Dependancy injection is the practice of "injecting" dependancies (depending on a configuration, rather than hard coding them. Rather than hard-coding a dependancy on FooUtils.foo(), you make a Fooable interface, which requires a function foo. In the dependant code (the type that will call foo), you will store an instance member of type Fooable. When you need to call foo, call self.myFoo.foo(). This way, you will be calling whatever implementation of Fooable has been provided ("injected") to the self instance at the time of its construction. It could be a MockFoo, a NoOpFoo, a ProdFoo, it doesn't care. All it knows is that its myFoo member has a foo function, and that it can be called to take care of all of it's foo needs.
The same thing above could also be achieve a base-class/sub-class relationship, which for these intents and purposes acts just like a protocol/conforming-type relationship.
The tools of the trade
As you noticed, Swift gives much more flexibility in Java. When writing a function, you have the option to use:
A global function
An instance function (of a struct, class, or enum)
A static function (of a struct, class, or enum)
A class function (of a class)
There is a time and a place where each is appropriate. Java shoves options 2 and 3 down your throat (mainly option 2), whereas Swift lets you lean on your own judgement more often. I'll talk about each case, when you might want to use it, and when you might not.
1) Global functions
These can be useful for one-of utility functions, where there isn't much benefit to " grouping" them in a particular way.
Pros:
Short names due to unqualified access (can access foo, rather than FooUtils.foo)
Short to write
Cons:
Pollutes the global name space, and makes auto-completion less useful.
Not grouped in a way that aids discoverability
Cannot be dependancy injected
Any accessed state must be global state, which is almost always a recipe for a disaster
2) Instance functions
Pros:
Group related operations under a common namespace
Have access to localized state (the members of self), which is almost always preferable over global state.
Can be dependancy injected
Can be overridden by subclasses
Cons:
Longer to write than global functions
Sometimes instances don't make sense. E.g. if you have to make an empty MathUtils object, just to use its pow instance method, which doesn't actually use any instance data (e.g. MathUtils().pow(2, 2))
3) Static functions
Pros:
Group related operations under a common namespace
Can be dependancy in Swift (where protocols can support the requirement for static functions, subscripts, and properties)
Cons:
Longer to write than global functions
It's hard to extend these to be stateful in the future. Once a function is written as static, it requires an API-breaking change to turn it into an instance function, which is necessary if the need for instance state ever arrises.
4) Class functions
For classes, static func is like final class func. These are supported in Java, but in Swift you can also have non-finals class functions. The only difference here is that they support overriding (by a subclass). All other pro/cons are shared with static functions.
Which one should I use?
It depends.
If the piece you're programming is one that would like to isolate for testing, then global functions aren't a candidate. You have to use either protocol or inheritance based dependancy injection. Static functions could be appropriate if the code does not nned to have some sort of instance state (and is never expected to need it), whereas an instance function should be when instance state is needed. If you're not sure, you should opt for an instance function, because as mentioned earlier, transitioning a function from static to instance is an API breaking change, and one that you would want to avoid if possible.
If the new piece is really simple, perhaps it could be a global function. E.g. print, min, abs, isKnownUniquelyReferenced, etc. But only if there's no grouping that makes sense. There are exceptions to look out for:
If your code repeats a common prefix, naming pattern, etc., that's a strong indication that a logical grouping exists, which could be better expressed as unification under a common namespace. For example:
func formatDecimal(_: Decimal) -> String { ... }
func formatCurrency(_: Price) -> String { ... }
func formatDate(_: Date) -> String { ... }
func formatDistance(_: Measurement<Distance>) -> String { ... }
Could be better expressed if these functions were grouped under a common umbrella. In this case, we don't need instance state, so we don't need to use instance methods. Additionally, it would make sense to have an instance of FormattingUtils (since it has no state, and nothing that could use that state), so outlawing the creation of instances is probably a good idea. An empty enum does just that.
enum FormatUtils {
func formatDecimal(_: Decimal) -> String { ... }
func formatCurrency(_: Price) -> String { ... }
func formatDate(_: Date) -> String { ... }
func formatDistance(_: Measurement<Distance>) -> String { ... }
}
Not only does this logical grouping "make sense", it also has the added benefit of bringing you one step closer to supporting dependancy injection for this type. All you would need is to extract the interface into a new FormatterUtils protocol, rename this type to ProdFormatterUtils, and change dependant code to rely on the protocol rather than the concrete type.
If you find that you have code like in case 1, but also find yourself repeating the same parameter in each function, that's a very strong indication that you have a type abstraction just waiting to be discovered. Consider this example:
func enableLED(pin: Int) { ... }
func disableLED(pin: Int) { ... }
func checkLEDStatus(pin: Int) -> Bool { ... }
Not only can we apply the refactoring from point 1 above, but we can also notice that pin: Int is a repeated parameter, which could be better expressed as an instance of a type. Compare:
class LED { // or struct/enum, depending on the situation.
let pin: Int
init(pin: Int)? {
guard pinNumberIsValid(pin) else { return nil }
self.pin = pin
}
func enable() { ... }
func disable() { ... }
func status() -> Bool { ... }
}
Compared to the refactoring from point 1, this changes the call site from
LEDUtils.enableLED(pin: 1)`
LEDUtils.disableLED(pin: 1)`
to
guard let redLED = LED(pin: 1) else { fatalError("Invalid LED pin!") }
redLED.enable();
redLED.disable();
Not only is this nicer, but now we have a way to clearly distinguish functions that expect any old integer, and those which expect an LED pin's number, by using Int vs LED. We also give a central place for all LED-related operations, and a central point at which we can validate that a pin number is indeed valid. You know that if you have an instance of LED provided to you, the pin is valid. You don't need to check it for yourself, because you can rely on it already having been checked (otherwise this LED instance wouldn't exist).
Many CocoaPod and native iOS libraries use protocols that they name either CustomClassDelegate or CustomClassDataSource as a means to do some setup or customization. I was wondering when I should use this programming model, because it seems like I could accomplish much of this with properties.
Example
If I define a custom class called SmurfViewController that has a SmurfLabel, is it better practice to store the smurfLabel as a private property and have a public computed property called smurf that looks like this:
private var smurfLabel = UILabel()
public var smurf: String {
get {
return smurfLabel.text
}
set(text) {
smurfLabel.text = text
}
}
or should I define a SmurfDataSource that has a public function that looks like this:
func textForSmurfLabel() -> String {
return "smurfText"
}
When should I use what here?
You should just use a property for that. Delegates and Datasources are for different controllers/Objects to speak to one another when the alternative is to instantiate the controller/object from the navigationStack/view hierarchy. A Delegate forms a specific communication between the two that allows for clear knowledge in what their relationship is while keeping them decoupled (assuming you try to keep it that way). I disagree with the article that says callbacks are "better". They are amazing and I advise using them often, but just understand that most options that swift provides you with have a place where they work best.
I might be slightly bias, but Swift is an amazing language with OOP being a backbone and everything it has was well put together in order to provide the correct tools for each situation you find yourself in.
I often find myself using both of those tools and one other more customizable option in my more advanced setups where I have an overseeing viewController that manages many child controllers. It has direct access to all of them that are active but if any of its children communicate with it, it is through delegates. Its main job is just to handle their place on the screen though, so I keep everything manageable.
Delegates and data sources are more appropriate for offloading behaviors to other entities, not simple values. In other words, if your type just needs a value for something, you are correct that it makes more sense to expose that as a property that can be set from the client code.
But what should happen (for example) when a user taps a specific table view cell is a behavior that shouldn't be hard coded into UITableView. Instead, for flexibility, any implementation of that behavior can be created in a delegate and called by the UITableView when appropriate.
In general, think of delegation as a way to make subclassing unnecessary, because the methods you would normally override in a subclass are instead moved into a protocol that can be implemented by ANY type, not just a subclass of the base type. And instead of calling internally implemented methods to get certain behaviors, your type is simply calling those behaviors on an external collaborating class (the delegate).
So perhaps the best guideline for when to use a data source or delegate is the question: "Would I need to subclass this class in order to change this value or behavior in the future". If the answer is no, because you can just set a property from client code, then don't use delegation. If the answer is yes, then offload that behavior to a delegate or data source instead of forcing future programmers to subclass your class to make it work for their use case.
Delegate is an interface for the undefined activities.
so when you make a SDK or framework, you must provide an interface so that users can write a proper code for the interfaces' expecting activity.
i.e, Table View needs a datasource to show it's contents, but the apple's library developers doesn't know the content whatever contents their library users will use. so they provided an interface like datasource, delegate.
and in the library, they just call this methods. that's the way the library should be made.
But in your code, the label is defined very explicitly as well as it's in the current view, and you don't need to make an interface for an undefined activity.
if you want know more about this kind of coding style, you need to do some researches on Software Design Pattern.
https://en.wikipedia.org/wiki/Observer_pattern
https://en.wikipedia.org/wiki/Delegation_pattern
https://en.wikipedia.org/wiki/Software_design_pattern
I love apple's sdk very much, because they used all the needed design patterns very properly.
It's possible to add extensions to existing Swift object types using extensions, as described in the language specification.
As a result, it's possible to create extensions such as:
extension String {
var utf8data:NSData {
return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
However, what's the best naming practice for Swift source files containing such extensions?
In the past, the convention was to use extendedtype+categoryname.m for the Objective-C
type as discussed in the Objective-C guide. But the Swift example doesn't have a category name, and calling it String.swift doesn't seem appropriate.
So the question is: given the above String extension, what should the swift source file be called?
Most examples I have seen mimic the Objective-C approach. The example extension above would be:
String+UTF8Data.swift
The advantages are that the naming convention makes it easy to understand that it is an extension, and which Class is being extended.
The problem with using Extensions.swift or even StringExtensions.swift is that it's not possible to infer the purpose of the file by its name without looking at its contents.
Using xxxable.swift approach as used by Java works okay for protocols or extensions that only define methods. But again, the example above defines an attribute so that UTF8Dataable.swift doesn't make much grammatical sense.
I prefer having a + to underline the fact it contains extensions :
String+Extensions.swift
And if the file gets too big, you can then split it for each purpose :
String+UTF8Data.swift
String+Encrypt.swift
There is no Swift convention. Keep it simple:
StringExtensions.swift
I create one file for each class I'm extending. If you use a single file for all extensions, it will quickly become a jungle.
I prefer StringExtensions.swift until I added too much things to split the file into something like String+utf8Data.swift and String+Encrypt.swift.
One more thing, to combine similar files into one will make your building more faster. Refer to Optimizing-Swift-Build-Times
Rather than adding my comments all over the place, I'm surfacing them all here in one answer.
Personally, I take a hybrid approach that gives both good usability and clarity, while also not cluttering up the API surface area for the object that I'm extending.
For instance, anything that makes sense to be available to any string would go in StringExtensions.swift such as trimRight() and removeBlankLines().
However, if I had an extension function such as formatAsAccountNumber() it would not go in that file because 'Account Number' is not something that would naturally apply to any/all strings and only makes sense in the context of accounts. In that case, I would create a file called Strings+AccountFormatting.swift or maybe even Strings+CustomFormatting.swift with a formatAsAccountNumber() function if there are several types/ways to actually format it.
Actually, in that last example, I actively dissuade my team from using extensions like that in the first place, and would instead encourage something like AccountNumberFormatter.format(String) instead as that doesn't touch the String API surface area at all, as it shouldn't. The exception would be if you defined that extension in the same file where it's used, but then it wouldn't have it's own filename anyway.
If you have a team-agreed set of common and miscellaneous enhancements, lumping them together as an Extensions.swift works as Keep-It-Simple first level solution. However, as your complexity grows, or the extensions become more involved, a hierarchy is needed to encapsulate the complexity. In such circumstances I recommend the following practice with an example.
I had a class which talks to my back-end, called Server. It started to grow bigger to cover two different target apps. Some people like a large file but just logically split up with extensions. My preference is to keep each file relatively short so I chose the following solution. Server originally conformed to CloudAdapterProtocol and implemented all its methods. What I did was to turn the protocol into a hierarchy, by making it refer to subordinate protocols:
protocol CloudAdapterProtocol: ReggyCloudProtocol, ProReggyCloudProtocol {
var server: CloudServer {
get set
}
func getServerApiVersion(handler: #escaping (String?, Error?) -> Swift.Void)
}
In Server.swift I have
import Foundation
import UIKit
import Alamofire
import AlamofireImage
class Server: CloudAdapterProtocol {
.
.
func getServerApiVersion(handler: #escaping (String?, Error?) -> Swift.Void) {
.
.
}
Server.swift then just implements the core server API for setting the server and getting the API version. The real work is split into two files:
Server_ReggyCloudProtocol.swift
Server_ProReggyCloudProtocol.swift
These implement the respective protocols.
It means you need to have import declarations in the other files (for Alamofire in this example) but its a clean solution in terms of segregating interfaces in my view.
I think this approach works equally well with externally specified classes as well as your own.
Why is this even a debate? Should I put all my sub classes into a file called _Subclasses.swift. I think not. Swift has module based name spacing. To extend a well known Swift class needs a file that is specific to its purpose. I could have a large team that creates a file that is UIViewExtensions.swift that express no purpose and will confuse developers and could be easily duplicated in the project which would not build. The Objective-C naming convention works fine and until Swift has real name spacing, it is the best way to go.
I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.
Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.
So, what's the whole point in these restrictions?
The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.
The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.
If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.
The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.
A small example, suppose we have:
class MyDate
{
public int y, m, d;
public void AdvanceDays(int n) { ... } // complicated month/year overflow
// other utility methods
};
You cannot prevent a user of the class to ignore AdvanceDays() and simply do:
date.d = date.d + 1; // next day
But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.
The whole point is to use private and protected to prevent exposing internal details of your class, so that other classes only have access to the public "interfaces" provided by your class. This can be worthwhile if done properly.
I agree that private can be a real pain, especially if you are extending classes from a library. Awhile back I had to extend various classes from the Piccolo.NET framework and it was refreshing that they had declared everything I needed as protected instead of private, so I was able to extend everything I needed without having to copy their code and/or modify the library. An important take-away lesson from that is if you are writing code for a library or other "re-usable" component, that you really should think twice before declaring anything private.
The keyword private shouldn't be used to privatize a property that you want to expose, but to protect the internal code of your class. I found them very helpful because they help you to define the portions of your code that must be hidden from those that can be accessible to everyone.
One example that comes to my mind is when you need to do some sort of adjustment or checking before setting/getting the value of a private member. Therefore you'd create a public setter/getter with some logic (check if something is null or any other calculations) instead of accessing the private variable directly and always having to handle that logic in your code. It helps with code contracts and what is expected.
Another example is helper functions. You might break down some of your bigger logic into smaller functions, but that doesn't mean you want to everyone to see and use these helper functions, you only want them to access your main API functions.
In other words, you want to hide some of the internals in your code from the interface.
See some videos on APIs, such as this Google talk.
Having recently had the extreme luxury of being able to design and implement an object system from scratch, I took the policy of forcing all variables to be (equivalent to) protected. My goal was to encourage users to always treat the variables as part of the implementation and not the specification. OTOH, I also left in hooks to allow code to break this restriction as there remain reasons to not follow it (e.g., the object serialization engine cannot follow the rules).
Note that my classes did not need to enforce security; the language had other mechanisms for that.
In my opinion the most important reason for use private members is hiding implementation, so that it can changed in the future without changing descendants.
Some languages - Smalltalk, for instance - don't have visibility modifiers at all.
In Smalltalk's case, all instance variables are always private and all methods are always public. A developer indicates that a method's "private" - something that might change, or a helper method that doesn't make much sense on its own - by putting the method in the "private" protocol.
Users of a class can then see that they should think twice about sending a message marked private to that class, but still have the freedom to make use of the method.
(Note: "properties" in Smalltalk are simply getter and setter methods.)
I personally rarely make use of protected members. I usually favor composition, the decorator pattern or the strategy pattern. There are very few cases in which I trust a subclass(ing programmer) to handle protected variables correctly. Sometimes I have protected methods to explicitly offer an interface specifically for subclasses, but these cases are actually rare.
Most of the time I have an absract base class with only public pure virtuals (talking C++ now), and implementing classes implement these. Sometimes they add some special initialization methods or other specific features, but the rest is private.
First of all 'properties' could refer to different things in different languages. For example, in Java you would be meaning instance variables, whilst C# has a distinction between the two.
I'm going to assume you mean instance variables since you mention getters/setters.
The reason as others have mentioned is Encapsulation. And what does Encapsulation buy us?
Flexibility
When things have to change (and they usually do), we are much less likely to break the build by properly encapsulating properties.
For example we may decide to make a change like:
int getFoo()
{
return foo;
}
int getFoo()
{
return bar + baz;
}
If we had not encapsulated 'foo' to begin with, then we'd have much more code to change. (than this one line)
Another reason to encapsulate a property, is to provide a way of bullet-proofing our code:
void setFoo(int val)
{
if(foo < 0)
throw MyException(); // or silently ignore
foo = val;
}
This is also handy as we can set a breakpoint in the mutator, so that we can break whenever something tries to modify our data.
If our property was public, then we could not do any of this!