O'Reilly logo

Head First Go by Jay McGavren

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10 encapsulation and embedding

Keep it to Yourself

Images

Mistakes happen. Your struct type's methods work great, if the struct's fields are set correctly. But suppose you're using data from a file to set those struct fields. Are you sure all that data is valid? If it's not, users could get strange errors when your type's methods are called! In this chapter, you'll learn about encapsulation: a way to protect those fields from invalid data.And what if your struct type needs methods that already exist on another type? You don't have to copy and paste the method code. If you embed the other type within your struct type, its methods will be promoted to your struct type. You can use the methods just as if they were defined on your own type! This chapter will show you how that works, too.

Creating a Date struct type

A local startup called Remind Me is developing a calendar application to help users remember birthdays, anniversaries, and more.

Images

The year, month, and day sound like they all need to be grouped together; none of those values would be useful by itself. A struct type would probably be useful for keeping those separate values together in a single bundle.

As we've seen, defined types can use any other type as their underlying type, including structs. In fact, struct types served as our ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required