What is the right way to think C # secure access fast?

In C #, we have a protected accessor that allows class members to be visible in inherited clans, but not for the rest.

This does not exist in Swift, so I am wondering what is the right approach for something like this:

I want to have a variable (internal behavior) and a public method using this variable in the base class. This variable will also be used in inherited clans.

Options that I see

  • Forget the base class and implement the variable and methods wherever you need it. INCORRECT , duplicated code
  • Implement compositional inheritance. I would create a class containing common methods, and this would be used by the composition instead of inheritance. LESS WRONG but still repeating code that could have been avoided with inheritance
  • Implement inheritance and make the variable internal in the base class. WRONG because it provides things without any excuse other than allowing the visibility of inherited clans.

Base Class Implementation Details

I want to have an instance of NSOperationQueue and a public method for canceling queued operations. I am adding new operations to this queue from inherited classes.

+5
source share
1 answer

In Swift, the correct answer is almost always protocols and extensions. This is almost never inheritance. Sometimes Cocoa stands in our way, because classes in Cocoa are more common than protocols, but the goal is almost always protocols and extensions. The subclass is our last choice.

Your specific case is confusing because NSOperationQueue already has an open method for canceling operations in the queue ( cancelAllOperations ). If you want to protect the queue from external access (to prevent callers from directly using addOperation ), then you must put the queue in a different type (i.e., Composition) and redirect what you want to the queue. More detailed information about the specific problem you are solving will help us to offer other similar solutions to Swift.

If you need something like protected or friend , private right solution. Put your subclass or your friend in the same file with the target and mark the private thing private . Also, put things that should work together in a framework, and tag the internal attribute. Swift Blog gives a good explanation of why this is an intentional choice.

+3
source

Source: https://habr.com/ru/post/1234790/


All Articles