Why is a retrieve function introduced here when the contract already provides this? - solidity

this is my first post and I am pretty new to programming and working my way through learning solidity with the help of freeCodeCamp on Youtube right now.
At around 1:48:00 in this video (https://www.youtube.com/watch?v=M576WGiDBdQ) the author introduces the retrieve function which basically has the same functionality of the statement in contract, right? When both of them lead to the same result, why would using the retrieve function be necessary in this case? Isn't this function just going to waste space? Or which advantages does it provide? Unfortunately he doesn't explain it and it's confusing me like hell.
Kind regards
contract SimpleStorage {
uint256 favoriteNumber;
function retrieve() public view returns (uint256) {
return favoriteNumber;
}
}

Storage variables default to internal visibility if you don't specify the visibility. So without that function you don't have a public getter for the variable.
You could remove the need for the view function by simply declaring the variable with public visibility:
uint256 public favoriteNumber;

Related

What to call an object that acts like an enter-only-once gate?

What would you call a stateful function/object x() -> bool with the following behavior: on the first call it returns TRUE, on all consecutive calls it returns FALSE. Maybe there is a pattern name already for such functionality?
The closest concept is the read-once object pattern from the Secure by Design book. Look at the paragraph below describing the object that allows to request the password only once.
A read-once object is, as the name implies, an object designed to be read once. This object
usually represents a value or concept in your domain that’s considered to be sensitive
(for example, passport numbers, credit card numbers, or passwords). The main purpose
of the read-once object is to facilitate detection of unintentional use of the data
it encapsulates.
public final class SensitiveValue {
private transient final AtomicReference<String> value;
public SensitiveValue(final String value) {
validate(value);
this.value = new AtomicReference<>(value);
}
public String value() {
return notNull(value.getAndSet(null),
"Sensitive value has already been consumed");
}
#Override
public String toString() {
return "SensitiveValue{value=*****}";
}
}
I don't know the full context of your problem but the book suggests to use the read-once object pattern in favor of security perspective. #jaco0646 also pointed out in the comments that the concept is similar to the circuit breaker pattern. Though it doesn't force for the object to always return the same value on consecutive calls. Instead, it temporary makes to obtain the stub value to give the external service some time to recover.

Is there a way to check if msg.sender owns some collection?

Is there a way to do the following:
function registerCollection(address __collection) public {
require(msg.sender == IERC721(__collection).owner), "Does not own contract");
...[rest of function]...
}
Is there a way, within solidity, to access the owner field of another contract. So I do not mean owns an NFT of another collection, which could be done by calling .ownerOf(tokenId) and comparing to msg.sender. I want to get the actual owner of the contract.
It's possible that a collection has a address public owner, especially if it inherits from Openzeppelin's Ownable library.
So you are able to get it like this:
interface IOwnable {
function owner() external view returns(address)
}
IOwnable(__collection).owner()
Though be aware that if a collection doesn't gave a public owner the call will revert.

Unity3D embedded Mono with Unity

