1/69
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
What is a variable?
A variable is a named reference or storage location used to hold a value that a program can work with.
Променливата е именувана референция или място за съхранение, което се използва за съхраняване на стойност, с която програмата работи.
What is a constant?
A constant is a value that is not intended to be changed after it has been initialized.
Константата е стойност, която не е предназначена да бъде променяна след инициализацията ѝ.
What is variable initialization?
Initialization is the process of giving a variable its initial value.
Инициализацията е процесът на задаване на начална стойност на променлива.
What is assignment?
Assignment is the operation of giving a variable a value or changing its current value.
Присвояването е операцията по задаване на стойност на променлива или промяна на текущата ѝ стойност.
What is the difference between a variable and a value?
A variable is a name or reference used to access data, while a value is the actual data stored or represented.
Променливата е име или референция, чрез която достъпваме данни, докато стойността е самите данни, които се съхраняват или представят.
Why should magic numbers usually be avoided?
They make code harder to understand and maintain. A named constant gives the value a clear meaning.
Те правят кода по-труден за разбиране и поддръжка. Именуваната константа придава ясно значение на стойността.
What is variable scope?
Scope defines where a variable can be accessed in a program.
Scope определя в коя част от програмата дадена променлива може да бъде достъпвана.
What is shadowing?
Shadowing occurs when a variable in an inner scope has the same name as a variable in an outer scope, hiding the outer variable within that scope.
Shadowing възниква, когато променлива във вътрешен scope има същото име като променлива във външен scope и скрива външната променлива в рамките на този scope.
Why are local variables generally preferred over global variables?
Local variables limit the scope of state and reduce hidden dependencies and unintended side effects.
Локалните променливи ограничават обхвата на състоянието и намаляват скритите зависимости и нежеланите странични ефекти.
What is mutable state?
Mutable state is data whose value or internal state can be changed after it has been created.
Mutable state е данни, чиято стойност или вътрешно състояние може да бъде променяно след създаването им.
What is immutable data?
Immutable data cannot be changed after it has been created. To represent a different value, a new value or object must be created.
Immutable данните не могат да бъдат променяни след създаването им. За представяне на различна стойност трябва да бъде създадена нова стойност или обект.
What is the difference between a constant and immutable data?
Константата обикновено не позволява на дадена променлива или референция да бъде пренасочена към друга стойност, докато immutable означава, че самата стойност или вътрешното състояние на обекта не може да бъде променено.
const user = {
name: "Ivan",
age: 30
};
user.age = 31;
const → ✅
immutable → ❌
Why can global mutable state be problematic?
Multiple parts of the program can modify it, creating hidden dependencies, unexpected side effects, race conditions, and code that is harder to test and reason about.
Различни части на програмата могат да го променят, което създава скрити зависимости, неочаквани странични ефекти, race conditions и код, който е по-труден за тестване и разбиране.
What is a race condition involving shared variables?
A race condition occurs when multiple concurrent operations access and modify shared state, and the result depends on the timing or order of those operations.
Race condition възниква, когато няколко конкурентни операции достъпват и променят споделено състояние и резултатът зависи от момента или реда на изпълнението им.
Why is immutability useful in concurrent programs?
Immutable data can be safely shared between concurrent operations because its state cannot be changed unexpectedly.
Immutable данните могат безопасно да бъдат споделяни между конкурентни операции, защото състоянието им не може да бъде променено неочаквано.
Why doesn't const necessarily mean an object is immutable?
In some languages, const prevents a variable or reference from being reassigned but does not prevent the referenced object's internal state from changing.
В някои езици const предотвратява повторното присвояване на променлива или референция, но не предотвратява промяната на вътрешното състояние на обекта, към който тя сочи.
What is a side effect?
A side effect is a change made by a function outside of its returned result, such as modifying shared state, writing to a file, or making a network request.
Side effect е промяна, извършена от функция извън върнатия от нея резултат, например промяна на споделено състояние, запис във файл или изпращане на мрежова заявка.
Why should a variable generally have the narrowest possible scope?
A narrow scope reduces the amount of code that can depend on the variable, making the program easier to understand, test, and maintain.
Тесният scope намалява броя части от кода, които могат да зависят от променливата, което прави програмата по-лесна за разбиране, тестване и поддръжка.
What problems can too many function parameters indicate?
They can indicate that the function has too many responsibilities or that related data should be grouped into an object or another appropriate abstraction.
Това може да означава, че функцията има прекалено много отговорности или че свързани данни трябва да бъдат групирани в обект или друга подходяща абстракция.
What is the difference between passing a value and passing a reference?
Passing a value gives the function a copy of the value, while passing a reference gives it access to the same underlying object or data. The exact behavior depends on the programming language.
При предаване по стойност функцията получава копие на стойността, докато при предаване по референция получава достъп до същия обект или данни. Точното поведение зависи от конкретния програмен език.
What is the difference between a variable's identity and its value?
Answer: A variable's identity refers to the variable itself as a named entity or storage location, while its value is the data associated with it at a particular point in time.
Отговор: Идентичността на променливата се отнася до самата променлива като именувана единица или място за съхранение, докато стойността е данните, свързани с нея в даден момент.
Why is minimizing mutable state generally considered good software design?
Answer: Minimizing mutable state reduces the number of possible program states and makes code easier to reason about, test, debug, and use safely in concurrent environments.
Отговор: Ограничаването на mutable state намалява броя на възможните състояния на програмата и прави кода по-лесен за разбиране, тестване и debugging, както и по-безопасен при concurrent execution.
What is the difference between rebinding a variable and mutating an object?
Answer: Rebinding changes which value or object a variable refers to, while mutation changes the internal state of the existing object.
Отговор: Rebinding променя към коя стойност или обект сочи променливата, докато mutation променя вътрешното състояние на вече съществуващия обект.
Why can shared mutable state make debugging difficult?
Answer: Any part of the program that has access to the shared state may change it, making it difficult to determine where and when an unexpected value was introduced.
Отговор: Всяка част от програмата, която има достъп до споделеното състояние, може да го промени, което затруднява определянето къде и кога се е появила неочакваната стойност.
What is a hidden dependency?
Answer: A hidden dependency occurs when code relies on external state or behavior that is not explicitly represented in its parameters or interface.
Отговор: Скритата зависимост възниква, когато кодът разчита на външно състояние или поведение, което не е явно представено чрез параметрите или интерфейса му.
Why can global constants still be useful?
Answer: Global constants can represent stable values that are conceptually shared across the application, such as configuration defaults, protocol limits, or well-defined domain values.
Отговор: Глобалните константи могат да бъдат полезни за стабилни стойности, които логически се споделят в приложението, например конфигурационни стойности, ограничения на протокол или добре дефинирани domain стойности.
When can a global variable be justified?
Answer: A global variable may be justified when the state is genuinely application-wide, carefully controlled, and its lifecycle and access patterns are well understood.
Отговор: Глобална променлива може да бъде оправдана, когато състоянието действително е общо за цялото приложение, контролира се внимателно и lifecycle-ът и начинът на достъп до него са добре разбрани.
Why is passing dependencies explicitly often better than using global variables?
Answer: Explicit dependencies make relationships visible, improve testability, reduce coupling, and make the behavior of a function easier to understand.
Отговор: Явните зависимости правят връзките между компонентите видими, подобряват testability, намаляват coupling-а и улесняват разбирането на поведението на функцията.
What is variable lifetime?
Answer: Variable lifetime is the period during which a variable exists and can potentially hold or reference a value.
Отговор: Lifetime на променливата е периодът, през който тя съществува и потенциално може да съдържа или да сочи към стойност.
How are scope and lifetime different?
Answer: Scope describes where a variable can be accessed, while lifetime describes how long the variable exists.
Отговор: Scope определя къде може да бъде достъпвана променливата, докато lifetime определя колко дълго съществува тя.
What problems can arise when variable names are reused too aggressively?
Answer: Reusing names can reduce readability, increase the chance of mistakes, and make debugging and understanding the code more difficult, especially in nested scopes.
Отговор: Прекомерното повторно използване на имена може да намали четимостта, да увеличи вероятността от грешки и да затрудни debugging-а и разбирането на кода, особено при nested scopes.
Why should constants usually have meaningful names?
Answer: A meaningful name communicates the purpose and domain meaning of a value, making the code easier to understand and maintain.
Отговор: Смисленото име показва предназначението и значението на дадена стойност в domain-а, което прави кода по-лесен за разбиране и поддръжка.
What is defensive copying and why can it be useful?
Answer: Defensive copying means creating a copy of mutable data before exposing or modifying it, preventing external code from unexpectedly changing internal state.
Отговор: Defensive copying означава създаване на копие на mutable данни, преди те да бъдат предоставени или променени, за да се предотврати неочаквана промяна на вътрешното състояние от външен код.
What is aliasing in programming?
Answer: Aliasing occurs when multiple variables or references point to the same underlying object or memory location.
Отговор: Aliasing възниква, когато няколко променливи или референции сочат към един и същ обект или memory location.
Why can aliasing be dangerous with mutable objects?
Answer: Changing the object through one reference can unexpectedly affect code that accesses the same object through another reference.
Отговор: Промяната на обекта чрез една референция може неочаквано да повлияе на кода, който достъпва същия обект чрез друга референция.
What is the benefit of treating data as immutable across module boundaries?
Answer: It reduces the risk that one module will unexpectedly modify state owned or used by another module, creating clearer boundaries between components.
Отговор: Това намалява риска един модул неочаквано да промени състояние, което принадлежи или се използва от друг модул, и създава по-ясни граници между компонентите.
Why can mutable default values be problematic in some programming languages?
Answer: If the same mutable object is reused across multiple calls, changes made during one call may unexpectedly affect later calls.
Отговор: Ако един и същ mutable обект се използва повторно при няколко извиквания, промени от едно извикване могат неочаквано да повлияят на следващи извиквания.
What is a temporal coupling problem involving variables?
Answer: Temporal coupling occurs when code must access or modify variables in a specific order for the program to work correctly, even though that requirement is not obvious from the interface.
Отговор: Temporal coupling възниква, когато кодът трябва да достъпва или променя променливи в определен ред, за да работи правилно, въпреки че това изискване не е очевидно от интерфейса.
How can immutability improve testability?
Answer: Immutable data reduces hidden state changes, making tests more deterministic and reducing the number of interactions that must be controlled or reset between tests.
Отговор: Immutable данните намаляват скритите промени в състоянието, което прави тестовете по-предвидими и намалява броя на взаимодействията, които трябва да бъдат контролирани или reset-вани между тестовете.
When should you prefer a local variable over a class-level or global variable?
Answer: Prefer a local variable when the value is only needed within a limited operation or scope. This keeps state close to where it is used and minimizes unnecessary coupling.
Отговор: Предпочитай локална променлива, когато стойността е необходима само в рамките на ограничена операция или scope. Така състоянието остава близо до мястото, където се използва, и се минимизира ненужният coupling.
What is the difference between state ownership and state access?
Answer: State ownership means being responsible for creating, modifying, and maintaining a piece of state. State access only means being able to read or use that state. Keeping ownership clear helps prevent unintended modifications and coupling.
Отговор: Ownership на състоянието означава да носиш отговорност за създаването, промяната и поддръжката му. Access означава само да имаш възможност да го четеш или използваш. Ясното ownership намалява неочакваните промени и coupling-а.
Why is exposing mutable internal state from a class or module considered dangerous?
Answer: External code can modify the internal state without going through the intended rules or validation of the owning component. This can break invariants and make the component harder to reason about.
Отговор: Външният код може да промени вътрешното състояние, без да премине през правилата или validation-а на компонента, който го притежава. Това може да наруши invariants и да направи компонента по-труден за разбиране и поддръжка.
What is an invariant, and how can variables threaten it?
Answer: An invariant is a condition that must remain true for an object or system to be considered valid. Poorly controlled mutable variables can allow code to put the object into an invalid state.
Отговор: Invariant е условие, което трябва да остане вярно, за да се счита даден обект или система за валидна. Неконтролираните mutable променливи могат да позволят на кода да постави обекта в невалидно състояние.
Why can replacing mutable state with immutable values simplify concurrency?
Answer: Immutable values can be shared between threads or tasks without requiring synchronization to protect their internal state, because their contents cannot change.
Отговор: Immutable стойностите могат да се споделят между threads или tasks без необходимост от synchronization за защита на вътрешното им състояние, защото съдържанието им не може да бъде променено.
What is the difference between thread-safe state and immutable state?
Answer: Immutable state cannot be changed, which often makes it inherently safe to share. Thread-safe mutable state can still change, but access and modification are coordinated using synchronization or other concurrency mechanisms.
Отговор: Immutable state не може да бъде променяно и затова обикновено е безопасно за споделяне. Thread-safe mutable state може да се променя, но достъпът и промените се координират чрез synchronization или други concurrency механизми.
Why can excessive use of constants also be a design smell?
Answer: Constants are useful for stable domain values, but creating constants for every value can obscure behavior, create unnecessary indirection, or hide configuration that should be explicit and contextual.
Отговор: Константите са полезни за стабилни domain стойности, но превръщането на всяка стойност в константа може да скрие логиката, да създаде ненужна indirection или да прикрие configuration, която трябва да бъде явна и контекстуална.
How can variable design affect API stability?
Answer: Exposing implementation details such as mutable fields or specific internal data structures makes clients depend on those details. Changing them later can therefore become a breaking change.
Отговор: Ако API-то излага implementation details като mutable полета или конкретни вътрешни data structures, клиентите могат да започнат да зависят от тях. Промяната им по-късно може да се превърне в breaking change.
What is the trade-off between copying data and sharing references?
Answer: Copying provides stronger isolation and reduces unintended mutations, but can increase memory usage and processing cost. Sharing references can be more efficient but introduces coupling and potential mutation problems.
Отговор: Копирането осигурява по-добра изолация и намалява риска от неочаквани промени, но може да увеличи използваната памет и computational cost. Споделянето на референции може да е по-ефективно, но създава coupling и потенциални проблеми с mutation.
How can careless variable lifetime management contribute to memory problems?
Answer: If references to objects remain reachable longer than necessary, the objects cannot be reclaimed by the runtime or memory manager. This can cause unnecessary memory retention and, depending on the environment, memory leaks.
Отговор: Ако референции към обекти останат достижими по-дълго от необходимото, обектите не могат да бъдат освободени от runtime-а или memory manager-а. Това може да доведе до ненужно задържане на памет и, в зависимост от средата, до memory leaks.
As a senior developer, how do you decide whether state should be mutable, immutable, local, shared, or global?
Answer: Consider ownership, lifetime, scope, concurrency, performance, testability, and how many components need to modify the state. Prefer the simplest design with the smallest necessary scope and the fewest mutation points, while avoiding premature optimization.
Отговор: Трябва да се вземат предвид ownership, lifetime, scope, concurrency, performance, testability и колко компонента трябва да могат да променят състоянието. Предпочита се най-простият дизайн с възможно най-тесен scope и минимален брой места, които могат да променят state-а, като същевременно се избягва premature optimization.
What is value semantics?
Answer: Value semantics means that a variable represents a value independently from other variables. Copying the value creates an independent value, so changing one does not affect the other.
Отговор: Value semantics означава, че променливата представлява стойност, независима от други променливи. Копирането на стойността създава независима стойност, така че промяната на едната не засяга другата.
What is reference semantics?
Answer: Reference semantics means that a variable refers to an object or piece of data rather than containing an independent copy of it. Multiple variables can therefore refer to the same underlying object.
Отговор: Reference semantics означава, че променливата сочи към обект или данни, вместо да съдържа независимо копие. Затова няколко променливи могат да сочат към един и същ обект.
What is the difference between equality and identity?
Answer: Equality asks whether two values are equivalent, while identity asks whether two references refer to the exact same object or entity.
Отговор: Equality проверява дали две стойности са еквивалентни, докато identity проверява дали две референции сочат към абсолютно един и същ обект или entity.
What is a shallow copy?
Answer: A shallow copy creates a new outer object but keeps references to the same nested objects as the original.
Отговор: Shallow copy създава нов външен обект, но запазва референции към същите вложени обекти като оригинала.
What is a deep copy?
Answer: A deep copy creates independent copies of the object and its nested objects, so mutations to the copy do not affect the original object's nested state.
Отговор: Deep copy създава независими копия на обекта и вложените му обекти, така че промените в копието да не засягат вложеното състояние на оригинала.
When is a shallow copy preferable to a deep copy?
Answer: A shallow copy can be preferable when nested objects are immutable, intentionally shared, or when copying the entire object graph would be unnecessarily expensive.
Отговор: Shallow copy може да е по-подходящо, когато вложените обекти са immutable, умишлено се споделят или когато копирането на целия object graph би било ненужно скъпо.
What is object aliasing?
Answer: Object aliasing occurs when multiple variables or references provide access to the same mutable object.
Отговор: Object aliasing възниква, когато няколко променливи или референции дават достъп до един и същ mutable обект.
Why can aliasing make code difficult to reason about?
Answer: A change made through one reference can affect another part of the program that holds a different reference to the same object.
Отговор: Промяна, направена чрез една референция, може да повлияе на друга част от програмата, която има различна референция към същия обект.
What is ownership in programming?
Answer: Ownership defines which component or part of a program is responsible for managing a resource or piece of state, including its lifecycle and allowed modifications.
Отговор: Ownership определя кой компонент или част от програмата е отговорен за даден ресурс или състояние, включително за неговия lifecycle и допустимите промени.
Why is clear ownership important in large systems?
Answer: Clear ownership reduces accidental modifications, makes responsibilities easier to understand, and helps prevent hidden dependencies between components.
Отговор: Ясното ownership намалява случайните промени, прави отговорностите по-лесни за разбиране и помага да се предотвратят скрити зависимости между компонентите.
What is the difference between scope and visibility?
Answer: Scope describes where a name can be resolved within the program, while visibility usually describes whether a declaration can be accessed from a particular context, often across modules or classes.
Отговор: Scope описва къде дадено име може да бъде намерено в програмата, докато visibility обикновено описва дали дадена декларация може да бъде достъпвана от конкретен контекст, например между модули или класове.
What is lexical scope?
Answer: Lexical scope means that the accessibility of variables is determined by where they are declared in the source code.
Отговор: Lexical scope означава, че достъпността на променливите се определя от мястото, на което са декларирани в source code-а.
What is name resolution?
Answer: Name resolution is the process a language or compiler uses to determine which declaration a particular variable or identifier refers to.
Отговор: Name resolution е процесът, чрез който езикът или компилаторът определя към коя декларация се отнася дадена променлива или identifier.
What is a closure, and how does it relate to variables?
Answer: A closure is a function together with access to variables from its surrounding lexical scope. Those captured variables may remain available even after the outer function has finished executing.
Отговор: Closure е функция заедно с достъпа ѝ до променливи от заобикалящия я lexical scope. Тези captured променливи могат да останат достъпни дори след приключването на външната функция.
What is the difference between compile-time and runtime constants?
Answer: A compile-time constant has a value known during compilation and may be embedded or optimized by the compiler. A runtime constant is assigned or determined during execution but is not intended to change afterward.
Отговор: Compile-time constant има стойност, известна по време на компилация, и може да бъде вградена или оптимизирана от компилатора. Runtime constant се задава или определя по време на изпълнение, но след това не е предназначена да се променя.
What is definite assignment?
Answer: Definite assignment is the requirement in some languages that a variable must be assigned a valid value before the program can read it.
Отговор: Definite assignment е изискване в някои езици променливата да получи валидна стойност, преди програмата да може да я прочете.
Why can uninitialized variables be dangerous?
Answer: Reading an uninitialized variable can produce undefined behavior, an error, an unexpected default value, or other language-specific behavior.
Отговор: Четенето на неинициализирана променлива може да доведе до undefined behavior, грешка, неочаквана default стойност или друго поведение според конкретния език.
What is variable lifetime in relation to memory management?
Answer: A variable's lifetime determines how long the variable or its associated storage remains relevant. Depending on the language, the underlying object may remain alive as long as there are references to it or until its owning scope or resource lifecycle ends.
Отговор: Lifetime определя колко дълго променливата или свързаното с нея storage остава необходимо. В зависимост от езика обектът може да остане жив, докато има референции към него или докато приключи scope-ът или lifecycle-ът на ресурса, който го притежава.
What is the difference between memory allocation and variable assignment?
Answer: Memory allocation reserves memory for data, while assignment associates a variable with a value or changes what value it represents. The two operations may happen together or independently depending on the language.
Отговор: Memory allocation заделя памет за данни, докато assignment свързва променлива със стойност или променя стойността, която тя представлява. Двете операции могат да се случат заедно или независимо според конкретния език.
Why should a senior developer care about the distinction between variables, references, objects, and memory?
Answer: Understanding these distinctions helps explain performance, mutation, copying, lifetime, concurrency, memory usage, and bugs. It also allows developers to reason about behavior instead of relying only on language syntax.
Отговор: Senior developer трябва да разбира тези разлики, защото те обясняват performance, mutation, copying, lifetime, concurrency, memory usage и различни видове bugs. Това позволява да разбира поведението на програмата, вместо да разчита само на syntax-а на езика.