Programming Interview Questions Flashcards
What is Object Oriented Programming?
A computer programming model
Organises software design around data and objects, rather than functions and logic
What are the benefits of OO Programming?
Beneficial for collaborative development
Code reusability, scalability and efficiency
What is a class?
User-defined data types
Act as the “blueprint” for objects, attributes and methods
What is an object?
Instances of a class, with specifically designed data
What are the main principles of OOP?
Encapsulation
Abstraction
Inheritance
Polymorphism
What is Encapsulation?
All important info is privately contained inside of an object
Each object is held privately within a defined class
Provides greater program security and avoids unintended data corruption
What is Abstraction?
Objects only reveal internal mechanisms that are relevant for the use of other objects - focuses on what an object does rather than how it does it
Simplifies complex systems by modelling them at a higher level of detail while hiding unnecessary implementation details
Helps developers easily make additional changes over time
What is Inheritance?
Classes can reuse code from other classes.
Allows developers to reuse common logic while maintaining a unique hierarchy
What is Polymorphism?
The ability to present the same interface for different data types (e.g. 1 method “Draw” for multiple children Square, Circle of a “Shape” class).
Reduces need for duplicate code
Examples of mainly OOP languages?
Java, Python, C++
Examples of pure OOP languages?
Ruby
JADE
Emerald
Downsides of OOP?
Overemphasises data component of software development
Can be complicated to write or take longer to compile
Alternative to OOP?
Functional programming e.g. Erlang
Many advanced programming languages allow users to combine models, e.g. JavaScript allows the combination of OOP and functional programming
What are design patterns?
Common and reusable solutions to problems given a certain context
What are anti-patterns?
“Bad” design patterns
Benefits & risks of design patterns?
Proven solution
Reusable
Expressive and Elegant
Prevent need for refactoring code
Lower size of codebase
Risk: might fall back on design pattern when there’s a better way to solve this particular problem
How many design patterns are there?
23
Types of software design patterns?
Creational
Behavioural
Structural
What are Creational Design Patterns?
Used for class instantiation
They can be Class creation or object-creational patterns
What are Structural Design Patterns?
Used for communication between objects
Designed to increase functionality of the classes involved
What are Behavioural Design Patterns?
Design Patterns that focus on how objects communicate and interact with each other
What are the architectural design patterns?
MVC Model View Controller
MVP Model View Presenter
MVVM Model View View Model
Describe MVC
Model = backend logic and data
View = interface components to display data
Controller = Input is directed here first
Benefits & risks of MVC
Provides separation of concern, separating front-end and back-end code
Makes it easier to update the application without interruption
Exposing the model to view can introduce security and performance concerns
Common for web apps
Describe MVP
Model = backend logic and data
View = input begins here
Presenter = processes request through the model and passes it back to the view
Benefits & risks of MVP
Common for Android apps, websites
Suited to make views reusable
Describe MVVM
Model = backend logic and data
View = input begins here
View-Model = only purpose is maintain the state of view and manipulate the model
Benefits & risks of MVVM
Used for mobile apps
Suited to help improve performance
Allows view-specific subsets of a model to be created, with the state and logic bound to the view.
What is a constructor?
A method used to initialise the state of an object
Method is called whenever an object is created
What is a destructor?
A method called when the object is destroyed
What is a virtual function?
A member function of a class
Its functionality can be overridden in its derived class
What is function overloading?
allows you to define multiple methods in a class with the same name but with different parameter lists.
Each overloaded method provides a different implementation of the same functionality
What is an abstract class?
A class that cannot be instantiated
Serves as a blueprint for other classes to inherit from
What is a ternary operator?
Equivalent to an if/else statement
What is the finalize method?
Performs cleanup on resources not being used
What are the argument types?
Call by Value - value passed only modified inside function
Call by Reference - value passed modified both inside and outside
What is method overriding?
Where a subclass’s method overrides the main class’s method. Uses same method name, parameter and type.
What is the difference between overloading and overriding?
Overloading is the same method with different arguments, overriding is a different method with the same argument in a child class
What are the access modifiers?
Private
Protected
Public
Friend
Protected Friend
What is a “sealed” class?
Access modifier which prevents other classes from inheriting from it.
How to call the base method without creating an instance?
Use static method
What is the difference between a structure and a class?
Structures are public by default and only stores data, classes are private and can store data and methods.
What is a pure virtual function?
A function which must be overridden in the derived class, but need not be defined.
What is the default access modifier in a class?
Private
What is coupling?
The degree of dependency of one class on another class; the ‘strength of relationship’ between modules.
Loose coupling is usually better than tight coupling
What is Loose Coupling?
Loose coupling = less interdependency, less coordination, less information flow.
Classes A and B are said to be ‘loosely coupled’ if the only knowledge that class A has about class B is what class B has exposed through its interface.
What is cohesion?
A measure of strength of relationship between the methods and data of a class
High cohesion is usually better than low cohesion
What are extension methods?
Allow you to add methods to existing types without creating new derived types, modifying the original code or using inheritance.
What is a static method?
A static method is a method that belongs to a class rather than an instance of a class, meaning you can call a static method without creating an object of the class.
What are some example of what you’d use Static methods for?
Mathematical operations, string manipulation methods, helper functions.
What are the programs in javascript called, and what is special about them?
They are called scripts
They are provided and executed as plain text, and don’t need special preparation or compilation to run.
What are browser engines, and how do they work?
Browsers have embedded engines, sometimes called a “Javascript Virtual Machine”, that:
1. Reads (parses) the script
2. Converts (compiles) the script to machine code
3. Runs the machine code.
What is Node.js?
A Javascript runtime environment
What is a runtime environment?
A software platform (e.g. operating system, web browser) that provides an environment for running code
Explain the difference between tuples, arrays and lists in C#
An array is an ordered data structure that can store multiple variables of the same type.
A tuple is an ordered data structure that contains a sequence of elements of different data types, and can only contain 8 elements.
A list is an ordered data structure that represents a strongly typed list of objects.
How to include more than 8 elements in a tuple C#?
Use nested tuples
What is a jagged array?
An array of arrays
What is the difference between a strongly typed and weakly typed programming language?
A strongly typed programming language, for example C#/python, is one in which the specification of data types is demanded.
Strongly typed languages are more likely to require explicit conversion
A weakly typed programming language, for example Javascript, does not require the explicit specification of different types of objects and variables, and can execute implicit type conversions at runtime.
Give an example of a difference between weakly and strongly typed programming languages.
Imagine comparing a string and number value. In C#, this will not compile as there’s a type mismatch. In Javascript, this code will compile and implicit conversion from the integer to a string will occur.
Benefits and weaknesses of strongly and weakly typed programming languages?
Strong typing enforces a rigid set of rules, increasing consistency
Leads to faster development through detecting errors earlier and better optimised code from the compiler
However, using strong typing means that a programmer may lose flexibility
What is a compiler?
A special program that translates a programming language’s source code into machine code (or another programming language).
Implicit vs Explicit conversion?
explicit type conversion is when the programmer intentionally changes the data type of a value. Explicit conversions have a risk of losing data, e.g. when converting a double to an int.
implicit type conversion is when the compiler automatically changes the data type of a value
explain what an Enum is in c#
An enum is a value type that represents a group of constants. Enums can be used to define options for config settings, etc.
What are the differences between reference types and value types?
Value types represent actual data values and are stored directly in memory where they are declared
Reference types store ‘addresses’ to where the actual data is located in memory. When you create a variable of a reference type, the variable stores a reference to the data, not the data itself.
Where are reference and value types typically stored?
Reference types are typically stored on the heap in memory, whereas value types are stored on the stack
What’s the difference between copying a value type and copying a reference type?
Copying a value type gives a copy of the actual data. Copying a reference type gives you a copy of the reference to the same data.
What’s the difference between a generic repository and normal repository in C#?
A normal repository implements its own specific methods for each entity type it deals with, whereas a generic repository provides a generic interface for CRUD operations that can be used with any entity type.
What does PostGIS do?
Extends capabilities of PostgreSQL relational database by adding support for storing, indexing and querying geographic data
In database design, what is a table?
A table is a structure that contains data
In database design, what is a view?
You can think of a view as a saved ‘SELECT’ statement that you can repeat. A view can join data from several tables.
What is the point of design patterns?
All patterns provide a way to let some part of a system vary independently of other parts
What are the SOLID principles?
The SOLID priniciples are:
Single Responsibility Principle
Open/Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
Explain the Single Responsibility Principle
Each class should do one thing only and have only one reason to change.
Explain the Open/Closed Principle
Open for extension, closed for modification
Open: designing components in a way that allows them to be extended or enhanced without modifying their existing code
Closed: Once an entity is defined and implemented, its behavious should remain stable and not be altered
Watch out for switch statements!
Explain the Liskov Substitution Principle
Objects of a superclass must be replaceable with objects of its subclasses
Explain the Interface Segregation Principle
Code should not be forced to depend upon methods it does not use
Watch out for large interfaces!
Explain the Dependency Inversion Principle
High-level modules should not depend on low-level modules, both should depend on abstractions.
What is the difference between inheritance and composition
Composition is a “has a” relationship, Inheritance is an “is a” relationship
Composition is achieved by instantiating variables of other objects, whereas Inheritance is achieved by extended classes
Benefits of composition
Composition is loosely coupled
Composition has access control
composition is easier to unit test
Downsides of inheritance
inheritance is tightly coupled
the structure of the parent is forced upon the child
What is the difference between compile time and runtime?
Compile time: the period where the programming code (e.g. C#) is being converted to machine code (e.g. binary), where syntax and semantics of the code are checked
Runtime: the period where a program is running (and generally occurs after compile time)
Explain the repository pattern
The repository pattern is a design pattern.
It provides an abstraction layer between the business logic of an application and the data storage mechanisms.
What does the repository pattern interface specify?
What operations (methods) are supported by the repository
What data (parameters) are required for each operation
The repository interface contains what it CAN do, but not HOW to do it.
The implementation details are in the respective repository class that implements the repository interface.
Explain the unit of work pattern
The Unit of Work pattern is a design pattern.
It helps to maintain consistency and integrity of data operations by managing transactions and coordinating multiple database operations within a single unit of work.
In the unit, either all operations succeed and are committed, or none of them are applied and they are rolled back.
Explain the difference between “scoped”, “singleton” and “transient”
In the context of dependency injection containers, these refer to different lifetimes of the services that the container manages
Transient: these services are created each time they are requested; a new instance of the service is created each time it’s resolved from the Dependency Injection container. Transient objects are always different, a new instance is provided to every controller and every service.
Scoped: these services are created once per request or usage scope; this means that a single instance of the service is created and shared within the scope of a single HTTP request (in the case of web applications). Scoped objects are the same within a request, but different across different requests.
Singleton: these services are created once and shared across the entire application lifetime. This means that a single instance of the service is created when it’s first created, and that same instance is reused for all subsequent requests. Singleton objects are the same for every object and every request.
What are scoped services used for
For components that need to maintain state across multiple operations within the same scope, such as database contexts in web applications.
What are transient services used for
For scenarios where a new instance is needed for each use
What are singleton services used for
For stateless (no internal data that changes over time) and thread-safe components that be can shared safely across the application, such as configuration settings
What are the benefits of the repository pattern?
Code cleaner and easier to maintain
Enables creation of loosely coupled systems
When unit testing, easy to replace a real repository with a fake implementation for testing
What is LINQ?
LINQ is a set of technologies based on the integration of query capabilities directly into the C# language.
What is SQL?
SQL stands for ‘structured query language’. SQL is used to query and manipulate the underlying relational databases, e.g. PostgreSQL
What is PostgreSQL?
An open-source object-relational database system based on POSTGRES
Explain what an inner join is
An inner join is a type of join operation used in relational databases to combine rows from two or more tables based on a related column between them. The inner join selects only the rows from both tables that have matching values in the specified column(s), excluding rows where there is no match.
Explain what a left outer join is
Returns all records from the left table, and matching records in the right table
Explain what a full outer join is
Combines the result of left and right outer join
Explain what a cross join is
Produces the cartesian product of rows between 2+ tables
What is a primary key?
A primary key is a special relational database table column (or set of columns) that uniquely identifies each row in the table. It allows for efficient data retrieval, indexing and referencing between tables
What are the key characteristics of a primary key?
Uniqueness
Non-nullability
Immutable (should not change once assigned to a record)
Indexed (typically indexed by database management system for faster lookup and retrieval operations)
Foreign key references
What is a foreign key?
A foreign key is a column (or set of columns) that establishes a link between data in two tables
What is dependency injection?
Dependency injection is a design pattern in which the dependencies of a component are provided from the outside rather than created internally. It is a technique for achieving inversion of control.
What is inversion of control?
In traditional programming, components control the flow of execution by instantiating and invoking the methods of other components or services they depend on.
Inversion of control is where the control of object creation and management is shifted from the components themselves to an external entity, typically a container or framework.
What is meant by a container with respect to dependency injection?
A container is a software component or framework that is responsible for managing the lifecycle, configuration and resolution of dependencies within an application.
What is SQL Injection?
SQL injection is a code injection technique. It is the placement of malicious code in SQL statements.
How to prevent SQL injection?
You can prevent SQL injection through the use of SQL parameters.
What are SQL parameters?
SQL parameters are values that are added to an SQL query at execution time
How are SQL parameters represented?
SQL parameters are represented in the SQL statement by an ‘@’ marker
What is meant by a framework?
A framework is a pre-built, reusable set of libraries, tools and components that provides a foundation for developing software applications.
What is a Linked List?
A linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next.
In its most basic form, each node contains data and a reference
What are the pros and cons of linked lists?
Pros:
Efficient memory utilisation - size decreases or increases as per requirement
Ease of insertion/deletion - no elements need to be shifted after insertion/deletion
Cons:
Many basic operations (such as obtaining the last node of the list) may require iterating through most or all of the list elements.
Give some applications of linked lists
Can help implement data structures such as stack, queue, hash maps and graphs
Can be used for navigation in web browsers
Benefits and Disadvantages of Linked Lists vs Arrays
Arrays are of fixed size while Linked Lists are of dynamic size.
Linked lists use more memory
Arrays have easier access to elements
Insertion and Deletion is faster for linked lists.
Explain the singleton pattern
The singleton pattern is a design pattern that ensures a class has only one instance and provides a global access point to that instance. It is a creational design pattern.
When is the singleton pattern used?
The singleton pattern is used when exactly one instance of a class is needed throughout the lifetime of an application
Give some examples of when you might use the singleton pattern?
You might need to implement the singleton pattern when managing shared resources or global configurations
How is the singleton pattern achieved?
The singleton pattern provides a way to restrict the instantiation of a class to a single object and provides a global access point to that instance.
This is achieved by:
Defining a private constructor to prevent external instantiation
Defining a static method or property to provide access to the single instance
What are some benefits of the singleton pattern?
Memory efficiency: only one instance of a class can be created
Lazy initialisation: allows instance to be created only when needed, improving performance and reducing startup time
What are some drawbacks of the singleton pattern?
Testing: Singleton classes can be difficult to test in isolation due to their global state and tight coupling with other parts of the application
Overuse: overusing the singleton pattern can lead to code complexity and dependencies on hidden global state, making the application harder to understand and maintain.
Explain how you might set up the Singleton Pattern in C#
Set up a private static instance variable e.g.
private static readonly Singleton instance = new Singleton();
Set up a private constructor to prevent external instantiation
private Singleton() { }
Set up a public static property to provide access to the single instance
public static Singleton Instance
{
get { return instance; }
}
Explain the strategy pattern
The Strategy Pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one of them, and make them interchangeable. It lets the algorithm vary independently from clients that use it.
Give an example of when you might use the strategy pattern
If you have a sorting algorithm that needs to be flexible enough to switch between different sorting strategies (bubble sort, quick sort, mergesort) based on different user input or user preferences
What are the benefits of the Strategy Pattern?
Flexibility: Strategies can be easily added, removed or replaced without modifying the client’s code
Encapsulation: each algorithm is encapsulated into its own class
Testability: Strategies can be tested independently
Reusability: Strategies can be reused across different contexts or applications
Explain the components of the strategy pattern
Strategy Interface: This is an interface or abstract class that defines a common interface for all supported algorithms.
Concrete Strategies: These are the concrete implementations of the strategy interface
Context: This is a class that uses the strategy interface to perform its operations. The context maintains a reference to a strategy object and delegates the algorithm’s execution to the strategy.
What is the observer pattern?
The observer pattern is design pattern where multiple observer objects (subscribers) are notified automatically when the state of a subject object (publisher) changes
How to implement the observer pattern
Define the Subject Interface: This interface defines the methods for attaching, detaching, and notifying observers.
Define the Observer Interface: This interface defines the method that subjects will use to notify observers of state changes.
Create Concrete Subject Class(es): These classes implement the subject interface and maintain a list of observers. They provide methods to attach, detach, and notify observers.
Create Concrete Observer Class(es): These classes implement the observer interface and define the behavior to be executed in response to notifications from subjects.
What are the advantages and disadvantages of the observer pattern
Advantages:
Loose coupling (between publishers and subscribers)
Disadvantages:
Performance overhead: can be performance issue if a lot of observers etc.
Ordering of notifications: the order in which observers are notified of state changes is not deterministic, which can lead to unexpected behaviour.
What is thread safety?
Thread safety refers to the ability of a program, module, or system to perform correctly and maintain consistent behavior when accessed or manipulated by multiple threads simultaneously