I've seen plenty of examples of calling static methods in my Unity C# code using C++. I haven't however seen any examples of how to call a single instance's method using C++. i.e rather than
public static void SomeMethod(
{
}
I really want to do:
public void SomeMethod()
{
}
I've managed to make the static implementation work by following some tutorials from but would love to know if the bottom method is possible. I've tried to add a definition for searching a method in a class.
MonoMethod* mono_method_desc_search_in_class (MonoMethodDesc *desc, MonoClass *klass);
But an implementation can't be found with the mono runtime that I was told to use from here: http://www.reigndesign.com/blog/unity-native-plugins-os-x/
Any guidance or knowledge of whether it's possible or how to do it would be appreciated.
Edit:
One other question. If I search for a gameObject, could I then use that to access the instance?
You don't say what platform you're developing for, but for iOS there's the UnitySendMessage function. I believe there are similar implementations for other platforms.
http://docs.unity3d.com/Documentation/Manual/PluginsForIOS.html
Calling C# / JavaScript back from native code
Unity iOS supports limited native-to-managed callback functionality via UnitySendMessage:
UnitySendMessage("GameObjectName1", "MethodName1", "Message to send");
The parameter must be a string, so I've used JSON to send more complex data.
Alternatively, everything that inherits from UnityEngine.Object has a GetInstanceID() method, which is guaranteed to be unique. Using this you could have a static method in C# that keeps a dictionary of recipient instances, and native code would always pass an integer ID to refer to the intended recipient.
static Dictionary<int, SomeClass> instanceDict = new Dictionary<...>();
void Awake() {
instanceDict.Add(GetInstanceID(), this);
}
void OnDestroy() {
instanceDict.Remove(GetInstanceID());
}
public static void SomeMethod(int recipientID, float someValue) {
instanceDict[recipientID].SomeMethod(someValue);
}

Do write-only properties have practical applications?

I don't know why I started thinking about this, but now I can't seem to stop.
In C# - and probably a lot of other languages, I remember that Delphi used to let you do this too - it's legal to write this syntax:
class WeirdClass
{
private void Hello(string name)
{
Console.WriteLine("Hello, {0}!", name);
}
public string Name
{
set { Hello(name); }
}
}
In other words, the property has a setter but no getter, it's write-only.
I guess I can't think of any reason why this should be illegal, but I've never actually seen it in the wild, and I've seen some pretty brilliant/horrifying code in the wild. It seems like a code smell; it seems like the compiler should be giving me a warning:
CS83417: Property 'Name' appears to be completely useless and stupid. Bad programmer! Consider replacing with a method.
But maybe I just haven't been doing this long enough, or have been working in too narrow a field to see any examples of the effective use of such a construct.
Are there real-life examples of write-only properties that either cannot be replaced by straight method calls or would become less intuitive?
My first reaction to this question was: "What about the java.util.Random#setSeed method?"
I think that write-only properties are useful in several scenarios. For example, when you don't want to expose the internal representation (encapsulation), while allowing to change the state of the object. java.util.Random is a very good example of such design.
Code Analysis (aka FxCop) does give you a diagnostic:
CA1044 : Microsoft.Design : Because
property 'WeirdClass.Name' is write-only,
either add a property getter with an
accessibility that is greater than or
equal to its setter or convert this
property into a method.
Write-only properties are actually quite useful, and I use them frequently. It's all about encapsulation -- restricting access to an object's components. You often need to provide one or more components to a class that it needs to use internally, but there's no reason to make them accessible to other classes. Doing so just makes your class more confusing ("do I use this getter or this method?"), and more likely that your class can be tampered with or have its real purpose bypassed.
See "Why getter and setter methods are evil" for an interesting discussion of this. I'm not quite as hardcore about it as the writer of the article, but I think it's a good thing to think about. I typically do use setters but rarely use getters.
I have code similar to the following in an XNA project. As you can see, Scale is write-only, it is useful and (reasonably) intuitive and a read property (get) would not make sense for it. Sure it could be replaced with a method, but I like the syntax.
public class MyGraphicalObject
{
public double ScaleX { get; set; }
public double ScaleY { get; set; }
public double ScaleZ { get; set; }
public double Scale { set { ScaleX = ScaleY = ScaleZ = value; } }
// more...
}
One use for a write-only property is to support setter dependency injection, which is typically used for optional parameters.
Let's say I had a class:
public class WhizbangService {
public WhizbangProvider Provider { set; private get; }
}
The WhizbangProvider is not intended to be accessed by the outside world. I'd never want to interact with service.Provider, it's too complex. I need a class like WhizbangService to act as a facade. Yet with the setter, I can do something like this:
service.Provider = new FireworksShow();
service.Start();
And the service starts a fireworks display. Or maybe you'd rather see a water and light show:
service.Stop();
service.Provider = new FountainDisplay(new StringOfLights(), 20, UnitOfTime.Seconds);
service.Start();
And so on....
This becomes especially useful if the property is defined in a base class. If you chose construction injection for this property, you'd need to write a constructor overload in any derived class.
public abstract class DisplayService {
public WhizbangProvider Provider { set; private get; }
}
public class WhizbangService : DisplayService { }
Here, the alternative with constructor injection is:
public abstract class DisplayService {
public WhizbangProvider Provider;
protected DisplayService(WhizbangProvider provider) {
Provider = provider ?? new DefaultProvider();
}
}
public class WhizbangService : DisplayService {
public WhizbangService(WhizbangProvider provider)
: base(provider)
{ }
}
This approach is messier in my opinion, because you need to some of the internal workings of the class, specifically, that if you pass null to the constructor, you'll get a reasonable default.
In MVP pattern it is common to write a property with a setter on the view (no need for a getter) - whenever the presenter sets it content the property will use that value to update some UI element.
See here for a small demonstration:
public partial class ShowMeTheTime : Page, ICurrentTimeView
{
protected void Page_Load(object sender, EventArgs e)
{
CurrentTimePresenter presenter = new CurrentTimePresenter(this);
presenter.InitView();
}
public DateTime CurrentTime
{
set { lblCurrentTime.Text = value.ToString(); }
}
}
The presenter InitView method simply sets the property's value:
public void InitView()
{
view.CurrentTime = DateTime.Now;
}
Making something write-only is usefulwhenever you're not supposed to read what you write.
For example, when drawing things onto the screen (this is precisely what the Desktop Window Manager does in Windows):
You can certainly draw to a screen, but you should never need to read back the data (let alone expect to get the same design as before).
Now, whether write-only properties are useful (as opposed to methods), I'm not sure how often they're used. I suppose you could imagine a situation with a "BackgroundColor" property, where writing to it sets the background color of the screen, but reading makes no sense (necessarily).
So I'm not sure about that part, but in general I just wanted to point out that there are use cases for situations in which you only write data, and never read it.
Although the .NET design guidelines recommend using a method ("SetMyWriteOnlyParameter") instead of a write-only property, I find write-only properties useful when creating linked objects from a serialised representation (from a database).
Our application represents oil-field production systems. We have the system as a whole (the "Model" object) and various Reservoir, Well, Node, Group etc objects.
The Model is created and read from database first - the other objects need to know which Model they belong to. However, the Model needs to know which lower object represents the Sales total. It makes sense for this information to be stored a Model property. If we do not want to have to do two reads of Model information, we need to be able to read the name of Sales object before its creation. Then, subsequently, we set the "SalesObject" variable to point to the actual object (so that, e.g., any change by the user of the name of this object does not cause problems)
We prefer to use a write-only property - 'SalesObjectName = "TopNode"' - rather than a method - 'SetSalesObjectName("TopNode") - because it seems to us that the latter suggests that the SalesObject exists.
This is a minor point, but enough to make us want to use a Write-Only property.
As far as I'm concerned, they don't. Every time I've used a write-only property as a quick hack I have later come to regret it. Usually I end up with a constructor or a full property.
Of course I'm trying to prove a negative, so maybe there is something I'm missing.
I can't stop thinking about this, either. I have a use case for a "write-only" property. I can't see good way out of it.
I want to construct a C# attribute that derives from AuthorizeAttribute for an ASP.NET MVC app. I have a service (say, IStore) that returns information that helps decide if the current user should be authorized. Constructor Injection won't work, becuase
public AllowedAttribute: AuthorizeAttribute
{
public AllowedAttribute(IStore store) {...}
private IStore Store { get; set; }
...
}
makes store a positional attribute parameter, but IStore is not a valid attribute parameter type, and the compiler won't build code that is annotated with it. I am forced to fall back on Property Setter Injection.
public AllowedAttribute: AuthorizeAttribute
{
[Inject] public IStore Store { private get; set; }
...
}
Along with all the other bad things about Property Setter instead of Constructor Injection, the service is a write-only property. Bad enough that I have to expose the setter to clients that shouldn't need to know about the implementation detail. It wouldn't do anybody any favors to let clients see the getter, too.
I think that the benefit of Dependency Injection trumps the guidelines against write-only properties for this scenario, unless I am missing something.
I just came across that situation when writing a program that reads data from a JSON database (Firebase). It uses Newtonsoft's Json.NET to populate the objects. The data are read-only, i.e., once loaded they won't change. Also, the objects are only deserialized and won't be serialized again. There may be better ways, but this solution just looks reasonable for me.
using Newtonsoft.Json;
// ...
public class SomeDatabaseClass
{
// JSON object contains a date-time field as string
[JsonProperty("expiration")]
public string ExpirationString
{
set
{
// Needs a custom parser to handle special date-time formats
Expiration = Resources.CustomParseDateTime(value);
}
}
// But this is what the program will effectively use.
// DateTime.MaxValue is just a default value
[JsonIgnore]
public DateTime Expiration { get; private set; } = DateTime.MaxValue;
// ...
}
No, I can' imagine any case where they can't be replaced, though there might people who consider them to be more readable.
Hypothetical case:
CommunicationDevice.Response = "Hello, World"
instead of
CommunicationDevice.SendResponse("Hello, World")
The major job would be to perform IO side-effects or validation.
Interestingly, VB .NET even got it's own keyword for this weird kind of property ;)
Public WriteOnly Property Foo() As Integer
Set(value As Integer)
' ... '
End Set
End Property
even though many "write-only" properties from outside actually have a private getter.
I recently worked on an application that handled passwords. (Note that I'm not claiming that the following is a good idea; I'm just describing what I did.)
I had a class, HashingPassword, which contained a password. The constructor took a password as an argument and stored it in a private attribute. Given one of these objects, you could either acquire a salted hash for the password, or check the password against a given salted hash. There was, of course, no way to retrieve the password from a HashingPassword object.
So then I had some other object, I don't remember what it was; let's pretend it was a password-protected banana. The Banana class had a set-only property called Password, which created a HashingPassword from the given value and stored it in a private attribute of Banana. Since the password attribute of HashingPassword was private, there was no way to write a getter for this property.
So why did I have a set-only property called Password instead of a method called SetPassword? Because it made sense. The effect was, in fact, to set the password of the Banana, and if I wanted to set the password of a Banana object, I would expect to do that by setting a property, not by calling a method.
Using a method called SetPassword wouldn't have had any major disadvantages. But I don't see any significant advantages, either.
I know this has been here for a long time, but I came across it and have a valid (imho) use-case:
When you post parameters to a webapi call from ajax, you can simply try to fill out the parameters class' properties and include validation or whatsoever.
public int MyFancyWepapiMethod([FromBody]CallParams p) {
return p.MyIntPropertyForAjax.HasValue ? p.MyIntPropertyForAjax.Value : 42;
}
public class CallParams
{
public int? MyIntPropertyForAjax;
public object TryMyIntPropertyForAjax
{
set
{
try { MyIntPropertyForAjax = Convert.ToInt32(value); }
catch { MyIntPropertyForAjax = null; }
}
}
}
On JavaScript side you can simply fill out the parameters including validation:
var callparameter = {
TryMyIntPropertyForAjax = 23
}
which is safe in this example, but if you handle userinput it might be not sure that you have a valid intvalue or something similar.

Examples in Test Driven Development By Example by Kent Beck

I'm reading through Test Driven Development: By Example and one of the examples is bugging me. In chapter 3 (Equality for all), the author creates an equals function in the Dollar class to compare two Dollar objects:
public boolean equals(Object object)
{
Dollar dollar= (Dollar) object;
return amount == dollar.amount;
}
Then, in the following chapter (4: Privacy), he makes amount a private member of the dollar class.
private int amount;
and the tests pass. Shouldn't this cause a compiler error in the equals method because while the object can access its own amount member as it is restricted from accessing the other Dollar object's amount member?
//shouldn't dollar.amount be no longer accessable?
return amount == dollar.amount
Am I fundamentally misunderstanding private?
UPDATE
I decided to go back and code along with the book manually and when I got to the next part (chapter 6 - Equality For All, Redux) where they push amount into a parent class and make it protected, I'm getting access problems:
public class Money
{
protected int amount;
}
public class Dollar : Money
{
public Dollar(int amount)
{
this.amount = amount;
}
// override object.Equals
public override bool Equals(object obj)
{
Money dollar = (Money)obj;
//"error CS1540: Cannot access protected member 'Money.amount'
// via a qualifier of type 'Money'; the qualifier must be of
// type 'Dollar' (or derived from it)" on the next line:
return amount == dollar.amount;
}
}
Does this mean that protected IS instance-based in C#?
Yep, you're fundamentally misunderstanding private. Privacy is class-specific, not instance-specific.
Fundamentally misunderstanding private, Dollar can access any Dollar private method if they are the same class.
Modifier private is class-private, not object-private.
In Java, private means class-private. Within the class, you can access that field in all instances of the class.
In Scala there is also an object-private scope which is written private[this]. Also in other respects Scala's scopes are more flexible (see this article for more information).
But in Java there is no object-private scope.
In languages of the C++ family (C++,Java,C#), access control is only at the class level. So private allows access to any instance of that class.
IIRC in Smalltalk privacy behaves as you expect.