Argument validation for class methods (2024)

20 visualizzazioni (ultimi 30 giorni)

Mostra commenti meno recenti

John il 11 Lug 2024 alle 15:25

  • Link

    Link diretto a questa domanda

    https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods

  • Link

    Link diretto a questa domanda

    https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods

Commentato: John il 11 Lug 2024 alle 19:41

Risposta accettata: Steven Lord

Apri in MATLAB Online

Is there a best practice for validating (or not validating) the 'self' arguments in class method definitions?

Consider:

classdef my_class < handle

properties

A;

end

methods

function obj = my_class

obj.A = 0;

end

function add_to_obj(obj, B)

arguments

obj my_class; %This seems unnecessary

% obj; %Alternately we could omit the 'class' specifier

B (1,1) double;

end

obj.A = obj.A + B;

end

end

end

The class specification of the obj argument seems superflous and should be self-evidently true. Are there performance implications for leaving it in there (i.e., if I'm calling add_to_obj a lot)? Should I just leave out the specifier (essentially bypassing the argument validation)?

0 Commenti

Mostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Accedi per rispondere a questa domanda.

Risposta accettata

Steven Lord il 11 Lug 2024 alle 15:51

  • Link

    Link diretto a questa risposta

    https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods#answer_1484428

  • Link

    Link diretto a questa risposta

    https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods#answer_1484428

Apri in MATLAB Online

The class specification of the obj argument seems superflous and should be self-evidently true.

Not necessarily. The first input argument to a class method is not always required to be an instance of that class! There are two common patterns where this may not be the case. Let's take a sym object as an example.

syms x

This command calls the plus method for the sym class, as we can tell using the which function.

y = x + 1

y=Argument validation for class methods (3)

which('plus(x,1)')

/MATLAB/toolbox/symbolic/symbolic/@sym/plus.m % sym method

This also calls the plus method for the sym class, even though 1 is not a sym. It doesn't call the plus defined for double arrays.

z = 1 + x

z=Argument validation for class methods (4)

which('plus(1, x)')

/MATLAB/toolbox/symbolic/symbolic/@sym/plus.m % sym method

which('plus(1, 2)')

built-in (/MATLAB/toolbox/matlab/ops/@double/plus) % double method

Another common pattern is when class precedence is involved. [I suppose the example above simplifies down to this as well, since as stated on that documentation page double is always inferior to classes defined using classdef, which is the case for the sym class.] The graph object in MATLAB has an overloaded plot method that can accept an axes handle as its first input.

g = graph(bucky);

ax = axes;

plot(ax, g)

Argument validation for class methods (5)

Despite the first input to plot being an axes object, MATLAB calls the graph plot method.

which('plot(ax, g)')

/MATLAB/toolbox/matlab/graphics/math/@graph/plot.m % graph method

This is because the graph class states that the axes class (technically matlab.graphics.axis.Axes) is one of its InferiorClasses (as listed in the metaclass information.) So if both a graph object and an axes object are in a method's argument list, regardless of the order in which they're listed in that argument list, we call graph's method.

q = ?graph;

{q.InferiorClasses.Name}.'

ans = 2x1 cell array

{'matlab.graphics.axis.Axes'} {'matlab.ui.control.UIAxes' }

class(ax)

ans = 'matlab.graphics.axis.Axes'

But to get back to your question about performance, measure it and find out! You'll probably want to use timeit or the Profiler as I suspect the impact with and without the validation is going to be so small tic and toc may not capture it. I strongly suspect that unless your method is very fast (returning a constant value) this probably isn't going to be your bottleneck.

3 Commenti

Mostra 1 commento meno recenteNascondi 1 commento meno recente

John il 11 Lug 2024 alle 17:36

Link diretto a questo commento

https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods#comment_3209068

  • Link

    Link diretto a questo commento

    https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods#comment_3209068

Apri in MATLAB Online

Thanks for your reply and the thorough response. But to play Devil's Advocate, you've partially sidestepped the original question. All of the examples (plus, plot, etc.) do not use arguments declarations for validation. If the method in question is written to support varargin inputs, or like plus are designed with internal calls design to sort out how to manage the input arguments, you're probably not using an arguments declaration anyhow.

I'll also grant that the overhead from doing the validation will be minimal in most applications. It's probably safer to include the validation if you expect users to invoke the method with

foo = my_class;

add_to_obj(foo, 5);

That way you'll get an error thrown during validation rather than a problem further down the line.

As an aside, I really like arguments as I find it much cleaner and succinct than working with inputParser in many situations. It would be useful to have an additional builtin validator, like mustBeEmptyOrA (e.g., allows an empty default, but if it isn't empty is has to satisfy mustBeA). This comes up often enough that it creates a dependency issue when distributing code.

Steven Lord il 11 Lug 2024 alle 19:21

Link diretto a questo commento

https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods#comment_3209153

  • Link

    Link diretto a questo commento

    https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods#comment_3209153

I used the plus function / method in my example, but your add_to_obj(obj, B) method looks like it is adding together obj and B, doesn't it? So it could be called plus, couldn't it?

Please contact Technical Support directly using this link to submit an enhancement request for mustBeEmptyOrA. When you do, please describe your use case (especially how the lack of it proves to be a problem when you distribute your code.) The developers benefit greatly when designing new features if they have real-world usage stories to help them consider design trade-offs.

John il 11 Lug 2024 alle 19:41

Link diretto a questo commento

https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods#comment_3209178

  • Link

    Link diretto a questo commento

    https://it.mathworks.com/matlabcentral/answers/2136563-argument-validation-for-class-methods#comment_3209178

My example was really just intended as a minimal demonstration. The real applications were quite different. But thanks nontheless. I'll put in a enhancement request, as you suggest.

Accedi per commentare.

Più risposte (0)

Accedi per rispondere a questa domanda.

Vedere anche

Tag

  • class definition
  • argument validation
  • arguments

Prodotti

  • MATLAB

Release

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Si è verificato un errore

Impossibile completare l'azione a causa delle modifiche apportate alla pagina. Ricarica la pagina per vedere lo stato aggiornato.


Translated by Argument validation for class methods (9)

Argument validation for class methods (10)

Seleziona un sito web

Seleziona un sito web per visualizzare contenuto tradotto dove disponibile e vedere eventi e offerte locali. In base alla tua area geografica, ti consigliamo di selezionare: .

Puoi anche selezionare un sito web dal seguente elenco:

Americhe

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europa

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom(English)

Asia-Pacifico

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本Japanese (日本語)
  • 한국Korean (한국어)

Contatta l’ufficio locale

Argument validation for class methods (2024)
Top Articles
Mollie And Allene Hari Where Are They Now
Tricia Vacanti Obituary
Moonrise Tonight Near Me
Salons Open Near Me Today
Craigslist Kentucky Cars And Trucks - By Owner
Ups Drop Off Newton Ks
Rs3 Rituals
True Or False Security Is A Team Effort
Ecolab Mppa Charges
Myzmanim Edison Nj
Thomas the Tank Engine
Maritime News Archives
Mobile Maher Terminal
Unit 8 Lesson 2 Coding Activity
Stolen Touches Neva Altaj Read Online Free
German American Bank Owenton Ky
Xiom Vega X Review & Playtesting • Racket Insight
Highplainsobserverperryton
Nephi Veterinarian
Alamy Contributor Forum
Infinity Pool Showtimes Near Cinemark 14 Chico
Cato's Dozen Crossword
Usc Human Biology
Maintenance Required Gear Selector Ecu
Fort Worth Craiglist
Charlotte North Carolina Craigslist Pets
Wall Street Journal Currency Exchange Rates Historical
Kemono Party Imbapovi
Hose Woe Crossword Clue
On-Campus Student Employment
Family Violence Prevention Program - YWCA Wheeling
Voyeur Mature Bikini
Gunblood Unblocked 66
Bdo Obsidian Blackstar
Liv Morgan Wedgie
Enlightenment Egg Calculator
Tires Shop Santoyo
Bridger Elementary Logan
Ma Scratch Tickets Codes
SYSTEMAX Software Development - PaintTool SAI
Ryker Webb 2022
Foolproof Module 6 Test Answers
Edye Ellis Obituary
Mama Mia Israel Soldier Original
Intel Core i3-4130 - CM8064601483615 / BX80646I34130
Einschlafen in nur wenigen Minuten: Was bringt die 4-7-8-Methode?
Shaws Myaci
358 Edgewood Drive Denver Colorado Zillow
Thirza (tier-sa) Caldwell on LinkedIn: #choosewell #orlandohealth
Cambridge Assessor Database
High Balance Bins 2023
Clarakitty 2022
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 5637

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.