A setter can help in that situation by having a separation between your library's public facing interface and its internal implementation details.Īgain, I rarely use Setters. You lose any flexibility of refactoring or changing that underlying field to a different datatype without breaking your library's backwards compatibility. Once you make a field public and are publishing a library, you can essentially never take it back without doing something very painful for you and your users like a backwards incompatible change via a major version bump. You are writing a library and don't want to commit to having internals of your library as its public facing interface. For example if you have a field in your struct like authors string, you may want a setter that clones the input slice so that the client that is setting authors doesn't have access to the underlying slice used inside your struct and do stuff like remove or add items from it outside the api you expose and make your struct inconsistent. You need to ensure that once set, the value of the field cannot be modified outside the api exposed by your struct. Your struct is designed to be used in a multi-threaded context and you can't safely update a field without additional synchronization. Then setting a new value for books will also require you to rebuild the index, hence you would wanna use a setter there. But you also maintain an index for quick lookups for the users of your api authorToBookBook. An example of this would be if you have a Library struct which has a private field books Book. Setting that field requires some additional side-effects. You don't want to willy-nilly accept anything as the value of the field and intend to do some validation on it before accepting it. But if you do need to have a private field directly writable from outside your struct, there are many reasons one might want to use a setter over making the field public like: I like to have my structs immutable once built as far as the outside world is concerned and rarely need setters. There's no reason to give a setter to a private field.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |